test.cc 955 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439
  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. bool cn_matched_next_to_dns_san = true;
  13648. SSLClient cli(HOST, port);
  13649. cli.enable_server_certificate_verification(true);
  13650. cli.set_ca_cert_path(CA_CERT_FILE);
  13651. cli.set_connection_timeout(5);
  13652. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13653. verify_callback_called = true;
  13654. if (!ctx.cert) return false;
  13655. dns_san_matched = ctx.check_hostname("a.zz");
  13656. ip_san_matched = ctx.check_hostname("42.46.122.122");
  13657. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  13658. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  13659. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  13660. return true; // Accept for the purpose of this test
  13661. });
  13662. cli.Get("/test");
  13663. ASSERT_TRUE(verify_callback_called)
  13664. << "Verify callback should have been called";
  13665. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  13666. EXPECT_TRUE(ip_san_matched)
  13667. << "verify_hostname should match an iPAddress SAN";
  13668. EXPECT_FALSE(ip_matched_via_dns_san)
  13669. << "An IP host must not be authenticated via a dNSName SAN";
  13670. EXPECT_FALSE(dns_matched_via_ip_san)
  13671. << "A DNS host must not be authenticated via an iPAddress SAN";
  13672. EXPECT_FALSE(cn_matched_next_to_dns_san)
  13673. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  13674. }
  13675. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  13676. // "www.*.example.test" names one host and not every host under example.test.
  13677. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  13678. using namespace httplib::tls;
  13679. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  13680. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  13681. ASSERT_TRUE(svr.is_valid());
  13682. svr.Get("/test", [](const Request &, Response &res) {
  13683. res.set_content("ok", "text/plain");
  13684. });
  13685. auto port = svr.bind_to_any_port(HOST);
  13686. thread t([&]() { svr.listen_after_bind(); });
  13687. auto se = detail::scope_exit([&] {
  13688. svr.stop();
  13689. t.join();
  13690. });
  13691. svr.wait_until_ready();
  13692. bool verify_callback_called = false;
  13693. bool leftmost_wildcard_matched = false;
  13694. bool wildcard_spanned_labels = true;
  13695. bool inner_wildcard_matched = true;
  13696. SSLClient cli(HOST, port);
  13697. cli.enable_server_certificate_verification(true);
  13698. cli.set_ca_cert_path(CA_CERT_FILE);
  13699. cli.set_connection_timeout(5);
  13700. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13701. verify_callback_called = true;
  13702. if (!ctx.cert) return false;
  13703. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  13704. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  13705. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  13706. return true; // Accept for the purpose of this test
  13707. });
  13708. cli.Get("/test");
  13709. ASSERT_TRUE(verify_callback_called)
  13710. << "Verify callback should have been called";
  13711. EXPECT_TRUE(leftmost_wildcard_matched)
  13712. << "A leftmost wildcard should match a single label";
  13713. EXPECT_FALSE(wildcard_spanned_labels)
  13714. << "A wildcard label must not match more than one label";
  13715. EXPECT_FALSE(inner_wildcard_matched)
  13716. << "A wildcard outside the leftmost label must not be honoured";
  13717. }
  13718. // sans() must report each SAN entry under its own type.
  13719. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  13720. using namespace httplib::tls;
  13721. // SANs: DNS:a.zz, IP:42.46.122.122
  13722. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13723. ASSERT_TRUE(svr.is_valid());
  13724. svr.Get("/test", [](const Request &, Response &res) {
  13725. res.set_content("ok", "text/plain");
  13726. });
  13727. auto port = svr.bind_to_any_port(HOST);
  13728. thread t([&]() { svr.listen_after_bind(); });
  13729. auto se = detail::scope_exit([&] {
  13730. svr.stop();
  13731. t.join();
  13732. });
  13733. svr.wait_until_ready();
  13734. bool verify_callback_called = false;
  13735. std::vector<SanEntry> sans;
  13736. SSLClient cli(HOST, port);
  13737. cli.enable_server_certificate_verification(true);
  13738. cli.set_ca_cert_path(CA_CERT_FILE);
  13739. cli.set_connection_timeout(5);
  13740. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13741. verify_callback_called = true;
  13742. if (!ctx.cert) return false;
  13743. sans = ctx.sans();
  13744. return true; // Accept for the purpose of this test
  13745. });
  13746. cli.Get("/test");
  13747. ASSERT_TRUE(verify_callback_called)
  13748. << "Verify callback should have been called";
  13749. auto has_san = [&](SanType type, const std::string &value) {
  13750. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  13751. return san.type == type && san.value == value;
  13752. });
  13753. };
  13754. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  13755. << "sans() should report the dNSName SAN";
  13756. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  13757. << "sans() should report the iPAddress SAN";
  13758. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  13759. << "sans() must not report the dNSName SAN as an address";
  13760. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  13761. << "sans() must not report the iPAddress SAN as a DNS name";
  13762. }
  13763. #endif
  13764. // mbedTLS-specific callback constructor test
  13765. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  13766. #ifdef CPPHTTPLIB_SSL_ENABLED
  13767. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  13768. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13769. ASSERT_TRUE(svr.is_valid());
  13770. // Set up a handler to verify client certificate is present
  13771. bool client_cert_verified = false;
  13772. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13773. // Verify that client certificate was provided
  13774. client_cert_verified = true;
  13775. res.set_content("success", "text/plain");
  13776. });
  13777. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13778. auto se = detail::scope_exit([&] {
  13779. svr.stop();
  13780. t.join();
  13781. ASSERT_FALSE(svr.is_running());
  13782. });
  13783. svr.wait_until_ready();
  13784. // Client with certificate
  13785. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13786. cli.enable_server_certificate_verification(false);
  13787. cli.set_connection_timeout(30);
  13788. auto res = cli.Get("/test");
  13789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13790. ASSERT_EQ(StatusCode::OK_200, res->status);
  13791. ASSERT_TRUE(client_cert_verified);
  13792. EXPECT_EQ("success", res->body);
  13793. }
  13794. #endif
  13795. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  13796. // backends
  13797. #ifdef CPPHTTPLIB_SSL_ENABLED
  13798. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  13799. using namespace httplib::tls;
  13800. // Test that when client CA cert file is provided,
  13801. // the server properly requests and validates client certificates
  13802. // Create a server with client authentication
  13803. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13804. ASSERT_TRUE(svr.is_valid());
  13805. bool handler_called = false;
  13806. svr.Get("/test", [&](const Request &req, Response &res) {
  13807. handler_called = true;
  13808. // Verify that a client certificate was provided
  13809. auto cert = req.peer_cert();
  13810. ASSERT_TRUE(static_cast<bool>(cert));
  13811. // Get the issuer name
  13812. std::string issuer_str = cert.issuer_name();
  13813. ASSERT_FALSE(issuer_str.empty());
  13814. // The client certificate should be issued by our test CA
  13815. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  13816. res.set_content("authenticated", "text/plain");
  13817. });
  13818. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13819. auto se = detail::scope_exit([&] {
  13820. svr.stop();
  13821. t.join();
  13822. ASSERT_FALSE(svr.is_running());
  13823. });
  13824. svr.wait_until_ready();
  13825. // Connect with a client certificate issued by the CA
  13826. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13827. cli.enable_server_certificate_verification(false);
  13828. cli.set_connection_timeout(30);
  13829. auto res = cli.Get("/test");
  13830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13831. ASSERT_EQ(StatusCode::OK_200, res->status);
  13832. ASSERT_TRUE(handler_called);
  13833. EXPECT_EQ("authenticated", res->body);
  13834. }
  13835. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  13836. using namespace httplib::tls;
  13837. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13838. ASSERT_TRUE(svr.is_valid());
  13839. svr.Get("/test", [](const Request &, Response &res) {
  13840. res.set_content("ok", "text/plain");
  13841. });
  13842. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13843. auto se = detail::scope_exit([&] {
  13844. svr.stop();
  13845. t.join();
  13846. });
  13847. svr.wait_until_ready();
  13848. SSLClient cli(HOST, PORT);
  13849. cli.enable_server_certificate_verification(false);
  13850. cli.set_connection_timeout(30);
  13851. bool cert_checked = false;
  13852. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13853. if (ctx.cert) {
  13854. auto sans = ctx.sans();
  13855. // Test certificate may or may not have SANs - just verify the API
  13856. // works If SANs exist, verify the types are valid
  13857. for (const auto &san : sans) {
  13858. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  13859. san.type == SanType::EMAIL || san.type == SanType::URI ||
  13860. san.type == SanType::OTHER);
  13861. EXPECT_FALSE(san.value.empty());
  13862. }
  13863. cert_checked = true;
  13864. }
  13865. return true;
  13866. });
  13867. auto res = cli.Get("/test");
  13868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13869. EXPECT_TRUE(cert_checked);
  13870. }
  13871. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  13872. using namespace httplib::tls;
  13873. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13874. ASSERT_TRUE(svr.is_valid());
  13875. svr.Get("/test", [](const Request &, Response &res) {
  13876. res.set_content("ok", "text/plain");
  13877. });
  13878. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13879. auto se = detail::scope_exit([&] {
  13880. svr.stop();
  13881. t.join();
  13882. });
  13883. svr.wait_until_ready();
  13884. SSLClient cli(HOST, PORT);
  13885. cli.enable_server_certificate_verification(false);
  13886. cli.set_connection_timeout(30);
  13887. bool validity_checked = false;
  13888. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13889. if (ctx.cert) {
  13890. time_t not_before = 0, not_after = 0;
  13891. bool result = ctx.validity(not_before, not_after);
  13892. EXPECT_TRUE(result);
  13893. // Verify that not_before < now < not_after for a valid cert
  13894. time_t now = time(nullptr);
  13895. EXPECT_LT(not_before, now);
  13896. EXPECT_GT(not_after, now);
  13897. validity_checked = true;
  13898. }
  13899. return true;
  13900. });
  13901. auto res = cli.Get("/test");
  13902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13903. EXPECT_TRUE(validity_checked);
  13904. }
  13905. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  13906. using namespace httplib::tls;
  13907. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13908. ASSERT_TRUE(svr.is_valid());
  13909. svr.Get("/test", [](const Request &, Response &res) {
  13910. res.set_content("ok", "text/plain");
  13911. });
  13912. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13913. auto se = detail::scope_exit([&] {
  13914. svr.stop();
  13915. t.join();
  13916. });
  13917. svr.wait_until_ready();
  13918. SSLClient cli(HOST, PORT);
  13919. cli.enable_server_certificate_verification(false);
  13920. cli.set_connection_timeout(30);
  13921. bool serial_checked = false;
  13922. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13923. if (ctx.cert) {
  13924. std::string serial = ctx.serial();
  13925. EXPECT_FALSE(serial.empty());
  13926. // Serial should be a hex string
  13927. for (char c : serial) {
  13928. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  13929. (c >= 'a' && c <= 'f'));
  13930. }
  13931. serial_checked = true;
  13932. }
  13933. return true;
  13934. });
  13935. auto res = cli.Get("/test");
  13936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13937. EXPECT_TRUE(serial_checked);
  13938. }
  13939. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  13940. // Test 1: Valid CA file - no error should be recorded
  13941. {
  13942. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13943. CLIENT_CA_CERT_FILE);
  13944. ASSERT_TRUE(svr.is_valid());
  13945. // With valid setup, last_ssl_error should be 0
  13946. EXPECT_EQ(0, svr.ssl_last_error());
  13947. }
  13948. // Test 2: Invalid CA file content
  13949. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  13950. {
  13951. // Create a temporary file with completely invalid content
  13952. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  13953. {
  13954. std::ofstream ofs(temp_invalid_ca);
  13955. ofs << "This is not a certificate file at all\n";
  13956. ofs << "Just plain text content\n";
  13957. }
  13958. // Create server with invalid CA file
  13959. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  13960. // Clean up temporary file
  13961. std::remove(temp_invalid_ca);
  13962. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  13963. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  13964. // Note: SSL_CTX_load_verify_locations typically fails first,
  13965. // but our error handling code path is still exercised
  13966. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  13967. }
  13968. }
  13969. TEST(VerifyCallbackTest, VerifyContextFields) {
  13970. using namespace httplib::tls;
  13971. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13972. ASSERT_TRUE(svr.is_valid());
  13973. svr.Get("/test", [](const Request &, Response &res) {
  13974. res.set_content("ok", "text/plain");
  13975. });
  13976. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13977. auto se = detail::scope_exit([&] {
  13978. svr.stop();
  13979. t.join();
  13980. });
  13981. svr.wait_until_ready();
  13982. SSLClient cli(HOST, PORT);
  13983. cli.enable_server_certificate_verification(false);
  13984. cli.set_connection_timeout(30);
  13985. int callback_count = 0;
  13986. bool saw_leaf_cert = false;
  13987. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13988. if (ctx.cert) {
  13989. callback_count++;
  13990. // We should see at least one certificate (the leaf)
  13991. std::string cn = ctx.subject_cn();
  13992. if (!cn.empty()) { saw_leaf_cert = true; }
  13993. // Verify context fields are populated
  13994. EXPECT_NE(ctx.session, nullptr);
  13995. EXPECT_GE(ctx.depth, 0);
  13996. }
  13997. return true;
  13998. });
  13999. auto res = cli.Get("/test");
  14000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14001. EXPECT_GT(callback_count, 0);
  14002. EXPECT_TRUE(saw_leaf_cert);
  14003. }
  14004. // A verifier belongs to the client that set it, not to the thread that set it.
  14005. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14006. using namespace httplib::tls;
  14007. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14008. ASSERT_TRUE(svr.is_valid());
  14009. svr.Get("/test", [](const Request &, Response &res) {
  14010. res.set_content("ok", "text/plain");
  14011. });
  14012. auto port = svr.bind_to_any_port(HOST);
  14013. thread t([&]() { svr.listen_after_bind(); });
  14014. auto se = detail::scope_exit([&] {
  14015. svr.stop();
  14016. t.join();
  14017. });
  14018. svr.wait_until_ready();
  14019. auto rejecting_calls = 0;
  14020. SSLClient rejecting(HOST, port);
  14021. rejecting.enable_server_certificate_verification(false);
  14022. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14023. rejecting_calls++;
  14024. return false;
  14025. });
  14026. auto accepting_calls = 0;
  14027. SSLClient accepting(HOST, port);
  14028. accepting.enable_server_certificate_verification(false);
  14029. // Set on another thread than the requests below.
  14030. thread([&]() {
  14031. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14032. accepting_calls++;
  14033. return true;
  14034. });
  14035. }).join();
  14036. // Requested on another thread than the verifier was set on.
  14037. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14038. EXPECT_GT(rejecting_calls, 0);
  14039. auto res = accepting.Get("/test");
  14040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14041. EXPECT_GT(accepting_calls, 0);
  14042. }
  14043. // VerifyContext::session is the same handle the other tls:: functions take.
  14044. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14045. using namespace httplib::tls;
  14046. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14047. ASSERT_TRUE(svr.is_valid());
  14048. svr.Get("/test", [](const Request &, Response &res) {
  14049. res.set_content("ok", "text/plain");
  14050. });
  14051. auto port = svr.bind_to_any_port(HOST);
  14052. thread t([&]() { svr.listen_after_bind(); });
  14053. auto se = detail::scope_exit([&] {
  14054. svr.stop();
  14055. t.join();
  14056. });
  14057. svr.wait_until_ready();
  14058. SSLClient cli(HOST, port);
  14059. cli.enable_server_certificate_verification(false);
  14060. session_t verifier_session = nullptr;
  14061. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14062. verifier_session = ctx.session;
  14063. return true;
  14064. });
  14065. session_t session_verifier_session = nullptr;
  14066. cli.set_session_verifier([&](session_t session) {
  14067. session_verifier_session = session;
  14068. return SSLVerifierResponse::NoDecisionMade;
  14069. });
  14070. auto res = cli.Get("/test");
  14071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14072. EXPECT_NE(nullptr, verifier_session);
  14073. EXPECT_EQ(session_verifier_session, verifier_session);
  14074. }
  14075. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14076. using httplib::tls::TlsError;
  14077. // Test that verify_error_to_string returns empty for success
  14078. std::string success_str = TlsError::verify_error_to_string(0);
  14079. EXPECT_TRUE(success_str.empty());
  14080. // Test that verify_error_to_string returns non-empty for error codes
  14081. // Using a common error code (certificate expired)
  14082. std::string error_str =
  14083. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14084. EXPECT_FALSE(error_str.empty());
  14085. }
  14086. TEST(SessionVerifierTest, CertificateAccepted) {
  14087. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14088. ASSERT_TRUE(svr.is_valid());
  14089. svr.Get("/test", [](const Request &, Response &res) {
  14090. res.set_content("ok", "text/plain");
  14091. });
  14092. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14093. auto se = detail::scope_exit([&] {
  14094. svr.stop();
  14095. t.join();
  14096. });
  14097. svr.wait_until_ready();
  14098. SSLClient cli(HOST, PORT);
  14099. cli.enable_server_certificate_verification(false);
  14100. cli.set_connection_timeout(30);
  14101. bool callback_called = false;
  14102. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14103. EXPECT_NE(session, nullptr);
  14104. callback_called = true;
  14105. return SSLVerifierResponse::CertificateAccepted;
  14106. });
  14107. auto res = cli.Get("/test");
  14108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14109. EXPECT_EQ(200, res->status);
  14110. EXPECT_TRUE(callback_called);
  14111. }
  14112. TEST(SessionVerifierTest, CertificateRejected) {
  14113. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14114. ASSERT_TRUE(svr.is_valid());
  14115. svr.Get("/test", [](const Request &, Response &res) {
  14116. res.set_content("ok", "text/plain");
  14117. });
  14118. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14119. auto se = detail::scope_exit([&] {
  14120. svr.stop();
  14121. t.join();
  14122. });
  14123. svr.wait_until_ready();
  14124. SSLClient cli(HOST, PORT);
  14125. cli.enable_server_certificate_verification(false);
  14126. cli.set_connection_timeout(30);
  14127. bool callback_called = false;
  14128. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14129. EXPECT_NE(session, nullptr);
  14130. callback_called = true;
  14131. return SSLVerifierResponse::CertificateRejected;
  14132. });
  14133. auto res = cli.Get("/test");
  14134. EXPECT_FALSE(res);
  14135. EXPECT_TRUE(callback_called);
  14136. }
  14137. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14138. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14139. ASSERT_TRUE(svr.is_valid());
  14140. svr.Get("/test", [](const Request &, Response &res) {
  14141. res.set_content("ok", "text/plain");
  14142. });
  14143. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14144. auto se = detail::scope_exit([&] {
  14145. svr.stop();
  14146. t.join();
  14147. });
  14148. svr.wait_until_ready();
  14149. // NoDecisionMade with verification disabled should succeed (no default check)
  14150. SSLClient cli(HOST, PORT);
  14151. cli.enable_server_certificate_verification(false);
  14152. cli.set_connection_timeout(30);
  14153. bool callback_called = false;
  14154. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14155. EXPECT_NE(session, nullptr);
  14156. callback_called = true;
  14157. return SSLVerifierResponse::NoDecisionMade;
  14158. });
  14159. auto res = cli.Get("/test");
  14160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14161. EXPECT_EQ(200, res->status);
  14162. EXPECT_TRUE(callback_called);
  14163. }
  14164. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14165. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14166. ASSERT_TRUE(svr.is_valid());
  14167. svr.Get("/test", [](const Request &, Response &res) {
  14168. res.set_content("ok", "text/plain");
  14169. });
  14170. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14171. auto se = detail::scope_exit([&] {
  14172. svr.stop();
  14173. t.join();
  14174. });
  14175. svr.wait_until_ready();
  14176. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14177. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14178. // so we only check that the request fails, not whether the callback was
  14179. // called.
  14180. SSLClient cli(HOST, PORT);
  14181. cli.enable_server_certificate_verification(true);
  14182. cli.set_connection_timeout(30);
  14183. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14184. EXPECT_NE(session, nullptr);
  14185. return SSLVerifierResponse::NoDecisionMade;
  14186. });
  14187. auto res = cli.Get("/test");
  14188. EXPECT_FALSE(res);
  14189. }
  14190. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14191. // Test SSL server using PemMemory constructor with client CA certificates
  14192. // Read PEM files
  14193. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14194. read_file(SERVER_CERT_FILE, server_cert_pem);
  14195. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14196. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14197. // Create SSLServer with PemMemory constructor including client CA
  14198. SSLServer::PemMemory server_pem = {
  14199. server_cert_pem.c_str(),
  14200. server_cert_pem.size(),
  14201. server_key_pem.c_str(),
  14202. server_key_pem.size(),
  14203. client_ca_pem.c_str(),
  14204. client_ca_pem.size(),
  14205. nullptr // no password for server key
  14206. };
  14207. SSLServer svr(server_pem);
  14208. ASSERT_TRUE(svr.is_valid());
  14209. // No SSL error should be recorded for valid setup
  14210. EXPECT_EQ(0, svr.ssl_last_error());
  14211. // Set up server endpoints
  14212. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14213. res.set_content("ok", "text/plain");
  14214. });
  14215. // Start server in a thread
  14216. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14217. svr.wait_until_ready();
  14218. // Connect with client certificate (using constructor with paths)
  14219. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14220. cli.enable_server_certificate_verification(false);
  14221. auto res = cli.Get("/test-pem-ca");
  14222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14223. EXPECT_EQ(200, res->status);
  14224. EXPECT_EQ("ok", res->body);
  14225. svr.stop();
  14226. server_thread.join();
  14227. }
  14228. #endif
  14229. #ifdef _WIN32
  14230. TEST(CleanupTest, WSACleanup) {
  14231. int ret = WSACleanup();
  14232. ASSERT_EQ(0, ret);
  14233. }
  14234. #endif
  14235. #ifndef CPPHTTPLIB_SSL_ENABLED
  14236. TEST(NoSSLSupport, SimpleInterface) {
  14237. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14238. }
  14239. #endif
  14240. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14241. TEST(InvalidScheme, SimpleInterface) {
  14242. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14243. }
  14244. #endif
  14245. TEST(NoScheme, SimpleInterface) {
  14246. Client cli("yahoo.com:80");
  14247. ASSERT_TRUE(cli.is_valid());
  14248. }
  14249. TEST(SendAPI, SimpleInterface_Online) {
  14250. Client cli("http://yahoo.com");
  14251. Request req;
  14252. req.method = "GET";
  14253. req.path = "/";
  14254. auto res = cli.send(req);
  14255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14256. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14257. }
  14258. TEST(SendAPI, WithParamsInRequest) {
  14259. Server svr;
  14260. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14261. EXPECT_TRUE(req.has_param("test"));
  14262. EXPECT_EQ("test_value", req.get_param_value("test"));
  14263. });
  14264. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14265. auto se = detail::scope_exit([&] {
  14266. svr.stop();
  14267. t.join();
  14268. ASSERT_FALSE(svr.is_running());
  14269. });
  14270. svr.wait_until_ready();
  14271. Client cli(HOST, PORT);
  14272. {
  14273. Request req;
  14274. req.method = "GET";
  14275. req.path = "/";
  14276. req.params.emplace("test", "test_value");
  14277. auto res = cli.send(req);
  14278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14279. }
  14280. {
  14281. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14283. }
  14284. }
  14285. TEST(ClientImplMethods, GetSocketTest) {
  14286. httplib::Server svr;
  14287. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14288. res.status = StatusCode::OK_200;
  14289. });
  14290. auto port = svr.bind_to_any_port("127.0.0.1");
  14291. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14292. auto se = detail::scope_exit([&] {
  14293. svr.stop();
  14294. thread.join();
  14295. ASSERT_FALSE(svr.is_running());
  14296. });
  14297. svr.wait_until_ready();
  14298. {
  14299. httplib::Client cli("127.0.0.1", port);
  14300. cli.set_keep_alive(true);
  14301. // Use the behavior of cpp-httplib of opening the connection
  14302. // only when the first request happens. If that changes,
  14303. // this test would be obsolete.
  14304. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14305. // This also implicitly tests the server. But other tests would fail much
  14306. // earlier than this one to be considered.
  14307. auto res = cli.Get("/");
  14308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14309. EXPECT_EQ(StatusCode::OK_200, res->status);
  14310. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14311. }
  14312. }
  14313. #ifdef CPPHTTPLIB_SSL_ENABLED
  14314. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  14315. Client cli("http://yahoo.com");
  14316. auto res = cli.Get("/");
  14317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14318. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14319. cli.set_follow_location(true);
  14320. res = cli.Get("/");
  14321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14322. EXPECT_EQ(StatusCode::OK_200, res->status);
  14323. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14324. }
  14325. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  14326. Client cli("https://yahoo.com");
  14327. auto res = cli.Get("/");
  14328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14329. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14330. cli.set_follow_location(true);
  14331. res = cli.Get("/");
  14332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14333. EXPECT_EQ(StatusCode::OK_200, res->status);
  14334. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14335. }
  14336. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  14337. Client cli("https://yahoo.com");
  14338. auto res = cli.Get("/");
  14339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14340. ASSERT_FALSE(!res);
  14341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14342. ASSERT_FALSE(res == nullptr);
  14343. ASSERT_TRUE(res != nullptr);
  14344. EXPECT_EQ(Error::Success, res.error());
  14345. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  14346. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  14347. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14348. cli.set_follow_location(true);
  14349. res = cli.Get("/");
  14350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14351. EXPECT_EQ(Error::Success, res.error());
  14352. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  14353. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  14354. EXPECT_EQ(StatusCode::OK_200, res->status);
  14355. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14356. }
  14357. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14358. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  14359. Client cli("https://cdnjs.cloudflare.com");
  14360. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  14361. Headers{{"Accept-Encoding", "br"}});
  14362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14363. EXPECT_EQ(StatusCode::OK_200, res->status);
  14364. EXPECT_EQ(287630U, res->body.size());
  14365. EXPECT_EQ("application/javascript; charset=utf-8",
  14366. res->get_header_value("Content-Type"));
  14367. }
  14368. #endif
  14369. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  14370. #undef REDIR_HOST // Silence compiler warning
  14371. #define REDIR_HOST "https://httpbingo.org"
  14372. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  14373. Client cli(REDIR_HOST);
  14374. cli.set_follow_location(true);
  14375. auto res =
  14376. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  14377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14378. EXPECT_EQ(StatusCode::OK_200, res->status);
  14379. }
  14380. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  14381. Client cli(REDIR_HOST);
  14382. cli.set_follow_location(true);
  14383. Params params;
  14384. params.emplace("url", "http://example.com");
  14385. params.emplace("status_code", "302");
  14386. auto res = cli.Get(REDIR_PATH, params, Headers{});
  14387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14388. EXPECT_EQ(StatusCode::OK_200, res->status);
  14389. }
  14390. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  14391. Client cli(REDIR_HOST);
  14392. cli.set_follow_location(true);
  14393. Params params;
  14394. params.emplace("url", "http://example.com");
  14395. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  14396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14397. EXPECT_EQ(StatusCode::OK_200, res->status);
  14398. }
  14399. TEST(HttpToHttpsRedirectTest, CertFile) {
  14400. auto ssl_port = PORT + 1;
  14401. Server svr;
  14402. ASSERT_TRUE(svr.is_valid());
  14403. svr.Get("/index", [&](const Request &, Response &res) {
  14404. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14405. "/index");
  14406. svr.stop();
  14407. });
  14408. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14409. ASSERT_TRUE(ssl_svr.is_valid());
  14410. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  14411. res.set_content("test", "text/plain");
  14412. ssl_svr.stop();
  14413. });
  14414. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14415. thread t2 =
  14416. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  14417. auto se = detail::scope_exit([&] {
  14418. t2.join();
  14419. t.join();
  14420. ASSERT_FALSE(svr.is_running());
  14421. });
  14422. svr.wait_until_ready();
  14423. ssl_svr.wait_until_ready();
  14424. Client cli("127.0.0.1", PORT);
  14425. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14426. cli.enable_server_certificate_verification(true);
  14427. cli.set_follow_location(true);
  14428. cli.set_connection_timeout(30);
  14429. auto res = cli.Get("/index");
  14430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14431. ASSERT_EQ(StatusCode::OK_200, res->status);
  14432. }
  14433. TEST(SSLClientRedirectTest, CertFile) {
  14434. auto ssl_port = PORT + 1;
  14435. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14436. ASSERT_TRUE(ssl_svr1.is_valid());
  14437. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14438. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14439. "/index");
  14440. ssl_svr1.stop();
  14441. });
  14442. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14443. ASSERT_TRUE(ssl_svr2.is_valid());
  14444. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14445. res.set_content("test", "text/plain");
  14446. ssl_svr2.stop();
  14447. });
  14448. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14449. thread t2 =
  14450. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14451. auto se = detail::scope_exit([&] {
  14452. t2.join();
  14453. t.join();
  14454. ASSERT_FALSE(ssl_svr1.is_running());
  14455. });
  14456. ssl_svr1.wait_until_ready();
  14457. ssl_svr2.wait_until_ready();
  14458. SSLClient cli("127.0.0.1", PORT);
  14459. std::string cert;
  14460. read_file(SERVER_CERT2_FILE, cert);
  14461. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14462. cli.enable_server_certificate_verification(true);
  14463. cli.set_follow_location(true);
  14464. cli.set_connection_timeout(30);
  14465. auto res = cli.Get("/index");
  14466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14467. ASSERT_EQ(StatusCode::OK_200, res->status);
  14468. }
  14469. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  14470. // another port, so the client follows it with a new client.
  14471. static Result GetThroughTlsRedirectToDifferentPort(
  14472. const std::function<void(SSLClient &)> &setup,
  14473. const char *target_cert = SERVER_CERT2_FILE) {
  14474. auto ssl_port = PORT + 1;
  14475. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14476. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14477. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14478. "/index");
  14479. });
  14480. SSLServer ssl_svr2(target_cert, SERVER_PRIVATE_KEY_FILE);
  14481. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14482. res.set_content("test", "text/plain");
  14483. });
  14484. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  14485. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  14486. auto se = detail::scope_exit([&] {
  14487. ssl_svr2.stop();
  14488. ssl_svr1.stop();
  14489. t2.join();
  14490. t.join();
  14491. });
  14492. ssl_svr1.wait_until_ready();
  14493. ssl_svr2.wait_until_ready();
  14494. SSLClient cli("127.0.0.1", PORT);
  14495. cli.set_follow_location(true);
  14496. cli.set_connection_timeout(30);
  14497. setup(cli);
  14498. return cli.Get("/index");
  14499. }
  14500. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  14501. auto calls = 0;
  14502. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  14503. cli.enable_server_certificate_verification(false);
  14504. // Accept the first server only.
  14505. cli.set_session_verifier([&](tls::session_t) {
  14506. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  14507. : SSLVerifierResponse::CertificateRejected;
  14508. });
  14509. });
  14510. EXPECT_FALSE(res);
  14511. EXPECT_EQ(2, calls);
  14512. }
  14513. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  14514. std::string pinned;
  14515. auto res = GetThroughTlsRedirectToDifferentPort(
  14516. [&](SSLClient &cli) {
  14517. cli.enable_server_certificate_verification(false);
  14518. // Pin the first certificate seen.
  14519. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  14520. if (pinned.empty()) { pinned = ctx.serial(); }
  14521. return ctx.serial() == pinned;
  14522. });
  14523. },
  14524. // A certificate other than the first server's.
  14525. SERVER_CERT_FILE);
  14526. EXPECT_FALSE(res);
  14527. EXPECT_FALSE(pinned.empty());
  14528. }
  14529. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  14530. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  14531. std::string cert;
  14532. read_file(SERVER_CERT2_FILE, cert);
  14533. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14534. });
  14535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14536. EXPECT_EQ(StatusCode::OK_200, res->status);
  14537. }
  14538. #endif
  14539. #ifdef CPPHTTPLIB_SSL_ENABLED
  14540. // Test that set_ca_cert_store() skips system certs (consistent with
  14541. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  14542. // should be trusted - system certs should NOT be loaded.
  14543. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  14544. // Load a specific cert that is NOT a system CA cert
  14545. std::string cert;
  14546. read_file(SERVER_CERT2_FILE, cert);
  14547. SSLClient cli("google.com");
  14548. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14549. cli.enable_server_certificate_verification(true);
  14550. // This should FAIL because:
  14551. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  14552. // 2. System certs should NOT be loaded when custom store is set
  14553. // If system certs WERE loaded, this would succeed
  14554. auto res = cli.Get("/");
  14555. ASSERT_FALSE(res);
  14556. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14557. }
  14558. // Same as above, but through the native store handle path. Regression test:
  14559. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  14560. // merged system certs into the user-provided store.
  14561. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  14562. std::string cert;
  14563. read_file(SERVER_CERT2_FILE, cert);
  14564. SSLClient cli("google.com");
  14565. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14566. cli.enable_server_certificate_verification(true);
  14567. auto res = cli.Get("/");
  14568. ASSERT_FALSE(res);
  14569. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14570. }
  14571. // A custom store set via the native handle must still verify a server whose
  14572. // cert it does contain.
  14573. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  14574. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14575. ASSERT_TRUE(svr.is_valid());
  14576. svr.Get("/test", [&](const Request &, Response &res) {
  14577. res.set_content("test", "text/plain");
  14578. });
  14579. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14580. auto se = detail::scope_exit([&] {
  14581. svr.stop();
  14582. t.join();
  14583. ASSERT_FALSE(svr.is_running());
  14584. });
  14585. svr.wait_until_ready();
  14586. SSLClient cli("127.0.0.1", PORT);
  14587. std::string cert;
  14588. read_file(SERVER_CERT2_FILE, cert);
  14589. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14590. cli.enable_server_certificate_verification(true);
  14591. cli.set_connection_timeout(30);
  14592. auto res = cli.Get("/test");
  14593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14594. ASSERT_EQ(StatusCode::OK_200, res->status);
  14595. }
  14596. // CA certs loaded through the universal Client must be transferred to the
  14597. // client created internally for following an HTTPS redirect. Regression test:
  14598. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  14599. // the CA data for redirect transfer.
  14600. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  14601. auto ssl_port = PORT + 1;
  14602. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14603. ASSERT_TRUE(ssl_svr1.is_valid());
  14604. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14605. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14606. "/index");
  14607. });
  14608. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14609. ASSERT_TRUE(ssl_svr2.is_valid());
  14610. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14611. res.set_content("test", "text/plain");
  14612. });
  14613. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14614. thread t2 =
  14615. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14616. auto se = detail::scope_exit([&] {
  14617. ssl_svr2.stop();
  14618. ssl_svr1.stop();
  14619. t2.join();
  14620. t.join();
  14621. ASSERT_FALSE(ssl_svr1.is_running());
  14622. });
  14623. ssl_svr1.wait_until_ready();
  14624. ssl_svr2.wait_until_ready();
  14625. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14626. std::string cert;
  14627. read_file(SERVER_CERT2_FILE, cert);
  14628. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14629. cli.enable_server_certificate_verification(true);
  14630. cli.set_follow_location(true);
  14631. cli.set_connection_timeout(30);
  14632. auto res = cli.Get("/index");
  14633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14634. ASSERT_EQ(StatusCode::OK_200, res->status);
  14635. }
  14636. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  14637. // so a host signed by a system CA verifies even though a custom CA is set
  14638. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  14639. std::string cert;
  14640. read_file(SERVER_CERT2_FILE, cert);
  14641. SSLClient cli("google.com");
  14642. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14643. cli.enable_system_ca(true);
  14644. cli.enable_server_certificate_verification(true);
  14645. auto res = cli.Get("/");
  14646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14647. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14648. }
  14649. // The custom CA remains effective when combined with the system CA
  14650. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  14651. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14652. ASSERT_TRUE(svr.is_valid());
  14653. svr.Get("/test", [&](const Request &, Response &res) {
  14654. res.set_content("test", "text/plain");
  14655. });
  14656. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14657. auto se = detail::scope_exit([&] {
  14658. svr.stop();
  14659. t.join();
  14660. ASSERT_FALSE(svr.is_running());
  14661. });
  14662. svr.wait_until_ready();
  14663. SSLClient cli("127.0.0.1", PORT);
  14664. std::string cert;
  14665. read_file(SERVER_CERT2_FILE, cert);
  14666. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14667. cli.enable_system_ca(true);
  14668. cli.enable_server_certificate_verification(true);
  14669. cli.set_connection_timeout(30);
  14670. auto res = cli.Get("/test");
  14671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14672. ASSERT_EQ(StatusCode::OK_200, res->status);
  14673. }
  14674. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  14675. // skip chain verification entirely (only the certificate identity was
  14676. // checked), so a server presenting an untrusted certificate with a matching
  14677. // IP SAN was accepted. The chain must be validated for IP hosts too.
  14678. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  14679. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14680. ASSERT_TRUE(svr.is_valid());
  14681. svr.Get("/test", [&](const Request &, Response &res) {
  14682. res.set_content("test", "text/plain");
  14683. });
  14684. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14685. auto se = detail::scope_exit([&] {
  14686. svr.stop();
  14687. t.join();
  14688. ASSERT_FALSE(svr.is_running());
  14689. });
  14690. svr.wait_until_ready();
  14691. SSLClient cli("127.0.0.1", PORT);
  14692. std::string cert;
  14693. // A trusted CA that did not sign the server certificate. The server cert
  14694. // (cert2) carries the matching IP SAN, so only chain validation can reject
  14695. // this connection.
  14696. read_file(CLIENT_CA_CERT_FILE, cert);
  14697. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14698. cli.enable_server_certificate_verification(true);
  14699. cli.set_connection_timeout(30);
  14700. auto res = cli.Get("/test");
  14701. ASSERT_FALSE(res);
  14702. }
  14703. // enable_system_ca(false) prevents system CA loading entirely
  14704. TEST(SSLClientTest, DisableSystemCa_Online) {
  14705. SSLClient cli("google.com");
  14706. cli.enable_system_ca(false);
  14707. cli.enable_server_certificate_verification(true);
  14708. auto res = cli.Get("/");
  14709. ASSERT_FALSE(res);
  14710. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  14711. // itself when the CA chain is empty
  14712. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  14713. res.error() == Error::SSLConnection);
  14714. }
  14715. // The universal Client forwards enable_system_ca()
  14716. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  14717. std::string cert;
  14718. read_file(SERVER_CERT2_FILE, cert);
  14719. Client cli("https://google.com");
  14720. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14721. cli.enable_system_ca(true);
  14722. cli.enable_server_certificate_verification(true);
  14723. auto res = cli.Get("/");
  14724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14725. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14726. }
  14727. // The system CA policy must carry over to the client created internally for
  14728. // following a cross-host HTTPS redirect
  14729. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  14730. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14731. ASSERT_TRUE(svr.is_valid());
  14732. svr.Get("/index", [&](const Request &, Response &res) {
  14733. res.set_redirect("https://www.google.com/");
  14734. });
  14735. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14736. auto se = detail::scope_exit([&] {
  14737. svr.stop();
  14738. t.join();
  14739. ASSERT_FALSE(svr.is_running());
  14740. });
  14741. svr.wait_until_ready();
  14742. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14743. std::string cert;
  14744. read_file(SERVER_CERT2_FILE, cert);
  14745. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14746. cli.enable_system_ca(true);
  14747. cli.enable_server_certificate_verification(true);
  14748. cli.set_follow_location(true);
  14749. cli.set_connection_timeout(30);
  14750. // Receiving any response proves the redirect client completed the TLS
  14751. // handshake with a system-CA-signed host
  14752. auto res = cli.Get("/index");
  14753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14754. }
  14755. TEST(MultipartFormDataTest, LargeData) {
  14756. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14757. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  14758. const ContentReader &content_reader) {
  14759. if (req.is_multipart_form_data()) {
  14760. std::vector<FormData> items;
  14761. content_reader(
  14762. [&](const FormData &file) {
  14763. items.push_back(file);
  14764. return true;
  14765. },
  14766. [&](const char *data, size_t data_length) {
  14767. items.back().content.append(data, data_length);
  14768. return true;
  14769. });
  14770. EXPECT_TRUE(std::string(items[0].name) == "document");
  14771. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14772. EXPECT_TRUE(items[0].filename == "2MB_data");
  14773. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14774. EXPECT_TRUE(items[1].name == "hello");
  14775. EXPECT_TRUE(items[1].content == "world");
  14776. EXPECT_TRUE(items[1].filename == "");
  14777. EXPECT_TRUE(items[1].content_type == "");
  14778. } else {
  14779. std::string body;
  14780. content_reader([&](const char *data, size_t data_length) {
  14781. body.append(data, data_length);
  14782. return true;
  14783. });
  14784. }
  14785. });
  14786. auto port = svr.bind_to_any_port(HOST);
  14787. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14788. auto se = detail::scope_exit([&] {
  14789. svr.stop();
  14790. t.join();
  14791. ASSERT_FALSE(svr.is_running());
  14792. });
  14793. svr.wait_until_ready();
  14794. {
  14795. std::string data(1024 * 1024 * 2, '.');
  14796. std::stringstream buffer;
  14797. buffer << data;
  14798. SSLClient cli(HOST, port);
  14799. cli.enable_server_certificate_verification(false);
  14800. UploadFormDataItems items{
  14801. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14802. {"hello", "world", "", ""},
  14803. };
  14804. auto res = cli.Post("/post", items);
  14805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14806. ASSERT_EQ(StatusCode::OK_200, res->status);
  14807. }
  14808. }
  14809. TEST(MultipartFormDataTest, DataProviderItems) {
  14810. std::random_device seed_gen;
  14811. std::mt19937 random(seed_gen());
  14812. std::string rand1;
  14813. rand1.resize(1000);
  14814. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  14815. std::string rand2;
  14816. rand2.resize(3000);
  14817. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  14818. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14819. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  14820. const ContentReader &content_reader) {
  14821. ASSERT_FALSE(req.is_multipart_form_data());
  14822. std::string body;
  14823. content_reader([&](const char *data, size_t data_length) {
  14824. body.append(data, data_length);
  14825. return true;
  14826. });
  14827. EXPECT_EQ(body, "");
  14828. });
  14829. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  14830. const ContentReader &content_reader) {
  14831. ASSERT_TRUE(req.is_multipart_form_data());
  14832. std::vector<FormData> items;
  14833. content_reader(
  14834. [&](const FormData &file) {
  14835. items.push_back(file);
  14836. return true;
  14837. },
  14838. [&](const char *data, size_t data_length) {
  14839. items.back().content.append(data, data_length);
  14840. return true;
  14841. });
  14842. ASSERT_TRUE(items.size() == 2);
  14843. EXPECT_EQ(std::string(items[0].name), "name1");
  14844. EXPECT_EQ(items[0].content, "Testing123");
  14845. EXPECT_EQ(items[0].filename, "filename1");
  14846. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14847. EXPECT_EQ(items[1].name, "name2");
  14848. EXPECT_EQ(items[1].content, "Testing456");
  14849. EXPECT_EQ(items[1].filename, "");
  14850. EXPECT_EQ(items[1].content_type, "");
  14851. });
  14852. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  14853. const ContentReader &content_reader) {
  14854. ASSERT_TRUE(req.is_multipart_form_data());
  14855. std::vector<FormData> items;
  14856. content_reader(
  14857. [&](const FormData &file) {
  14858. items.push_back(file);
  14859. return true;
  14860. },
  14861. [&](const char *data, size_t data_length) {
  14862. items.back().content.append(data, data_length);
  14863. return true;
  14864. });
  14865. ASSERT_TRUE(items.size() == 2);
  14866. EXPECT_EQ(items[0].name, "name3");
  14867. EXPECT_EQ(items[0].content, rand1);
  14868. EXPECT_EQ(items[0].filename, "filename3");
  14869. EXPECT_EQ(items[0].content_type, "");
  14870. EXPECT_EQ(items[1].name, "name4");
  14871. EXPECT_EQ(items[1].content, rand2);
  14872. EXPECT_EQ(items[1].filename, "filename4");
  14873. EXPECT_EQ(items[1].content_type, "");
  14874. });
  14875. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  14876. const ContentReader &content_reader) {
  14877. ASSERT_TRUE(req.is_multipart_form_data());
  14878. std::vector<FormData> items;
  14879. content_reader(
  14880. [&](const FormData &file) {
  14881. items.push_back(file);
  14882. return true;
  14883. },
  14884. [&](const char *data, size_t data_length) {
  14885. items.back().content.append(data, data_length);
  14886. return true;
  14887. });
  14888. ASSERT_TRUE(items.size() == 4);
  14889. EXPECT_EQ(std::string(items[0].name), "name1");
  14890. EXPECT_EQ(items[0].content, "Testing123");
  14891. EXPECT_EQ(items[0].filename, "filename1");
  14892. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14893. EXPECT_EQ(items[1].name, "name2");
  14894. EXPECT_EQ(items[1].content, "Testing456");
  14895. EXPECT_EQ(items[1].filename, "");
  14896. EXPECT_EQ(items[1].content_type, "");
  14897. EXPECT_EQ(items[2].name, "name3");
  14898. EXPECT_EQ(items[2].content, rand1);
  14899. EXPECT_EQ(items[2].filename, "filename3");
  14900. EXPECT_EQ(items[2].content_type, "");
  14901. EXPECT_EQ(items[3].name, "name4");
  14902. EXPECT_EQ(items[3].content, rand2);
  14903. EXPECT_EQ(items[3].filename, "filename4");
  14904. EXPECT_EQ(items[3].content_type, "");
  14905. });
  14906. auto port = svr.bind_to_any_port("localhost");
  14907. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14908. auto se = detail::scope_exit([&] {
  14909. svr.stop();
  14910. t.join();
  14911. ASSERT_FALSE(svr.is_running());
  14912. });
  14913. svr.wait_until_ready();
  14914. {
  14915. SSLClient cli("localhost", port);
  14916. cli.enable_server_certificate_verification(false);
  14917. UploadFormDataItems items{
  14918. {"name1", "Testing123", "filename1", "application/octet-stream"},
  14919. {"name2", "Testing456", "", ""}, // not a file
  14920. };
  14921. {
  14922. auto res = cli.Post("/post-none", {}, {}, {});
  14923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14924. ASSERT_EQ(StatusCode::OK_200, res->status);
  14925. }
  14926. FormDataProviderItems providers;
  14927. {
  14928. auto res =
  14929. cli.Post("/post-items", {}, items, providers); // empty providers
  14930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14931. ASSERT_EQ(StatusCode::OK_200, res->status);
  14932. }
  14933. providers.push_back({"name3",
  14934. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14935. // test the offset is given correctly at each step
  14936. if (!offset)
  14937. sink.os.write(rand1.data(), 30);
  14938. else if (offset == 30)
  14939. sink.os.write(rand1.data() + 30, 300);
  14940. else if (offset == 330)
  14941. sink.os.write(rand1.data() + 330, 670);
  14942. else if (offset == rand1.size())
  14943. sink.done();
  14944. return true;
  14945. },
  14946. "filename3",
  14947. {}});
  14948. providers.push_back({"name4",
  14949. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14950. // test the offset is given correctly at each step
  14951. if (!offset)
  14952. sink.os.write(rand2.data(), 2000);
  14953. else if (offset == 2000)
  14954. sink.os.write(rand2.data() + 2000, 1);
  14955. else if (offset == 2001)
  14956. sink.os.write(rand2.data() + 2001, 999);
  14957. else if (offset == rand2.size())
  14958. sink.done();
  14959. return true;
  14960. },
  14961. "filename4",
  14962. {}});
  14963. {
  14964. auto res = cli.Post("/post-providers", {}, {}, providers);
  14965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14966. ASSERT_EQ(StatusCode::OK_200, res->status);
  14967. }
  14968. {
  14969. auto res = cli.Post("/post-both", {}, items, providers);
  14970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14971. ASSERT_EQ(StatusCode::OK_200, res->status);
  14972. }
  14973. }
  14974. }
  14975. TEST(MultipartFormDataTest, BadHeader) {
  14976. Server svr;
  14977. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14978. res.set_content("ok", "text/plain");
  14979. });
  14980. thread t = thread([&] { svr.listen(HOST, PORT); });
  14981. auto se = detail::scope_exit([&] {
  14982. svr.stop();
  14983. t.join();
  14984. ASSERT_FALSE(svr.is_running());
  14985. });
  14986. svr.wait_until_ready();
  14987. const std::string body =
  14988. "This is the preamble. It is to be ignored, though it\r\n"
  14989. "is a handy place for composition agents to include an\r\n"
  14990. "explanatory note to non-MIME conformant readers.\r\n"
  14991. "\r\n"
  14992. "\r\n"
  14993. "--simple boundary\r\n"
  14994. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14995. ": BAD...\r\n"
  14996. "\r\n"
  14997. "value1\r\n"
  14998. "--simple boundary\r\n"
  14999. "Content-Disposition: form-data; name=\"field2\"; "
  15000. "filename=\"example.txt\"\r\n"
  15001. "\r\n"
  15002. "value2\r\n"
  15003. "--simple boundary--\r\n"
  15004. "This is the epilogue. It is also to be ignored.\r\n";
  15005. std::string content_type =
  15006. R"(multipart/form-data; boundary="simple boundary")";
  15007. Client cli(HOST, PORT);
  15008. auto res = cli.Post("/post", body, content_type.c_str());
  15009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15010. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15011. }
  15012. TEST(MultipartFormDataTest, WithPreamble) {
  15013. Server svr;
  15014. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15015. res.set_content("ok", "text/plain");
  15016. });
  15017. thread t = thread([&] { svr.listen(HOST, PORT); });
  15018. auto se = detail::scope_exit([&] {
  15019. svr.stop();
  15020. t.join();
  15021. ASSERT_FALSE(svr.is_running());
  15022. });
  15023. svr.wait_until_ready();
  15024. const std::string body =
  15025. "This is the preamble. It is to be ignored, though it\r\n"
  15026. "is a handy place for composition agents to include an\r\n"
  15027. "explanatory note to non-MIME conformant readers.\r\n"
  15028. "\r\n"
  15029. "\r\n"
  15030. "--simple boundary\r\n"
  15031. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15032. "\r\n"
  15033. "value1\r\n"
  15034. "--simple boundary\r\n"
  15035. "Content-Disposition: form-data; name=\"field2\"; "
  15036. "filename=\"example.txt\"\r\n"
  15037. "\r\n"
  15038. "value2\r\n"
  15039. "--simple boundary--\r\n"
  15040. "This is the epilogue. It is also to be ignored.\r\n";
  15041. std::string content_type =
  15042. R"(multipart/form-data; boundary="simple boundary")";
  15043. Client cli(HOST, PORT);
  15044. auto res = cli.Post("/post", body, content_type.c_str());
  15045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15046. EXPECT_EQ(StatusCode::OK_200, res->status);
  15047. }
  15048. TEST(MultipartFormDataTest, PostCustomBoundary) {
  15049. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15050. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  15051. const ContentReader &content_reader) {
  15052. if (req.is_multipart_form_data()) {
  15053. std::vector<FormData> items;
  15054. content_reader(
  15055. [&](const FormData &file) {
  15056. items.push_back(file);
  15057. return true;
  15058. },
  15059. [&](const char *data, size_t data_length) {
  15060. items.back().content.append(data, data_length);
  15061. return true;
  15062. });
  15063. EXPECT_TRUE(std::string(items[0].name) == "document");
  15064. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15065. EXPECT_TRUE(items[0].filename == "2MB_data");
  15066. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15067. EXPECT_TRUE(items[1].name == "hello");
  15068. EXPECT_TRUE(items[1].content == "world");
  15069. EXPECT_TRUE(items[1].filename == "");
  15070. EXPECT_TRUE(items[1].content_type == "");
  15071. } else {
  15072. std::string body;
  15073. content_reader([&](const char *data, size_t data_length) {
  15074. body.append(data, data_length);
  15075. return true;
  15076. });
  15077. }
  15078. });
  15079. auto port = svr.bind_to_any_port("localhost");
  15080. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15081. auto se = detail::scope_exit([&] {
  15082. svr.stop();
  15083. t.join();
  15084. ASSERT_FALSE(svr.is_running());
  15085. });
  15086. svr.wait_until_ready();
  15087. {
  15088. std::string data(1024 * 1024 * 2, '.');
  15089. std::stringstream buffer;
  15090. buffer << data;
  15091. SSLClient cli("localhost", port);
  15092. cli.enable_server_certificate_verification(false);
  15093. UploadFormDataItems items{
  15094. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15095. {"hello", "world", "", ""},
  15096. };
  15097. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  15098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15099. ASSERT_EQ(StatusCode::OK_200, res->status);
  15100. }
  15101. }
  15102. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  15103. std::string data(1024 * 1024 * 2, '&');
  15104. std::stringstream buffer;
  15105. buffer << data;
  15106. Client cli("https://localhost:8080");
  15107. UploadFormDataItems items{
  15108. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15109. {"hello", "world", "", ""},
  15110. };
  15111. for (const char &c : " \t\r\n") {
  15112. auto res =
  15113. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  15114. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15115. ASSERT_FALSE(res);
  15116. }
  15117. }
  15118. TEST(MultipartFormDataTest, PutFormData) {
  15119. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15120. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  15121. const ContentReader &content_reader) {
  15122. if (req.is_multipart_form_data()) {
  15123. std::vector<FormData> items;
  15124. content_reader(
  15125. [&](const FormData &file) {
  15126. items.push_back(file);
  15127. return true;
  15128. },
  15129. [&](const char *data, size_t data_length) {
  15130. items.back().content.append(data, data_length);
  15131. return true;
  15132. });
  15133. EXPECT_TRUE(std::string(items[0].name) == "document");
  15134. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15135. EXPECT_TRUE(items[0].filename == "2MB_data");
  15136. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15137. EXPECT_TRUE(items[1].name == "hello");
  15138. EXPECT_TRUE(items[1].content == "world");
  15139. EXPECT_TRUE(items[1].filename == "");
  15140. EXPECT_TRUE(items[1].content_type == "");
  15141. } else {
  15142. std::string body;
  15143. content_reader([&](const char *data, size_t data_length) {
  15144. body.append(data, data_length);
  15145. return true;
  15146. });
  15147. }
  15148. });
  15149. auto port = svr.bind_to_any_port("localhost");
  15150. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15151. auto se = detail::scope_exit([&] {
  15152. svr.stop();
  15153. t.join();
  15154. ASSERT_FALSE(svr.is_running());
  15155. });
  15156. svr.wait_until_ready();
  15157. {
  15158. std::string data(1024 * 1024 * 2, '&');
  15159. std::stringstream buffer;
  15160. buffer << data;
  15161. SSLClient cli("localhost", port);
  15162. cli.enable_server_certificate_verification(false);
  15163. UploadFormDataItems items{
  15164. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15165. {"hello", "world", "", ""},
  15166. };
  15167. auto res = cli.Put("/put", items);
  15168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15169. ASSERT_EQ(StatusCode::OK_200, res->status);
  15170. }
  15171. }
  15172. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  15173. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15174. svr.Put("/put_customboundary",
  15175. [&](const Request &req, const Response & /*res*/,
  15176. const ContentReader &content_reader) {
  15177. if (req.is_multipart_form_data()) {
  15178. std::vector<FormData> items;
  15179. content_reader(
  15180. [&](const FormData &file) {
  15181. items.push_back(file);
  15182. return true;
  15183. },
  15184. [&](const char *data, size_t data_length) {
  15185. items.back().content.append(data, data_length);
  15186. return true;
  15187. });
  15188. EXPECT_TRUE(std::string(items[0].name) == "document");
  15189. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15190. EXPECT_TRUE(items[0].filename == "2MB_data");
  15191. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15192. EXPECT_TRUE(items[1].name == "hello");
  15193. EXPECT_TRUE(items[1].content == "world");
  15194. EXPECT_TRUE(items[1].filename == "");
  15195. EXPECT_TRUE(items[1].content_type == "");
  15196. } else {
  15197. std::string body;
  15198. content_reader([&](const char *data, size_t data_length) {
  15199. body.append(data, data_length);
  15200. return true;
  15201. });
  15202. }
  15203. });
  15204. auto port = svr.bind_to_any_port("localhost");
  15205. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15206. auto se = detail::scope_exit([&] {
  15207. svr.stop();
  15208. t.join();
  15209. ASSERT_FALSE(svr.is_running());
  15210. });
  15211. svr.wait_until_ready();
  15212. {
  15213. std::string data(1024 * 1024 * 2, '&');
  15214. std::stringstream buffer;
  15215. buffer << data;
  15216. SSLClient cli("localhost", port);
  15217. cli.enable_server_certificate_verification(false);
  15218. UploadFormDataItems items{
  15219. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15220. {"hello", "world", "", ""},
  15221. };
  15222. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  15223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15224. ASSERT_EQ(StatusCode::OK_200, res->status);
  15225. }
  15226. }
  15227. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  15228. std::string data(1024 * 1024 * 2, '&');
  15229. std::stringstream buffer;
  15230. buffer << data;
  15231. Client cli("https://localhost:8080");
  15232. cli.enable_server_certificate_verification(false);
  15233. UploadFormDataItems items{
  15234. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15235. {"hello", "world", "", ""},
  15236. };
  15237. for (const char &c : " \t\r\n") {
  15238. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  15239. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15240. ASSERT_FALSE(res);
  15241. }
  15242. }
  15243. TEST(MultipartFormDataTest, AlternateFilename) {
  15244. auto handled = false;
  15245. Server svr;
  15246. svr.Post("/test", [&](const Request &req, Response &res) {
  15247. ASSERT_EQ(2u, req.form.files.size());
  15248. ASSERT_EQ(1u, req.form.fields.size());
  15249. // Test files
  15250. const auto &file1 = req.form.get_file("file1");
  15251. ASSERT_EQ("file1", file1.name);
  15252. ASSERT_EQ("A.txt", file1.filename);
  15253. ASSERT_EQ("text/plain", file1.content_type);
  15254. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  15255. const auto &file2 = req.form.get_file("file2");
  15256. ASSERT_EQ("file2", file2.name);
  15257. ASSERT_EQ("a.html", file2.filename);
  15258. ASSERT_EQ("text/html", file2.content_type);
  15259. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  15260. file2.content);
  15261. // Test text field
  15262. const auto &text = req.form.get_field("text");
  15263. ASSERT_EQ("text default", text);
  15264. res.set_content("ok", "text/plain");
  15265. handled = true;
  15266. });
  15267. thread t = thread([&] { svr.listen(HOST, PORT); });
  15268. auto se = detail::scope_exit([&] {
  15269. svr.stop();
  15270. t.join();
  15271. ASSERT_FALSE(svr.is_running());
  15272. ASSERT_TRUE(handled);
  15273. });
  15274. svr.wait_until_ready();
  15275. auto req = "POST /test HTTP/1.1\r\n"
  15276. "Host: localhost\r\n"
  15277. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15278. "Content-Length: 399\r\n"
  15279. "\r\n"
  15280. "----------\r\n"
  15281. "Content-Disposition: form-data; name=\"text\"\r\n"
  15282. "\r\n"
  15283. "text default\r\n"
  15284. "----------\r\n"
  15285. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  15286. "filename=\"a.txt\"; name=\"file1\"\r\n"
  15287. "Content-Type: text/plain\r\n"
  15288. "\r\n"
  15289. "Content of a.txt.\r\n"
  15290. "\r\n"
  15291. "----------\r\n"
  15292. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  15293. "\"a.html\"\r\n"
  15294. "Content-Type: text/html\r\n"
  15295. "\r\n"
  15296. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  15297. "\r\n"
  15298. "------------\r\n";
  15299. ASSERT_TRUE(send_request(1, req));
  15300. }
  15301. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  15302. auto handled = false;
  15303. Server svr;
  15304. svr.Post("/test", [&](const Request &req, Response &res) {
  15305. // Case-insensitive "utf-8''" prefix with a long value
  15306. const auto &file = req.form.get_file("file1");
  15307. ASSERT_EQ("file1", file.name);
  15308. // 8000 chars exercises both the Content-Disposition parser and the
  15309. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  15310. // Prior to the fix, std::regex_match on this header would cause O(N)
  15311. // stack recursion in libstdc++, leading to SIGSEGV.
  15312. std::string expected_filename(8000, 'A');
  15313. ASSERT_EQ(expected_filename, file.filename);
  15314. res.set_content("ok", "text/plain");
  15315. handled = true;
  15316. });
  15317. thread t = thread([&] { svr.listen(HOST, PORT); });
  15318. auto se = detail::scope_exit([&] {
  15319. svr.stop();
  15320. t.join();
  15321. ASSERT_FALSE(svr.is_running());
  15322. ASSERT_TRUE(handled);
  15323. });
  15324. svr.wait_until_ready();
  15325. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  15326. // Regression test for GHSA-qq6v-r583-3h69
  15327. std::string long_filename(8000, 'A');
  15328. std::string body = "----------\r\n"
  15329. "Content-Disposition: form-data; name=\"file1\"; "
  15330. "filename*=\"Utf-8''" +
  15331. long_filename +
  15332. "\"\r\n"
  15333. "\r\n"
  15334. "hello\r\n"
  15335. "------------\r\n";
  15336. auto req = "POST /test HTTP/1.1\r\n"
  15337. "Host: localhost\r\n"
  15338. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15339. "Content-Length: " +
  15340. std::to_string(body.size()) + "\r\n\r\n" + body;
  15341. ASSERT_TRUE(send_request(1, req));
  15342. }
  15343. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  15344. auto handled = false;
  15345. Server svr;
  15346. svr.Post("/test", [&](const Request &req, Response &) {
  15347. ASSERT_EQ(2u, req.form.fields.size());
  15348. const auto &text1 = req.form.get_field("text1");
  15349. ASSERT_EQ("text1", text1);
  15350. const auto &text2 = req.form.get_field("text2");
  15351. ASSERT_EQ("text2", text2);
  15352. handled = true;
  15353. });
  15354. thread t = thread([&] { svr.listen(HOST, PORT); });
  15355. auto se = detail::scope_exit([&] {
  15356. svr.stop();
  15357. t.join();
  15358. ASSERT_FALSE(svr.is_running());
  15359. ASSERT_TRUE(handled);
  15360. });
  15361. svr.wait_until_ready();
  15362. auto req = "POST /test HTTP/1.1\r\n"
  15363. "Host: localhost\r\n"
  15364. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15365. "Content-Length: 146\r\n"
  15366. "\r\n----------\r\n"
  15367. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15368. "\r\n"
  15369. "text1"
  15370. "\r\n----------\r\n"
  15371. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15372. "\r\n"
  15373. "text2"
  15374. "\r\n------------";
  15375. std::string response;
  15376. ASSERT_TRUE(send_request(1, req, &response));
  15377. ASSERT_EQ("200", response.substr(9, 3));
  15378. }
  15379. TEST(MultipartFormDataTest, ContentLength) {
  15380. auto handled = false;
  15381. Server svr;
  15382. svr.Post("/test", [&](const Request &req, Response &) {
  15383. ASSERT_EQ(2u, req.form.fields.size());
  15384. const auto &text1 = req.form.get_field("text1");
  15385. ASSERT_EQ("text1", text1);
  15386. const auto &text2 = req.form.get_field("text2");
  15387. ASSERT_EQ("text2", text2);
  15388. handled = true;
  15389. });
  15390. thread t = thread([&] { svr.listen(HOST, PORT); });
  15391. auto se = detail::scope_exit([&] {
  15392. svr.stop();
  15393. t.join();
  15394. ASSERT_FALSE(svr.is_running());
  15395. ASSERT_TRUE(handled);
  15396. });
  15397. svr.wait_until_ready();
  15398. auto req = "POST /test HTTP/1.1\r\n"
  15399. "Host: localhost\r\n"
  15400. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15401. "Content-Length: 167\r\n"
  15402. "\r\n----------\r\n"
  15403. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15404. "Content-Length: 5\r\n"
  15405. "\r\n"
  15406. "text1"
  15407. "\r\n----------\r\n"
  15408. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15409. "\r\n"
  15410. "text2"
  15411. "\r\n------------\r\n";
  15412. std::string response;
  15413. ASSERT_TRUE(send_request(1, req, &response));
  15414. ASSERT_EQ("200", response.substr(9, 3));
  15415. }
  15416. TEST(MultipartFormDataTest, AccessPartHeaders) {
  15417. auto handled = false;
  15418. Server svr;
  15419. svr.Post("/test", [&](const Request &req, Response &) {
  15420. ASSERT_EQ(2u, req.form.fields.size());
  15421. const auto &text1 = req.form.get_field("text1");
  15422. ASSERT_EQ("text1", text1);
  15423. // TODO: Add header access for text fields if needed
  15424. const auto &text2 = req.form.get_field("text2");
  15425. ASSERT_EQ("text2", text2);
  15426. // TODO: Header access for text fields needs to be implemented
  15427. // auto &headers = it->second.headers;
  15428. // ASSERT_EQ(3U, headers.size());
  15429. // auto custom_header = headers.find("x-whatever");
  15430. // ASSERT_TRUE(custom_header != headers.end());
  15431. // ASSERT_NE("customvalue", custom_header->second);
  15432. // ASSERT_EQ("CustomValue", custom_header->second);
  15433. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  15434. handled = true;
  15435. });
  15436. thread t = thread([&] { svr.listen(HOST, PORT); });
  15437. auto se = detail::scope_exit([&] {
  15438. svr.stop();
  15439. t.join();
  15440. ASSERT_FALSE(svr.is_running());
  15441. ASSERT_TRUE(handled);
  15442. });
  15443. svr.wait_until_ready();
  15444. auto req = "POST /test HTTP/1.1\r\n"
  15445. "Host: localhost\r\n"
  15446. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15447. "Content-Length: 232\r\n"
  15448. "\r\n----------\r\n"
  15449. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15450. "Content-Length: 5\r\n"
  15451. "X-Test: 1\r\n"
  15452. "\r\n"
  15453. "text1"
  15454. "\r\n----------\r\n"
  15455. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15456. "Content-Type: text/plain\r\n"
  15457. "X-Whatever: CustomValue\r\n"
  15458. "\r\n"
  15459. "text2"
  15460. "\r\n------------\r\n"
  15461. "That should be disregarded. Not even read";
  15462. std::string response;
  15463. ASSERT_TRUE(send_request(1, req, &response));
  15464. ASSERT_EQ("200", response.substr(9, 3));
  15465. }
  15466. TEST(MultipartFormDataTest, LargeHeader) {
  15467. auto handled = false;
  15468. Server svr;
  15469. svr.Post("/test", [&](const Request &req, Response &) {
  15470. ASSERT_EQ(1u, req.form.fields.size());
  15471. const auto &text = req.form.get_field("name1");
  15472. ASSERT_EQ("text1", text);
  15473. handled = true;
  15474. });
  15475. thread t = thread([&] { svr.listen(HOST, PORT); });
  15476. auto se = detail::scope_exit([&] {
  15477. svr.stop();
  15478. t.join();
  15479. ASSERT_FALSE(svr.is_running());
  15480. ASSERT_TRUE(handled);
  15481. });
  15482. svr.wait_until_ready();
  15483. auto boundary = std::string("cpp-httplib-multipart-data");
  15484. std::string content = "--" + boundary +
  15485. "\r\n"
  15486. "Content-Disposition: form-data; name=\"name1\"\r\n"
  15487. "\r\n"
  15488. "text1\r\n"
  15489. "--" +
  15490. boundary + "--\r\n";
  15491. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  15492. "Host: localhost\r\n"
  15493. "Content-Type: multipart/form-data;boundary=" +
  15494. boundary +
  15495. "\r\n"
  15496. "Content-Length: " +
  15497. std::to_string(content.size()) +
  15498. "\r\n"
  15499. "Dummy-Header: ";
  15500. std::string header_suffix = "\r\n"
  15501. "\r\n";
  15502. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  15503. size_t header_dummy_size =
  15504. read_buff_size -
  15505. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  15506. auto header_dummy = std::string(header_dummy_size, '@');
  15507. auto req = header_prefix + header_dummy + header_suffix + content;
  15508. std::string response;
  15509. ASSERT_TRUE(send_request(1, req, &response));
  15510. ASSERT_EQ("200", response.substr(9, 3));
  15511. }
  15512. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  15513. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  15514. // (not chunked Transfer-Encoding) after the streaming refactor.
  15515. auto handled = false;
  15516. Server svr;
  15517. svr.Post("/upload", [&](const Request &req, Response &res) {
  15518. auto cl_it = req.headers.find("Content-Length");
  15519. EXPECT_TRUE(cl_it != req.headers.end());
  15520. auto te_it = req.headers.find("Transfer-Encoding");
  15521. EXPECT_TRUE(te_it == req.headers.end());
  15522. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  15523. res.set_content("ok", "text/plain");
  15524. handled = true;
  15525. });
  15526. auto port = svr.bind_to_any_port(HOST);
  15527. auto t = thread([&] { svr.listen_after_bind(); });
  15528. auto se = detail::scope_exit([&] {
  15529. svr.stop();
  15530. t.join();
  15531. ASSERT_FALSE(svr.is_running());
  15532. ASSERT_TRUE(handled);
  15533. });
  15534. svr.wait_until_ready();
  15535. UploadFormDataItems items = {
  15536. {"field1", "hello", "", "text/plain"},
  15537. {"file1", "world", "test.txt", "application/octet-stream"},
  15538. };
  15539. Client cli(HOST, port);
  15540. auto res = cli.Post("/upload", {}, items);
  15541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15542. EXPECT_EQ(StatusCode::OK_200, res->status);
  15543. }
  15544. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  15545. // Verify that make_multipart_content_provider coalesces many small segments
  15546. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  15547. constexpr size_t kItemCount = 1000;
  15548. UploadFormDataItems items;
  15549. items.reserve(kItemCount);
  15550. for (size_t i = 0; i < kItemCount; i++) {
  15551. items.push_back(
  15552. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15553. }
  15554. const std::string boundary = "----test-boundary";
  15555. auto content_length = detail::get_multipart_content_length(items, boundary);
  15556. auto provider = detail::make_multipart_content_provider(items, boundary);
  15557. // Drive the provider the same way write_content_with_progress does
  15558. size_t write_count = 0;
  15559. size_t total_bytes = 0;
  15560. DataSink sink;
  15561. size_t offset = 0;
  15562. sink.write = [&](const char *d, size_t l) -> bool {
  15563. (void)d;
  15564. write_count++;
  15565. total_bytes += l;
  15566. offset += l;
  15567. return true;
  15568. };
  15569. sink.is_writable = []() -> bool { return true; };
  15570. while (offset < content_length) {
  15571. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  15572. }
  15573. EXPECT_EQ(content_length, total_bytes);
  15574. // The total number of segments is 3 * kItemCount + 1 = 3001.
  15575. // With buffering into 64KB blocks, write_count should be much smaller.
  15576. auto segment_count = 3 * kItemCount + 1;
  15577. EXPECT_LT(write_count, segment_count / 10);
  15578. }
  15579. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  15580. // Integration test: send many UploadFormDataItems and verify the server
  15581. // receives all of them correctly (#2410).
  15582. constexpr size_t kItemCount = 500;
  15583. auto handled = false;
  15584. Server svr;
  15585. svr.Post("/upload", [&](const Request &req, Response &res) {
  15586. EXPECT_EQ(kItemCount, req.form.fields.size());
  15587. for (size_t i = 0; i < kItemCount; i++) {
  15588. auto key = "field" + std::to_string(i);
  15589. auto val = "value" + std::to_string(i);
  15590. auto it = req.form.fields.find(key);
  15591. if (it != req.form.fields.end()) {
  15592. EXPECT_EQ(val, it->second.content);
  15593. } else {
  15594. ADD_FAILURE() << "Missing field: " << key;
  15595. }
  15596. }
  15597. res.set_content("ok", "text/plain");
  15598. handled = true;
  15599. });
  15600. auto port = svr.bind_to_any_port(HOST);
  15601. auto t = thread([&] { svr.listen_after_bind(); });
  15602. auto se = detail::scope_exit([&] {
  15603. svr.stop();
  15604. t.join();
  15605. ASSERT_FALSE(svr.is_running());
  15606. ASSERT_TRUE(handled);
  15607. });
  15608. svr.wait_until_ready();
  15609. UploadFormDataItems items;
  15610. items.reserve(kItemCount);
  15611. for (size_t i = 0; i < kItemCount; i++) {
  15612. items.push_back(
  15613. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15614. }
  15615. Client cli(HOST, port);
  15616. auto res = cli.Post("/upload", items);
  15617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15618. EXPECT_EQ(StatusCode::OK_200, res->status);
  15619. }
  15620. TEST(MultipartFormDataTest, MakeFileProvider) {
  15621. // Verify make_file_provider sends a file's contents correctly.
  15622. const std::string file_content(4096, 'Z');
  15623. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  15624. {
  15625. std::ofstream ofs(tmp_path, std::ios::binary);
  15626. ofs.write(file_content.data(),
  15627. static_cast<std::streamsize>(file_content.size()));
  15628. }
  15629. auto handled = false;
  15630. Server svr;
  15631. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  15632. const ContentReader &content_reader) {
  15633. ASSERT_TRUE(req.is_multipart_form_data());
  15634. std::vector<FormData> items;
  15635. content_reader(
  15636. [&](const FormData &file) {
  15637. items.push_back(file);
  15638. return true;
  15639. },
  15640. [&](const char *data, size_t data_length) {
  15641. items.back().content.append(data, data_length);
  15642. return true;
  15643. });
  15644. ASSERT_EQ(1u, items.size());
  15645. EXPECT_EQ("myfile", items[0].name);
  15646. EXPECT_EQ("data.bin", items[0].filename);
  15647. EXPECT_EQ("application/octet-stream", items[0].content_type);
  15648. EXPECT_EQ(file_content, items[0].content);
  15649. handled = true;
  15650. });
  15651. auto port = svr.bind_to_any_port(HOST);
  15652. auto t = thread([&] { svr.listen_after_bind(); });
  15653. auto se = detail::scope_exit([&] {
  15654. svr.stop();
  15655. t.join();
  15656. ASSERT_FALSE(svr.is_running());
  15657. ASSERT_TRUE(handled);
  15658. std::remove(tmp_path.c_str());
  15659. });
  15660. svr.wait_until_ready();
  15661. FormDataProviderItems providers;
  15662. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  15663. "application/octet-stream"));
  15664. Client cli(HOST, port);
  15665. auto res = cli.Post("/upload", {}, {}, providers);
  15666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15667. EXPECT_EQ(StatusCode::OK_200, res->status);
  15668. }
  15669. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  15670. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  15671. // (100) headers is rejected with a 400 Bad Request response.
  15672. Server svr;
  15673. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15674. res.set_content("ok", "text/plain");
  15675. });
  15676. thread t = thread([&] { svr.listen(HOST, PORT); });
  15677. auto se = detail::scope_exit([&] {
  15678. svr.stop();
  15679. t.join();
  15680. ASSERT_FALSE(svr.is_running());
  15681. });
  15682. svr.wait_until_ready();
  15683. // Build a multipart part with 101 custom headers (exceeding
  15684. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  15685. std::stringstream body;
  15686. body << "--simpleboundary\r\n"
  15687. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  15688. for (int i = 0; i < 101; i++) {
  15689. body << "X-Custom-Header-" << i << ": value\r\n";
  15690. }
  15691. body << "\r\n"
  15692. << "value1\r\n"
  15693. << "--simpleboundary--\r\n";
  15694. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  15695. Client cli(HOST, PORT);
  15696. auto res = cli.Post("/post", body.str(), content_type.c_str());
  15697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15698. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15699. }
  15700. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  15701. // A body that never contains the declared boundary must not be accumulated
  15702. // while the parser waits for it. Buffering it would also make every read
  15703. // rescan everything seen so far, which is quadratic in the body size.
  15704. Server svr;
  15705. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15706. res.set_content("ok", "text/plain");
  15707. });
  15708. auto port = svr.bind_to_any_port(HOST);
  15709. thread t = thread([&] { svr.listen_after_bind(); });
  15710. auto se = detail::scope_exit([&] {
  15711. svr.stop();
  15712. t.join();
  15713. ASSERT_FALSE(svr.is_running());
  15714. });
  15715. svr.wait_until_ready();
  15716. Client cli(HOST, port);
  15717. cli.set_read_timeout(60, 0);
  15718. cli.set_write_timeout(60, 0);
  15719. // '-' is the worst case: it matches the first character of the boundary, so
  15720. // every position has to be checked against it.
  15721. auto post_dashes = [&](size_t size) {
  15722. const std::string body(size, '-');
  15723. auto start = std::chrono::steady_clock::now();
  15724. auto res =
  15725. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  15726. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  15727. std::chrono::steady_clock::now() - start)
  15728. .count();
  15729. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15730. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  15731. return ms;
  15732. };
  15733. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  15734. // Windows.
  15735. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  15736. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  15737. // Comparing the two sizes rather than checking an absolute duration keeps
  15738. // this meaningful across build types and CI load, both of which move the
  15739. // absolute numbers by more than an order of magnitude. Four times the bytes
  15740. // costs about four times the time when parsing is linear, and about sixteen
  15741. // times when the body is buffered and rescanned.
  15742. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  15743. EXPECT_LT(ms_16mb, ms_4mb * 10)
  15744. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  15745. << "ms, which suggests the body is being buffered and rescanned";
  15746. }
  15747. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  15748. // A boundary can only be followed by CRLF or by "--", so anything else is
  15749. // malformed no matter what comes next. The parser must say so right away
  15750. // instead of buffering the rest of the declared body.
  15751. Server svr;
  15752. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15753. res.set_content("ok", "text/plain");
  15754. });
  15755. auto port = svr.bind_to_any_port(HOST);
  15756. thread t = thread([&] { svr.listen_after_bind(); });
  15757. auto se = detail::scope_exit([&] {
  15758. svr.stop();
  15759. t.join();
  15760. ASSERT_FALSE(svr.is_running());
  15761. });
  15762. svr.wait_until_ready();
  15763. // Announce a 1 MB body but send only the malformed prefix. A parser that
  15764. // buffers instead of failing would still be waiting for the remaining bytes.
  15765. const std::string body = "--zzzz\r\n"
  15766. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15767. "\r\n"
  15768. "text1"
  15769. "\r\n--zzzzXX";
  15770. const std::string req = "POST /post HTTP/1.1\r\n"
  15771. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15772. "Content-Length: 1048576\r\n"
  15773. "\r\n" +
  15774. body;
  15775. std::string response;
  15776. ASSERT_TRUE(send_request(3, req, &response, port));
  15777. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  15778. EXPECT_EQ("400", response.substr(9, 3));
  15779. }
  15780. // Posts a multipart body split into two writes, so that the server sees the
  15781. // split at whatever offset the caller chose, and expects the single "text1"
  15782. // field to come through.
  15783. static void expect_split_multipart_ok(const std::string &body1,
  15784. const std::string &body2) {
  15785. auto handled = false;
  15786. Server svr;
  15787. svr.Post("/post", [&](const Request &req, Response &) {
  15788. EXPECT_EQ(1u, req.form.fields.size());
  15789. EXPECT_EQ("text1", req.form.get_field("text1"));
  15790. handled = true;
  15791. });
  15792. auto port = svr.bind_to_any_port(HOST);
  15793. thread t = thread([&] { svr.listen_after_bind(); });
  15794. auto se = detail::scope_exit([&] {
  15795. svr.stop();
  15796. t.join();
  15797. ASSERT_FALSE(svr.is_running());
  15798. ASSERT_TRUE(handled);
  15799. });
  15800. svr.wait_until_ready();
  15801. // "Connection: close" makes the server close once it has answered, so the
  15802. // response drain ends immediately instead of idling until the read timeout.
  15803. const std::string head =
  15804. "POST /post HTTP/1.1\r\n"
  15805. "Host: localhost\r\n"
  15806. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15807. "Connection: close\r\n"
  15808. "Content-Length: " +
  15809. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  15810. std::string response;
  15811. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  15812. ASSERT_GE(response.size(), 12u) << "no response";
  15813. EXPECT_EQ("200", response.substr(9, 3));
  15814. }
  15815. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  15816. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  15817. // ignored, including when it does not arrive in the same read as the
  15818. // close-delimiter itself.
  15819. expect_split_multipart_ok("--zzzz\r\n"
  15820. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15821. "\r\n"
  15822. "text1"
  15823. "\r\n--zzzz--",
  15824. "\r\nthis epilogue must be ignored\r\n");
  15825. }
  15826. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  15827. // The initial boundary may be preceded by a preamble of any length and may
  15828. // straddle a read boundary. Discarding data while waiting for it must not
  15829. // throw away a partial boundary sitting at the end of the buffer.
  15830. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  15831. "zz\r\n"
  15832. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15833. "\r\n"
  15834. "text1"
  15835. "\r\n--zzzz--\r\n");
  15836. }
  15837. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  15838. // The received boundary was only checked for being non-empty, so it could be
  15839. // as long as a header is allowed to be. The parser scans the body for
  15840. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  15841. // costs a nearly full comparison at nearly every position, making the
  15842. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  15843. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  15844. Server svr;
  15845. svr.Post("/post", [](const Request &req, Response &res) {
  15846. EXPECT_EQ(1u, req.form.fields.size());
  15847. EXPECT_EQ("text1", req.form.get_field("text1"));
  15848. res.set_content("ok", "text/plain");
  15849. });
  15850. auto port = svr.bind_to_any_port(HOST);
  15851. thread t = thread([&] { svr.listen_after_bind(); });
  15852. auto se = detail::scope_exit([&] {
  15853. svr.stop();
  15854. t.join();
  15855. ASSERT_FALSE(svr.is_running());
  15856. });
  15857. svr.wait_until_ready();
  15858. Client cli(HOST, port);
  15859. auto post_with_boundary_of_length = [&](size_t len) {
  15860. const std::string boundary(len, 'a');
  15861. const std::string body =
  15862. "--" + boundary +
  15863. "\r\n"
  15864. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15865. "\r\n"
  15866. "text1"
  15867. "\r\n--" +
  15868. boundary + "--\r\n";
  15869. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  15870. };
  15871. auto res = post_with_boundary_of_length(70);
  15872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15873. EXPECT_EQ(StatusCode::OK_200, res->status);
  15874. res = post_with_boundary_of_length(71);
  15875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15876. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15877. }
  15878. TEST(MakeFileBodyTest, Basic) {
  15879. const std::string file_content(4096, 'Z');
  15880. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  15881. {
  15882. std::ofstream ofs(tmp_path, std::ios::binary);
  15883. ofs.write(file_content.data(),
  15884. static_cast<std::streamsize>(file_content.size()));
  15885. }
  15886. auto handled = false;
  15887. Server svr;
  15888. svr.Post("/upload", [&](const Request &req, Response &res) {
  15889. EXPECT_EQ(file_content, req.body);
  15890. handled = true;
  15891. res.status = StatusCode::OK_200;
  15892. });
  15893. auto port = svr.bind_to_any_port(HOST);
  15894. auto t = thread([&] { svr.listen_after_bind(); });
  15895. auto se = detail::scope_exit([&] {
  15896. svr.stop();
  15897. t.join();
  15898. ASSERT_FALSE(svr.is_running());
  15899. ASSERT_TRUE(handled);
  15900. std::remove(tmp_path.c_str());
  15901. });
  15902. svr.wait_until_ready();
  15903. auto fb = make_file_body(tmp_path);
  15904. ASSERT_GT(fb.first, 0u);
  15905. Client cli(HOST, port);
  15906. auto res =
  15907. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  15908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15909. EXPECT_EQ(StatusCode::OK_200, res->status);
  15910. }
  15911. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  15912. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  15913. {
  15914. std::ofstream ofs(path, std::ios::binary);
  15915. const std::string content(100, 'A');
  15916. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15917. }
  15918. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15919. auto body = make_file_body(path);
  15920. ASSERT_EQ(100u, body.first);
  15921. ASSERT_TRUE(static_cast<bool>(body.second));
  15922. // Rewritten shorter after its length was measured - and, on a server, after
  15923. // that length has already gone out as Content-Length.
  15924. {
  15925. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  15926. const std::string content(10, 'A');
  15927. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15928. }
  15929. std::string written;
  15930. DataSink sink;
  15931. sink.write = [&](const char *d, size_t l) {
  15932. written.append(d, l);
  15933. return true;
  15934. };
  15935. // The provider has to report failure. write_content_with_progress() advances
  15936. // its offset only by what was written, so a provider that returns true
  15937. // without completing the length it promised is called again straight away,
  15938. // and again.
  15939. EXPECT_FALSE(body.second(0, body.first, sink));
  15940. EXPECT_EQ(std::string(10, 'A'), written);
  15941. }
  15942. TEST(MakeFileBodyTest, WholeFileIsSent) {
  15943. const std::string path = "./httplib_test_make_file_body_whole.bin";
  15944. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  15945. {
  15946. std::ofstream ofs(path, std::ios::binary);
  15947. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15948. }
  15949. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15950. auto body = make_file_body(path);
  15951. ASSERT_EQ(content.size(), body.first);
  15952. ASSERT_TRUE(static_cast<bool>(body.second));
  15953. std::string written;
  15954. DataSink sink;
  15955. sink.write = [&](const char *d, size_t l) {
  15956. written.append(d, l);
  15957. return true;
  15958. };
  15959. EXPECT_TRUE(body.second(0, body.first, sink));
  15960. EXPECT_EQ(content, written);
  15961. }
  15962. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  15963. static constexpr unsigned int number_of_tasks{1000000};
  15964. std::atomic_uint count{0};
  15965. std::unique_ptr<TaskQueue> task_queue{
  15966. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  15967. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15968. auto queued = task_queue->enqueue(
  15969. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  15970. EXPECT_TRUE(queued);
  15971. }
  15972. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15973. task_queue->shutdown();
  15974. #else
  15975. EXPECT_NO_THROW(task_queue->shutdown());
  15976. #endif
  15977. EXPECT_EQ(number_of_tasks, count.load());
  15978. }
  15979. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  15980. static constexpr unsigned int number_of_tasks{1000000};
  15981. static constexpr unsigned int qlimit{2};
  15982. unsigned int queued_count{0};
  15983. std::atomic_uint count{0};
  15984. std::unique_ptr<TaskQueue> task_queue{
  15985. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  15986. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15987. if (task_queue->enqueue(
  15988. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  15989. queued_count++;
  15990. }
  15991. }
  15992. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15993. task_queue->shutdown();
  15994. #else
  15995. EXPECT_NO_THROW(task_queue->shutdown());
  15996. #endif
  15997. EXPECT_EQ(queued_count, count.load());
  15998. EXPECT_TRUE(queued_count <= number_of_tasks);
  15999. EXPECT_TRUE(queued_count >= qlimit);
  16000. }
  16001. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  16002. // Use a short idle timeout so a dynamic thread spawns, times out and
  16003. // exits during the test, and the pool keeps working afterwards.
  16004. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16005. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16006. /*idle_timeout_sec=*/1}};
  16007. std::atomic_uint count{0};
  16008. std::condition_variable cv;
  16009. std::mutex mtx;
  16010. bool release = false;
  16011. // Block the base thread so the second task spawns a dynamic thread.
  16012. EXPECT_TRUE(task_queue->enqueue([&] {
  16013. std::unique_lock<std::mutex> lock(mtx);
  16014. while (!release) {
  16015. cv.wait(lock);
  16016. }
  16017. count++;
  16018. }));
  16019. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16020. // Let the dynamic thread finish its task and exceed the idle timeout.
  16021. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16022. {
  16023. std::unique_lock<std::mutex> lock(mtx);
  16024. release = true;
  16025. }
  16026. cv.notify_all();
  16027. // The pool must still accept and run tasks after the dynamic thread exited.
  16028. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16029. task_queue->shutdown();
  16030. EXPECT_EQ(3u, count.load());
  16031. }
  16032. TEST(TaskQueueTest, MaxQueuedRequests) {
  16033. static constexpr unsigned int qlimit{3};
  16034. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  16035. std::condition_variable sem_cv;
  16036. std::mutex sem_mtx;
  16037. int credits = 0;
  16038. bool queued;
  16039. /* Fill up the queue with tasks that will block until we give them credits to
  16040. * complete. */
  16041. for (unsigned int n = 0; n <= qlimit;) {
  16042. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  16043. std::unique_lock<std::mutex> lock(sem_mtx);
  16044. while (credits <= 0) {
  16045. sem_cv.wait(lock);
  16046. }
  16047. /* Consume the credit and signal the test code if they are all gone. */
  16048. if (--credits == 0) { sem_cv.notify_one(); }
  16049. });
  16050. if (n < qlimit) {
  16051. /* The first qlimit enqueues must succeed. */
  16052. EXPECT_TRUE(queued);
  16053. } else {
  16054. /* The last one will succeed only when the worker thread
  16055. * starts and dequeues the first blocking task. Although
  16056. * not necessary for the correctness of this test, we sleep for
  16057. * a short while to avoid busy waiting. */
  16058. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16059. }
  16060. if (queued) { n++; }
  16061. }
  16062. /* Further enqueues must fail since the queue is full. */
  16063. for (auto i = 0; i < 4; i++) {
  16064. queued = task_queue->enqueue([] {});
  16065. EXPECT_FALSE(queued);
  16066. }
  16067. /* Give the credits to allow the previous tasks to complete. */
  16068. {
  16069. std::unique_lock<std::mutex> lock(sem_mtx);
  16070. credits += qlimit + 1;
  16071. }
  16072. sem_cv.notify_all();
  16073. /* Wait for all the credits to be consumed. */
  16074. {
  16075. std::unique_lock<std::mutex> lock(sem_mtx);
  16076. while (credits > 0) {
  16077. sem_cv.wait(lock);
  16078. }
  16079. }
  16080. /* Check that we are able again to enqueue at least qlimit tasks. */
  16081. for (unsigned int i = 0; i < qlimit; i++) {
  16082. queued = task_queue->enqueue([] {});
  16083. EXPECT_TRUE(queued);
  16084. }
  16085. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16086. task_queue->shutdown();
  16087. #else
  16088. EXPECT_NO_THROW(task_queue->shutdown());
  16089. #endif
  16090. }
  16091. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  16092. Server svr;
  16093. std::string method;
  16094. std::string body;
  16095. auto has_content_length = false;
  16096. auto has_transfer_encoding = false;
  16097. std::atomic<int> bad_requests{0};
  16098. // Leftover body bytes get parsed as a malformed request and answered with
  16099. // 400
  16100. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  16101. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  16102. });
  16103. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  16104. res.set_redirect("/down", StatusCode::SeeOther_303);
  16105. });
  16106. svr.Get("/down", [&](const Request &req, Response &res) {
  16107. method = req.method;
  16108. body = req.body;
  16109. has_content_length = req.has_header("Content-Length");
  16110. has_transfer_encoding = req.has_header("Transfer-Encoding");
  16111. res.set_content("ok", "text/plain");
  16112. });
  16113. auto port = svr.bind_to_any_port(HOST);
  16114. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16115. auto se = detail::scope_exit([&] {
  16116. svr.stop();
  16117. thread.join();
  16118. ASSERT_FALSE(svr.is_running());
  16119. });
  16120. svr.wait_until_ready();
  16121. const std::string payload = "SECRET-BODY";
  16122. auto check = [&](Client &cli, const Result &res) {
  16123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16124. EXPECT_EQ(StatusCode::OK_200, res->status);
  16125. EXPECT_EQ("ok", res->body);
  16126. EXPECT_EQ("GET", method);
  16127. EXPECT_TRUE(body.empty());
  16128. EXPECT_FALSE(has_content_length);
  16129. EXPECT_FALSE(has_transfer_encoding);
  16130. // Nothing of the original body may be left on the connection
  16131. auto res2 = cli.Get("/down");
  16132. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16133. EXPECT_EQ(StatusCode::OK_200, res2->status);
  16134. EXPECT_EQ("ok", res2->body);
  16135. EXPECT_EQ(0, bad_requests);
  16136. };
  16137. // With content length
  16138. {
  16139. Client cli(HOST, port);
  16140. cli.set_keep_alive(true);
  16141. cli.set_follow_location(true);
  16142. auto res = cli.Post(
  16143. "/up", payload.size(),
  16144. [&](size_t offset, size_t length, DataSink &sink) {
  16145. return sink.write(payload.data() + offset, length);
  16146. },
  16147. "text/plain");
  16148. check(cli, res);
  16149. }
  16150. // Without content length (chunked)
  16151. {
  16152. Client cli(HOST, port);
  16153. cli.set_keep_alive(true);
  16154. cli.set_follow_location(true);
  16155. auto res = cli.Post(
  16156. "/up",
  16157. [&](size_t /*offset*/, DataSink &sink) {
  16158. sink.write(payload.data(), payload.size());
  16159. sink.done();
  16160. return true;
  16161. },
  16162. "text/plain");
  16163. check(cli, res);
  16164. }
  16165. }
  16166. TEST(RedirectTest, LocationPathIsNotDecoded) {
  16167. Server svr;
  16168. std::string target;
  16169. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  16170. // Echo the still-encoded name back in the Location
  16171. const std::string prefix = "/start/";
  16172. res.status = StatusCode::Found_302;
  16173. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  16174. });
  16175. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  16176. target = req.target;
  16177. res.set_content("ok", "text/plain");
  16178. });
  16179. auto port = svr.bind_to_any_port(HOST);
  16180. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16181. auto se = detail::scope_exit([&] {
  16182. svr.stop();
  16183. thread.join();
  16184. ASSERT_FALSE(svr.is_running());
  16185. });
  16186. svr.wait_until_ready();
  16187. // Decoding the Location path would turn the first four into a path
  16188. // separator, a query delimiter, a fragment delimiter and a different
  16189. // percent-encoded octet. The rest must keep reaching the server as they are.
  16190. const std::vector<std::string> names = {
  16191. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  16192. };
  16193. for (auto path_encode : {true, false}) {
  16194. Client cli(HOST, port);
  16195. cli.set_follow_location(true);
  16196. cli.set_path_encode(path_encode);
  16197. for (const auto &name : names) {
  16198. target.clear();
  16199. auto res = cli.Get("/start/" + name);
  16200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16201. EXPECT_EQ(StatusCode::OK_200, res->status);
  16202. EXPECT_EQ("/dest/" + name, target);
  16203. }
  16204. }
  16205. }
  16206. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  16207. Server svr;
  16208. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16209. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  16210. });
  16211. svr.Get("/hello", [](const Request &req, Response &res) {
  16212. res.set_content(req.get_param_value("key"), "text/plain");
  16213. });
  16214. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16215. auto se = detail::scope_exit([&] {
  16216. svr.stop();
  16217. thread.join();
  16218. ASSERT_FALSE(svr.is_running());
  16219. });
  16220. svr.wait_until_ready();
  16221. {
  16222. Client cli(HOST, PORT);
  16223. cli.set_follow_location(true);
  16224. auto res = cli.Get("/");
  16225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16226. EXPECT_EQ(StatusCode::OK_200, res->status);
  16227. EXPECT_EQ("val&key2=val2", res->body);
  16228. }
  16229. }
  16230. #endif
  16231. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  16232. Server svr;
  16233. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16234. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  16235. });
  16236. svr.Get("/hello", [](const Request &req, Response &res) {
  16237. res.set_content(req.get_param_value("key"), "text/plain");
  16238. });
  16239. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16240. auto se = detail::scope_exit([&] {
  16241. svr.stop();
  16242. thread.join();
  16243. ASSERT_FALSE(svr.is_running());
  16244. });
  16245. svr.wait_until_ready();
  16246. {
  16247. Client cli(HOST, PORT);
  16248. cli.set_follow_location(true);
  16249. auto res = cli.Get("/");
  16250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16251. EXPECT_EQ(StatusCode::OK_200, res->status);
  16252. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  16253. }
  16254. }
  16255. TEST(RedirectTest, RedirectWithPlusInPath) {
  16256. Server svr;
  16257. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16258. res.set_redirect("/a+b");
  16259. });
  16260. // Route pattern uses regex; escape + as \\+
  16261. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  16262. res.set_content(req.path, "text/plain");
  16263. });
  16264. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16265. auto se = detail::scope_exit([&] {
  16266. svr.stop();
  16267. thread.join();
  16268. ASSERT_FALSE(svr.is_running());
  16269. });
  16270. svr.wait_until_ready();
  16271. {
  16272. Client cli(HOST, PORT);
  16273. cli.set_follow_location(true);
  16274. auto res = cli.Get("/");
  16275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16276. EXPECT_EQ(StatusCode::OK_200, res->status);
  16277. EXPECT_EQ("/a+b", res->body);
  16278. }
  16279. }
  16280. TEST(RedirectTest, ResolveRelativeLocation) {
  16281. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  16282. const std::vector<std::pair<std::string, std::string>> cases = {
  16283. {"g", "/b/c/g"},
  16284. {"./g", "/b/c/g"},
  16285. {"g/", "/b/c/g/"},
  16286. {"?y", "/b/c/d;p?y"},
  16287. {"g?y", "/b/c/g?y"},
  16288. {"#s", "/b/c/d;p?q#s"},
  16289. {"g#s", "/b/c/g#s"},
  16290. {"g?y#s", "/b/c/g?y#s"},
  16291. {";x", "/b/c/;x"},
  16292. {"g;x", "/b/c/g;x"},
  16293. {".", "/b/c/"},
  16294. {"./", "/b/c/"},
  16295. {"..", "/b/"},
  16296. {"../", "/b/"},
  16297. {"../g", "/b/g"},
  16298. {"../..", "/"},
  16299. {"../../", "/"},
  16300. {"../../g", "/g"},
  16301. {"../../../g", "/g"},
  16302. {"g.", "/b/c/g."},
  16303. {".g", "/b/c/.g"},
  16304. {"g..", "/b/c/g.."},
  16305. {"..g", "/b/c/..g"},
  16306. {"./../g", "/b/g"},
  16307. {"./g/.", "/b/c/g/"},
  16308. {"g/./h", "/b/c/g/h"},
  16309. {"g/../h", "/b/c/h"},
  16310. {"g;x=1/./y", "/b/c/g;x=1/y"},
  16311. {"g;x=1/../y", "/b/c/y"},
  16312. {"g?y/./x", "/b/c/g?y/./x"},
  16313. {"g#s/../x", "/b/c/g#s/../x"},
  16314. // Not relative-path references, so left for parse_url.
  16315. {"/g", "/g"},
  16316. {"//g", "//g"},
  16317. {"http://g/x", "http://g/x"},
  16318. {"g:h", "g:h"},
  16319. };
  16320. for (const auto &c : cases) {
  16321. EXPECT_EQ(c.second,
  16322. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  16323. << c.first;
  16324. }
  16325. }
  16326. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  16327. Server svr;
  16328. svr.Get("/dir/page", [](const Request &req, Response &res) {
  16329. res.set_redirect(req.get_param_value("to"));
  16330. });
  16331. svr.Get("/dir/next", [](const Request &req, Response &res) {
  16332. res.set_content(req.target, "text/plain");
  16333. });
  16334. svr.Get("/other", [](const Request &req, Response &res) {
  16335. res.set_content(req.target, "text/plain");
  16336. });
  16337. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16338. auto se = detail::scope_exit([&] {
  16339. svr.stop();
  16340. thread.join();
  16341. ASSERT_FALSE(svr.is_running());
  16342. });
  16343. svr.wait_until_ready();
  16344. const std::vector<std::pair<std::string, std::string>> cases = {
  16345. {"next", "/dir/next"},
  16346. {"./next?x=1", "/dir/next?x=1"},
  16347. {"../other", "/other"},
  16348. };
  16349. for (const auto &c : cases) {
  16350. Client cli(HOST, PORT);
  16351. cli.set_follow_location(true);
  16352. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  16353. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  16354. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  16355. EXPECT_EQ(c.second, res->body) << c.first;
  16356. }
  16357. }
  16358. #ifdef CPPHTTPLIB_SSL_ENABLED
  16359. TEST(RedirectTest, Issue2185_Online) {
  16360. SSLClient client("github.com");
  16361. client.set_follow_location(true);
  16362. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  16363. "Coollab-Windows.zip");
  16364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16365. EXPECT_EQ(StatusCode::OK_200, res->status);
  16366. EXPECT_EQ(9920427U, res->body.size());
  16367. }
  16368. #endif
  16369. TEST(VulnerabilityTest, CRLFInjection) {
  16370. Server svr;
  16371. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  16372. res.set_content("Hello 1", "text/plain");
  16373. });
  16374. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  16375. res.set_content("Hello 2", "text/plain");
  16376. });
  16377. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  16378. res.set_content("Hello 3", "text/plain");
  16379. });
  16380. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  16381. res.set_content("Hello 4", "text/plain");
  16382. });
  16383. svr.set_logger([](const Request &req, const Response & /*res*/) {
  16384. for (const auto &x : req.headers) {
  16385. auto key = x.first;
  16386. EXPECT_STRNE("evil", key.c_str());
  16387. }
  16388. });
  16389. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16390. auto se = detail::scope_exit([&] {
  16391. svr.stop();
  16392. thread.join();
  16393. ASSERT_FALSE(svr.is_running());
  16394. });
  16395. svr.wait_until_ready();
  16396. {
  16397. Client cli(HOST, PORT);
  16398. cli.Post("/test1", "A=B",
  16399. "application/x-www-form-urlencoded\r\nevil: hello1");
  16400. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  16401. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  16402. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  16403. }
  16404. }
  16405. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  16406. auto server_thread = std::thread([] {
  16407. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16408. default_socket_options(srv);
  16409. sockaddr_in addr{};
  16410. addr.sin_family = AF_INET;
  16411. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16412. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16413. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  16414. ::listen(srv, 1);
  16415. sockaddr_in cli_addr{};
  16416. socklen_t cli_len = sizeof(cli_addr);
  16417. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16418. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  16419. std::string buf_all;
  16420. char buf[2048];
  16421. ssize_t n;
  16422. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  16423. buf_all.append(buf, static_cast<size_t>(n));
  16424. size_t pos;
  16425. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  16426. auto request_block = buf_all.substr(0, pos + 4); // include separator
  16427. auto e = request_block.find("\r\n");
  16428. if (e != std::string::npos) {
  16429. auto request_line = request_block.substr(0, e);
  16430. std::string msg =
  16431. "CRLF injection detected in request line: '" + request_line + "'";
  16432. EXPECT_FALSE(true) << msg;
  16433. }
  16434. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  16435. ::send(cli,
  16436. #ifdef _WIN32
  16437. static_cast<const char *>(resp.c_str()),
  16438. static_cast<int>(resp.size()),
  16439. #else
  16440. resp.c_str(), resp.size(),
  16441. #endif
  16442. 0);
  16443. buf_all.erase(0, pos + 4);
  16444. }
  16445. }
  16446. detail::close_socket(cli);
  16447. detail::close_socket(srv);
  16448. });
  16449. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16450. auto cli = Client("127.0.0.1", PORT + 1);
  16451. auto headers = Headers{
  16452. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  16453. {"Connection", "keep-alive"}};
  16454. auto res = cli.Get("/hi", headers);
  16455. EXPECT_FALSE(res);
  16456. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16457. server_thread.join();
  16458. }
  16459. // A request rejected before any byte reaches the socket must fail right away
  16460. // instead of waiting for a response the server will never send.
  16461. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  16462. // The kernel completes the TCP handshake from the listen backlog, so the
  16463. // client connects, but nothing ever reads, responds or closes.
  16464. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16465. default_socket_options(srv);
  16466. sockaddr_in addr{};
  16467. addr.sin_family = AF_INET;
  16468. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16469. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16470. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16471. ASSERT_EQ(0, ::listen(srv, 8));
  16472. auto cli = Client("127.0.0.1", PORT + 1);
  16473. cli.set_read_timeout(10, 0);
  16474. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  16475. return std::chrono::duration_cast<std::chrono::milliseconds>(
  16476. std::chrono::steady_clock::now() - start)
  16477. .count();
  16478. };
  16479. {
  16480. Request req;
  16481. req.method = "GE T";
  16482. req.path = "/";
  16483. auto start = std::chrono::steady_clock::now();
  16484. auto res = cli.send(req);
  16485. EXPECT_FALSE(res);
  16486. EXPECT_EQ(Error::Write, res.error());
  16487. EXPECT_LT(elapsed_ms(start), 1000);
  16488. }
  16489. {
  16490. auto start = std::chrono::steady_clock::now();
  16491. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  16492. EXPECT_FALSE(res);
  16493. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16494. EXPECT_LT(elapsed_ms(start), 1000);
  16495. }
  16496. EXPECT_FALSE(cli.is_socket_open());
  16497. detail::close_socket(srv);
  16498. }
  16499. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  16500. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16501. default_socket_options(srv);
  16502. sockaddr_in addr{};
  16503. addr.sin_family = AF_INET;
  16504. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16505. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16506. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16507. ASSERT_EQ(0, ::listen(srv, 1));
  16508. std::string received;
  16509. auto server_thread = std::thread([&] {
  16510. auto sock = ::accept(srv, nullptr, nullptr);
  16511. if (sock == INVALID_SOCKET) { return; }
  16512. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  16513. char buf[2048];
  16514. ssize_t n;
  16515. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  16516. received.append(buf, static_cast<size_t>(n));
  16517. }
  16518. detail::close_socket(sock);
  16519. });
  16520. {
  16521. auto cli = Client("127.0.0.1", PORT + 1);
  16522. // "Z" sorts after the default headers, so writing straight to the socket
  16523. // would have sent the request line and those headers before the rejection.
  16524. auto handle =
  16525. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  16526. EXPECT_FALSE(handle.is_valid());
  16527. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  16528. }
  16529. server_thread.join();
  16530. detail::close_socket(srv);
  16531. EXPECT_TRUE(received.empty()) << received;
  16532. }
  16533. TEST(PathParamsTest, StaticMatch) {
  16534. const auto pattern = "/users/all";
  16535. detail::PathParamsMatcher matcher(pattern);
  16536. Request request;
  16537. request.path = "/users/all";
  16538. ASSERT_TRUE(matcher.match(request));
  16539. std::unordered_map<std::string, std::string> expected_params = {};
  16540. EXPECT_EQ(request.path_params, expected_params);
  16541. }
  16542. TEST(PathParamsTest, StaticMismatch) {
  16543. const auto pattern = "/users/all";
  16544. detail::PathParamsMatcher matcher(pattern);
  16545. Request request;
  16546. request.path = "/users/1";
  16547. ASSERT_FALSE(matcher.match(request));
  16548. }
  16549. TEST(PathParamsTest, SingleParamInTheMiddle) {
  16550. const auto pattern = "/users/:id/subscriptions";
  16551. detail::PathParamsMatcher matcher(pattern);
  16552. Request request;
  16553. request.path = "/users/42/subscriptions";
  16554. ASSERT_TRUE(matcher.match(request));
  16555. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16556. EXPECT_EQ(request.path_params, expected_params);
  16557. }
  16558. TEST(PathParamsTest, SingleParamInTheEnd) {
  16559. const auto pattern = "/users/:id";
  16560. detail::PathParamsMatcher matcher(pattern);
  16561. Request request;
  16562. request.path = "/users/24";
  16563. ASSERT_TRUE(matcher.match(request));
  16564. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  16565. EXPECT_EQ(request.path_params, expected_params);
  16566. }
  16567. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  16568. const auto pattern = "/users/:id/";
  16569. detail::PathParamsMatcher matcher(pattern);
  16570. Request request;
  16571. request.path = "/users/42/";
  16572. ASSERT_TRUE(matcher.match(request));
  16573. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16574. EXPECT_EQ(request.path_params, expected_params);
  16575. }
  16576. TEST(PathParamsTest, EmptyParam) {
  16577. const auto pattern = "/users/:id/";
  16578. detail::PathParamsMatcher matcher(pattern);
  16579. Request request;
  16580. request.path = "/users//";
  16581. ASSERT_TRUE(matcher.match(request));
  16582. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  16583. EXPECT_EQ(request.path_params, expected_params);
  16584. }
  16585. TEST(PathParamsTest, FragmentMismatch) {
  16586. const auto pattern = "/users/:id/";
  16587. detail::PathParamsMatcher matcher(pattern);
  16588. Request request;
  16589. request.path = "/admins/24/";
  16590. ASSERT_FALSE(matcher.match(request));
  16591. }
  16592. TEST(PathParamsTest, ExtraFragments) {
  16593. const auto pattern = "/users/:id";
  16594. detail::PathParamsMatcher matcher(pattern);
  16595. Request request;
  16596. request.path = "/users/42/subscriptions";
  16597. ASSERT_FALSE(matcher.match(request));
  16598. }
  16599. TEST(PathParamsTest, MissingTrailingParam) {
  16600. const auto pattern = "/users/:id";
  16601. detail::PathParamsMatcher matcher(pattern);
  16602. Request request;
  16603. request.path = "/users";
  16604. ASSERT_FALSE(matcher.match(request));
  16605. }
  16606. TEST(PathParamsTest, MissingParamInTheMiddle) {
  16607. const auto pattern = "/users/:id/subscriptions";
  16608. detail::PathParamsMatcher matcher(pattern);
  16609. Request request;
  16610. request.path = "/users/subscriptions";
  16611. ASSERT_FALSE(matcher.match(request));
  16612. }
  16613. TEST(PathParamsTest, MultipleParams) {
  16614. const auto pattern = "/users/:userid/subscriptions/:subid";
  16615. detail::PathParamsMatcher matcher(pattern);
  16616. Request request;
  16617. request.path = "/users/42/subscriptions/2";
  16618. ASSERT_TRUE(matcher.match(request));
  16619. std::unordered_map<std::string, std::string> expected_params = {
  16620. {"userid", "42"}, {"subid", "2"}};
  16621. EXPECT_EQ(request.path_params, expected_params);
  16622. }
  16623. TEST(PathParamsTest, SequenceOfParams) {
  16624. const auto pattern = "/values/:x/:y/:z";
  16625. detail::PathParamsMatcher matcher(pattern);
  16626. Request request;
  16627. request.path = "/values/1/2/3";
  16628. ASSERT_TRUE(matcher.match(request));
  16629. std::unordered_map<std::string, std::string> expected_params = {
  16630. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  16631. EXPECT_EQ(request.path_params, expected_params);
  16632. }
  16633. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  16634. const auto pattern = "/prefix:suffix";
  16635. detail::PathParamsMatcher matcher(pattern);
  16636. Request request;
  16637. request.path = "/prefix:suffix";
  16638. ASSERT_TRUE(matcher.match(request));
  16639. const std::unordered_map<std::string, std::string> expected_params = {};
  16640. EXPECT_EQ(request.path_params, expected_params);
  16641. }
  16642. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  16643. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  16644. // calling thread's stack on a long enough path for a quantified pattern;
  16645. // RegexMatcher must refuse to run regex matching on paths beyond
  16646. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  16647. detail::RegexMatcher matcher("/files/(.*)");
  16648. Request within_limit;
  16649. within_limit.path = "/files/" + std::string(10, 'A');
  16650. EXPECT_TRUE(matcher.match(within_limit));
  16651. Request over_limit;
  16652. over_limit.path =
  16653. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  16654. EXPECT_FALSE(matcher.match(over_limit));
  16655. }
  16656. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  16657. Server svr;
  16658. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  16659. res.set_content("ok", "text/plain");
  16660. });
  16661. auto port = svr.bind_to_any_port(HOST);
  16662. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16663. auto se = detail::scope_exit([&] {
  16664. svr.stop();
  16665. thread.join();
  16666. ASSERT_FALSE(svr.is_running());
  16667. });
  16668. svr.wait_until_ready();
  16669. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  16670. // request URI limit; this used to be able to crash the process.
  16671. std::string path =
  16672. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  16673. std::string req = "GET " + path +
  16674. " HTTP/1.1\r\n"
  16675. "Host: " +
  16676. std::string(HOST) + ":" + std::to_string(port) +
  16677. "\r\n"
  16678. "Connection: close\r\n"
  16679. "\r\n";
  16680. std::string response;
  16681. ASSERT_TRUE(send_request(5, req, &response, port));
  16682. EXPECT_NE(std::string::npos, response.find("404"));
  16683. }
  16684. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  16685. Server svr;
  16686. auto handler = [](const Request & /*req*/, Response &res) {
  16687. res.set_content("hit", "text/plain");
  16688. };
  16689. // No regex metacharacter, so this one is compared literally
  16690. svr.Get("/literal/route", handler);
  16691. // '.' is a regex metacharacter, so this one must keep regex semantics
  16692. svr.Get("/a.c", handler);
  16693. auto port = svr.bind_to_any_port(HOST);
  16694. std::thread t([&]() { svr.listen_after_bind(); });
  16695. auto se = detail::scope_exit([&] {
  16696. svr.stop();
  16697. t.join();
  16698. ASSERT_FALSE(svr.is_running());
  16699. });
  16700. svr.wait_until_ready();
  16701. Client cli(HOST, port);
  16702. struct {
  16703. const char *path;
  16704. int status;
  16705. } cases[] = {
  16706. {"/literal/route", StatusCode::OK_200},
  16707. {"/literal/routes", StatusCode::NotFound_404},
  16708. {"/literal/rout", StatusCode::NotFound_404},
  16709. {"/abc", StatusCode::OK_200},
  16710. {"/a.c", StatusCode::OK_200},
  16711. };
  16712. for (const auto &x : cases) {
  16713. auto res = cli.Get(x.path);
  16714. ASSERT_TRUE(res) << x.path;
  16715. EXPECT_EQ(x.status, res->status) << x.path;
  16716. }
  16717. }
  16718. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  16719. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  16720. // from exhausting the stack, so it must only constrain routes that actually
  16721. // run a regular expression. A literal route is matched by comparison and
  16722. // stays usable at any length.
  16723. Server svr;
  16724. const std::string pattern =
  16725. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  16726. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  16727. res.set_content("hit", "text/plain");
  16728. });
  16729. auto port = svr.bind_to_any_port(HOST);
  16730. std::thread t([&]() { svr.listen_after_bind(); });
  16731. auto se = detail::scope_exit([&] {
  16732. svr.stop();
  16733. t.join();
  16734. ASSERT_FALSE(svr.is_running());
  16735. });
  16736. svr.wait_until_ready();
  16737. Client cli(HOST, port);
  16738. auto res = cli.Get(pattern);
  16739. ASSERT_TRUE(res);
  16740. EXPECT_EQ(StatusCode::OK_200, res->status);
  16741. }
  16742. TEST(ParseUrlTest, VariousPatterns) {
  16743. {
  16744. detail::UrlComponents uc;
  16745. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  16746. EXPECT_EQ("http", uc.scheme);
  16747. EXPECT_EQ("example.com", uc.host);
  16748. EXPECT_EQ("8080", uc.port);
  16749. EXPECT_EQ("/path", uc.path);
  16750. EXPECT_EQ("?q=1", uc.query);
  16751. }
  16752. {
  16753. detail::UrlComponents uc;
  16754. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  16755. EXPECT_EQ("https", uc.scheme);
  16756. EXPECT_EQ("example.com", uc.host);
  16757. EXPECT_TRUE(uc.port.empty());
  16758. EXPECT_EQ("/path", uc.path);
  16759. }
  16760. {
  16761. detail::UrlComponents uc;
  16762. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  16763. EXPECT_EQ("::1", uc.host);
  16764. EXPECT_EQ("8080", uc.port);
  16765. EXPECT_EQ("/path", uc.path);
  16766. }
  16767. {
  16768. detail::UrlComponents uc;
  16769. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  16770. }
  16771. {
  16772. // Bytes after the IPv6 literal must be a delimiter, not folded into
  16773. // the path while the connection still targets the bracketed host.
  16774. detail::UrlComponents uc;
  16775. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  16776. }
  16777. {
  16778. detail::UrlComponents uc;
  16779. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  16780. }
  16781. {
  16782. detail::UrlComponents uc;
  16783. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  16784. EXPECT_EQ("::1", uc.host);
  16785. EXPECT_TRUE(uc.port.empty());
  16786. EXPECT_EQ("/path", uc.path);
  16787. }
  16788. {
  16789. detail::UrlComponents uc;
  16790. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  16791. EXPECT_TRUE(uc.scheme.empty());
  16792. EXPECT_EQ("example.com", uc.host);
  16793. EXPECT_EQ("/path", uc.path);
  16794. EXPECT_EQ("?q=1", uc.query);
  16795. }
  16796. {
  16797. detail::UrlComponents uc;
  16798. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  16799. EXPECT_TRUE(uc.host.empty());
  16800. EXPECT_EQ("/path", uc.path);
  16801. EXPECT_EQ("?q=1", uc.query);
  16802. }
  16803. {
  16804. detail::UrlComponents uc;
  16805. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  16806. EXPECT_EQ("example.com", uc.host);
  16807. EXPECT_EQ("8080", uc.port);
  16808. }
  16809. {
  16810. // Unix socket path — must not be parsed as host
  16811. detail::UrlComponents uc;
  16812. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  16813. EXPECT_TRUE(uc.host.empty());
  16814. }
  16815. {
  16816. detail::UrlComponents uc;
  16817. ASSERT_TRUE(detail::parse_url("", uc));
  16818. EXPECT_TRUE(uc.host.empty());
  16819. EXPECT_TRUE(uc.path.empty());
  16820. }
  16821. {
  16822. detail::UrlComponents uc;
  16823. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  16824. }
  16825. {
  16826. detail::UrlComponents uc;
  16827. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  16828. }
  16829. {
  16830. // Accepted by parse_url; callers restrict to http/https
  16831. detail::UrlComponents uc;
  16832. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  16833. EXPECT_EQ("ftp", uc.scheme);
  16834. }
  16835. {
  16836. detail::UrlComponents uc;
  16837. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  16838. }
  16839. {
  16840. detail::UrlComponents uc;
  16841. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  16842. }
  16843. }
  16844. TEST(ParseUrlTest, FragmentHandling) {
  16845. {
  16846. detail::UrlComponents uc;
  16847. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  16848. EXPECT_EQ("/path", uc.path);
  16849. EXPECT_TRUE(uc.query.empty());
  16850. }
  16851. {
  16852. detail::UrlComponents uc;
  16853. ASSERT_TRUE(detail::parse_url("#frag", uc));
  16854. EXPECT_TRUE(uc.path.empty());
  16855. EXPECT_TRUE(uc.query.empty());
  16856. }
  16857. }
  16858. TEST(ParseUrlTest, UserinfoHandling) {
  16859. // userinfo, and a backslash some parsers take for '/', are rejected: such
  16860. // parsers would see evil.com as the host.
  16861. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  16862. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  16863. for (auto url : urls) {
  16864. detail::UrlComponents uc;
  16865. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  16866. }
  16867. }
  16868. TEST(ParseUrlTest, IPv6EdgeCases) {
  16869. {
  16870. detail::UrlComponents uc;
  16871. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  16872. EXPECT_TRUE(uc.scheme.empty());
  16873. EXPECT_EQ("::1", uc.host);
  16874. EXPECT_EQ("8080", uc.port);
  16875. }
  16876. {
  16877. // Zone ID '%25' is not in [a-fA-F0-9:]
  16878. detail::UrlComponents uc;
  16879. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  16880. }
  16881. }
  16882. TEST(ParseUrlTest, SchemeEdgeCases) {
  16883. {
  16884. detail::UrlComponents uc;
  16885. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  16886. }
  16887. {
  16888. detail::UrlComponents uc;
  16889. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  16890. }
  16891. {
  16892. detail::UrlComponents uc;
  16893. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  16894. }
  16895. }
  16896. TEST(ParseUrlTest, PortEdgeCases) {
  16897. {
  16898. detail::UrlComponents uc;
  16899. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  16900. EXPECT_TRUE(uc.port.empty());
  16901. EXPECT_EQ("/path", uc.path);
  16902. }
  16903. {
  16904. // parse_url accepts any port string; validation is done by parse_port
  16905. detail::UrlComponents uc;
  16906. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  16907. EXPECT_EQ("abc", uc.port);
  16908. }
  16909. }
  16910. TEST(ParseUrlTest, WebSocketPatterns) {
  16911. {
  16912. detail::UrlComponents uc;
  16913. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  16914. EXPECT_EQ("ws", uc.scheme);
  16915. EXPECT_EQ("echo.example.com", uc.host);
  16916. EXPECT_EQ("8080", uc.port);
  16917. EXPECT_EQ("/ws", uc.path);
  16918. }
  16919. {
  16920. detail::UrlComponents uc;
  16921. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  16922. EXPECT_EQ("wss", uc.scheme);
  16923. EXPECT_EQ("echo.example.com", uc.host);
  16924. EXPECT_TRUE(uc.port.empty());
  16925. EXPECT_EQ("/ws", uc.path);
  16926. }
  16927. }
  16928. TEST(ParseUrlTest, QueryOnly) {
  16929. detail::UrlComponents uc;
  16930. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  16931. EXPECT_TRUE(uc.host.empty());
  16932. EXPECT_TRUE(uc.path.empty());
  16933. EXPECT_EQ("?q=1&r=2", uc.query);
  16934. }
  16935. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  16936. detail::UrlComponents uc;
  16937. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  16938. EXPECT_TRUE(uc.scheme.empty());
  16939. EXPECT_EQ("example.com", uc.host);
  16940. EXPECT_EQ("443", uc.port);
  16941. EXPECT_EQ("/path", uc.path);
  16942. }
  16943. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  16944. // If ipv6 regex working, regex match codepath is taken.
  16945. // else port will default to 80 in Client impl
  16946. int clientImplMagicPort = 80;
  16947. int port = 4321;
  16948. // above ports must be different to avoid false negative
  16949. EXPECT_NE(clientImplMagicPort, port);
  16950. std::string ipV6TestURL = "http://[ff06::c3]";
  16951. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  16952. CLIENT_PRIVATE_KEY_FILE);
  16953. EXPECT_EQ(cli.port(), port);
  16954. }
  16955. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  16956. auto file_path = "./www/dir/index.html";
  16957. auto dir_path = "./www/dir";
  16958. detail::FileStat stat_file(file_path);
  16959. EXPECT_TRUE(stat_file.is_file());
  16960. EXPECT_FALSE(stat_file.is_dir());
  16961. detail::FileStat stat_dir(dir_path);
  16962. EXPECT_FALSE(stat_dir.is_file());
  16963. EXPECT_TRUE(stat_dir.is_dir());
  16964. }
  16965. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  16966. // IPv4 with default HTTP port (80)
  16967. EXPECT_EQ("example.com",
  16968. detail::make_host_and_port_string("example.com", 80, false));
  16969. // IPv4 with default HTTPS port (443)
  16970. EXPECT_EQ("example.com",
  16971. detail::make_host_and_port_string("example.com", 443, true));
  16972. // IPv4 with non-default HTTP port
  16973. EXPECT_EQ("example.com:8080",
  16974. detail::make_host_and_port_string("example.com", 8080, false));
  16975. // IPv4 with non-default HTTPS port
  16976. EXPECT_EQ("example.com:8443",
  16977. detail::make_host_and_port_string("example.com", 8443, true));
  16978. // IPv6 with default HTTP port (80)
  16979. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  16980. // IPv6 with default HTTPS port (443)
  16981. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  16982. // IPv6 with non-default HTTP port
  16983. EXPECT_EQ("[::1]:8080",
  16984. detail::make_host_and_port_string("::1", 8080, false));
  16985. // IPv6 with non-default HTTPS port
  16986. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  16987. // IPv6 full address with default port
  16988. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  16989. detail::make_host_and_port_string(
  16990. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  16991. // IPv6 full address with non-default port
  16992. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  16993. detail::make_host_and_port_string(
  16994. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  16995. // IPv6 localhost with non-default port
  16996. EXPECT_EQ("[::1]:3000",
  16997. detail::make_host_and_port_string("::1", 3000, false));
  16998. // IPv6 with zone ID (link-local address) with default port
  16999. EXPECT_EQ("[fe80::1%eth0]",
  17000. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  17001. // IPv6 with zone ID (link-local address) with non-default port
  17002. EXPECT_EQ("[fe80::1%eth0]:8080",
  17003. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  17004. // Edge case: Port 443 with is_ssl=false (should add port)
  17005. EXPECT_EQ("example.com:443",
  17006. detail::make_host_and_port_string("example.com", 443, false));
  17007. // Edge case: Port 80 with is_ssl=true (should add port)
  17008. EXPECT_EQ("example.com:80",
  17009. detail::make_host_and_port_string("example.com", 80, true));
  17010. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  17011. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  17012. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  17013. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  17014. // Security fix: Already bracketed IPv6 should not get double brackets
  17015. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  17016. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  17017. EXPECT_EQ("[::1]:8080",
  17018. detail::make_host_and_port_string("[::1]", 8080, false));
  17019. EXPECT_EQ("[2001:db8::1]:8080",
  17020. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  17021. EXPECT_EQ("[fe80::1%eth0]",
  17022. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  17023. EXPECT_EQ("[fe80::1%eth0]:8080",
  17024. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  17025. // Edge case: Empty host (should return as-is)
  17026. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  17027. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  17028. // This is a known limitation but shouldn't crash
  17029. EXPECT_EQ("[host:name]",
  17030. detail::make_host_and_port_string("host:name", 80, false));
  17031. // Port number edge cases (no validation, but should not crash)
  17032. EXPECT_EQ("example.com:0",
  17033. detail::make_host_and_port_string("example.com", 0, false));
  17034. EXPECT_EQ("example.com:-1",
  17035. detail::make_host_and_port_string("example.com", -1, false));
  17036. EXPECT_EQ("example.com:65535",
  17037. detail::make_host_and_port_string("example.com", 65535, false));
  17038. EXPECT_EQ("example.com:65536",
  17039. detail::make_host_and_port_string("example.com", 65536, false));
  17040. }
  17041. #ifdef CPPHTTPLIB_SSL_ENABLED
  17042. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  17043. httplib::SSLClient cli("roblox.com", 443);
  17044. cli.set_follow_location(true);
  17045. auto res = cli.Get("/");
  17046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17047. EXPECT_EQ(StatusCode::OK_200, res->status);
  17048. }
  17049. #endif
  17050. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  17051. Server svr;
  17052. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17053. EXPECT_EQ(res.status, 400);
  17054. });
  17055. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17056. auto se = detail::scope_exit([&] {
  17057. svr.stop();
  17058. thread.join();
  17059. ASSERT_FALSE(svr.is_running());
  17060. });
  17061. svr.wait_until_ready();
  17062. Client cli(HOST, PORT);
  17063. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  17064. }
  17065. TEST(InvalidHeaderCharsTest, is_field_name) {
  17066. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  17067. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  17068. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  17069. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  17070. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  17071. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  17072. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  17073. EXPECT_FALSE(detail::fields::is_field_name(""));
  17074. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  17075. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  17076. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  17077. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  17078. }
  17079. TEST(InvalidHeaderCharsTest, is_field_value) {
  17080. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  17081. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  17082. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  17083. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  17084. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  17085. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  17086. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  17087. EXPECT_TRUE(detail::fields::is_field_value(""));
  17088. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  17089. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  17090. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  17091. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  17092. EXPECT_TRUE(detail::fields::is_field_value("0"));
  17093. }
  17094. TEST(InvalidHeaderCharsTest, OnServer) {
  17095. Server svr;
  17096. svr.Get("/test_name", [&](const Request &req, Response &res) {
  17097. std::string header = "Not Set";
  17098. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17099. res.set_header(header, "value");
  17100. res.set_content("Page Content Page Content", "text/plain");
  17101. });
  17102. svr.Get("/test_value", [&](const Request &req, Response &res) {
  17103. std::string header = "Not Set";
  17104. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17105. res.set_header("X-Test", header);
  17106. res.set_content("Page Content Page Content", "text/plain");
  17107. });
  17108. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17109. auto se = detail::scope_exit([&] {
  17110. svr.stop();
  17111. thread.join();
  17112. ASSERT_FALSE(svr.is_running());
  17113. });
  17114. svr.wait_until_ready();
  17115. Client cli(HOST, PORT);
  17116. {
  17117. auto res = cli.Get(
  17118. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17120. EXPECT_EQ("Page Content Page Content", res->body);
  17121. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17122. }
  17123. {
  17124. auto res = cli.Get(
  17125. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17127. EXPECT_EQ("Page Content Page Content", res->body);
  17128. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17129. }
  17130. }
  17131. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  17132. auto handled = false;
  17133. Server svr;
  17134. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17135. thread t = thread([&] { svr.listen(HOST, PORT); });
  17136. auto se = detail::scope_exit([&] {
  17137. svr.stop();
  17138. t.join();
  17139. ASSERT_FALSE(svr.is_running());
  17140. ASSERT_FALSE(handled);
  17141. });
  17142. svr.wait_until_ready();
  17143. auto req = "POST /test HTTP/1.1\r\n"
  17144. "Content-Length: x\r\n"
  17145. "\r\n";
  17146. std::string response;
  17147. ASSERT_TRUE(send_request(1, req, &response));
  17148. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17149. response.substr(0, response.find("\r\n")));
  17150. }
  17151. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  17152. // case-insensitive, and a server that receives a 100-continue expectation in
  17153. // an HTTP/1.0 request MUST ignore it.
  17154. static void probe_expect(int port, const std::string &req, bool *got_100) {
  17155. std::string response;
  17156. ASSERT_TRUE(send_request(1, req, &response, port));
  17157. *got_100 = response.find("100 Continue") != std::string::npos;
  17158. }
  17159. class ExpectTokenTest : public ::testing::Test {
  17160. protected:
  17161. void SetUp() override {
  17162. svr_.Post("/p", [](const Request &, Response &res) {
  17163. res.set_content("ok", "text/plain");
  17164. });
  17165. port_ = svr_.bind_to_any_port(HOST);
  17166. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17167. svr_.wait_until_ready();
  17168. }
  17169. void TearDown() override {
  17170. svr_.stop();
  17171. if (thread_.joinable()) { thread_.join(); }
  17172. }
  17173. std::string request(const char *version, const char *expect_value) const {
  17174. return std::string("POST /p ") + version +
  17175. "\r\n"
  17176. "Host: localhost\r\n"
  17177. "Content-Length: 2\r\n"
  17178. "Connection: close\r\n"
  17179. "Expect: " +
  17180. expect_value +
  17181. "\r\n"
  17182. "\r\n"
  17183. "hi";
  17184. }
  17185. Server svr_;
  17186. int port_ = 0;
  17187. thread thread_;
  17188. };
  17189. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  17190. bool got_100 = false;
  17191. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  17192. EXPECT_TRUE(got_100);
  17193. }
  17194. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  17195. bool got_100 = true;
  17196. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  17197. EXPECT_FALSE(got_100);
  17198. }
  17199. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  17200. bool got_100 = false;
  17201. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  17202. EXPECT_TRUE(got_100);
  17203. }
  17204. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  17205. bool got_100 = false;
  17206. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  17207. EXPECT_TRUE(got_100);
  17208. }
  17209. // `100 Continue` is sent only when the server starts reading the body, so a
  17210. // request rejected before that never invites the client to send it. The
  17211. // requests below carry the expectation but withhold the body, as a client
  17212. // waiting for `100 Continue` would.
  17213. // A POST that expects `100 Continue` and withholds its two-byte body.
  17214. static std::string expect_headers_only(const std::string &path) {
  17215. return "POST " + path +
  17216. " HTTP/1.1\r\n"
  17217. "Host: localhost\r\n"
  17218. "Content-Length: 2\r\n"
  17219. "Expect: 100-continue\r\n"
  17220. "\r\n";
  17221. }
  17222. class ExpectLazyContinueTest : public ::testing::Test {
  17223. protected:
  17224. void SetUp() override {
  17225. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  17226. if (req.path == "/pre-routing") {
  17227. res.status = StatusCode::Unauthorized_401;
  17228. return Server::HandlerResponse::Handled;
  17229. }
  17230. return Server::HandlerResponse::Unhandled;
  17231. });
  17232. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  17233. if (req.matched_route == "/pre-request") {
  17234. res.status = StatusCode::Forbidden_403;
  17235. return Server::HandlerResponse::Handled;
  17236. }
  17237. return Server::HandlerResponse::Unhandled;
  17238. });
  17239. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  17240. res.set_content("ok", "text/plain");
  17241. });
  17242. svr_.Post("/pre-request", [](const Request &, Response &res) {
  17243. res.set_content("ok", "text/plain");
  17244. });
  17245. svr_.Post("/reader-used", [](const Request &, Response &res,
  17246. const ContentReader &content_reader) {
  17247. std::string body;
  17248. content_reader([&](const char *data, size_t len) {
  17249. body.append(data, len);
  17250. return true;
  17251. });
  17252. res.set_content(body, "text/plain");
  17253. });
  17254. svr_.Post("/reader-unused",
  17255. [](const Request &, Response &res, const ContentReader &) {
  17256. res.set_content("ignored", "text/plain");
  17257. });
  17258. port_ = svr_.bind_to_any_port(HOST);
  17259. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17260. svr_.wait_until_ready();
  17261. }
  17262. void TearDown() override {
  17263. svr_.stop();
  17264. if (thread_.joinable()) { thread_.join(); }
  17265. }
  17266. // Sends `req` and reads until the server closes the connection. Returns
  17267. // false if the read had to wait for the client-side timeout instead.
  17268. bool send_until_closed(const std::string &req, std::string *resp) const {
  17269. auto start = std::chrono::steady_clock::now();
  17270. if (!send_request(3, req, resp, port_)) { return false; }
  17271. auto elapsed = std::chrono::steady_clock::now() - start;
  17272. return elapsed < std::chrono::seconds(2);
  17273. }
  17274. // The final response comes without `100 Continue`, and the server closes
  17275. // the connection since the body may or may not follow.
  17276. void expect_final_without_interim(const std::string &path,
  17277. const char *status_line) const {
  17278. std::string resp;
  17279. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  17280. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  17281. EXPECT_EQ(0u, resp.find(status_line));
  17282. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17283. }
  17284. Server svr_;
  17285. int port_ = 0;
  17286. thread thread_;
  17287. };
  17288. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  17289. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  17290. }
  17291. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  17292. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  17293. }
  17294. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  17295. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  17296. }
  17297. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  17298. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  17299. }
  17300. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  17301. // The body follows once `100 Continue` has had time to arrive.
  17302. auto req = expect_headers_only("/reader-used");
  17303. req.insert(req.size() - 2, "Connection: close\r\n");
  17304. std::string resp;
  17305. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  17306. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  17307. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  17308. EXPECT_NE(std::string::npos, resp.find("hi"));
  17309. }
  17310. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  17311. // Large enough for the client to add `Expect: 100-continue` itself.
  17312. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  17313. std::atomic<bool> body_sent{false};
  17314. Client cli(HOST, port_);
  17315. auto res = cli.Post(
  17316. "/pre-request", length,
  17317. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  17318. body_sent = true;
  17319. std::string chunk(len, 'x');
  17320. sink.write(chunk.data(), chunk.size());
  17321. return true;
  17322. },
  17323. "application/octet-stream");
  17324. ASSERT_TRUE(res);
  17325. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  17326. EXPECT_FALSE(body_sent);
  17327. }
  17328. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  17329. Server svr;
  17330. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  17331. return StatusCode::ExpectationFailed_417;
  17332. });
  17333. svr.Post("/p", [](const Request &, Response &res) {
  17334. res.set_content("ok", "text/plain");
  17335. });
  17336. auto port = svr.bind_to_any_port(HOST);
  17337. thread t = thread([&] { svr.listen_after_bind(); });
  17338. auto se = detail::scope_exit([&] {
  17339. svr.stop();
  17340. t.join();
  17341. });
  17342. svr.wait_until_ready();
  17343. std::string resp;
  17344. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  17345. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  17346. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17347. // Exactly one response: the route handler must not run after the 417.
  17348. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  17349. }
  17350. #ifndef _WIN32
  17351. TEST(Expect100ContinueTest, ServerClosesConnection) {
  17352. static constexpr char reject[] = "Unauthorized";
  17353. static constexpr char accept[] = "Upload accepted";
  17354. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  17355. Server svr;
  17356. svr.set_expect_100_continue_handler(
  17357. [](const Request & /*req*/, Response &res) {
  17358. res.status = StatusCode::Unauthorized_401;
  17359. res.set_content(reject, "text/plain");
  17360. return res.status;
  17361. });
  17362. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  17363. res.set_content(accept, "text/plain");
  17364. });
  17365. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17366. auto se = detail::scope_exit([&] {
  17367. svr.stop();
  17368. thread.join();
  17369. ASSERT_FALSE(svr.is_running());
  17370. });
  17371. svr.wait_until_ready();
  17372. {
  17373. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  17374. curl_easy_init(), &curl_easy_cleanup};
  17375. ASSERT_NE(curl, nullptr);
  17376. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  17377. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  17378. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  17379. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  17380. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  17381. &curl_slist_free_all};
  17382. ASSERT_NE(list, nullptr);
  17383. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  17384. struct read_data {
  17385. size_t read_size;
  17386. size_t total_size;
  17387. } data = {0, total_size};
  17388. using read_callback_t =
  17389. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17390. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  17391. void *userdata) -> size_t {
  17392. read_data *d = (read_data *)userdata;
  17393. if (!userdata || d->read_size >= d->total_size) { return 0; }
  17394. std::fill_n(ptr, size * nmemb, 'A');
  17395. d->read_size += size * nmemb;
  17396. return size * nmemb;
  17397. };
  17398. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  17399. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  17400. std::vector<char> buffer;
  17401. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  17402. using write_callback_t =
  17403. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17404. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  17405. void *userdata) -> size_t {
  17406. std::vector<char> *buf = (std::vector<char> *)userdata;
  17407. buf->reserve(buf->size() + size * nmemb + 1);
  17408. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  17409. return size * nmemb;
  17410. };
  17411. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  17412. {
  17413. const auto res = curl_easy_perform(curl.get());
  17414. ASSERT_EQ(res, CURLE_OK);
  17415. }
  17416. {
  17417. auto response_code = long{};
  17418. const auto res =
  17419. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  17420. ASSERT_EQ(res, CURLE_OK);
  17421. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  17422. }
  17423. {
  17424. auto dl = curl_off_t{};
  17425. const auto res =
  17426. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  17427. ASSERT_EQ(res, CURLE_OK);
  17428. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  17429. }
  17430. {
  17431. buffer.push_back('\0');
  17432. ASSERT_STRCASEEQ(buffer.data(), reject);
  17433. }
  17434. }
  17435. }
  17436. #endif
  17437. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  17438. // Regression test for #2458.
  17439. //
  17440. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  17441. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  17442. // ticket can make the client socket spuriously readable during the
  17443. // 100-continue wait. If the readiness is mistaken for an incoming response,
  17444. // the client withholds the body and then blocks reading a response that never
  17445. // comes, failing with `Failed to read connection`.
  17446. //
  17447. // A correct client (like curl) sends the body once no `100 Continue` arrives
  17448. // within the timeout. This raw OpenSSL server deliberately never sends
  17449. // `100 Continue`; the client must still deliver the body and receive 200.
  17450. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  17451. signal(SIGPIPE, SIG_IGN);
  17452. const auto port = PORT + 4;
  17453. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17454. ASSERT_NE(srv, INVALID_SOCKET);
  17455. int opt = 1;
  17456. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  17457. sockaddr_in addr{};
  17458. addr.sin_family = AF_INET;
  17459. addr.sin_port = htons(static_cast<uint16_t>(port));
  17460. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17461. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17462. ASSERT_EQ(0, ::listen(srv, 1));
  17463. std::atomic<size_t> server_body_bytes{0};
  17464. auto server_thread = std::thread([&] {
  17465. sockaddr_in cli_addr{};
  17466. socklen_t cli_len = sizeof(cli_addr);
  17467. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17468. if (cli == INVALID_SOCKET) { return; }
  17469. // Bound the lifetime of the server side so a buggy client (which never
  17470. // sends the body) cannot make this thread block forever on join.
  17471. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  17472. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  17473. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  17474. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  17475. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  17476. SSL *ssl = SSL_new(ctx);
  17477. SSL_set_fd(ssl, static_cast<int>(cli));
  17478. if (SSL_accept(ssl) > 0) {
  17479. // Read the request headers. Reading here also flushes the TLS 1.3
  17480. // session tickets to the client. Deliberately do NOT send
  17481. // `100 Continue`.
  17482. std::string buf;
  17483. char tmp[1024];
  17484. while (buf.find("\r\n\r\n") == std::string::npos) {
  17485. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17486. if (n <= 0) { break; }
  17487. buf.append(tmp, static_cast<size_t>(n));
  17488. }
  17489. // A correct client sends the body now; count what arrives.
  17490. auto pos = buf.find("\r\n\r\n");
  17491. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  17492. while (body < 4096) {
  17493. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17494. if (n <= 0) { break; }
  17495. body += static_cast<size_t>(n);
  17496. }
  17497. server_body_bytes = body;
  17498. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  17499. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  17500. SSL_shutdown(ssl);
  17501. }
  17502. SSL_free(ssl);
  17503. detail::close_socket(cli);
  17504. SSL_CTX_free(ctx);
  17505. });
  17506. auto se = detail::scope_exit([&] {
  17507. server_thread.join();
  17508. detail::close_socket(srv);
  17509. });
  17510. SSLClient cli("127.0.0.1", port);
  17511. cli.enable_server_certificate_verification(false);
  17512. cli.set_connection_timeout(5, 0);
  17513. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  17514. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  17515. std::string body(4096, 'A');
  17516. auto res = cli.Put("/api/test", body, "application/json");
  17517. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  17518. EXPECT_EQ(StatusCode::OK_200, res->status);
  17519. EXPECT_EQ(body.size(), server_body_bytes.load());
  17520. }
  17521. #endif
  17522. template <typename S, typename C>
  17523. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  17524. svr.Get("/stream", [&](const Request &, Response &res) {
  17525. auto data = new std::string("01234567890123456789");
  17526. res.set_content_provider(
  17527. data->size(), "text/plain",
  17528. [&, data](size_t offset, size_t length, DataSink &sink) {
  17529. const size_t DATA_CHUNK_SIZE = 4;
  17530. const auto &d = *data;
  17531. std::this_thread::sleep_for(std::chrono::seconds(1));
  17532. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  17533. return true;
  17534. },
  17535. [data](bool success) {
  17536. EXPECT_FALSE(success);
  17537. delete data;
  17538. });
  17539. });
  17540. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  17541. auto i = new size_t(0);
  17542. res.set_content_provider(
  17543. "text/plain",
  17544. [i](size_t, DataSink &sink) {
  17545. if (*i < 5) {
  17546. std::this_thread::sleep_for(std::chrono::seconds(1));
  17547. sink.write("abcd", 4);
  17548. (*i)++;
  17549. } else {
  17550. sink.done();
  17551. }
  17552. return true;
  17553. },
  17554. [i](bool success) {
  17555. EXPECT_FALSE(success);
  17556. delete i;
  17557. });
  17558. });
  17559. svr.Get("/chunked", [&](const Request &, Response &res) {
  17560. auto i = new size_t(0);
  17561. res.set_chunked_content_provider(
  17562. "text/plain",
  17563. [i](size_t, DataSink &sink) {
  17564. if (*i < 5) {
  17565. std::this_thread::sleep_for(std::chrono::seconds(1));
  17566. sink.os << "abcd";
  17567. (*i)++;
  17568. } else {
  17569. sink.done();
  17570. }
  17571. return true;
  17572. },
  17573. [i](bool success) {
  17574. EXPECT_FALSE(success);
  17575. delete i;
  17576. });
  17577. });
  17578. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  17579. auto se = detail::scope_exit([&] {
  17580. svr.stop();
  17581. listen_thread.join();
  17582. ASSERT_FALSE(svr.is_running());
  17583. });
  17584. svr.wait_until_ready();
  17585. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  17586. {
  17587. auto start = std::chrono::steady_clock::now();
  17588. auto res = cli.Get("/stream");
  17589. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17590. std::chrono::steady_clock::now() - start)
  17591. .count();
  17592. ASSERT_FALSE(res);
  17593. EXPECT_EQ(Error::Read, res.error());
  17594. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17595. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17596. }
  17597. {
  17598. auto start = std::chrono::steady_clock::now();
  17599. auto res = cli.Get("/stream_without_length");
  17600. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17601. std::chrono::steady_clock::now() - start)
  17602. .count();
  17603. ASSERT_FALSE(res);
  17604. EXPECT_EQ(Error::Read, res.error());
  17605. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17606. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17607. }
  17608. {
  17609. auto start = std::chrono::steady_clock::now();
  17610. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  17611. EXPECT_EQ("abcd", string(data, data_length));
  17612. return true;
  17613. });
  17614. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17615. std::chrono::steady_clock::now() - start)
  17616. .count();
  17617. ASSERT_FALSE(res);
  17618. EXPECT_EQ(Error::Read, res.error());
  17619. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17620. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17621. }
  17622. }
  17623. TEST(MaxTimeoutTest, ContentStream) {
  17624. time_t timeout = 2000;
  17625. time_t threshold = 200;
  17626. Server svr;
  17627. Client cli("localhost", PORT);
  17628. max_timeout_test(svr, cli, timeout, threshold);
  17629. }
  17630. #ifdef CPPHTTPLIB_SSL_ENABLED
  17631. TEST(MaxTimeoutTest, ContentStreamSSL) {
  17632. time_t timeout = 2000;
  17633. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  17634. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17635. SSLClient cli("localhost", PORT);
  17636. cli.enable_server_certificate_verification(false);
  17637. max_timeout_test(svr, cli, timeout, threshold);
  17638. }
  17639. #endif
  17640. class EventDispatcher {
  17641. public:
  17642. EventDispatcher() {}
  17643. bool wait_event(DataSink *sink) {
  17644. unique_lock<mutex> lk(m_);
  17645. int id = id_;
  17646. // Wait with timeout to prevent hanging if client disconnects
  17647. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  17648. [&] { return cid_ == id; })) {
  17649. return false; // Timeout occurred
  17650. }
  17651. sink->write(message_.data(), message_.size());
  17652. return true;
  17653. }
  17654. void send_event(const string &message) {
  17655. lock_guard<mutex> lk(m_);
  17656. cid_ = id_++;
  17657. message_ = message;
  17658. cv_.notify_all();
  17659. }
  17660. private:
  17661. mutex m_;
  17662. condition_variable cv_;
  17663. atomic_int id_{0};
  17664. atomic_int cid_{-1};
  17665. string message_;
  17666. };
  17667. TEST(ClientInThreadTest, Issue2068) {
  17668. EventDispatcher ed;
  17669. Server svr;
  17670. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  17671. res.set_chunked_content_provider("text/event-stream",
  17672. [&](size_t /*offset*/, DataSink &sink) {
  17673. return ed.wait_event(&sink);
  17674. });
  17675. });
  17676. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  17677. svr.wait_until_ready();
  17678. thread event_thread([&] {
  17679. int id = 0;
  17680. while (svr.is_running()) {
  17681. this_thread::sleep_for(chrono::milliseconds(500));
  17682. std::stringstream ss;
  17683. ss << "data: " << id << "\n\n";
  17684. ed.send_event(ss.str());
  17685. id++;
  17686. }
  17687. });
  17688. auto se = detail::scope_exit([&] {
  17689. svr.stop();
  17690. listen_thread.join();
  17691. event_thread.join();
  17692. ASSERT_FALSE(svr.is_running());
  17693. });
  17694. {
  17695. auto client = detail::make_unique<Client>(HOST, PORT);
  17696. client->set_read_timeout(std::chrono::minutes(10));
  17697. std::atomic<bool> stop{false};
  17698. std::thread t([&] {
  17699. client->Get("/event1",
  17700. [&](const char *, size_t) -> bool { return !stop; });
  17701. });
  17702. std::this_thread::sleep_for(std::chrono::seconds(2));
  17703. stop = true;
  17704. client->stop();
  17705. t.join();
  17706. // Reset client after thread has finished
  17707. client.reset();
  17708. }
  17709. }
  17710. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  17711. auto handled = false;
  17712. Server svr;
  17713. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17714. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17715. auto se = detail::scope_exit([&] {
  17716. svr.stop();
  17717. t.join();
  17718. ASSERT_FALSE(svr.is_running());
  17719. ASSERT_FALSE(handled);
  17720. });
  17721. svr.wait_until_ready();
  17722. // Two Content-Length headers with different values — must be rejected
  17723. auto req = "POST /test HTTP/1.1\r\n"
  17724. "Content-Length: 5\r\n"
  17725. "Content-Length: 10\r\n"
  17726. "\r\n"
  17727. "hello";
  17728. std::string response;
  17729. ASSERT_TRUE(send_request(1, req, &response));
  17730. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17731. response.substr(0, response.find("\r\n")));
  17732. }
  17733. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  17734. auto handled = false;
  17735. Server svr;
  17736. svr.Post("/test", [&](const Request &, Response &res) {
  17737. handled = true;
  17738. res.set_content("ok", "text/plain");
  17739. });
  17740. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17741. auto se = detail::scope_exit([&] {
  17742. svr.stop();
  17743. t.join();
  17744. ASSERT_FALSE(svr.is_running());
  17745. ASSERT_TRUE(handled);
  17746. });
  17747. svr.wait_until_ready();
  17748. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  17749. auto req = "POST /test HTTP/1.1\r\n"
  17750. "Host: localhost\r\n"
  17751. "Content-Length: 5\r\n"
  17752. "Content-Length: 5\r\n"
  17753. "\r\n"
  17754. "hello";
  17755. std::string response;
  17756. ASSERT_TRUE(send_request(1, req, &response));
  17757. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  17758. }
  17759. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  17760. Server svr;
  17761. svr.Get("/test", [](const Request &, Response &res) {
  17762. res.set_content("ok", "text/plain");
  17763. });
  17764. auto port = svr.bind_to_any_port(HOST);
  17765. thread t = thread([&] { svr.listen_after_bind(); });
  17766. auto se = detail::scope_exit([&] {
  17767. svr.stop();
  17768. t.join();
  17769. ASSERT_FALSE(svr.is_running());
  17770. });
  17771. svr.wait_until_ready();
  17772. auto status_line = [&](const std::string &host_lines) {
  17773. std::string res;
  17774. send_request(
  17775. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  17776. &res, port);
  17777. return res.substr(0, res.find("\r\n"));
  17778. };
  17779. const char *accepted[] = {
  17780. "Host: localhost\r\n",
  17781. "Host: a.example:8080\r\n",
  17782. "Host: my_service\r\n",
  17783. "Host: [::1]:8080\r\n",
  17784. "Host: [fe80::1%25eth0]\r\n",
  17785. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  17786. };
  17787. for (auto host_lines : accepted) {
  17788. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  17789. }
  17790. const char *rejected[] = {
  17791. "Host: a.example\r\nHost: b.example\r\n",
  17792. "Host: a.example\r\nHost: a.example\r\n",
  17793. "Host: a@b.example\r\n",
  17794. "Host: a.example/b\r\n",
  17795. "Host: a.example\\b\r\n",
  17796. "Host: a.example?b\r\n",
  17797. "Host: a.example#b\r\n",
  17798. "Host: a.example b.example\r\n",
  17799. };
  17800. for (auto host_lines : rejected) {
  17801. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  17802. << host_lines;
  17803. }
  17804. }
  17805. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  17806. Server svr;
  17807. svr.Get("/", [](const Request &req, Response &res) {
  17808. EXPECT_EQ(2U, req.trailers.size());
  17809. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  17810. // Denied
  17811. EXPECT_FALSE(req.has_trailer("Content-Length"));
  17812. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  17813. // Accepted
  17814. EXPECT_TRUE(req.has_trailer("X-Hello"));
  17815. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  17816. EXPECT_TRUE(req.has_trailer("X-World"));
  17817. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  17818. res.set_content("ok", "text/plain");
  17819. });
  17820. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17821. auto se = detail::scope_exit([&] {
  17822. svr.stop();
  17823. t.join();
  17824. ASSERT_FALSE(svr.is_running());
  17825. });
  17826. svr.wait_until_ready();
  17827. const std::string req = "GET / HTTP/1.1\r\n"
  17828. "Transfer-Encoding: chunked\r\n"
  17829. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  17830. "\r\n"
  17831. "0\r\n"
  17832. "Content-Length: 10\r\n"
  17833. "Host: internal.local\r\n"
  17834. "Content-Type: malicious/content\r\n"
  17835. "Cookie: any\r\n"
  17836. "Set-Cookie: any\r\n"
  17837. "X-Forwarded-For: attacker.com\r\n"
  17838. "X-Real-Ip: 1.1.1.1\r\n"
  17839. "X-Hello: hello\r\n"
  17840. "X-World: world\r\n"
  17841. "\r\n";
  17842. std::string res;
  17843. ASSERT_TRUE(send_request(1, req, &res));
  17844. }
  17845. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  17846. // several field lines, and the combined value is what has to be parsed. A
  17847. // Trailer field split across lines therefore declares every name it lists;
  17848. // reading only the first line silently drops the trailers the later lines
  17849. // declare. The prohibited-trailer filter still applies to every line.
  17850. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  17851. Server svr;
  17852. size_t observed_trailer_count = 0;
  17853. std::string observed_hello;
  17854. std::string observed_world;
  17855. bool observed_content_length = true;
  17856. svr.Get("/", [&](const Request &req, Response &res) {
  17857. observed_trailer_count = req.trailers.size();
  17858. observed_hello = req.get_trailer_value("X-Hello");
  17859. observed_world = req.get_trailer_value("X-World");
  17860. observed_content_length = req.has_trailer("Content-Length");
  17861. res.set_content("ok", "text/plain");
  17862. });
  17863. auto port = svr.bind_to_any_port(HOST);
  17864. thread t = thread([&]() { svr.listen_after_bind(); });
  17865. auto se = detail::scope_exit([&] {
  17866. svr.stop();
  17867. t.join();
  17868. ASSERT_FALSE(svr.is_running());
  17869. });
  17870. svr.wait_until_ready();
  17871. const std::string req = "GET / HTTP/1.1\r\n"
  17872. "Host: localhost\r\n"
  17873. "Transfer-Encoding: chunked\r\n"
  17874. "Trailer: X-Hello\r\n"
  17875. "Trailer: X-World, Content-Length\r\n"
  17876. "\r\n"
  17877. "0\r\n"
  17878. "X-Hello: hello\r\n"
  17879. "X-World: world\r\n"
  17880. "Content-Length: 10\r\n"
  17881. "\r\n";
  17882. std::string res;
  17883. ASSERT_TRUE(send_request(1, req, &res, port));
  17884. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  17885. // Accepted: both field lines contribute to the declared set
  17886. EXPECT_EQ(2U, observed_trailer_count);
  17887. EXPECT_EQ(observed_hello, "hello");
  17888. EXPECT_EQ(observed_world, "world");
  17889. // Denied: a prohibited name stays prohibited on a later field line
  17890. EXPECT_FALSE(observed_content_length);
  17891. }
  17892. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  17893. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  17894. // unbounded run of fields that are never declared, because the counter would
  17895. // only advance for declared fields.
  17896. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  17897. Server svr;
  17898. bool handler_called = false;
  17899. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  17900. handler_called = true;
  17901. res.set_content("ok", "text/plain");
  17902. });
  17903. auto port = svr.bind_to_any_port(HOST);
  17904. thread t = thread([&]() { svr.listen_after_bind(); });
  17905. auto se = detail::scope_exit([&] {
  17906. svr.stop();
  17907. t.join();
  17908. ASSERT_FALSE(svr.is_running());
  17909. });
  17910. svr.wait_until_ready();
  17911. // Declare nothing, then send far more undeclared trailer fields than the
  17912. // header-count limit. Parsing must stop and reject the request rather than
  17913. // read every line.
  17914. std::string req = "GET / HTTP/1.1\r\n"
  17915. "Transfer-Encoding: chunked\r\n"
  17916. "\r\n"
  17917. "0\r\n";
  17918. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  17919. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  17920. }
  17921. req += "\r\n";
  17922. std::string res;
  17923. ASSERT_TRUE(send_request(1, req, &res, port));
  17924. // The request is rejected before the handler runs.
  17925. EXPECT_FALSE(handler_called);
  17926. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  17927. }
  17928. // The set of declared trailer names is capped so a peer cannot grow it without
  17929. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  17930. // declared past the cap is not honored, even if the field is actually sent.
  17931. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  17932. Server svr;
  17933. // One name inside the cap and one past it, so the test tracks the cap rather
  17934. // than a fixed count.
  17935. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  17936. const std::string within_cap_name = "X-T-0";
  17937. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  17938. bool observed_within_cap = false;
  17939. bool observed_past_cap = false;
  17940. svr.Get("/", [&](const Request &req, Response &res) {
  17941. observed_within_cap = req.has_trailer(within_cap_name);
  17942. observed_past_cap = req.has_trailer(past_cap_name);
  17943. res.set_content("ok", "text/plain");
  17944. });
  17945. auto port = svr.bind_to_any_port(HOST);
  17946. thread t = thread([&]() { svr.listen_after_bind(); });
  17947. auto se = detail::scope_exit([&] {
  17948. svr.stop();
  17949. t.join();
  17950. ASSERT_FALSE(svr.is_running());
  17951. });
  17952. svr.wait_until_ready();
  17953. // Declare more trailer names than the cap in a single Trailer field, then
  17954. // actually send the first (within the cap) and the last (past it).
  17955. std::string trailer_decl = "Trailer: ";
  17956. for (int i = 0; i < declared_count; i++) {
  17957. if (i != 0) { trailer_decl += ", "; }
  17958. trailer_decl += "X-T-" + std::to_string(i);
  17959. }
  17960. trailer_decl += "\r\n";
  17961. const std::string req = "GET / HTTP/1.1\r\n"
  17962. "Host: localhost\r\n"
  17963. "Transfer-Encoding: chunked\r\n" +
  17964. trailer_decl +
  17965. "\r\n"
  17966. "0\r\n" +
  17967. within_cap_name + ": a\r\n" + past_cap_name +
  17968. ": b\r\n"
  17969. "\r\n";
  17970. std::string res;
  17971. ASSERT_TRUE(send_request(1, req, &res, port));
  17972. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  17973. // A name within the cap is honored; one declared past the cap is dropped.
  17974. EXPECT_TRUE(observed_within_cap);
  17975. EXPECT_FALSE(observed_past_cap);
  17976. }
  17977. // A direct client that is not listed in trusted_proxies must not be able to
  17978. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  17979. // the peer address on the actual TCP connection determines whether the
  17980. // header is honored.
  17981. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  17982. Server svr;
  17983. // Deliberately does NOT include the loopback address the test client
  17984. // actually connects from, so the direct connection is not a trusted proxy.
  17985. svr.set_trusted_proxies({"203.0.113.66"});
  17986. std::string observed_remote_addr;
  17987. svr.Get("/ip", [&](const Request &req, Response &res) {
  17988. observed_remote_addr = req.remote_addr;
  17989. res.set_content("ok", "text/plain");
  17990. });
  17991. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17992. auto se = detail::scope_exit([&] {
  17993. svr.stop();
  17994. t.join();
  17995. ASSERT_FALSE(svr.is_running());
  17996. });
  17997. svr.wait_until_ready();
  17998. Client cli(HOST, PORT);
  17999. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  18000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18001. EXPECT_EQ(StatusCode::OK_200, res->status);
  18002. // The connecting peer is not a trusted proxy, so the spoofed header must be
  18003. // ignored entirely and the real connection-level address retained.
  18004. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18005. observed_remote_addr == "127.0.0.1");
  18006. }
  18007. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  18008. Server svr;
  18009. std::string observed_remote_addr;
  18010. std::string observed_xff;
  18011. svr.Get("/ip", [&](const Request &req, Response &res) {
  18012. observed_remote_addr = req.remote_addr;
  18013. observed_xff = req.get_header_value("X-Forwarded-For");
  18014. res.set_content("ok", "text/plain");
  18015. });
  18016. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18017. auto se = detail::scope_exit([&] {
  18018. svr.stop();
  18019. t.join();
  18020. ASSERT_FALSE(svr.is_running());
  18021. });
  18022. svr.wait_until_ready();
  18023. Client cli(HOST, PORT);
  18024. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  18025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18026. EXPECT_EQ(StatusCode::OK_200, res->status);
  18027. EXPECT_EQ(observed_xff, "203.0.113.66");
  18028. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18029. observed_remote_addr == "127.0.0.1");
  18030. }
  18031. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  18032. Server svr;
  18033. svr.set_trusted_proxies({"203.0.113.66"});
  18034. std::string observed_remote_addr;
  18035. std::string observed_xff;
  18036. svr.Get("/ip", [&](const Request &req, Response &res) {
  18037. observed_remote_addr = req.remote_addr;
  18038. observed_xff = req.get_header_value("X-Forwarded-For");
  18039. res.set_content("ok", "text/plain");
  18040. });
  18041. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18042. auto se = detail::scope_exit([&] {
  18043. svr.stop();
  18044. t.join();
  18045. ASSERT_FALSE(svr.is_running());
  18046. });
  18047. svr.wait_until_ready();
  18048. Client cli(HOST, PORT);
  18049. auto res = cli.Get("/ip");
  18050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18051. EXPECT_EQ(StatusCode::OK_200, res->status);
  18052. EXPECT_EQ(observed_xff, "");
  18053. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18054. observed_remote_addr == "127.0.0.1");
  18055. }
  18056. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  18057. Server svr;
  18058. // Include the loopback address the test client actually connects from, so
  18059. // the direct connection itself is recognized as the trusted proxy hop.
  18060. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  18061. std::string observed_remote_addr;
  18062. std::string observed_xff;
  18063. svr.Get("/ip", [&](const Request &req, Response &res) {
  18064. observed_remote_addr = req.remote_addr;
  18065. observed_xff = req.get_header_value("X-Forwarded-For");
  18066. res.set_content("ok", "text/plain");
  18067. });
  18068. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18069. auto se = detail::scope_exit([&] {
  18070. svr.stop();
  18071. t.join();
  18072. ASSERT_FALSE(svr.is_running());
  18073. });
  18074. svr.wait_until_ready();
  18075. Client cli(HOST, PORT);
  18076. auto res = cli.Get(
  18077. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  18078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18079. EXPECT_EQ(StatusCode::OK_200, res->status);
  18080. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  18081. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18082. }
  18083. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  18084. Server svr;
  18085. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  18086. std::string observed_remote_addr;
  18087. std::string observed_xff;
  18088. svr.Get("/ip", [&](const Request &req, Response &res) {
  18089. observed_remote_addr = req.remote_addr;
  18090. observed_xff = req.get_header_value("X-Forwarded-For");
  18091. res.set_content("ok", "text/plain");
  18092. });
  18093. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18094. auto se = detail::scope_exit([&] {
  18095. svr.stop();
  18096. t.join();
  18097. ASSERT_FALSE(svr.is_running());
  18098. });
  18099. svr.wait_until_ready();
  18100. Client cli(HOST, PORT);
  18101. auto res = cli.Get(
  18102. "/ip",
  18103. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18105. EXPECT_EQ(StatusCode::OK_200, res->status);
  18106. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18107. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18108. }
  18109. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  18110. Server svr;
  18111. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18112. std::string observed_remote_addr;
  18113. std::string observed_xff;
  18114. svr.Get("/ip", [&](const Request &req, Response &res) {
  18115. observed_remote_addr = req.remote_addr;
  18116. observed_xff = req.get_header_value("X-Forwarded-For");
  18117. res.set_content("ok", "text/plain");
  18118. });
  18119. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18120. auto se = detail::scope_exit([&] {
  18121. svr.stop();
  18122. t.join();
  18123. ASSERT_FALSE(svr.is_running());
  18124. });
  18125. svr.wait_until_ready();
  18126. Client cli(HOST, PORT);
  18127. auto res = cli.Get(
  18128. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  18129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18130. EXPECT_EQ(StatusCode::OK_200, res->status);
  18131. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  18132. // by the closest hop) is used. The leftmost entry is fully client-controlled
  18133. // and must not be selected.
  18134. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  18135. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  18136. }
  18137. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  18138. Server svr;
  18139. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  18140. std::string observed_remote_addr;
  18141. svr.Get("/ip", [&](const Request &req, Response &res) {
  18142. observed_remote_addr = req.remote_addr;
  18143. res.set_content("ok", "text/plain");
  18144. });
  18145. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18146. auto se = detail::scope_exit([&] {
  18147. svr.stop();
  18148. t.join();
  18149. ASSERT_FALSE(svr.is_running());
  18150. });
  18151. svr.wait_until_ready();
  18152. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  18153. // a forged address and the trusted proxy's own address; the forged value must
  18154. // not win over the address the trusted proxy actually recorded.
  18155. Client cli(HOST, PORT);
  18156. auto res = cli.Get(
  18157. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  18158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18159. EXPECT_EQ(StatusCode::OK_200, res->status);
  18160. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  18161. }
  18162. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  18163. Server svr;
  18164. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18165. std::string observed_remote_addr;
  18166. std::string observed_xff;
  18167. svr.Get("/ip", [&](const Request &req, Response &res) {
  18168. observed_remote_addr = req.remote_addr;
  18169. observed_xff = req.get_header_value("X-Forwarded-For");
  18170. res.set_content("ok", "text/plain");
  18171. });
  18172. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18173. auto se = detail::scope_exit([&] {
  18174. svr.stop();
  18175. t.join();
  18176. ASSERT_FALSE(svr.is_running());
  18177. });
  18178. svr.wait_until_ready();
  18179. Client cli(HOST, PORT);
  18180. auto res = cli.Get(
  18181. "/ip",
  18182. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18184. EXPECT_EQ(StatusCode::OK_200, res->status);
  18185. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18186. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18187. }
  18188. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  18189. Server svr;
  18190. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18191. std::string observed_remote_addr;
  18192. std::string observed_xff;
  18193. svr.Get("/ip", [&](const Request &req, Response &res) {
  18194. observed_remote_addr = req.remote_addr;
  18195. observed_xff = req.get_header_value("X-Forwarded-For");
  18196. res.set_content("ok", "text/plain");
  18197. });
  18198. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18199. auto se = detail::scope_exit([&] {
  18200. svr.stop();
  18201. t.join();
  18202. ASSERT_FALSE(svr.is_running());
  18203. });
  18204. svr.wait_until_ready();
  18205. std::string raw_req =
  18206. "GET /ip HTTP/1.1\r\n"
  18207. "Host: localhost\r\n"
  18208. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  18209. "Connection: close\r\n"
  18210. "\r\n";
  18211. std::string out;
  18212. ASSERT_TRUE(send_request(5, raw_req, &out));
  18213. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18214. // Header parser trims surrounding whitespace of the header value
  18215. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  18216. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18217. }
  18218. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  18219. // one comma-joined value, in the order received. Proxies such as HAProxy append
  18220. // their own X-Forwarded-For as a separate field line rather than extending the
  18221. // one the client sent, so every occurrence has to be taken into account.
  18222. // Reading only the first one hands back the address the client chose.
  18223. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  18224. Server svr;
  18225. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18226. std::string observed_remote_addr;
  18227. size_t observed_xff_count = 0;
  18228. svr.Get("/ip", [&](const Request &req, Response &res) {
  18229. observed_remote_addr = req.remote_addr;
  18230. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  18231. res.set_content("ok", "text/plain");
  18232. });
  18233. auto port = svr.bind_to_any_port(HOST);
  18234. thread t = thread([&]() { svr.listen_after_bind(); });
  18235. auto se = detail::scope_exit([&] {
  18236. svr.stop();
  18237. t.join();
  18238. ASSERT_FALSE(svr.is_running());
  18239. });
  18240. svr.wait_until_ready();
  18241. // The client supplies the first field line; the trusted proxy appends the
  18242. // address it observed as a second one.
  18243. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  18244. "Host: localhost\r\n"
  18245. "X-Forwarded-For: 1.2.3.4\r\n"
  18246. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  18247. "Connection: close\r\n"
  18248. "\r\n";
  18249. std::string out;
  18250. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18251. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18252. EXPECT_EQ(observed_xff_count, 2U);
  18253. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18254. // The same chain spread over one field line per hop derives the same client
  18255. // address, i.e. the split and the comma-joined representations agree.
  18256. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  18257. "Host: localhost\r\n"
  18258. "X-Forwarded-For: 1.2.3.4\r\n"
  18259. "X-Forwarded-For: 198.51.100.23\r\n"
  18260. "X-Forwarded-For: 192.0.2.45\r\n"
  18261. "Connection: close\r\n"
  18262. "\r\n";
  18263. out.clear();
  18264. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  18265. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18266. EXPECT_EQ(observed_xff_count, 3U);
  18267. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18268. }
  18269. // An X-Forwarded-For header whose value parses to zero IP segments must not
  18270. // crash the server (it used to call front() on an empty vector inside
  18271. // get_client_ip). The connection-level remote address must be retained instead.
  18272. static void run_malformed_xff_test(const std::string &xff_value) {
  18273. Server svr;
  18274. svr.set_trusted_proxies({"192.0.2.45"});
  18275. std::string observed_remote_addr;
  18276. svr.Get("/ip", [&](const Request &req, Response &res) {
  18277. observed_remote_addr = req.remote_addr;
  18278. res.set_content("ok", "text/plain");
  18279. });
  18280. int port = 0;
  18281. thread t = thread([&]() {
  18282. port = svr.bind_to_any_port(HOST);
  18283. svr.listen_after_bind();
  18284. });
  18285. auto se = detail::scope_exit([&] {
  18286. svr.stop();
  18287. t.join();
  18288. ASSERT_FALSE(svr.is_running());
  18289. });
  18290. svr.wait_until_ready();
  18291. Client cli(HOST, port);
  18292. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  18293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18294. EXPECT_EQ(StatusCode::OK_200, res->status);
  18295. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18296. observed_remote_addr == "127.0.0.1");
  18297. }
  18298. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  18299. run_malformed_xff_test("");
  18300. }
  18301. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  18302. run_malformed_xff_test(",");
  18303. }
  18304. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  18305. run_malformed_xff_test(", , ,");
  18306. }
  18307. // The same rule applies to Accept: a request whose acceptable types are spread
  18308. // over several field lines must be negotiated against all of them.
  18309. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  18310. // case-insensitive connection options. Comparing the whole field value against
  18311. // one option misses a client that sends several of them, and misses every
  18312. // casing but the one written in the comparison.
  18313. //
  18314. // Sends req, reads the response, then reuses the same socket for a second
  18315. // request to find out whether the server kept the connection.
  18316. static void probe_connection_reuse(int port, const std::string &req,
  18317. bool *announced_close, bool *reusable) {
  18318. auto error = Error::Success;
  18319. auto sock = detail::create_client_socket(
  18320. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18321. /*connection_timeout_sec=*/5, 0,
  18322. /*read_timeout_sec=*/1, 0,
  18323. /*write_timeout_sec=*/5, 0, std::string(), error);
  18324. ASSERT_NE(sock, INVALID_SOCKET);
  18325. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  18326. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  18327. "Host: localhost\r\n"
  18328. "Connection: close\r\n"
  18329. "\r\n";
  18330. std::string first_response;
  18331. std::string second_response;
  18332. detail::process_client_socket(
  18333. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  18334. [&](Stream &strm) {
  18335. if (strm.write(req.data(), req.size()) !=
  18336. static_cast<ssize_t>(req.size())) {
  18337. return false;
  18338. }
  18339. char buf[512];
  18340. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  18341. // Headers plus the two-byte body of the handler below
  18342. while (reader.getline()) {
  18343. first_response += reader.ptr();
  18344. if (first_response.find("ok") != std::string::npos) { break; }
  18345. }
  18346. if (strm.write(second.data(), second.size()) !=
  18347. static_cast<ssize_t>(second.size())) {
  18348. return true;
  18349. }
  18350. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  18351. while (reader2.getline()) {
  18352. second_response += reader2.ptr();
  18353. if (second_response.find("ok") != std::string::npos) { break; }
  18354. }
  18355. return true;
  18356. });
  18357. *announced_close =
  18358. first_response.find("Connection: close") != std::string::npos;
  18359. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  18360. }
  18361. class ConnectionTokenTest : public ::testing::Test {
  18362. protected:
  18363. void SetUp() override {
  18364. svr_.Get("/keepalive", [](const Request &, Response &res) {
  18365. res.set_content("ok", "text/plain");
  18366. });
  18367. port_ = svr_.bind_to_any_port(HOST);
  18368. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18369. svr_.wait_until_ready();
  18370. }
  18371. void TearDown() override {
  18372. svr_.stop();
  18373. if (thread_.joinable()) { thread_.join(); }
  18374. }
  18375. Server svr_;
  18376. int port_ = 0;
  18377. thread thread_;
  18378. };
  18379. // "close" alongside another option still closes the connection, and the
  18380. // response says so rather than leaving the peer to discover it.
  18381. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  18382. bool announced_close = false;
  18383. bool reusable = true;
  18384. probe_connection_reuse(port_,
  18385. "GET /keepalive HTTP/1.1\r\n"
  18386. "Host: localhost\r\n"
  18387. "Connection: keep-alive, close\r\n"
  18388. "\r\n",
  18389. &announced_close, &reusable);
  18390. EXPECT_TRUE(announced_close);
  18391. EXPECT_FALSE(reusable);
  18392. }
  18393. // "close" split over two field lines is the same list, so it is honored too.
  18394. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  18395. bool announced_close = false;
  18396. bool reusable = true;
  18397. probe_connection_reuse(port_,
  18398. "GET /keepalive HTTP/1.1\r\n"
  18399. "Host: localhost\r\n"
  18400. "Connection: keep-alive\r\n"
  18401. "Connection: close\r\n"
  18402. "\r\n",
  18403. &announced_close, &reusable);
  18404. EXPECT_TRUE(announced_close);
  18405. EXPECT_FALSE(reusable);
  18406. }
  18407. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  18408. // keep-alive in the spelling everyone actually sends keeps its connection.
  18409. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  18410. bool announced_close = false;
  18411. bool reusable = false;
  18412. probe_connection_reuse(port_,
  18413. "GET /keepalive HTTP/1.0\r\n"
  18414. "Host: localhost\r\n"
  18415. "Connection: keep-alive\r\n"
  18416. "\r\n",
  18417. &announced_close, &reusable);
  18418. EXPECT_FALSE(announced_close);
  18419. EXPECT_TRUE(reusable);
  18420. }
  18421. // A token the value merely contains is not the token itself.
  18422. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  18423. bool announced_close = false;
  18424. bool reusable = false;
  18425. probe_connection_reuse(port_,
  18426. "GET /keepalive HTTP/1.1\r\n"
  18427. "Host: localhost\r\n"
  18428. "Connection: notclose\r\n"
  18429. "\r\n",
  18430. &announced_close, &reusable);
  18431. EXPECT_FALSE(announced_close);
  18432. EXPECT_TRUE(reusable);
  18433. }
  18434. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  18435. Server svr;
  18436. std::vector<std::string> observed_types;
  18437. svr.Get("/", [&](const Request &req, Response &res) {
  18438. observed_types = req.accept_content_types;
  18439. res.set_content("ok", "text/plain");
  18440. });
  18441. auto port = svr.bind_to_any_port(HOST);
  18442. thread t = thread([&]() { svr.listen_after_bind(); });
  18443. auto se = detail::scope_exit([&] {
  18444. svr.stop();
  18445. t.join();
  18446. ASSERT_FALSE(svr.is_running());
  18447. });
  18448. svr.wait_until_ready();
  18449. Client cli(HOST, port);
  18450. Headers headers;
  18451. headers.emplace("Accept", "text/plain;q=0.5");
  18452. headers.emplace("Accept", "application/json");
  18453. auto res = cli.Get("/", headers);
  18454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18455. EXPECT_EQ(StatusCode::OK_200, res->status);
  18456. // Sorted by q-value, so the second field line's type comes first
  18457. ASSERT_EQ(2U, observed_types.size());
  18458. EXPECT_EQ("application/json", observed_types[0]);
  18459. EXPECT_EQ("text/plain", observed_types[1]);
  18460. }
  18461. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  18462. // empty field line must not contribute a bare comma to the combined value.
  18463. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  18464. Server svr;
  18465. std::vector<std::string> observed_types;
  18466. svr.Get("/", [&](const Request &req, Response &res) {
  18467. observed_types = req.accept_content_types;
  18468. res.set_content("ok", "text/plain");
  18469. });
  18470. auto port = svr.bind_to_any_port(HOST);
  18471. thread t = thread([&]() { svr.listen_after_bind(); });
  18472. auto se = detail::scope_exit([&] {
  18473. svr.stop();
  18474. t.join();
  18475. ASSERT_FALSE(svr.is_running());
  18476. });
  18477. svr.wait_until_ready();
  18478. // Empty first field line, then a real one
  18479. std::string raw_req = "GET / HTTP/1.1\r\n"
  18480. "Host: localhost\r\n"
  18481. "Accept:\r\n"
  18482. "Accept: application/json\r\n"
  18483. "Connection: close\r\n"
  18484. "\r\n";
  18485. std::string out;
  18486. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18487. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18488. ASSERT_EQ(1U, observed_types.size());
  18489. EXPECT_EQ("application/json", observed_types[0]);
  18490. }
  18491. // The skip in get_combined_header_value() is what keeps an empty field line
  18492. // from contributing a bare comma. Only a trailing empty field line exercises
  18493. // it: a leading one is already covered by the "combined is still empty" check,
  18494. // and parse_accept_header() now ignores the empty element either way, so the
  18495. // request-level test above can no longer tell the two apart.
  18496. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  18497. Headers headers;
  18498. headers.emplace("Accept", "text/html");
  18499. headers.emplace("Accept", "");
  18500. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  18501. headers.clear();
  18502. headers.emplace("Accept", "");
  18503. headers.emplace("Accept", "application/json");
  18504. EXPECT_EQ("application/json",
  18505. detail::get_combined_header_value(headers, "Accept"));
  18506. }
  18507. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18508. // An encoding offered on a later Accept-Encoding field line is still offered.
  18509. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  18510. Server svr;
  18511. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18512. res.set_content(std::string(1024, 'x'), "text/plain");
  18513. });
  18514. auto port = svr.bind_to_any_port(HOST);
  18515. thread t = thread([&]() { svr.listen_after_bind(); });
  18516. auto se = detail::scope_exit([&] {
  18517. svr.stop();
  18518. t.join();
  18519. ASSERT_FALSE(svr.is_running());
  18520. });
  18521. svr.wait_until_ready();
  18522. Client cli(HOST, port);
  18523. cli.set_decompress(false);
  18524. Headers headers;
  18525. headers.emplace("Accept-Encoding", "identity");
  18526. headers.emplace("Accept-Encoding", "gzip");
  18527. auto res = cli.Get("/", headers);
  18528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18529. EXPECT_EQ(StatusCode::OK_200, res->status);
  18530. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  18531. }
  18532. #endif
  18533. #ifndef _WIN32
  18534. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  18535. Server svr;
  18536. svr.Post("/post", [&](const Request &req, Response &res) {
  18537. res.set_content(req.body, "text/plain");
  18538. });
  18539. svr.Put("/put", [&](const Request &req, Response &res) {
  18540. res.set_content(req.body, "text/plain");
  18541. });
  18542. svr.Patch("/patch", [&](const Request &req, Response &res) {
  18543. res.set_content(req.body, "text/plain");
  18544. });
  18545. svr.Delete("/delete", [&](const Request &req, Response &res) {
  18546. res.set_content(req.body, "text/plain");
  18547. });
  18548. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18549. auto se = detail::scope_exit([&] {
  18550. svr.stop();
  18551. t.join();
  18552. ASSERT_FALSE(svr.is_running());
  18553. });
  18554. svr.wait_until_ready();
  18555. std::string resp;
  18556. // POST without Content-Length
  18557. ASSERT_TRUE(send_request(5,
  18558. "POST /post HTTP/1.1\r\n"
  18559. "Host: localhost\r\n"
  18560. "Connection: close\r\n"
  18561. "\r\n",
  18562. &resp));
  18563. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18564. // PUT without Content-Length
  18565. resp.clear();
  18566. ASSERT_TRUE(send_request(5,
  18567. "PUT /put HTTP/1.1\r\n"
  18568. "Host: localhost\r\n"
  18569. "Connection: close\r\n"
  18570. "\r\n",
  18571. &resp));
  18572. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18573. // PATCH without Content-Length
  18574. resp.clear();
  18575. ASSERT_TRUE(send_request(5,
  18576. "PATCH /patch HTTP/1.1\r\n"
  18577. "Host: localhost\r\n"
  18578. "Connection: close\r\n"
  18579. "\r\n",
  18580. &resp));
  18581. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18582. // DELETE without Content-Length
  18583. resp.clear();
  18584. ASSERT_TRUE(send_request(5,
  18585. "DELETE /delete HTTP/1.1\r\n"
  18586. "Host: localhost\r\n"
  18587. "Connection: close\r\n"
  18588. "\r\n",
  18589. &resp));
  18590. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18591. }
  18592. #endif
  18593. //==============================================================================
  18594. // open_stream() Tests
  18595. //==============================================================================
  18596. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  18597. std::string result;
  18598. char buf[8192];
  18599. ssize_t n;
  18600. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18601. result.append(buf, static_cast<size_t>(n));
  18602. }
  18603. return result;
  18604. }
  18605. // Mock stream for unit tests
  18606. class MockStream : public Stream {
  18607. public:
  18608. std::string data;
  18609. size_t pos = 0;
  18610. ssize_t error_after = -1; // -1 = no error
  18611. explicit MockStream(const std::string &d, ssize_t err = -1)
  18612. : data(d), error_after(err) {}
  18613. bool is_readable() const override { return true; }
  18614. bool wait_readable() const override { return true; }
  18615. bool wait_writable() const override { return true; }
  18616. ssize_t read(char *ptr, size_t size) override {
  18617. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  18618. if (pos >= data.size()) return 0;
  18619. size_t limit =
  18620. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  18621. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  18622. std::memcpy(ptr, data.data() + pos, to_read);
  18623. pos += to_read;
  18624. return static_cast<ssize_t>(to_read);
  18625. }
  18626. ssize_t write(const char *, size_t) override { return -1; }
  18627. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  18628. ip = "127.0.0.1";
  18629. port = 0;
  18630. }
  18631. void get_local_ip_and_port(std::string &ip, int &port) const override {
  18632. ip = "127.0.0.1";
  18633. port = 0;
  18634. }
  18635. socket_t socket() const override { return INVALID_SOCKET; }
  18636. time_t duration() const override { return 0; }
  18637. };
  18638. TEST(StreamHandleTest, Basic) {
  18639. ClientImpl::StreamHandle handle;
  18640. EXPECT_FALSE(handle.is_valid());
  18641. handle.response = detail::make_unique<Response>();
  18642. handle.error = Error::Connection;
  18643. EXPECT_FALSE(handle.is_valid());
  18644. handle.error = Error::Success;
  18645. EXPECT_TRUE(handle.is_valid());
  18646. }
  18647. TEST(BodyReaderTest, Basic) {
  18648. MockStream stream("Hello, World!");
  18649. detail::BodyReader reader;
  18650. reader.stream = &stream;
  18651. reader.content_length = 13;
  18652. char buf[32];
  18653. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  18654. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  18655. EXPECT_TRUE(reader.eof);
  18656. }
  18657. TEST(BodyReaderTest, NoStream) {
  18658. detail::BodyReader reader;
  18659. char buf[32];
  18660. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18661. EXPECT_EQ(Error::Connection, reader.last_error);
  18662. }
  18663. TEST(BodyReaderTest, Error) {
  18664. MockStream stream("Hello, World!", 5);
  18665. detail::BodyReader reader;
  18666. reader.stream = &stream;
  18667. reader.content_length = 13;
  18668. char buf[32];
  18669. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  18670. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18671. EXPECT_EQ(Error::Read, reader.last_error);
  18672. }
  18673. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  18674. // Mock-based StreamHandle tests relying on private internals are removed.
  18675. class OpenStreamTest : public ::testing::Test {
  18676. protected:
  18677. void SetUp() override {
  18678. svr_.Get("/hello", [](const Request &, Response &res) {
  18679. res.set_content("Hello World!", "text/plain");
  18680. });
  18681. svr_.Get("/large", [](const Request &, Response &res) {
  18682. res.set_content(std::string(10000, 'X'), "text/plain");
  18683. });
  18684. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  18685. res.set_content("Hello World!", "image/jpeg");
  18686. res.set_header("Content-Encoding", "UTF-8");
  18687. });
  18688. svr_.Get("/chunked", [](const Request &, Response &res) {
  18689. res.set_chunked_content_provider("text/plain",
  18690. [](size_t offset, DataSink &sink) {
  18691. if (offset < 15) {
  18692. sink.write("chunk", 5);
  18693. return true;
  18694. }
  18695. sink.done();
  18696. return true;
  18697. });
  18698. });
  18699. svr_.Get("/compressible", [](const Request &, Response &res) {
  18700. res.set_chunked_content_provider("text/plain", [](size_t offset,
  18701. DataSink &sink) {
  18702. if (offset < 100 * 1024) {
  18703. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  18704. sink.write(chunk.data(), chunk.size());
  18705. return true;
  18706. }
  18707. sink.done();
  18708. return true;
  18709. });
  18710. });
  18711. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  18712. [](const Request & /*req*/, Response &res) {
  18713. auto i = new int(0);
  18714. res.set_header("Trailer", "Content-Length, X-Allowed");
  18715. res.set_chunked_content_provider(
  18716. "text/plain",
  18717. [i](size_t /*offset*/, DataSink &sink) {
  18718. switch (*i) {
  18719. case 0: sink.os << "123"; break;
  18720. case 1: sink.os << "456"; break;
  18721. case 2: sink.os << "789"; break;
  18722. case 3: {
  18723. sink.done_with_trailer(
  18724. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  18725. } break;
  18726. }
  18727. (*i)++;
  18728. return true;
  18729. },
  18730. [i](bool success) {
  18731. EXPECT_TRUE(success);
  18732. delete i;
  18733. });
  18734. });
  18735. // Echo headers endpoint for header-related tests
  18736. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  18737. std::string body;
  18738. for (const auto &h : req.headers) {
  18739. body.append(h.first);
  18740. body.push_back(':');
  18741. body.append(h.second);
  18742. body.push_back('\n');
  18743. }
  18744. res.set_content(body, "text/plain");
  18745. });
  18746. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  18747. std::string body;
  18748. for (const auto &h : req.headers) {
  18749. body.append(h.first);
  18750. body.push_back(':');
  18751. body.append(h.second);
  18752. body.push_back('\n');
  18753. }
  18754. res.set_content(body, "text/plain");
  18755. });
  18756. port_ = svr_.bind_to_any_port("127.0.0.1");
  18757. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18758. svr_.wait_until_ready();
  18759. }
  18760. void TearDown() override {
  18761. svr_.stop();
  18762. if (thread_.joinable()) thread_.join();
  18763. }
  18764. Server svr_;
  18765. std::thread thread_;
  18766. int port_ = 0;
  18767. };
  18768. TEST_F(OpenStreamTest, Basic) {
  18769. Client cli("127.0.0.1", port_);
  18770. auto handle = cli.open_stream("GET", "/hello");
  18771. EXPECT_TRUE(handle.is_valid());
  18772. EXPECT_EQ("Hello World!", read_all(handle));
  18773. }
  18774. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  18775. Client cli("127.0.0.1", port_);
  18776. auto handle = cli.open_stream("GET", "/unknown-encoding");
  18777. ASSERT_TRUE(handle.is_valid());
  18778. EXPECT_EQ("Hello World!", read_all(handle));
  18779. }
  18780. TEST_F(OpenStreamTest, SmallBuffer) {
  18781. Client cli("127.0.0.1", port_);
  18782. auto handle = cli.open_stream("GET", "/hello");
  18783. std::string result;
  18784. char buf[4];
  18785. ssize_t n;
  18786. while ((n = handle.read(buf, sizeof(buf))) > 0)
  18787. result.append(buf, static_cast<size_t>(n));
  18788. EXPECT_EQ("Hello World!", result);
  18789. }
  18790. TEST_F(OpenStreamTest, DefaultHeaders) {
  18791. Client cli("127.0.0.1", port_);
  18792. // open_stream GET should include Host, User-Agent and Accept-Encoding
  18793. {
  18794. auto handle = cli.open_stream("GET", "/echo-headers");
  18795. ASSERT_TRUE(handle.is_valid());
  18796. auto body = read_all(handle);
  18797. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  18798. std::string::npos);
  18799. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  18800. std::string::npos);
  18801. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  18802. }
  18803. // open_stream POST with body and no explicit content_type should NOT add
  18804. // text/plain Content-Type (behavior differs from non-streaming path), but
  18805. // should include Content-Length
  18806. {
  18807. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  18808. ASSERT_TRUE(handle.is_valid());
  18809. auto body = read_all(handle);
  18810. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  18811. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  18812. }
  18813. // open_stream POST with explicit Content-Type should preserve it
  18814. {
  18815. auto handle = cli.open_stream("POST", "/echo-headers", {},
  18816. {{"Content-Type", "application/custom"}},
  18817. "{}", "application/custom");
  18818. ASSERT_TRUE(handle.is_valid());
  18819. auto body = read_all(handle);
  18820. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  18821. }
  18822. // User-specified User-Agent must not be overwritten for stream API
  18823. {
  18824. auto handle = cli.open_stream("GET", "/echo-headers", {},
  18825. {{"User-Agent", "MyAgent/1.2"}});
  18826. ASSERT_TRUE(handle.is_valid());
  18827. auto body = read_all(handle);
  18828. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  18829. }
  18830. }
  18831. TEST_F(OpenStreamTest, Large) {
  18832. Client cli("127.0.0.1", port_);
  18833. auto handle = cli.open_stream("GET", "/large");
  18834. EXPECT_EQ(10000u, read_all(handle).size());
  18835. }
  18836. TEST_F(OpenStreamTest, ConnectionError) {
  18837. Client cli("127.0.0.1", 9999);
  18838. auto handle = cli.open_stream("GET", "/hello");
  18839. EXPECT_FALSE(handle.is_valid());
  18840. }
  18841. TEST_F(OpenStreamTest, Chunked) {
  18842. Client cli("127.0.0.1", port_);
  18843. auto handle = cli.open_stream("GET", "/chunked");
  18844. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18845. "Transfer-Encoding") == "chunked");
  18846. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  18847. }
  18848. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  18849. Client cli("127.0.0.1", port_);
  18850. auto handle =
  18851. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  18852. ASSERT_TRUE(handle.is_valid());
  18853. // Consume body to allow trailers to be received/parsed
  18854. auto body = read_all(handle);
  18855. // Explicitly parse trailers (ensure trailers are available for assertion)
  18856. handle.parse_trailers_if_needed();
  18857. EXPECT_EQ(std::string("123456789"), body);
  18858. // The response should include a Trailer header declaring both names
  18859. ASSERT_TRUE(handle.response);
  18860. EXPECT_TRUE(handle.response->has_header("Trailer"));
  18861. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  18862. handle.response->get_header_value("Trailer"));
  18863. // Prohibited trailer must not be present
  18864. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  18865. // Allowed trailer should be present
  18866. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  18867. EXPECT_EQ(std::string("yes"),
  18868. handle.response->get_trailer_value("X-Allowed"));
  18869. // Verify trailers are NOT present as regular headers
  18870. EXPECT_EQ(std::string(""),
  18871. handle.response->get_header_value("Content-Length"));
  18872. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  18873. }
  18874. // Accepts one connection on an OS-assigned port, which it hands over through
  18875. // port_promise, reads the request head and sends back response. after_send,
  18876. // if given, runs on the connection before it is closed.
  18877. static std::thread
  18878. serve_single_response(std::promise<int> &port_promise,
  18879. const std::string &response,
  18880. std::function<void(socket_t)> after_send = nullptr) {
  18881. return std::thread([&port_promise, response, after_send] {
  18882. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18883. default_socket_options(srv);
  18884. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18885. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  18886. sockaddr_in addr{};
  18887. addr.sin_family = AF_INET;
  18888. addr.sin_port = htons(0); // Let OS assign a free port
  18889. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18890. int opt = 1;
  18891. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  18892. #ifdef _WIN32
  18893. reinterpret_cast<const char *>(&opt),
  18894. #else
  18895. &opt,
  18896. #endif
  18897. sizeof(opt));
  18898. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  18899. ::listen(srv, 1) != 0) {
  18900. port_promise.set_value(-1);
  18901. detail::close_socket(srv);
  18902. return;
  18903. }
  18904. socklen_t addr_len = sizeof(addr);
  18905. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  18906. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  18907. sockaddr_in cli_addr{};
  18908. socklen_t cli_len = sizeof(cli_addr);
  18909. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18910. if (cli != INVALID_SOCKET) {
  18911. // Read the complete HTTP request (until the blank line that terminates
  18912. // headers) before sending the response. If the server closes the socket
  18913. // while the client's request data is still unread in the kernel receive
  18914. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  18915. // connection on both sides: it discards the client's receive buffer
  18916. // (which already holds our response) and causes any in-progress write on
  18917. // the client to fail with ECONNRESET. Reading all request data first
  18918. // ensures close() emits a graceful FIN.
  18919. {
  18920. char rbuf[256];
  18921. std::string req;
  18922. while (req.find("\r\n\r\n") == std::string::npos) {
  18923. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  18924. if (n <= 0) { break; }
  18925. req.append(rbuf, static_cast<size_t>(n));
  18926. }
  18927. }
  18928. ::send(cli,
  18929. #ifdef _WIN32
  18930. static_cast<const char *>(response.c_str()),
  18931. static_cast<int>(response.size()),
  18932. #else
  18933. response.c_str(), response.size(),
  18934. #endif
  18935. 0);
  18936. if (after_send) { after_send(cli); }
  18937. detail::close_socket(cli);
  18938. }
  18939. detail::close_socket(srv);
  18940. });
  18941. }
  18942. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  18943. #ifndef _WIN32
  18944. signal(SIGPIPE, SIG_IGN);
  18945. #endif
  18946. std::promise<int> port_promise;
  18947. auto port_future = port_promise.get_future();
  18948. auto server_thread =
  18949. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  18950. "Content-Type: text/plain\r\n"
  18951. "Content-Length: not-a-number\r\n"
  18952. "Connection: close\r\n"
  18953. "\r\n"
  18954. "hello");
  18955. auto port = port_future.get();
  18956. ASSERT_GT(port, 0);
  18957. Client cli("127.0.0.1", port);
  18958. auto handle = cli.open_stream("GET", "/");
  18959. EXPECT_FALSE(handle.is_valid());
  18960. server_thread.join();
  18961. }
  18962. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  18963. #ifndef _WIN32
  18964. signal(SIGPIPE, SIG_IGN);
  18965. #endif
  18966. std::promise<int> port_promise;
  18967. auto port_future = port_promise.get_future();
  18968. auto server_thread = serve_single_response(
  18969. port_promise, "HTTP/1.1 200 OK\r\n"
  18970. "Content-Type: text/plain\r\n"
  18971. "Content-Length: 99999999999999999999999999\r\n"
  18972. "Connection: close\r\n"
  18973. "\r\n"
  18974. "hello");
  18975. auto port = port_future.get();
  18976. ASSERT_GT(port, 0);
  18977. // Historically std::stoull would throw std::out_of_range here and crash
  18978. // the process, then parsing silently clamped to a bogus framing length and
  18979. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  18980. // so the stream fails to open, matching the not-a-number case above. The
  18981. // process still must NOT terminate.
  18982. Client cli("127.0.0.1", port);
  18983. auto handle = cli.open_stream("GET", "/");
  18984. EXPECT_FALSE(handle.is_valid());
  18985. server_thread.join();
  18986. }
  18987. // Serves `response` to the single request `fn` makes with a fresh client.
  18988. template <typename Fn>
  18989. static void with_single_response(const std::string &response, Fn fn) {
  18990. #ifndef _WIN32
  18991. signal(SIGPIPE, SIG_IGN);
  18992. #endif
  18993. std::promise<int> port_promise;
  18994. auto port_future = port_promise.get_future();
  18995. auto server_thread = serve_single_response(port_promise, response);
  18996. auto se = detail::scope_exit([&] { server_thread.join(); });
  18997. auto port = port_future.get();
  18998. ASSERT_GT(port, 0);
  18999. Client cli("127.0.0.1", port);
  19000. fn(cli);
  19001. }
  19002. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  19003. const char *responses[] = {
  19004. "HTTP/1.1 103 Early Hints\r\n"
  19005. "Link: </style.css>; rel=preload\r\n"
  19006. "\r\n"
  19007. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19008. "HTTP/1.1 100 Continue\r\n"
  19009. "X-Note: interim\r\n"
  19010. "\r\n"
  19011. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19012. };
  19013. for (auto response : responses) {
  19014. with_single_response(response, [](Client &cli) {
  19015. auto res = cli.Get("/");
  19016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19017. EXPECT_EQ(StatusCode::OK_200, res->status);
  19018. EXPECT_EQ("ok", res->body);
  19019. });
  19020. }
  19021. }
  19022. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  19023. #ifndef _WIN32
  19024. signal(SIGPIPE, SIG_IGN);
  19025. #endif
  19026. // The server answers the head without asking for the body. Bytes it then
  19027. // reads on the connection would be taken for the body the request declared.
  19028. auto closed_by_client = false;
  19029. std::promise<int> port_promise;
  19030. auto server_thread = serve_single_response(
  19031. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  19032. [&](socket_t sock) {
  19033. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19034. char buf[256];
  19035. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  19036. });
  19037. Client cli("127.0.0.1", port_promise.get_future().get());
  19038. cli.set_keep_alive(true);
  19039. cli.set_read_timeout(1, 0);
  19040. // Long enough for the client to send Expect: 100-continue.
  19041. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19043. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19044. cli.Get("/second");
  19045. server_thread.join();
  19046. EXPECT_TRUE(closed_by_client);
  19047. }
  19048. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  19049. // Long enough for the client to send Expect: 100-continue
  19050. with_single_response(
  19051. "HTTP/1.1 103 Early Hints\r\n"
  19052. "Link: </style.css>; rel=preload\r\n"
  19053. "\r\n"
  19054. "HTTP/1.1 401 Unauthorized\r\n"
  19055. "Content-Length: 0\r\n\r\n",
  19056. [](Client &cli) {
  19057. cli.set_read_timeout(2, 0);
  19058. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19060. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19061. });
  19062. }
  19063. #ifdef CPPHTTPLIB_SSL_ENABLED
  19064. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  19065. #ifndef _WIN32
  19066. signal(SIGPIPE, SIG_IGN);
  19067. #endif
  19068. auto reused = false;
  19069. std::promise<int> port_promise;
  19070. auto server_thread = serve_single_response(
  19071. port_promise,
  19072. "HTTP/1.1 401 Unauthorized\r\n"
  19073. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  19074. "Content-Length: 0\r\n\r\n",
  19075. [&](socket_t sock) {
  19076. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19077. char buf[256];
  19078. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  19079. });
  19080. Client cli("127.0.0.1", port_promise.get_future().get());
  19081. cli.set_keep_alive(true);
  19082. cli.set_digest_auth("user", "pass");
  19083. cli.set_read_timeout(1, 0);
  19084. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19085. server_thread.join();
  19086. EXPECT_FALSE(reused);
  19087. }
  19088. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  19089. // Any other answer to CONNECT would read as the origin's response.
  19090. struct {
  19091. const char *response;
  19092. bool passed_on;
  19093. } cases[] = {
  19094. {"HTTP/1.1 201 Created\r\n"
  19095. "Set-Cookie: session=from-proxy\r\n"
  19096. "Content-Length: 0\r\n\r\n",
  19097. false},
  19098. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  19099. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  19100. "Content-Length: 0\r\n\r\n",
  19101. true},
  19102. };
  19103. for (const auto &c : cases) {
  19104. std::promise<int> port_promise;
  19105. auto server_thread = serve_single_response(port_promise, c.response);
  19106. SSLClient cli("example.com", 443);
  19107. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  19108. auto res = cli.Get("/");
  19109. server_thread.join();
  19110. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  19111. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  19112. if (res) {
  19113. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19114. }
  19115. }
  19116. }
  19117. #endif
  19118. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  19119. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  19120. // the chunked coding and drop Content-Length, so a front-end that trusts
  19121. // Content-Length would disagree about where the body ends (response
  19122. // smuggling). The client must reject such a response.
  19123. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  19124. for (const char *te : {"chunked", "gzip, chunked"}) {
  19125. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  19126. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  19127. "\r\n" + "Connection: close\r\n" + "\r\n" +
  19128. "5\r\nhello\r\n0\r\n\r\n";
  19129. with_single_response(response, [&](Client &cli) {
  19130. auto res = cli.Get("/");
  19131. EXPECT_FALSE(static_cast<bool>(res)) << te;
  19132. EXPECT_EQ(Error::Read, res.error()) << te;
  19133. });
  19134. with_single_response(response, [&](Client &cli) {
  19135. auto handle = cli.open_stream("GET", "/");
  19136. EXPECT_FALSE(handle.is_valid()) << te;
  19137. EXPECT_EQ(Error::Read, handle.error) << te;
  19138. });
  19139. }
  19140. }
  19141. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  19142. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  19143. // closing the connection (unlike a request, which must be rejected).
  19144. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  19145. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19146. "Transfer-Encoding: chunked\r\n"
  19147. "Connection: close\r\n"
  19148. "\r\n"
  19149. "5\r\nhello\r\n0\r\n\r\n",
  19150. "HTTP/1.1 200 OK\r\n"
  19151. "Transfer-Encoding: gzip\r\n"
  19152. "Connection: close\r\n"
  19153. "\r\n"
  19154. "hello"}) {
  19155. with_single_response(response, [&](Client &cli) {
  19156. auto res = cli.Get("/");
  19157. ASSERT_TRUE(static_cast<bool>(res)) << response;
  19158. EXPECT_EQ("hello", res->body);
  19159. });
  19160. with_single_response(response, [&](Client &cli) {
  19161. auto handle = cli.open_stream("GET", "/");
  19162. ASSERT_TRUE(handle.is_valid()) << response;
  19163. EXPECT_EQ("hello", read_all(handle));
  19164. });
  19165. }
  19166. }
  19167. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  19168. // framing headers describe nothing to read and must not be rejected.
  19169. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  19170. const std::string framing = "Content-Length: 5\r\n"
  19171. "Transfer-Encoding: chunked\r\n"
  19172. "Connection: close\r\n"
  19173. "\r\n";
  19174. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19175. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  19176. });
  19177. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19178. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  19179. });
  19180. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  19181. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  19182. with_single_response(response, [&](Client &cli) {
  19183. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  19184. });
  19185. with_single_response(response, [&](Client &cli) {
  19186. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  19187. });
  19188. }
  19189. }
  19190. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  19191. // response, is faulty framing, so the connection is not reused after it.
  19192. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  19193. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19194. "Content-Length: 0\r\n"
  19195. "Transfer-Encoding: chunked\r\n"
  19196. "\r\n"
  19197. "5\r\nhello\r\n0\r\n\r\n",
  19198. "HTTP/1.0 200 Connection established\r\n"
  19199. "Connection: keep-alive\r\n"
  19200. "Transfer-Encoding: chunked\r\n"
  19201. "\r\n"
  19202. "5\r\nhello\r\n0\r\n\r\n"}) {
  19203. with_single_response(response, [&](Client &cli) {
  19204. cli.set_keep_alive(true);
  19205. auto res = cli.Get("/");
  19206. ASSERT_TRUE(res) << response;
  19207. EXPECT_EQ("hello", res->body);
  19208. EXPECT_FALSE(cli.is_socket_open()) << response;
  19209. });
  19210. }
  19211. }
  19212. // A payload max length of 0 means no limit, however the body is framed.
  19213. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  19214. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19215. "Transfer-Encoding: chunked\r\n"
  19216. "\r\n"
  19217. "5\r\nhello\r\n0\r\n\r\n",
  19218. "HTTP/1.1 200 OK\r\n"
  19219. "Connection: close\r\n"
  19220. "\r\n"
  19221. "hello"}) {
  19222. with_single_response(response, [&](Client &cli) {
  19223. cli.set_payload_max_length(0);
  19224. auto res = cli.Get("/");
  19225. ASSERT_TRUE(res) << response;
  19226. EXPECT_EQ("hello", res->body) << response;
  19227. });
  19228. }
  19229. }
  19230. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  19231. Server svr;
  19232. svr.set_payload_max_length(0);
  19233. svr.Post("/echo", [](const Request &req, Response &res) {
  19234. res.set_content(req.body, "text/plain");
  19235. });
  19236. auto port = svr.bind_to_any_port(HOST);
  19237. thread t = thread([&] { svr.listen_after_bind(); });
  19238. auto se = detail::scope_exit([&] {
  19239. svr.stop();
  19240. t.join();
  19241. ASSERT_FALSE(svr.is_running());
  19242. });
  19243. svr.wait_until_ready();
  19244. Client cli(HOST, port);
  19245. auto res = cli.Post(
  19246. "/echo",
  19247. [](size_t /*offset*/, DataSink &sink) {
  19248. sink.write("hello", 5);
  19249. sink.done();
  19250. return true;
  19251. },
  19252. "text/plain");
  19253. ASSERT_TRUE(res);
  19254. EXPECT_EQ(StatusCode::OK_200, res->status);
  19255. EXPECT_EQ("hello", res->body);
  19256. }
  19257. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19258. TEST_F(OpenStreamTest, Gzip) {
  19259. Client cli("127.0.0.1", port_);
  19260. auto handle = cli.open_stream("GET", "/compressible", {},
  19261. {{"Accept-Encoding", "gzip"}});
  19262. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  19263. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19264. }
  19265. #endif
  19266. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19267. TEST_F(OpenStreamTest, Brotli) {
  19268. Client cli("127.0.0.1", port_);
  19269. auto handle =
  19270. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  19271. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  19272. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19273. }
  19274. #endif
  19275. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19276. TEST_F(OpenStreamTest, Zstd) {
  19277. Client cli("127.0.0.1", port_);
  19278. auto handle = cli.open_stream("GET", "/compressible", {},
  19279. {{"Accept-Encoding", "zstd"}});
  19280. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  19281. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19282. }
  19283. #endif
  19284. #ifdef CPPHTTPLIB_SSL_ENABLED
  19285. class SSLOpenStreamTest : public ::testing::Test {
  19286. protected:
  19287. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  19288. void SetUp() override {
  19289. svr_.Get("/hello", [](const Request &, Response &res) {
  19290. res.set_content("Hello SSL World!", "text/plain");
  19291. });
  19292. svr_.Get("/chunked", [](const Request &, Response &res) {
  19293. res.set_chunked_content_provider("text/plain",
  19294. [](size_t offset, DataSink &sink) {
  19295. if (offset < 15) {
  19296. sink.write("chunk", 5);
  19297. return true;
  19298. }
  19299. sink.done();
  19300. return true;
  19301. });
  19302. });
  19303. svr_.Post("/echo", [](const Request &req, Response &res) {
  19304. res.set_content(req.body, req.get_header_value("Content-Type"));
  19305. });
  19306. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  19307. std::string body = req.body;
  19308. res.set_chunked_content_provider(
  19309. "text/plain", [body](size_t offset, DataSink &sink) {
  19310. if (offset < body.size()) {
  19311. sink.write(body.data() + offset, body.size() - offset);
  19312. }
  19313. sink.done();
  19314. return true;
  19315. });
  19316. });
  19317. port_ = svr_.bind_to_any_port("127.0.0.1");
  19318. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19319. svr_.wait_until_ready();
  19320. }
  19321. void TearDown() override {
  19322. svr_.stop();
  19323. if (thread_.joinable()) thread_.join();
  19324. }
  19325. SSLServer svr_;
  19326. std::thread thread_;
  19327. int port_ = 0;
  19328. };
  19329. TEST_F(SSLOpenStreamTest, Basic) {
  19330. SSLClient cli("127.0.0.1", port_);
  19331. cli.enable_server_certificate_verification(false);
  19332. auto handle = cli.open_stream("GET", "/hello");
  19333. ASSERT_TRUE(handle.is_valid());
  19334. EXPECT_EQ("Hello SSL World!", read_all(handle));
  19335. }
  19336. TEST_F(SSLOpenStreamTest, Chunked) {
  19337. SSLClient cli("127.0.0.1", port_);
  19338. cli.enable_server_certificate_verification(false);
  19339. auto handle = cli.open_stream("GET", "/chunked");
  19340. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19341. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19342. "Transfer-Encoding") == "chunked");
  19343. auto body = read_all(handle);
  19344. EXPECT_EQ("chunkchunkchunk", body);
  19345. }
  19346. TEST_F(SSLOpenStreamTest, Post) {
  19347. SSLClient cli("127.0.0.1", port_);
  19348. cli.enable_server_certificate_verification(false);
  19349. auto handle =
  19350. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  19351. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19352. EXPECT_EQ(200, handle.response->status);
  19353. auto body = read_all(handle);
  19354. EXPECT_EQ("Hello SSL POST", body);
  19355. }
  19356. TEST_F(SSLOpenStreamTest, PostChunked) {
  19357. SSLClient cli("127.0.0.1", port_);
  19358. cli.enable_server_certificate_verification(false);
  19359. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  19360. "Chunked SSL Data", "text/plain");
  19361. ASSERT_TRUE(handle.is_valid());
  19362. EXPECT_EQ(200, handle.response->status);
  19363. auto body = read_all(handle);
  19364. EXPECT_EQ("Chunked SSL Data", body);
  19365. }
  19366. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  19367. // Content-Length is terminated by the server closing the connection. When the
  19368. // SSL peer sends a close_notify after the body, the client must treat it as a
  19369. // clean EOF and return a successful response rather than an error.
  19370. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  19371. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19372. ASSERT_TRUE(svr.is_valid());
  19373. svr.set_keep_alive_max_count(1);
  19374. const std::string expected_body = "Hello from connection-close response!";
  19375. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  19376. res.set_content_provider("text/plain",
  19377. [&](size_t offset, DataSink &sink) -> bool {
  19378. if (offset < expected_body.size()) {
  19379. sink.write(expected_body.data() + offset,
  19380. expected_body.size() - offset);
  19381. }
  19382. sink.done();
  19383. return true;
  19384. });
  19385. });
  19386. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  19387. auto se = detail::scope_exit([&] {
  19388. svr.stop();
  19389. listen_thread.join();
  19390. ASSERT_FALSE(svr.is_running());
  19391. });
  19392. svr.wait_until_ready();
  19393. SSLClient cli(HOST, PORT);
  19394. cli.enable_server_certificate_verification(false);
  19395. auto res = cli.Get("/no-content-length");
  19396. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  19397. EXPECT_EQ(StatusCode::OK_200, res->status);
  19398. EXPECT_EQ(expected_body, res->body);
  19399. }
  19400. #endif // CPPHTTPLIB_SSL_ENABLED
  19401. //==============================================================================
  19402. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  19403. // results for various scenarios.
  19404. //==============================================================================
  19405. TEST(ParityTest, GetVsOpenStream) {
  19406. Server svr;
  19407. const std::string path = "/parity";
  19408. const std::string content = "Parity test content: hello world";
  19409. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19410. res.set_content(content, "text/plain");
  19411. });
  19412. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19413. auto se = detail::scope_exit([&] {
  19414. svr.stop();
  19415. t.join();
  19416. ASSERT_FALSE(svr.is_running());
  19417. });
  19418. svr.wait_until_ready();
  19419. Client cli(HOST, PORT);
  19420. // Non-stream path
  19421. auto r1 = cli.Get(path);
  19422. ASSERT_TRUE(r1);
  19423. EXPECT_EQ(StatusCode::OK_200, r1->status);
  19424. // Stream path
  19425. auto h = cli.open_stream("GET", path);
  19426. ASSERT_TRUE(h.is_valid());
  19427. EXPECT_EQ(r1->body, read_all(h));
  19428. }
  19429. // Helper to compress data with provided compressor type T
  19430. template <typename Compressor>
  19431. static std::string compress_payload_for_parity(const std::string &in) {
  19432. std::string out;
  19433. Compressor compressor;
  19434. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  19435. [&](const char *data, size_t n) {
  19436. out.append(data, n);
  19437. return true;
  19438. });
  19439. EXPECT_TRUE(ok);
  19440. return out;
  19441. }
  19442. // Helper function for compression parity tests
  19443. template <typename Compressor>
  19444. static void test_compression_parity(const std::string &original,
  19445. const std::string &path,
  19446. const std::string &encoding) {
  19447. const std::string compressed =
  19448. compress_payload_for_parity<Compressor>(original);
  19449. Server svr;
  19450. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19451. res.set_content(compressed, "application/octet-stream");
  19452. res.set_header("Content-Encoding", encoding);
  19453. });
  19454. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  19455. auto se = detail::scope_exit([&] {
  19456. svr.stop();
  19457. t.join();
  19458. ASSERT_FALSE(svr.is_running());
  19459. });
  19460. svr.wait_until_ready();
  19461. Client cli(HOST, PORT);
  19462. // Non-streaming
  19463. {
  19464. auto res = cli.Get(path);
  19465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19466. EXPECT_EQ(StatusCode::OK_200, res->status);
  19467. EXPECT_EQ(original, res->body);
  19468. }
  19469. // Streaming
  19470. {
  19471. auto h = cli.open_stream("GET", path);
  19472. ASSERT_TRUE(h.is_valid());
  19473. EXPECT_EQ(original, read_all(h));
  19474. }
  19475. }
  19476. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19477. TEST(ParityTest, Gzip) {
  19478. test_compression_parity<detail::gzip_compressor>(
  19479. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  19480. }
  19481. #endif
  19482. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19483. TEST(ParityTest, Brotli) {
  19484. test_compression_parity<detail::brotli_compressor>(
  19485. "Hello, brotli parity test payload", "/parity-br", "br");
  19486. }
  19487. #endif
  19488. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19489. TEST(ParityTest, Zstd) {
  19490. test_compression_parity<detail::zstd_compressor>(
  19491. "Zstandard parity test payload", "/parity-zstd", "zstd");
  19492. }
  19493. #endif
  19494. //==============================================================================
  19495. // New Stream API Tests
  19496. //==============================================================================
  19497. inline std::string read_body(httplib::stream::Result &result) {
  19498. std::string body;
  19499. while (result.next()) {
  19500. body.append(result.data(), result.size());
  19501. }
  19502. return body;
  19503. }
  19504. TEST(ClientConnectionTest, Basic) {
  19505. httplib::ClientConnection conn;
  19506. EXPECT_FALSE(conn.is_open());
  19507. conn.sock = 1;
  19508. EXPECT_TRUE(conn.is_open());
  19509. httplib::ClientConnection conn2(std::move(conn));
  19510. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  19511. conn2.sock = INVALID_SOCKET;
  19512. }
  19513. // Unified test server for all stream::* tests
  19514. class StreamApiTest : public ::testing::Test {
  19515. protected:
  19516. void SetUp() override {
  19517. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19518. res.set_content("Hello World!", "text/plain");
  19519. });
  19520. svr_.Get("/echo-params",
  19521. [](const httplib::Request &req, httplib::Response &res) {
  19522. std::string r;
  19523. for (const auto &p : req.params) {
  19524. if (!r.empty()) r += "&";
  19525. r += p.first + "=" + p.second;
  19526. }
  19527. res.set_content(r, "text/plain");
  19528. });
  19529. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19530. res.set_content(req.body, req.get_header_value("Content-Type"));
  19531. });
  19532. svr_.Post("/echo-headers",
  19533. [](const httplib::Request &req, httplib::Response &res) {
  19534. std::string r;
  19535. for (const auto &h : req.headers)
  19536. r += h.first + ": " + h.second + "\n";
  19537. res.set_content(r, "text/plain");
  19538. });
  19539. svr_.Post("/echo-params",
  19540. [](const httplib::Request &req, httplib::Response &res) {
  19541. std::string r = "params:";
  19542. for (const auto &p : req.params)
  19543. r += p.first + "=" + p.second + ";";
  19544. res.set_content(r + " body:" + req.body, "text/plain");
  19545. });
  19546. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  19547. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  19548. });
  19549. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19550. res.set_content("PUT:" + req.body, "text/plain");
  19551. });
  19552. svr_.Patch("/echo",
  19553. [](const httplib::Request &req, httplib::Response &res) {
  19554. res.set_content("PATCH:" + req.body, "text/plain");
  19555. });
  19556. svr_.Delete(
  19557. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  19558. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  19559. "text/plain");
  19560. });
  19561. svr_.Get("/head-test",
  19562. [](const httplib::Request &, httplib::Response &res) {
  19563. res.set_content("body for HEAD", "text/plain");
  19564. });
  19565. svr_.Options("/options",
  19566. [](const httplib::Request &, httplib::Response &res) {
  19567. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  19568. });
  19569. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  19570. svr_.wait_until_ready();
  19571. }
  19572. void TearDown() override {
  19573. svr_.stop();
  19574. if (thread_.joinable()) thread_.join();
  19575. }
  19576. httplib::Server svr_;
  19577. std::thread thread_;
  19578. };
  19579. // stream::Get tests
  19580. TEST_F(StreamApiTest, GetBasic) {
  19581. httplib::Client cli(HOST, PORT);
  19582. auto result = httplib::stream::Get(cli, "/hello");
  19583. ASSERT_TRUE(result.is_valid());
  19584. EXPECT_EQ(200, result.status());
  19585. EXPECT_EQ("Hello World!", read_body(result));
  19586. }
  19587. TEST_F(StreamApiTest, GetWithParams) {
  19588. httplib::Client cli(HOST, PORT);
  19589. httplib::Params params{{"foo", "bar"}};
  19590. auto result = httplib::stream::Get(cli, "/echo-params", params);
  19591. ASSERT_TRUE(result.is_valid());
  19592. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  19593. }
  19594. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19595. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  19596. httplib::Client cli(HOST, PORT);
  19597. cli.set_payload_max_length(0);
  19598. auto result = httplib::stream::Get(cli, "/hello");
  19599. ASSERT_TRUE(result.is_valid());
  19600. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  19601. EXPECT_EQ("Hello World!", read_body(result));
  19602. }
  19603. #endif
  19604. TEST_F(StreamApiTest, GetConnectionError) {
  19605. httplib::Client cli(HOST, 9999);
  19606. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  19607. }
  19608. TEST_F(StreamApiTest, Get404) {
  19609. httplib::Client cli(HOST, PORT);
  19610. auto result = httplib::stream::Get(cli, "/nonexistent");
  19611. EXPECT_TRUE(result.is_valid());
  19612. EXPECT_EQ(404, result.status());
  19613. }
  19614. // stream::Post tests
  19615. TEST_F(StreamApiTest, PostBasic) {
  19616. httplib::Client cli(HOST, PORT);
  19617. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  19618. "application/json");
  19619. ASSERT_TRUE(result.is_valid());
  19620. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  19621. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  19622. }
  19623. TEST_F(StreamApiTest, PostWithHeaders) {
  19624. httplib::Client cli(HOST, PORT);
  19625. httplib::Headers headers{{"X-Custom", "value"}};
  19626. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  19627. "text/plain");
  19628. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  19629. }
  19630. TEST_F(StreamApiTest, PostWithParams) {
  19631. httplib::Client cli(HOST, PORT);
  19632. httplib::Params params{{"k", "v"}};
  19633. auto result =
  19634. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  19635. auto body = read_body(result);
  19636. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  19637. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  19638. }
  19639. TEST_F(StreamApiTest, PostLarge) {
  19640. httplib::Client cli(HOST, PORT);
  19641. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  19642. size_t total = 0;
  19643. while (result.next()) {
  19644. total += result.size();
  19645. }
  19646. EXPECT_EQ(100u * 1024u, total);
  19647. }
  19648. // stream::Put/Patch tests
  19649. TEST_F(StreamApiTest, PutAndPatch) {
  19650. httplib::Client cli(HOST, PORT);
  19651. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  19652. EXPECT_EQ("PUT:test", read_body(put));
  19653. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  19654. EXPECT_EQ("PATCH:test", read_body(patch));
  19655. }
  19656. // stream::Delete tests
  19657. TEST_F(StreamApiTest, Delete) {
  19658. httplib::Client cli(HOST, PORT);
  19659. auto del1 = httplib::stream::Delete(cli, "/resource");
  19660. EXPECT_EQ("Deleted", read_body(del1));
  19661. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  19662. EXPECT_EQ("Deleted:data", read_body(del2));
  19663. }
  19664. // stream::Head/Options tests
  19665. TEST_F(StreamApiTest, HeadAndOptions) {
  19666. httplib::Client cli(HOST, PORT);
  19667. auto head = httplib::stream::Head(cli, "/head-test");
  19668. EXPECT_TRUE(head.is_valid());
  19669. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  19670. auto opts = httplib::stream::Options(cli, "/options");
  19671. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  19672. }
  19673. // SSL stream::* tests
  19674. #ifdef CPPHTTPLIB_SSL_ENABLED
  19675. class SSLStreamApiTest : public ::testing::Test {
  19676. protected:
  19677. void SetUp() override {
  19678. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19679. res.set_content("Hello SSL!", "text/plain");
  19680. });
  19681. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19682. res.set_content(req.body, "text/plain");
  19683. });
  19684. port_ = svr_.bind_to_any_port("127.0.0.1");
  19685. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19686. svr_.wait_until_ready();
  19687. }
  19688. void TearDown() override {
  19689. svr_.stop();
  19690. if (thread_.joinable()) thread_.join();
  19691. }
  19692. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  19693. std::thread thread_;
  19694. int port_ = 0;
  19695. };
  19696. TEST_F(SSLStreamApiTest, GetAndPost) {
  19697. httplib::SSLClient cli("127.0.0.1", port_);
  19698. cli.enable_server_certificate_verification(false);
  19699. auto get = httplib::stream::Get(cli, "/hello");
  19700. EXPECT_EQ("Hello SSL!", read_body(get));
  19701. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  19702. EXPECT_EQ("test", read_body(post));
  19703. }
  19704. #endif
  19705. // Tests for Error::Timeout and Error::ConnectionClosed error types
  19706. // These errors are set in SocketStream/SSLSocketStream and propagated through
  19707. // BodyReader
  19708. TEST(ErrorHandlingTest, StreamReadTimeout) {
  19709. // Test that read timeout during streaming is detected
  19710. // Use a large content-length response where server delays mid-stream
  19711. Server svr;
  19712. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19713. // Send a large response with delay in the middle
  19714. res.set_content_provider(
  19715. 1000, // content_length
  19716. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  19717. if (offset < 100) {
  19718. // Send first 100 bytes immediately
  19719. std::string data(100, 'A');
  19720. sink.write(data.c_str(), data.size());
  19721. return true;
  19722. }
  19723. // Then delay longer than client timeout
  19724. std::this_thread::sleep_for(std::chrono::seconds(3));
  19725. std::string data(900, 'B');
  19726. sink.write(data.c_str(), data.size());
  19727. return true;
  19728. });
  19729. });
  19730. auto port = 8091;
  19731. std::thread t([&]() { svr.listen("localhost", port); });
  19732. svr.wait_until_ready();
  19733. Client cli("localhost", port);
  19734. cli.set_read_timeout(1, 0); // 1 second timeout
  19735. auto handle = cli.open_stream("GET", "/slow-stream");
  19736. ASSERT_TRUE(handle.is_valid());
  19737. char buf[256];
  19738. ssize_t total = 0;
  19739. ssize_t n;
  19740. bool got_error = false;
  19741. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19742. total += n;
  19743. }
  19744. if (n < 0) {
  19745. got_error = true;
  19746. // Should be timeout or read error
  19747. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19748. handle.get_read_error() == Error::Read)
  19749. << "Actual error: " << to_string(handle.get_read_error());
  19750. }
  19751. // Either we got an error, or we got less data than expected
  19752. EXPECT_TRUE(got_error || total < 1000)
  19753. << "Expected timeout but got all " << total << " bytes";
  19754. svr.stop();
  19755. t.join();
  19756. }
  19757. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  19758. // Test connection closed detection via BodyReader
  19759. Server svr;
  19760. std::atomic<bool> close_now{false};
  19761. svr.Get("/will-close", [&](const Request &, Response &res) {
  19762. res.set_content_provider(
  19763. 10000, // Large content_length that we won't fully send
  19764. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19765. if (offset < 100) {
  19766. std::string data(100, 'X');
  19767. sink.write(data.c_str(), data.size());
  19768. return true;
  19769. }
  19770. // Wait for signal then abort
  19771. while (!close_now) {
  19772. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19773. }
  19774. return false; // Abort - server will close connection
  19775. });
  19776. });
  19777. auto port = 8092;
  19778. std::thread t([&]() { svr.listen("localhost", port); });
  19779. svr.wait_until_ready();
  19780. Client cli("localhost", port);
  19781. auto handle = cli.open_stream("GET", "/will-close");
  19782. ASSERT_TRUE(handle.is_valid());
  19783. char buf[256];
  19784. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19785. EXPECT_GT(n, 0) << "First read should succeed";
  19786. // Signal server to close
  19787. close_now = true;
  19788. // Keep reading until error or EOF
  19789. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19790. // Keep reading
  19791. }
  19792. // Should get an error since content_length wasn't satisfied
  19793. if (n < 0) {
  19794. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19795. handle.get_read_error() == Error::Read)
  19796. << "Actual error: " << to_string(handle.get_read_error());
  19797. }
  19798. svr.stop();
  19799. t.join();
  19800. }
  19801. #ifdef CPPHTTPLIB_SSL_ENABLED
  19802. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  19803. // Test that read timeout during SSL streaming is detected
  19804. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19805. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19806. res.set_content_provider(
  19807. 1000, "text/plain",
  19808. [](size_t offset, size_t /*length*/, DataSink &sink) {
  19809. if (offset < 100) {
  19810. std::string data(100, 'A');
  19811. sink.write(data.c_str(), data.size());
  19812. return true;
  19813. }
  19814. std::this_thread::sleep_for(std::chrono::seconds(3));
  19815. std::string data(900, 'B');
  19816. sink.write(data.c_str(), data.size());
  19817. return true;
  19818. });
  19819. });
  19820. auto port = 8093;
  19821. std::thread t([&]() { svr.listen("localhost", port); });
  19822. svr.wait_until_ready();
  19823. SSLClient cli("localhost", port);
  19824. cli.enable_server_certificate_verification(false);
  19825. cli.set_read_timeout(1, 0); // 1 second timeout
  19826. auto handle = cli.open_stream("GET", "/slow-stream");
  19827. ASSERT_TRUE(handle.is_valid());
  19828. char buf[256];
  19829. ssize_t total = 0;
  19830. ssize_t n;
  19831. bool got_error = false;
  19832. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19833. total += n;
  19834. }
  19835. if (n < 0) {
  19836. got_error = true;
  19837. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19838. handle.get_read_error() == Error::Read)
  19839. << "Actual error: " << to_string(handle.get_read_error());
  19840. }
  19841. EXPECT_TRUE(got_error || total < 1000)
  19842. << "Expected timeout but got all " << total << " bytes";
  19843. svr.stop();
  19844. t.join();
  19845. }
  19846. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  19847. // Test SSL connection closed detection
  19848. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19849. std::atomic<bool> close_now{false};
  19850. svr.Get("/will-close", [&](const Request &, Response &res) {
  19851. res.set_content_provider(
  19852. 10000, "text/plain",
  19853. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19854. if (offset < 100) {
  19855. std::string data(100, 'X');
  19856. sink.write(data.c_str(), data.size());
  19857. return true;
  19858. }
  19859. while (!close_now) {
  19860. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19861. }
  19862. return false;
  19863. });
  19864. });
  19865. auto port = 8094;
  19866. std::thread t([&]() { svr.listen("localhost", port); });
  19867. svr.wait_until_ready();
  19868. SSLClient cli("localhost", port);
  19869. cli.enable_server_certificate_verification(false);
  19870. auto handle = cli.open_stream("GET", "/will-close");
  19871. ASSERT_TRUE(handle.is_valid());
  19872. char buf[256];
  19873. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19874. EXPECT_GT(n, 0);
  19875. // Signal server to close
  19876. close_now = true;
  19877. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19878. // Keep reading
  19879. }
  19880. if (n < 0) {
  19881. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19882. handle.get_read_error() == Error::Read)
  19883. << "Actual error: " << to_string(handle.get_read_error());
  19884. }
  19885. svr.stop();
  19886. t.join();
  19887. }
  19888. #endif
  19889. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  19890. using namespace httplib;
  19891. // Create a test file
  19892. const char *fname = "etag_testfile.txt";
  19893. const char *content = "etag-content";
  19894. {
  19895. std::ofstream ofs(fname);
  19896. ofs << content;
  19897. ASSERT_TRUE(ofs.good());
  19898. }
  19899. Server svr;
  19900. svr.set_mount_point("/static", ".");
  19901. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19902. svr.wait_until_ready();
  19903. Client cli(HOST, PORT);
  19904. // First request: should get 200 with ETag header
  19905. auto res1 = cli.Get("/static/etag_testfile.txt");
  19906. ASSERT_TRUE(res1);
  19907. ASSERT_EQ(200, res1->status);
  19908. ASSERT_TRUE(res1->has_header("ETag"));
  19909. std::string etag = res1->get_header_value("ETag");
  19910. EXPECT_FALSE(etag.empty());
  19911. // Verify ETag format: W/"hex-hex"
  19912. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  19913. EXPECT_EQ('W', etag[0]);
  19914. EXPECT_EQ('/', etag[1]);
  19915. EXPECT_EQ('"', etag[2]);
  19916. EXPECT_EQ('"', etag.back());
  19917. // Exact match: expect 304 Not Modified
  19918. Headers h2 = {{"If-None-Match", etag}};
  19919. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  19920. ASSERT_TRUE(res2);
  19921. EXPECT_EQ(304, res2->status);
  19922. // Wildcard match: expect 304 Not Modified
  19923. Headers h3 = {{"If-None-Match", "*"}};
  19924. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  19925. ASSERT_TRUE(res3);
  19926. EXPECT_EQ(304, res3->status);
  19927. // Non-matching ETag: expect 200
  19928. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  19929. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  19930. ASSERT_TRUE(res4);
  19931. EXPECT_EQ(200, res4->status);
  19932. // Multiple ETags with one matching: expect 304
  19933. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  19934. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  19935. ASSERT_TRUE(res5);
  19936. EXPECT_EQ(304, res5->status);
  19937. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  19938. // that equivalent to the single comma-separated list above, so the match on
  19939. // the second line must still be found.
  19940. Headers h6;
  19941. h6.emplace("If-None-Match", "W/\"other\"");
  19942. h6.emplace("If-None-Match", etag);
  19943. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  19944. ASSERT_TRUE(res6);
  19945. EXPECT_EQ(304, res6->status);
  19946. svr.stop();
  19947. t.join();
  19948. std::remove(fname);
  19949. }
  19950. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  19951. using namespace httplib;
  19952. Server svr;
  19953. svr.set_mount_point("/static", ".");
  19954. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19955. svr.wait_until_ready();
  19956. Client cli(HOST, PORT);
  19957. // Send If-None-Match: * to a non-existent file
  19958. Headers h = {{"If-None-Match", "*"}};
  19959. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  19960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19961. EXPECT_EQ(404, res->status);
  19962. svr.stop();
  19963. t.join();
  19964. }
  19965. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  19966. using namespace httplib;
  19967. // Create a test file
  19968. const char *fname = "etag_boundary_testfile.txt";
  19969. const char *content = "boundary-test";
  19970. {
  19971. std::ofstream ofs(fname);
  19972. ofs << content;
  19973. ASSERT_TRUE(ofs.good());
  19974. }
  19975. Server svr;
  19976. svr.set_mount_point("/static", ".");
  19977. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19978. svr.wait_until_ready();
  19979. Client cli(HOST, PORT);
  19980. // Get the actual ETag
  19981. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  19982. ASSERT_TRUE(res1);
  19983. ASSERT_EQ(200, res1->status);
  19984. ASSERT_TRUE(res1->has_header("ETag"));
  19985. std::string etag = res1->get_header_value("ETag");
  19986. // Test 1: Very long ETag value (longer than actual ETag)
  19987. // Should NOT match and return 200 (not trigger out-of-bounds read)
  19988. Headers h1 = {{"If-None-Match", "W/"
  19989. "\"very-long-etag-value-that-is-much-longer-"
  19990. "than-the-actual-etag-value\""}};
  19991. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  19992. ASSERT_TRUE(res2);
  19993. EXPECT_EQ(200, res2->status); // Should not match
  19994. // Test 2: Long string followed by wildcard
  19995. // Should match on "*" and return 304 (without out-of-bounds read on the long
  19996. // string)
  19997. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  19998. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  19999. ASSERT_TRUE(res3);
  20000. EXPECT_EQ(304, res3->status); // Should match on "*"
  20001. // Test 3: Wildcard followed by long string
  20002. // Should match on "*" immediately and return 304
  20003. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  20004. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  20005. ASSERT_TRUE(res4);
  20006. EXPECT_EQ(304, res4->status); // Should match on "*"
  20007. // Test 4: Multiple long non-matching values
  20008. // Should NOT match and return 200 (test that all comparisons are safe)
  20009. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  20010. "W/\"second-long-non-matching-value\", "
  20011. "W/\"third-long-non-matching-value\""}};
  20012. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  20013. ASSERT_TRUE(res5);
  20014. EXPECT_EQ(200, res5->status); // Should not match
  20015. // Test 5: Single character that is not "*" (edge case)
  20016. Headers h5 = {{"If-None-Match", "X"}};
  20017. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  20018. ASSERT_TRUE(res6);
  20019. EXPECT_EQ(200, res6->status); // Should not match
  20020. svr.stop();
  20021. t.join();
  20022. std::remove(fname);
  20023. }
  20024. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  20025. using namespace httplib;
  20026. // Create a test file
  20027. const char *fname = "ims_testfile.txt";
  20028. const char *content = "if-modified-since-test";
  20029. {
  20030. std::ofstream ofs(fname);
  20031. ofs << content;
  20032. ASSERT_TRUE(ofs.good());
  20033. }
  20034. Server svr;
  20035. svr.set_mount_point("/static", ".");
  20036. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20037. svr.wait_until_ready();
  20038. Client cli(HOST, PORT);
  20039. // First request: should get 200 with Last-Modified header
  20040. auto res1 = cli.Get("/static/ims_testfile.txt");
  20041. ASSERT_TRUE(res1);
  20042. ASSERT_EQ(200, res1->status);
  20043. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20044. std::string last_modified = res1->get_header_value("Last-Modified");
  20045. EXPECT_FALSE(last_modified.empty());
  20046. // If-Modified-Since with same time: expect 304
  20047. Headers h2 = {{"If-Modified-Since", last_modified}};
  20048. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  20049. ASSERT_TRUE(res2);
  20050. EXPECT_EQ(304, res2->status);
  20051. // If-Modified-Since with future time: expect 304
  20052. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20053. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  20054. ASSERT_TRUE(res3);
  20055. EXPECT_EQ(304, res3->status);
  20056. // If-Modified-Since with past time: expect 200
  20057. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20058. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  20059. ASSERT_TRUE(res4);
  20060. EXPECT_EQ(200, res4->status);
  20061. // If-None-Match takes precedence over If-Modified-Since
  20062. // (send matching ETag with old If-Modified-Since -> should still be 304)
  20063. ASSERT_TRUE(res1->has_header("ETag"));
  20064. std::string etag = res1->get_header_value("ETag");
  20065. Headers h5 = {{"If-None-Match", etag},
  20066. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20067. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  20068. ASSERT_TRUE(res5);
  20069. EXPECT_EQ(304, res5->status);
  20070. svr.stop();
  20071. t.join();
  20072. std::remove(fname);
  20073. }
  20074. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  20075. using namespace httplib;
  20076. Server svr;
  20077. // Endpoint that returns compressible content
  20078. svr.Get("/compressible", [](const Request &, Response &res) {
  20079. // Return a large enough body to trigger compression
  20080. std::string body(1000, 'a');
  20081. res.set_content(body, "text/plain");
  20082. });
  20083. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20084. svr.wait_until_ready();
  20085. Client cli(HOST, PORT);
  20086. // Request with gzip support: should get Vary header when compressed
  20087. cli.set_compress(true);
  20088. auto res1 = cli.Get("/compressible");
  20089. ASSERT_TRUE(res1);
  20090. EXPECT_EQ(200, res1->status);
  20091. // If Content-Encoding is set, Vary should also be set
  20092. if (res1->has_header("Content-Encoding")) {
  20093. EXPECT_TRUE(res1->has_header("Vary"));
  20094. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  20095. }
  20096. // Request without Accept-Encoding header: should not have compression
  20097. Headers h_no_compress;
  20098. auto res2 = cli.Get("/compressible", h_no_compress);
  20099. ASSERT_TRUE(res2);
  20100. EXPECT_EQ(200, res2->status);
  20101. // Verify Vary header is present when compression is applied
  20102. // (the exact behavior depends on server configuration)
  20103. svr.stop();
  20104. t.join();
  20105. }
  20106. TEST(ETagTest, IfRangeWithETag) {
  20107. using namespace httplib;
  20108. // Create a test file with known content
  20109. const char *fname = "if_range_testfile.txt";
  20110. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  20111. {
  20112. std::ofstream ofs(fname);
  20113. ofs << content;
  20114. ASSERT_TRUE(ofs.good());
  20115. }
  20116. Server svr;
  20117. svr.set_mount_point("/static", ".");
  20118. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20119. svr.wait_until_ready();
  20120. Client cli(HOST, PORT);
  20121. // First request: get ETag
  20122. auto res1 = cli.Get("/static/if_range_testfile.txt");
  20123. ASSERT_TRUE(res1);
  20124. ASSERT_EQ(200, res1->status);
  20125. ASSERT_TRUE(res1->has_header("ETag"));
  20126. std::string etag = res1->get_header_value("ETag");
  20127. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  20128. // Since our server generates weak ETags (W/"..."), If-Range with our
  20129. // ETag should NOT result in partial content - it should return full content.
  20130. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  20131. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  20132. ASSERT_TRUE(res2);
  20133. // Weak ETag in If-Range -> full content (200), not partial (206)
  20134. EXPECT_EQ(200, res2->status);
  20135. EXPECT_EQ(content, res2->body);
  20136. EXPECT_FALSE(res2->has_header("Content-Range"));
  20137. // Range request with non-matching If-Range (ETag): should get 200 (full
  20138. // content)
  20139. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  20140. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  20141. ASSERT_TRUE(res3);
  20142. EXPECT_EQ(200, res3->status);
  20143. EXPECT_EQ(content, res3->body);
  20144. EXPECT_FALSE(res3->has_header("Content-Range"));
  20145. // Range request with strong ETag (hypothetical - our server doesn't generate
  20146. // strong ETags, but if client sends a strong ETag that doesn't match, it
  20147. // should return full content)
  20148. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  20149. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  20150. ASSERT_TRUE(res4);
  20151. EXPECT_EQ(200, res4->status);
  20152. EXPECT_EQ(content, res4->body);
  20153. EXPECT_FALSE(res4->has_header("Content-Range"));
  20154. svr.stop();
  20155. t.join();
  20156. std::remove(fname);
  20157. }
  20158. TEST(ETagTest, IfRangeWithDate) {
  20159. using namespace httplib;
  20160. // Create a test file
  20161. const char *fname = "if_range_date_testfile.txt";
  20162. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  20163. {
  20164. std::ofstream ofs(fname);
  20165. ofs << content;
  20166. ASSERT_TRUE(ofs.good());
  20167. }
  20168. Server svr;
  20169. svr.set_mount_point("/static", ".");
  20170. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20171. svr.wait_until_ready();
  20172. Client cli(HOST, PORT);
  20173. // First request: get Last-Modified
  20174. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  20175. ASSERT_TRUE(res1);
  20176. ASSERT_EQ(200, res1->status);
  20177. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20178. std::string last_modified = res1->get_header_value("Last-Modified");
  20179. // Range request with matching If-Range (date): should get 206
  20180. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  20181. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  20182. ASSERT_TRUE(res2);
  20183. EXPECT_EQ(206, res2->status);
  20184. EXPECT_EQ("FGHIJ", res2->body);
  20185. // Range request with old If-Range date: should get 200 (full content)
  20186. Headers h3 = {{"Range", "bytes=5-9"},
  20187. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20188. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  20189. ASSERT_TRUE(res3);
  20190. EXPECT_EQ(200, res3->status);
  20191. EXPECT_EQ(content, res3->body);
  20192. // Range request with future If-Range date: should get 206
  20193. Headers h4 = {{"Range", "bytes=0-4"},
  20194. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20195. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  20196. ASSERT_TRUE(res4);
  20197. EXPECT_EQ(206, res4->status);
  20198. EXPECT_EQ("ABCDE", res4->body);
  20199. svr.stop();
  20200. t.join();
  20201. std::remove(fname);
  20202. }
  20203. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  20204. using namespace httplib;
  20205. const char *fname = "etag_malformed.txt";
  20206. const char *content = "malformed-etag";
  20207. {
  20208. std::ofstream ofs(fname);
  20209. ofs << content;
  20210. ASSERT_TRUE(ofs.good());
  20211. }
  20212. Server svr;
  20213. svr.set_mount_point("/static", ".");
  20214. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20215. svr.wait_until_ready();
  20216. Client cli(HOST, PORT);
  20217. // baseline: should get 200 and an ETag
  20218. auto res1 = cli.Get("/static/etag_malformed.txt");
  20219. ASSERT_TRUE(res1);
  20220. ASSERT_EQ(200, res1->status);
  20221. ASSERT_TRUE(res1->has_header("ETag"));
  20222. // Malformed ETag value (missing quotes) should be treated as non-matching
  20223. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  20224. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  20225. ASSERT_TRUE(res_bad);
  20226. EXPECT_EQ(200, res_bad->status);
  20227. // Whitespace-only header value should be considered invalid / non-matching
  20228. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  20229. "Host: localhost\r\n"
  20230. "If-None-Match: \r\n"
  20231. "Connection: close\r\n"
  20232. "\r\n";
  20233. std::string out;
  20234. ASSERT_TRUE(send_request(5, raw_req, &out));
  20235. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20236. svr.stop();
  20237. t.join();
  20238. std::remove(fname);
  20239. }
  20240. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  20241. using namespace httplib;
  20242. const char *fname = "ims_invalid_format.txt";
  20243. const char *content = "ims-bad-format";
  20244. {
  20245. std::ofstream ofs(fname);
  20246. ofs << content;
  20247. ASSERT_TRUE(ofs.good());
  20248. }
  20249. Server svr;
  20250. svr.set_mount_point("/static", ".");
  20251. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20252. svr.wait_until_ready();
  20253. Client cli(HOST, PORT);
  20254. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  20255. ASSERT_TRUE(res1);
  20256. ASSERT_EQ(200, res1->status);
  20257. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20258. // If-Modified-Since with invalid format should not result in 304
  20259. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  20260. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  20261. ASSERT_TRUE(res_bad);
  20262. EXPECT_EQ(200, res_bad->status);
  20263. // If-Range with invalid date format should be treated as mismatch -> full
  20264. // content (200)
  20265. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  20266. {"If-Range", "invalid-date"}};
  20267. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  20268. ASSERT_TRUE(res_ifrange);
  20269. EXPECT_EQ(200, res_ifrange->status);
  20270. svr.stop();
  20271. t.join();
  20272. std::remove(fname);
  20273. }
  20274. TEST(ETagTest, IfRangeWithMalformedETag) {
  20275. using namespace httplib;
  20276. const char *fname = "ifrange_malformed.txt";
  20277. const std::string content = "0123456789";
  20278. {
  20279. std::ofstream ofs(fname);
  20280. ofs << content;
  20281. ASSERT_TRUE(ofs.good());
  20282. }
  20283. Server svr;
  20284. svr.set_mount_point("/static", ".");
  20285. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20286. svr.wait_until_ready();
  20287. Client cli(HOST, PORT);
  20288. // First request: get ETag
  20289. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  20290. ASSERT_TRUE(res1);
  20291. ASSERT_EQ(200, res1->status);
  20292. ASSERT_TRUE(res1->has_header("ETag"));
  20293. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  20294. // full content (200)
  20295. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  20296. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  20297. ASSERT_TRUE(res2);
  20298. EXPECT_EQ(200, res2->status);
  20299. EXPECT_EQ(content, res2->body);
  20300. svr.stop();
  20301. t.join();
  20302. std::remove(fname);
  20303. }
  20304. TEST(ETagTest, ExtremeLargeDateValues) {
  20305. using namespace httplib;
  20306. const char *fname = "ims_extreme_date.txt";
  20307. const char *content = "ims-extreme-date";
  20308. {
  20309. std::ofstream ofs(fname);
  20310. ofs << content;
  20311. ASSERT_TRUE(ofs.good());
  20312. }
  20313. Server svr;
  20314. svr.set_mount_point("/static", ".");
  20315. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20316. svr.wait_until_ready();
  20317. Client cli(HOST, PORT);
  20318. auto res1 = cli.Get(std::string("/static/") + fname);
  20319. ASSERT_TRUE(res1);
  20320. ASSERT_EQ(200, res1->status);
  20321. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20322. // Extremely large year that may overflow date parsing routines.
  20323. Headers h_large_date = {
  20324. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20325. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  20326. ASSERT_TRUE(res_bad);
  20327. // Expect server to treat this as invalid/mismatch and return full content
  20328. EXPECT_EQ(200, res_bad->status);
  20329. // If-Range with extremely large date should be treated as mismatch -> full
  20330. // content (200)
  20331. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  20332. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20333. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  20334. ASSERT_TRUE(res_ifrange);
  20335. EXPECT_EQ(200, res_ifrange->status);
  20336. svr.stop();
  20337. t.join();
  20338. std::remove(fname);
  20339. }
  20340. TEST(ETagTest, NegativeFileModificationTime) {
  20341. using namespace httplib;
  20342. const char *fname = "ims_negative_mtime.txt";
  20343. const std::string content = "negative-mtime";
  20344. {
  20345. std::ofstream ofs(fname);
  20346. ofs << content;
  20347. ASSERT_TRUE(ofs.good());
  20348. }
  20349. // Try to set file mtime to a negative value. This may fail on some
  20350. // platforms/filesystems; if it fails, the test will still verify server
  20351. // behaves safely by performing a regular conditional request.
  20352. #if defined(__APPLE__) || defined(__linux__)
  20353. bool set_negative = false;
  20354. do {
  20355. struct timeval times[2];
  20356. // access time: now
  20357. times[0].tv_sec = time(nullptr);
  20358. times[0].tv_usec = 0;
  20359. // modification time: negative (e.g., -1)
  20360. times[1].tv_sec = -1;
  20361. times[1].tv_usec = 0;
  20362. if (utimes(fname, times) == 0) { set_negative = true; }
  20363. } while (0);
  20364. #else
  20365. bool set_negative = false;
  20366. #endif
  20367. Server svr;
  20368. svr.set_mount_point("/static", ".");
  20369. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20370. svr.wait_until_ready();
  20371. Client cli(HOST, PORT);
  20372. auto res1 = cli.Get(std::string("/static/") + fname);
  20373. ASSERT_TRUE(res1);
  20374. ASSERT_EQ(200, res1->status);
  20375. bool has_last_modified = res1->has_header("Last-Modified");
  20376. std::string last_modified;
  20377. if (has_last_modified) {
  20378. last_modified = res1->get_header_value("Last-Modified");
  20379. }
  20380. if (set_negative) {
  20381. // If we successfully set a negative mtime, ensure server returns a
  20382. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  20383. // with an old date and ensure server handles it without crash.
  20384. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  20385. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  20386. ASSERT_TRUE(res2);
  20387. // Behavior may vary; at minimum ensure server responds (200 or 304).
  20388. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  20389. } else {
  20390. // Could not set negative mtime on this platform; fall back to verifying
  20391. // that normal invalid/malformed dates are treated safely (non-304).
  20392. Headers h_bad_date = {
  20393. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20394. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  20395. ASSERT_TRUE(res_bad);
  20396. EXPECT_EQ(200, res_bad->status);
  20397. }
  20398. svr.stop();
  20399. t.join();
  20400. std::remove(fname);
  20401. }
  20402. //==============================================================================
  20403. // Integration Tests with Server
  20404. //==============================================================================
  20405. class SSEIntegrationTest : public ::testing::Test {
  20406. protected:
  20407. void SetUp() override {
  20408. stop_server_.store(false);
  20409. events_.clear();
  20410. server_ = httplib::detail::make_unique<Server>();
  20411. setup_server();
  20412. start_server();
  20413. }
  20414. void TearDown() override {
  20415. stop_server_.store(true);
  20416. event_cv_.notify_all();
  20417. server_->stop();
  20418. if (server_thread_.joinable()) { server_thread_.join(); }
  20419. }
  20420. void setup_server() {
  20421. // Simple SSE endpoint
  20422. server_->Get("/events", [this](const Request &req, Response &res) {
  20423. auto last_id = req.get_header_value("Last-Event-ID");
  20424. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  20425. res.set_chunked_content_provider(
  20426. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  20427. std::unique_lock<std::mutex> lock(event_mutex_);
  20428. if (event_cv_.wait_for(
  20429. lock, std::chrono::milliseconds(200), [this] {
  20430. return !events_.empty() || stop_server_.load();
  20431. })) {
  20432. if (stop_server_.load()) { return false; }
  20433. if (!events_.empty()) {
  20434. std::string event = events_.front();
  20435. events_.erase(events_.begin());
  20436. sink.write(event.data(), event.size());
  20437. return true;
  20438. }
  20439. }
  20440. return !stop_server_.load();
  20441. });
  20442. });
  20443. // Endpoint that returns error
  20444. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  20445. res.status = 500;
  20446. res.set_content("Internal Server Error", "text/plain");
  20447. });
  20448. // Endpoint for custom event types
  20449. server_->Get("/custom-events", [](const Request &, Response &res) {
  20450. res.set_chunked_content_provider(
  20451. "text/event-stream", [](size_t offset, DataSink &sink) {
  20452. if (offset == 0) {
  20453. std::string event = "event: update\ndata: updated\n\n"
  20454. "event: delete\ndata: deleted\n\n";
  20455. sink.write(event.data(), event.size());
  20456. }
  20457. return false; // End stream after sending
  20458. });
  20459. });
  20460. }
  20461. void start_server() {
  20462. port_ = server_->bind_to_any_port(HOST);
  20463. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20464. // Wait for server to start
  20465. while (!server_->is_running()) {
  20466. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20467. }
  20468. }
  20469. int get_port() const { return port_; }
  20470. void send_event(const std::string &event) {
  20471. std::lock_guard<std::mutex> lock(event_mutex_);
  20472. events_.push_back(event);
  20473. event_cv_.notify_all();
  20474. }
  20475. std::unique_ptr<Server> server_;
  20476. std::thread server_thread_;
  20477. std::mutex event_mutex_;
  20478. std::condition_variable event_cv_;
  20479. std::vector<std::string> events_;
  20480. std::atomic<bool> stop_server_{false};
  20481. std::string last_received_event_id_;
  20482. int port_ = 0;
  20483. };
  20484. //==============================================================================
  20485. // SSE Parsing Tests
  20486. //==============================================================================
  20487. class SSEParsingTest : public SSEIntegrationTest {
  20488. protected:
  20489. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  20490. // A trailing sentinel event tells when the whole stream has been parsed.
  20491. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  20492. auto body = stream + "event: end\ndata: end\n\n";
  20493. server_->Get("/parse", [body](const Request &, Response &res) {
  20494. res.set_content(body, "text/event-stream");
  20495. });
  20496. return collect("/parse");
  20497. }
  20498. // Runs SSEClient against path until an "end" event arrives and returns the
  20499. // messages dispatched before it
  20500. std::vector<sse::SSEMessage> collect(const std::string &path) {
  20501. Client client(HOST, get_port());
  20502. sse::SSEClient sse(client, path);
  20503. std::mutex mutex;
  20504. std::condition_variable cv;
  20505. std::vector<sse::SSEMessage> messages;
  20506. auto done = false;
  20507. sse.on_message([&](const sse::SSEMessage &msg) {
  20508. std::lock_guard<std::mutex> lock(mutex);
  20509. // Ignore a replay from a reconnect that races with stop()
  20510. if (!done) { messages.push_back(msg); }
  20511. });
  20512. sse.on_event("end", [&](const sse::SSEMessage &) {
  20513. std::lock_guard<std::mutex> lock(mutex);
  20514. done = true;
  20515. cv.notify_all();
  20516. });
  20517. sse.set_reconnect_interval(100);
  20518. sse.start_async();
  20519. {
  20520. std::unique_lock<std::mutex> lock(mutex);
  20521. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  20522. }
  20523. sse.stop();
  20524. EXPECT_TRUE(done);
  20525. return messages;
  20526. }
  20527. };
  20528. TEST_F(SSEParsingTest, SingleLineData) {
  20529. auto msgs = parse("data: hello\n\n");
  20530. ASSERT_EQ(msgs.size(), 1u);
  20531. EXPECT_EQ(msgs[0].data, "hello");
  20532. EXPECT_EQ(msgs[0].event, "message");
  20533. }
  20534. TEST_F(SSEParsingTest, MultiLineData) {
  20535. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  20536. ASSERT_EQ(msgs.size(), 1u);
  20537. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  20538. }
  20539. TEST_F(SSEParsingTest, CustomEventType) {
  20540. auto msgs = parse("event: update\ndata: payload\n\n");
  20541. ASSERT_EQ(msgs.size(), 1u);
  20542. EXPECT_EQ(msgs[0].event, "update");
  20543. EXPECT_EQ(msgs[0].data, "payload");
  20544. }
  20545. TEST_F(SSEParsingTest, EventIdHandling) {
  20546. auto msgs = parse("id: 12345\ndata: test\n\n");
  20547. ASSERT_EQ(msgs.size(), 1u);
  20548. EXPECT_EQ(msgs[0].id, "12345");
  20549. }
  20550. TEST_F(SSEParsingTest, EmptyEventId) {
  20551. auto msgs = parse("id:\ndata: test\n\n");
  20552. ASSERT_EQ(msgs.size(), 1u);
  20553. EXPECT_EQ(msgs[0].id, "");
  20554. }
  20555. TEST_F(SSEParsingTest, CommentsIgnored) {
  20556. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  20557. ASSERT_EQ(msgs.size(), 1u);
  20558. EXPECT_EQ(msgs[0].data, "hello");
  20559. EXPECT_EQ(msgs[0].event, "message");
  20560. }
  20561. TEST_F(SSEParsingTest, ColonInValue) {
  20562. auto msgs = parse("data: hello:world:test\n\n");
  20563. ASSERT_EQ(msgs.size(), 1u);
  20564. EXPECT_EQ(msgs[0].data, "hello:world:test");
  20565. }
  20566. TEST_F(SSEParsingTest, FieldNameOnly) {
  20567. // A line without a colon is a field name with an empty value
  20568. auto msgs = parse("data\n\n");
  20569. ASSERT_EQ(msgs.size(), 1u);
  20570. EXPECT_EQ(msgs[0].data, "");
  20571. }
  20572. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  20573. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  20574. ASSERT_EQ(msgs.size(), 1u);
  20575. EXPECT_EQ(msgs[0].event, "update");
  20576. EXPECT_EQ(msgs[0].data, "hello");
  20577. }
  20578. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  20579. auto msgs = parse("data\r\n\r\n");
  20580. ASSERT_EQ(msgs.size(), 1u);
  20581. EXPECT_EQ(msgs[0].data, "");
  20582. }
  20583. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  20584. auto msgs = parse("event: update\rdata: hello\r\r");
  20585. ASSERT_EQ(msgs.size(), 1u);
  20586. EXPECT_EQ(msgs[0].event, "update");
  20587. EXPECT_EQ(msgs[0].data, "hello");
  20588. }
  20589. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  20590. // Chunk boundaries fall inside every \r\n and right before the first one
  20591. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  20592. "\n\r", "\nevent: end\ndata: end\n\n"};
  20593. server_->Get("/split", [chunks](const Request &, Response &res) {
  20594. auto i = std::make_shared<size_t>(0);
  20595. res.set_chunked_content_provider(
  20596. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  20597. if (*i == chunks.size()) {
  20598. sink.done();
  20599. } else {
  20600. sink.write(chunks[*i].data(), chunks[*i].size());
  20601. (*i)++;
  20602. }
  20603. return true;
  20604. });
  20605. });
  20606. auto msgs = collect("/split");
  20607. ASSERT_EQ(msgs.size(), 1u);
  20608. EXPECT_EQ(msgs[0].event, "update");
  20609. EXPECT_EQ(msgs[0].data, "hello");
  20610. }
  20611. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  20612. // Only a BOM at the start of the stream is ignored
  20613. auto msgs = parse("\xEF\xBB\xBF"
  20614. "data: first\n\n"
  20615. "\xEF\xBB\xBF"
  20616. "data: second\n\n");
  20617. ASSERT_EQ(msgs.size(), 1u);
  20618. EXPECT_EQ(msgs[0].data, "first");
  20619. }
  20620. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  20621. auto msgs = parse("unknown: value\ndata: hello\n\n");
  20622. ASSERT_EQ(msgs.size(), 1u);
  20623. EXPECT_EQ(msgs[0].data, "hello");
  20624. EXPECT_EQ(msgs[0].event, "message");
  20625. }
  20626. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  20627. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  20628. ASSERT_EQ(msgs.size(), 2u);
  20629. EXPECT_EQ(msgs[0].data, "hello");
  20630. EXPECT_EQ(msgs[1].data, "hello");
  20631. }
  20632. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  20633. // An event without data is not dispatched, and its type must not leak
  20634. // into the next event
  20635. auto msgs = parse("event: update\n\ndata: hello\n\n");
  20636. ASSERT_EQ(msgs.size(), 1u);
  20637. EXPECT_EQ(msgs[0].event, "message");
  20638. EXPECT_EQ(msgs[0].data, "hello");
  20639. }
  20640. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  20641. // The first connection sends only an id; the second echoes back the
  20642. // Last-Event-ID it was reconnected with
  20643. std::atomic<int> connection_count{0};
  20644. server_->Get("/id-only", [&](const Request &req, Response &res) {
  20645. if (connection_count++ == 0) {
  20646. res.set_content("id: 42\n\n", "text/event-stream");
  20647. } else {
  20648. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20649. "\n\nevent: end\ndata: end\n\n",
  20650. "text/event-stream");
  20651. }
  20652. });
  20653. auto msgs = collect("/id-only");
  20654. ASSERT_EQ(msgs.size(), 1u);
  20655. EXPECT_EQ(msgs[0].data, "42");
  20656. }
  20657. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  20658. // The first connection sets an id and then clears it with an empty one; the
  20659. // second reports whether it was reconnected with a Last-Event-ID
  20660. std::atomic<int> connection_count{0};
  20661. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  20662. if (connection_count++ == 0) {
  20663. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  20664. "text/event-stream");
  20665. } else {
  20666. res.set_content(
  20667. std::string("data: ") +
  20668. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  20669. "\n\nevent: end\ndata: end\n\n",
  20670. "text/event-stream");
  20671. }
  20672. });
  20673. auto msgs = collect("/id-clear");
  20674. ASSERT_EQ(msgs.size(), 3u);
  20675. EXPECT_EQ(msgs[0].id, "1");
  20676. EXPECT_EQ(msgs[1].id, "");
  20677. EXPECT_EQ(msgs[2].data, "not sent");
  20678. }
  20679. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  20680. // The first connection sets an id and then sends ids that cannot be carried
  20681. // in a header; the second echoes back the Last-Event-ID it was reconnected
  20682. // with
  20683. std::atomic<int> connection_count{0};
  20684. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  20685. if (connection_count++ == 0) {
  20686. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  20687. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  20688. "text/event-stream");
  20689. } else {
  20690. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20691. "\n\nevent: end\ndata: end\n\n",
  20692. "text/event-stream");
  20693. }
  20694. });
  20695. auto msgs = collect("/id-unsendable");
  20696. ASSERT_EQ(msgs.size(), 1u);
  20697. EXPECT_EQ(msgs[0].data, "42");
  20698. }
  20699. TEST_F(SSEParsingTest, CompleteEventParsing) {
  20700. auto msgs = parse("event: notification\nid: evt-42\n"
  20701. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  20702. ASSERT_EQ(msgs.size(), 1u);
  20703. EXPECT_EQ(msgs[0].event, "notification");
  20704. EXPECT_EQ(msgs[0].id, "evt-42");
  20705. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  20706. }
  20707. TEST(SSEMessageTest, Clear) {
  20708. sse::SSEMessage msg;
  20709. msg.event = "custom";
  20710. msg.data = "some data";
  20711. msg.id = "123";
  20712. msg.clear();
  20713. EXPECT_EQ(msg.event, "message");
  20714. EXPECT_EQ(msg.data, "");
  20715. EXPECT_EQ(msg.id, "");
  20716. }
  20717. //==============================================================================
  20718. // SSE Integration Tests
  20719. //==============================================================================
  20720. // Test: Successful connection and on_open callback
  20721. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  20722. // Add a simple endpoint that sends one event and closes
  20723. server_->Get("/simple-event", [](const Request &, Response &res) {
  20724. res.set_chunked_content_provider(
  20725. "text/event-stream", [](size_t offset, DataSink &sink) {
  20726. if (offset == 0) {
  20727. std::string event = "data: hello\n\n";
  20728. sink.write(event.data(), event.size());
  20729. }
  20730. return false; // Close stream after sending
  20731. });
  20732. });
  20733. Client client("localhost", get_port());
  20734. sse::SSEClient sse(client, "/simple-event");
  20735. std::atomic<bool> open_called{false};
  20736. std::atomic<bool> message_received{false};
  20737. sse.on_open([&open_called]() { open_called.store(true); });
  20738. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  20739. if (msg.data == "hello") { message_received.store(true); }
  20740. });
  20741. sse.set_reconnect_interval(100);
  20742. sse.set_max_reconnect_attempts(1);
  20743. // Start async
  20744. sse.start_async();
  20745. // Wait for message to be processed
  20746. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20747. sse.stop();
  20748. EXPECT_TRUE(open_called.load());
  20749. EXPECT_TRUE(message_received.load());
  20750. }
  20751. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  20752. // A data line that never ends.
  20753. server_->Get("/endless-line", [](const Request &, Response &res) {
  20754. res.set_chunked_content_provider(
  20755. "text/event-stream", [](size_t offset, DataSink &sink) {
  20756. if (offset == 0) { sink.write("data: ", 6); }
  20757. std::string chunk(64 * 1024, 'A');
  20758. return sink.write(chunk.data(), chunk.size());
  20759. });
  20760. });
  20761. Client client("localhost", get_port());
  20762. sse::SSEClient sse(client, "/endless-line");
  20763. std::atomic<bool> too_long{false};
  20764. sse.on_error([&](Error err) {
  20765. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  20766. });
  20767. sse.set_max_reconnect_attempts(1);
  20768. sse.start_async();
  20769. for (int i = 0; i < 500 && !too_long; i++) {
  20770. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20771. }
  20772. sse.stop();
  20773. EXPECT_TRUE(too_long);
  20774. }
  20775. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  20776. // Far more in all than the client's payload limit below.
  20777. server_->Get("/many-events", [](const Request &, Response &res) {
  20778. res.set_chunked_content_provider(
  20779. "text/event-stream", [](size_t offset, DataSink &sink) {
  20780. if (offset == 0) {
  20781. std::string events;
  20782. for (int i = 0; i < 1000; i++) {
  20783. events += "data: message\n\n";
  20784. }
  20785. sink.write(events.data(), events.size());
  20786. }
  20787. return false;
  20788. });
  20789. });
  20790. Client client("localhost", get_port());
  20791. client.set_payload_max_length(1024);
  20792. sse::SSEClient sse(client, "/many-events");
  20793. std::atomic<int> messages{0};
  20794. std::atomic<bool> too_large{false};
  20795. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  20796. sse.on_error([&](Error err) {
  20797. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  20798. });
  20799. sse.set_max_reconnect_attempts(1);
  20800. sse.start_async();
  20801. for (int i = 0; i < 500 && messages < 1000; i++) {
  20802. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20803. }
  20804. sse.stop();
  20805. EXPECT_GE(messages.load(), 1000);
  20806. EXPECT_FALSE(too_large);
  20807. }
  20808. // Test: on_message callback
  20809. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  20810. // Endpoint that sends multiple events then closes
  20811. server_->Get("/multi-event", [](const Request &, Response &res) {
  20812. res.set_chunked_content_provider(
  20813. "text/event-stream", [](size_t offset, DataSink &sink) {
  20814. if (offset == 0) {
  20815. std::string events = "data: message1\n\ndata: message2\n\n";
  20816. sink.write(events.data(), events.size());
  20817. }
  20818. return false;
  20819. });
  20820. });
  20821. Client client("localhost", get_port());
  20822. sse::SSEClient sse(client, "/multi-event");
  20823. std::vector<std::string> received_messages;
  20824. std::mutex messages_mutex;
  20825. sse.on_message([&](const sse::SSEMessage &msg) {
  20826. std::lock_guard<std::mutex> lock(messages_mutex);
  20827. received_messages.push_back(msg.data);
  20828. });
  20829. sse.set_reconnect_interval(100);
  20830. sse.set_max_reconnect_attempts(1);
  20831. sse.start_async();
  20832. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20833. sse.stop();
  20834. std::lock_guard<std::mutex> lock(messages_mutex);
  20835. EXPECT_GE(received_messages.size(), 2u);
  20836. if (received_messages.size() >= 2) {
  20837. EXPECT_EQ(received_messages[0], "message1");
  20838. EXPECT_EQ(received_messages[1], "message2");
  20839. }
  20840. }
  20841. // Test: on_event for specific types
  20842. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  20843. Client client("localhost", get_port());
  20844. sse::SSEClient sse(client, "/custom-events");
  20845. std::atomic<bool> update_received{false};
  20846. std::atomic<bool> delete_received{false};
  20847. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  20848. if (msg.data == "updated") { update_received.store(true); }
  20849. });
  20850. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  20851. if (msg.data == "deleted") { delete_received.store(true); }
  20852. });
  20853. sse.set_max_reconnect_attempts(1);
  20854. sse.start_async();
  20855. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  20856. sse.stop();
  20857. EXPECT_TRUE(update_received.load());
  20858. EXPECT_TRUE(delete_received.load());
  20859. }
  20860. // Test: on_error callback on connection failure
  20861. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  20862. // Connect to a non-existent port
  20863. Client client("localhost", 59999);
  20864. sse::SSEClient sse(client, "/events");
  20865. std::atomic<bool> error_called{false};
  20866. Error received_error = Error::Success;
  20867. sse.on_error([&](Error err) {
  20868. error_called.store(true);
  20869. received_error = err;
  20870. });
  20871. sse.set_reconnect_interval(50);
  20872. sse.set_max_reconnect_attempts(1);
  20873. sse.start_async();
  20874. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20875. sse.stop();
  20876. EXPECT_TRUE(error_called.load());
  20877. EXPECT_NE(received_error, Error::Success);
  20878. }
  20879. // Test: Last-Event-ID header sent on reconnect
  20880. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  20881. // Endpoint that sends event with ID
  20882. server_->Get("/event-with-id", [](const Request &, Response &res) {
  20883. res.set_chunked_content_provider(
  20884. "text/event-stream", [](size_t offset, DataSink &sink) {
  20885. if (offset == 0) {
  20886. std::string event = "id: evt-123\ndata: test\n\n";
  20887. sink.write(event.data(), event.size());
  20888. }
  20889. return false;
  20890. });
  20891. });
  20892. Client client("localhost", get_port());
  20893. sse::SSEClient sse(client, "/event-with-id");
  20894. std::atomic<bool> id_received{false};
  20895. sse.on_message([&](const sse::SSEMessage &msg) {
  20896. if (!msg.id.empty()) { id_received.store(true); }
  20897. });
  20898. sse.set_reconnect_interval(100);
  20899. sse.set_max_reconnect_attempts(1);
  20900. sse.start_async();
  20901. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20902. sse.stop();
  20903. EXPECT_TRUE(id_received.load());
  20904. EXPECT_EQ(sse.last_event_id(), "evt-123");
  20905. }
  20906. // Test: Manual stop
  20907. TEST_F(SSEIntegrationTest, ManualStop) {
  20908. // Endpoint that sends one event and stays open briefly
  20909. std::atomic<bool> handler_running{true};
  20910. server_->Get("/stay-open", [&handler_running](const Request &,
  20911. Response &res) {
  20912. res.set_chunked_content_provider(
  20913. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  20914. if (offset == 0) {
  20915. std::string event = "data: connected\n\n";
  20916. sink.write(event.data(), event.size());
  20917. }
  20918. // Keep connection open while handler_running is true
  20919. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  20920. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20921. }
  20922. return false;
  20923. });
  20924. });
  20925. Client client("localhost", get_port());
  20926. sse::SSEClient sse(client, "/stay-open");
  20927. std::atomic<bool> connected{false};
  20928. sse.on_open([&connected]() { connected.store(true); });
  20929. sse.set_reconnect_interval(100);
  20930. sse.set_max_reconnect_attempts(1);
  20931. sse.start_async();
  20932. // Wait for connection to establish
  20933. for (int i = 0; i < 20 && !connected.load(); ++i) {
  20934. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20935. }
  20936. EXPECT_TRUE(connected.load());
  20937. EXPECT_TRUE(sse.is_connected());
  20938. // Signal handler to stop
  20939. handler_running.store(false);
  20940. // Stop SSE client
  20941. sse.stop();
  20942. EXPECT_FALSE(sse.is_connected());
  20943. }
  20944. // Test: SSEClient with custom headers
  20945. TEST_F(SSEIntegrationTest, CustomHeaders) {
  20946. // Setup a server endpoint that checks for custom header
  20947. std::atomic<bool> header_received{false};
  20948. server_->Get("/header-check", [&](const Request &req, Response &res) {
  20949. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  20950. header_received.store(true);
  20951. }
  20952. res.set_chunked_content_provider("text/event-stream",
  20953. [](size_t, DataSink &) { return false; });
  20954. });
  20955. Client client("localhost", get_port());
  20956. Headers headers = {{"X-Custom-Header", "custom-value"}};
  20957. sse::SSEClient sse(client, "/header-check", headers);
  20958. sse.set_max_reconnect_attempts(1);
  20959. sse.start_async();
  20960. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20961. sse.stop();
  20962. EXPECT_TRUE(header_received.load());
  20963. }
  20964. // Test: Reconnect interval configuration
  20965. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  20966. Client client("localhost", get_port());
  20967. sse::SSEClient sse(client, "/events");
  20968. auto &result = sse.set_reconnect_interval(500);
  20969. // Builder pattern should return reference to self
  20970. EXPECT_EQ(&result, &sse);
  20971. }
  20972. // Test: Max reconnect attempts
  20973. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  20974. // Connect to non-existent port to force reconnects
  20975. Client client("localhost", 59998);
  20976. sse::SSEClient sse(client, "/events");
  20977. std::atomic<int> error_count{0};
  20978. sse.on_error([&](Error) { error_count.fetch_add(1); });
  20979. sse.set_reconnect_interval(50);
  20980. sse.set_max_reconnect_attempts(2);
  20981. auto start = std::chrono::steady_clock::now();
  20982. sse.start(); // Blocking call
  20983. auto end = std::chrono::steady_clock::now();
  20984. // Should have stopped after 2 failed attempts
  20985. EXPECT_GE(error_count.load(), 2);
  20986. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  20987. auto duration =
  20988. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  20989. #ifdef _WIN32
  20990. // Windows is much slower for socket connection failures
  20991. EXPECT_LT(duration.count(), 7000);
  20992. #else
  20993. EXPECT_LT(duration.count(), 1000);
  20994. #endif
  20995. }
  20996. // Test: Multi-line data in integration
  20997. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  20998. // Endpoint with multi-line data
  20999. server_->Get("/multiline-data", [](const Request &, Response &res) {
  21000. res.set_chunked_content_provider(
  21001. "text/event-stream", [](size_t offset, DataSink &sink) {
  21002. if (offset == 0) {
  21003. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  21004. sink.write(event.data(), event.size());
  21005. }
  21006. return false;
  21007. });
  21008. });
  21009. Client client("localhost", get_port());
  21010. sse::SSEClient sse(client, "/multiline-data");
  21011. std::string received_data;
  21012. std::mutex data_mutex;
  21013. sse.on_message([&](const sse::SSEMessage &msg) {
  21014. std::lock_guard<std::mutex> lock(data_mutex);
  21015. received_data = msg.data;
  21016. });
  21017. sse.set_reconnect_interval(100);
  21018. sse.set_max_reconnect_attempts(1);
  21019. sse.start_async();
  21020. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21021. sse.stop();
  21022. std::lock_guard<std::mutex> lock(data_mutex);
  21023. EXPECT_EQ(received_data, "line1\nline2\nline3");
  21024. }
  21025. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  21026. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  21027. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  21028. DataSink &sink) {
  21029. if (offset == 0) {
  21030. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  21031. sink.write(events.data(), events.size());
  21032. }
  21033. return false;
  21034. });
  21035. });
  21036. Client client("localhost", get_port());
  21037. sse::SSEClient sse(client, "/empty-data-lines");
  21038. std::mutex mutex;
  21039. std::condition_variable cv;
  21040. std::vector<std::string> received;
  21041. sse.on_message([&](const sse::SSEMessage &msg) {
  21042. std::lock_guard<std::mutex> lock(mutex);
  21043. received.push_back(msg.data);
  21044. cv.notify_all();
  21045. });
  21046. sse.set_max_reconnect_attempts(1);
  21047. sse.start_async();
  21048. {
  21049. std::unique_lock<std::mutex> lock(mutex);
  21050. cv.wait_for(lock, std::chrono::seconds(2),
  21051. [&] { return received.size() >= 3; });
  21052. }
  21053. sse.stop();
  21054. ASSERT_GE(received.size(), 3u);
  21055. EXPECT_EQ(received[0], "");
  21056. EXPECT_EQ(received[1], "\nhello");
  21057. EXPECT_EQ(received[2], "");
  21058. }
  21059. // Test: Auto-reconnect after server disconnection
  21060. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  21061. std::atomic<int> connection_count{0};
  21062. std::atomic<int> message_count{0};
  21063. // Endpoint that sends one event and closes, forcing reconnect
  21064. server_->Get("/reconnect-test",
  21065. [&connection_count](const Request &, Response &res) {
  21066. connection_count.fetch_add(1);
  21067. res.set_chunked_content_provider(
  21068. "text/event-stream", [](size_t offset, DataSink &sink) {
  21069. if (offset == 0) {
  21070. std::string event = "data: hello\n\n";
  21071. sink.write(event.data(), event.size());
  21072. }
  21073. return false; // Close connection after sending
  21074. });
  21075. });
  21076. Client client("localhost", get_port());
  21077. sse::SSEClient sse(client, "/reconnect-test");
  21078. sse.on_message([&message_count](const sse::SSEMessage &) {
  21079. message_count.fetch_add(1);
  21080. });
  21081. sse.set_reconnect_interval(100);
  21082. sse.set_max_reconnect_attempts(3);
  21083. sse.start_async();
  21084. // Wait long enough for multiple reconnects
  21085. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21086. sse.stop();
  21087. // Should have connected multiple times (initial + reconnects)
  21088. EXPECT_GE(connection_count.load(), 2);
  21089. // Should have received messages from multiple connections
  21090. EXPECT_GE(message_count.load(), 2);
  21091. }
  21092. // Test: A retry field that is not all ASCII digits is ignored
  21093. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  21094. std::atomic<int> connection_count{0};
  21095. server_->Get("/bad-retry",
  21096. [&connection_count](const Request &, Response &res) {
  21097. connection_count.fetch_add(1);
  21098. res.set_chunked_content_provider(
  21099. "text/event-stream", [](size_t offset, DataSink &sink) {
  21100. if (offset == 0) {
  21101. std::string event = "retry: -1\ndata: hello\n\n";
  21102. sink.write(event.data(), event.size());
  21103. }
  21104. return false;
  21105. });
  21106. });
  21107. Client client("localhost", get_port());
  21108. sse::SSEClient sse(client, "/bad-retry");
  21109. sse.set_reconnect_interval(10000);
  21110. sse.start_async();
  21111. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21112. sse.stop();
  21113. EXPECT_EQ(connection_count.load(), 1);
  21114. }
  21115. // Test: A retry field of all ASCII digits sets the reconnection time
  21116. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  21117. std::mutex mutex;
  21118. std::condition_variable cv;
  21119. std::vector<std::chrono::steady_clock::time_point> connected_at;
  21120. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  21121. {
  21122. std::lock_guard<std::mutex> lock(mutex);
  21123. connected_at.push_back(std::chrono::steady_clock::now());
  21124. cv.notify_all();
  21125. }
  21126. res.set_chunked_content_provider(
  21127. "text/event-stream", [](size_t offset, DataSink &sink) {
  21128. if (offset == 0) {
  21129. std::string event = "retry: 0\ndata: hello\n\n";
  21130. sink.write(event.data(), event.size());
  21131. }
  21132. return false;
  21133. });
  21134. });
  21135. Client client("localhost", get_port());
  21136. sse::SSEClient sse(client, "/zero-retry");
  21137. sse.set_reconnect_interval(10000);
  21138. sse.start_async();
  21139. {
  21140. std::unique_lock<std::mutex> lock(mutex);
  21141. cv.wait_for(lock, std::chrono::seconds(5),
  21142. [&] { return connected_at.size() >= 2; });
  21143. }
  21144. sse.stop();
  21145. // The server-supplied interval is applied, but never below 100ms, so
  21146. // "retry: 0" does not cause a busy reconnect loop
  21147. std::lock_guard<std::mutex> lock(mutex);
  21148. ASSERT_GE(connected_at.size(), 2u);
  21149. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  21150. connected_at[1] - connected_at[0])
  21151. .count();
  21152. EXPECT_GE(interval_ms, 100);
  21153. }
  21154. // Test: Last-Event-ID sent on reconnect
  21155. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  21156. std::atomic<int> connection_count{0};
  21157. std::vector<std::string> received_last_event_ids;
  21158. std::mutex id_mutex;
  21159. // Endpoint that checks Last-Event-ID header and sends event with ID
  21160. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  21161. int conn = connection_count.fetch_add(1);
  21162. // Capture the Last-Event-ID header from each connection
  21163. {
  21164. std::lock_guard<std::mutex> lock(id_mutex);
  21165. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  21166. }
  21167. res.set_chunked_content_provider(
  21168. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  21169. if (offset == 0) {
  21170. std::string event =
  21171. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  21172. sink.write(event.data(), event.size());
  21173. }
  21174. return false;
  21175. });
  21176. });
  21177. Client client("localhost", get_port());
  21178. sse::SSEClient sse(client, "/reconnect-with-id");
  21179. sse.set_reconnect_interval(100);
  21180. sse.set_max_reconnect_attempts(3);
  21181. sse.start_async();
  21182. // Wait for at least 2 connections
  21183. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21184. sse.stop();
  21185. // Verify behavior
  21186. std::lock_guard<std::mutex> lock(id_mutex);
  21187. EXPECT_GE(received_last_event_ids.size(), 2u);
  21188. // First connection should have no Last-Event-ID
  21189. if (!received_last_event_ids.empty()) {
  21190. EXPECT_EQ(received_last_event_ids[0], "");
  21191. }
  21192. // Second connection should have Last-Event-ID from first connection
  21193. if (received_last_event_ids.size() >= 2) {
  21194. EXPECT_EQ(received_last_event_ids[1], "event-0");
  21195. }
  21196. }
  21197. // Test: set_headers updates headers used on reconnect
  21198. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  21199. std::vector<std::string> received_tokens;
  21200. std::mutex token_mutex;
  21201. // Endpoint that captures Authorization header
  21202. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  21203. {
  21204. std::lock_guard<std::mutex> lock(token_mutex);
  21205. received_tokens.push_back(req.get_header_value("Authorization"));
  21206. }
  21207. res.set_chunked_content_provider(
  21208. "text/event-stream", [](size_t offset, DataSink &sink) {
  21209. if (offset == 0) {
  21210. std::string event = "data: hello\n\n";
  21211. sink.write(event.data(), event.size());
  21212. }
  21213. return false; // Close connection to trigger reconnect
  21214. });
  21215. });
  21216. Client client("localhost", get_port());
  21217. Headers headers = {{"Authorization", "Bearer old-token"}};
  21218. sse::SSEClient sse(client, "/auth-check", headers);
  21219. // Update headers on each successful connection
  21220. sse.on_open(
  21221. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  21222. sse.set_reconnect_interval(100);
  21223. sse.set_max_reconnect_attempts(3);
  21224. sse.start_async();
  21225. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21226. sse.stop();
  21227. std::lock_guard<std::mutex> lock(token_mutex);
  21228. ASSERT_GE(received_tokens.size(), 2u);
  21229. // First connection uses original header
  21230. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  21231. // Second connection uses updated header from set_headers
  21232. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  21233. }
  21234. // Test: 401 allows reconnection (so on_error can refresh headers)
  21235. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  21236. std::atomic<int> connection_count{0};
  21237. // Endpoint: returns 401 on first attempt, 200 on second
  21238. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  21239. int conn = connection_count.fetch_add(1);
  21240. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  21241. res.status = StatusCode::Unauthorized_401;
  21242. res.set_content("Unauthorized", "text/plain");
  21243. return;
  21244. }
  21245. res.set_chunked_content_provider(
  21246. "text/event-stream", [](size_t offset, DataSink &sink) {
  21247. if (offset == 0) {
  21248. std::string event = "data: authenticated\n\n";
  21249. sink.write(event.data(), event.size());
  21250. }
  21251. return false;
  21252. });
  21253. });
  21254. Client client("localhost", get_port());
  21255. Headers headers = {{"Authorization", "Bearer expired"}};
  21256. sse::SSEClient sse(client, "/auth-retry", headers);
  21257. std::atomic<bool> message_received{false};
  21258. // Refresh token on error
  21259. sse.on_error(
  21260. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  21261. sse.on_message([&](const sse::SSEMessage &msg) {
  21262. if (msg.data == "authenticated") { message_received.store(true); }
  21263. });
  21264. sse.set_reconnect_interval(100);
  21265. sse.set_max_reconnect_attempts(3);
  21266. sse.start_async();
  21267. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21268. sse.stop();
  21269. // Should have reconnected after 401 and succeeded with new token
  21270. EXPECT_GE(connection_count.load(), 2);
  21271. EXPECT_TRUE(message_received.load());
  21272. }
  21273. TEST(Issue2318Test, EmptyHostString) {
  21274. {
  21275. httplib::Client cli_empty("", PORT);
  21276. auto res = cli_empty.Get("/");
  21277. ASSERT_FALSE(res);
  21278. EXPECT_EQ(httplib::Error::Connection, res.error());
  21279. }
  21280. {
  21281. httplib::Client cli(" ", PORT);
  21282. auto res = cli.Get("/");
  21283. ASSERT_FALSE(res);
  21284. EXPECT_EQ(httplib::Error::Connection, res.error());
  21285. }
  21286. }
  21287. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21288. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  21289. Server svr;
  21290. // Set a small payload limit (1KB)
  21291. svr.set_payload_max_length(1024);
  21292. svr.Post("/test", [&](const Request &req, Response &res) {
  21293. res.set_content("Body size: " + std::to_string(req.body.size()),
  21294. "text/plain");
  21295. });
  21296. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  21297. auto se = detail::scope_exit([&] {
  21298. svr.stop();
  21299. listen_thread.join();
  21300. });
  21301. svr.wait_until_ready();
  21302. // Create data that compresses well but exceeds limit when decompressed
  21303. // 8KB of repeated null bytes compresses to a very small size
  21304. std::string original_data(8 * 1024, '\0');
  21305. // Compress the data using gzip
  21306. std::string compressed_data;
  21307. detail::gzip_compressor compressor;
  21308. compressor.compress(original_data.data(), original_data.size(), true,
  21309. [&](const char *data, size_t size) {
  21310. compressed_data.append(data, size);
  21311. return true;
  21312. });
  21313. // Verify compression worked (compressed should be much smaller)
  21314. ASSERT_LT(compressed_data.size(), original_data.size());
  21315. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  21316. // Send compressed data with Content-Encoding: gzip
  21317. Client cli(HOST, PORT);
  21318. Headers headers = {{"Content-Encoding", "gzip"}};
  21319. auto res =
  21320. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  21321. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  21322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21323. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  21324. }
  21325. #endif
  21326. // ============================================================================
  21327. // OpenSSL-Specific Tests
  21328. // ============================================================================
  21329. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  21330. X509 *readCertificate(const std::string &strFileName) {
  21331. std::ifstream inStream(strFileName);
  21332. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  21333. std::istreambuf_iterator<char>());
  21334. if (strCertPEM.empty()) return (nullptr);
  21335. BIO *pbCert = BIO_new(BIO_s_mem());
  21336. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  21337. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  21338. BIO_free(pbCert);
  21339. return (pCert);
  21340. }
  21341. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  21342. std::ifstream inStream(strFileName);
  21343. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  21344. std::istreambuf_iterator<char>());
  21345. if (strPrivateKeyPEM.empty()) return (nullptr);
  21346. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  21347. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  21348. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  21349. BIO_free(pbPrivKey);
  21350. return (pPrivateKey);
  21351. }
  21352. TEST(BindServerTest, UpdateCerts) {
  21353. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21354. int port = svr.bind_to_any_port("0.0.0.0");
  21355. ASSERT_TRUE(svr.is_valid());
  21356. ASSERT_TRUE(port > 0);
  21357. X509 *cert = readCertificate(SERVER_CERT_FILE);
  21358. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  21359. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  21360. ASSERT_TRUE(cert != nullptr);
  21361. ASSERT_TRUE(ca_cert != nullptr);
  21362. ASSERT_TRUE(key != nullptr);
  21363. X509_STORE *cert_store = X509_STORE_new();
  21364. X509_STORE_add_cert(cert_store, ca_cert);
  21365. // svr.update_certs(cert, key, cert_store); // deprecated
  21366. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  21367. CLIENT_CA_CERT_FILE);
  21368. ASSERT_TRUE(svr.is_valid());
  21369. svr.stop();
  21370. X509_STORE_free(cert_store);
  21371. X509_free(cert);
  21372. X509_free(ca_cert);
  21373. EVP_PKEY_free(key);
  21374. }
  21375. // Test that update_certs() updates client CA list correctly
  21376. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  21377. // Start with file-based constructor
  21378. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21379. ASSERT_TRUE(svr.is_valid());
  21380. // Initially no client CA list should be set
  21381. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  21382. ASSERT_TRUE(ssl_ctx != nullptr);
  21383. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  21384. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  21385. EXPECT_EQ(0, count_before);
  21386. // Now update with client CA (PEM string)
  21387. std::string cert_pem, key_pem, ca_pem;
  21388. read_file(SERVER_CERT_FILE, cert_pem);
  21389. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  21390. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  21391. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  21392. ASSERT_TRUE(svr.is_valid());
  21393. // Now client CA list should be set
  21394. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  21395. ASSERT_TRUE(ca_list_after != nullptr);
  21396. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  21397. }
  21398. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  21399. // Test that the file-path SSLServer constructor properly sets the client CA
  21400. // list that is sent to clients during the TLS handshake (CertificateRequest)
  21401. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21402. ASSERT_TRUE(svr.is_valid());
  21403. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  21404. ASSERT_TRUE(ssl_ctx != nullptr);
  21405. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  21406. ASSERT_TRUE(ca_list != nullptr);
  21407. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  21408. }
  21409. #endif
  21410. // ============================================================================
  21411. // MbedTLS-Specific Tests
  21412. // ============================================================================
  21413. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  21414. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  21415. using namespace httplib::tls;
  21416. // Track if callback was invoked
  21417. bool callback_invoked = false;
  21418. // The callback receives void* ctx which is actually MbedTlsContext*
  21419. // We can access the mbedtls_ssl_config via the context
  21420. auto setup_callback = [&callback_invoked](void *ctx) {
  21421. callback_invoked = true;
  21422. // Cast to MbedTlsContext* to access the ssl config
  21423. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  21424. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  21425. // Use static variables to hold certificate data (simplified for test)
  21426. static mbedtls_x509_crt own_cert;
  21427. static mbedtls_pk_context own_key;
  21428. static mbedtls_x509_crt ca_chain;
  21429. static bool initialized = false;
  21430. if (!initialized) {
  21431. mbedtls_x509_crt_init(&own_cert);
  21432. mbedtls_pk_init(&own_key);
  21433. mbedtls_x509_crt_init(&ca_chain);
  21434. // Load server certificate
  21435. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  21436. return false;
  21437. }
  21438. // Load server private key.
  21439. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  21440. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  21441. #if MBEDTLS_VERSION_MAJOR == 3
  21442. ,
  21443. mbedtls_ctr_drbg_random, nullptr
  21444. #endif
  21445. ) != 0) {
  21446. return false;
  21447. }
  21448. // Load CA chain for client verification
  21449. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  21450. return false;
  21451. }
  21452. initialized = true;
  21453. }
  21454. // Configure the SSL config
  21455. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  21456. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  21457. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  21458. // Set minimum TLS version using mbedTLS native API
  21459. #if MBEDTLS_VERSION_MAJOR >= 3
  21460. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  21461. #else
  21462. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  21463. MBEDTLS_SSL_MINOR_VERSION_3);
  21464. #endif
  21465. return true;
  21466. };
  21467. SSLServer svr(setup_callback);
  21468. ASSERT_TRUE(svr.is_valid());
  21469. ASSERT_TRUE(callback_invoked);
  21470. svr.Get("/test", [&](const Request &req, Response &res) {
  21471. res.set_content("test", "text/plain");
  21472. auto cert = req.peer_cert();
  21473. ASSERT_TRUE(static_cast<bool>(cert));
  21474. auto common_name = cert.subject_cn();
  21475. EXPECT_EQ("Common Name", common_name);
  21476. });
  21477. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21478. auto se = detail::scope_exit([&] {
  21479. svr.stop();
  21480. t.join();
  21481. ASSERT_FALSE(svr.is_running());
  21482. });
  21483. svr.wait_until_ready();
  21484. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  21485. cli.enable_server_certificate_verification(false);
  21486. cli.set_connection_timeout(30);
  21487. auto res = cli.Get("/test");
  21488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21489. ASSERT_EQ(StatusCode::OK_200, res->status);
  21490. }
  21491. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  21492. // context (owning mbedtls_ssl_config) before shutting down a still-open
  21493. // keep-alive SSL session, which reads through that config in
  21494. // mbedtls_ssl_close_notify.
  21495. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  21496. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21497. ASSERT_TRUE(svr.is_valid());
  21498. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  21499. res.set_content("test", "text/plain");
  21500. });
  21501. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21502. auto se = detail::scope_exit([&] {
  21503. svr.stop();
  21504. t.join();
  21505. ASSERT_FALSE(svr.is_running());
  21506. });
  21507. svr.wait_until_ready();
  21508. {
  21509. SSLClient cli(HOST, PORT);
  21510. cli.enable_server_certificate_verification(false);
  21511. cli.set_keep_alive(true);
  21512. auto res = cli.Get("/test");
  21513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21514. ASSERT_EQ(StatusCode::OK_200, res->status);
  21515. // cli is destructed here with the keep-alive SSL session still open.
  21516. }
  21517. }
  21518. #endif
  21519. // WebSocket Tests
  21520. TEST(WebSocketTest, RSVBitsMustBeZero) {
  21521. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  21522. // defining the meaning of these bits has been negotiated.
  21523. auto make_frame = [](uint8_t first_byte) {
  21524. std::string frame;
  21525. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  21526. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  21527. frame += "Hello";
  21528. return frame;
  21529. };
  21530. // RSV1 set (0x40)
  21531. {
  21532. detail::BufferStream strm;
  21533. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  21534. ws::Opcode opcode;
  21535. std::string payload;
  21536. bool fin;
  21537. EXPECT_EQ(
  21538. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21539. ws::impl::FrameRead::Fail);
  21540. }
  21541. // RSV2 set (0x20)
  21542. {
  21543. detail::BufferStream strm;
  21544. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  21545. ws::Opcode opcode;
  21546. std::string payload;
  21547. bool fin;
  21548. EXPECT_EQ(
  21549. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21550. ws::impl::FrameRead::Fail);
  21551. }
  21552. // RSV3 set (0x10)
  21553. {
  21554. detail::BufferStream strm;
  21555. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  21556. ws::Opcode opcode;
  21557. std::string payload;
  21558. bool fin;
  21559. EXPECT_EQ(
  21560. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21561. ws::impl::FrameRead::Fail);
  21562. }
  21563. // No RSV bits set - should succeed
  21564. {
  21565. detail::BufferStream strm;
  21566. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  21567. ws::Opcode opcode;
  21568. std::string payload;
  21569. bool fin;
  21570. EXPECT_EQ(
  21571. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21572. ws::impl::FrameRead::Ok);
  21573. EXPECT_EQ(ws::Opcode::Text, opcode);
  21574. EXPECT_EQ("Hello", payload);
  21575. EXPECT_TRUE(fin);
  21576. }
  21577. }
  21578. TEST(WebSocketTest, ControlFrameValidation) {
  21579. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  21580. // payload length <= 125.
  21581. // Ping with FIN=0 - must be rejected
  21582. {
  21583. detail::BufferStream strm;
  21584. std::string frame;
  21585. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  21586. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21587. strm.write(frame.data(), frame.size());
  21588. ws::Opcode opcode;
  21589. std::string payload;
  21590. bool fin;
  21591. EXPECT_EQ(
  21592. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21593. ws::impl::FrameRead::Fail);
  21594. }
  21595. // Close with FIN=0 - must be rejected
  21596. {
  21597. detail::BufferStream strm;
  21598. std::string frame;
  21599. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  21600. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21601. strm.write(frame.data(), frame.size());
  21602. ws::Opcode opcode;
  21603. std::string payload;
  21604. bool fin;
  21605. EXPECT_EQ(
  21606. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21607. ws::impl::FrameRead::Fail);
  21608. }
  21609. // Ping with payload_len=126 (extended length) - must be rejected
  21610. {
  21611. detail::BufferStream strm;
  21612. std::string frame;
  21613. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21614. frame += static_cast<char>(126); // payload_len=126 (>125)
  21615. frame += static_cast<char>(0x00); // extended length high byte
  21616. frame += static_cast<char>(126); // extended length low byte
  21617. frame += std::string(126, 'x');
  21618. strm.write(frame.data(), frame.size());
  21619. ws::Opcode opcode;
  21620. std::string payload;
  21621. bool fin;
  21622. EXPECT_EQ(
  21623. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21624. ws::impl::FrameRead::Fail);
  21625. }
  21626. // Ping with FIN=1 and payload_len=125 - should succeed
  21627. {
  21628. detail::BufferStream strm;
  21629. std::string frame;
  21630. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21631. frame += static_cast<char>(125); // payload_len=125
  21632. frame += std::string(125, 'x');
  21633. strm.write(frame.data(), frame.size());
  21634. ws::Opcode opcode;
  21635. std::string payload;
  21636. bool fin;
  21637. EXPECT_EQ(
  21638. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21639. ws::impl::FrameRead::Ok);
  21640. EXPECT_EQ(ws::Opcode::Ping, opcode);
  21641. EXPECT_EQ(125u, payload.size());
  21642. EXPECT_TRUE(fin);
  21643. }
  21644. }
  21645. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  21646. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  21647. // length MUST be 0.
  21648. // MSB set - must be rejected
  21649. {
  21650. detail::BufferStream strm;
  21651. std::string frame;
  21652. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21653. frame += static_cast<char>(127); // 64-bit extended length
  21654. frame += static_cast<char>(0x80); // MSB set (invalid)
  21655. frame += std::string(7, '\0'); // remaining 7 bytes of length
  21656. strm.write(frame.data(), frame.size());
  21657. ws::Opcode opcode;
  21658. std::string payload;
  21659. bool fin;
  21660. EXPECT_EQ(
  21661. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21662. ws::impl::FrameRead::Fail);
  21663. }
  21664. // MSB clear - should pass length parsing (will be rejected by max_len,
  21665. // but that's a different check; use a small length to verify)
  21666. {
  21667. detail::BufferStream strm;
  21668. std::string frame;
  21669. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21670. frame += static_cast<char>(127); // 64-bit extended length
  21671. frame += std::string(7, '\0'); // high bytes = 0
  21672. frame += static_cast<char>(0x03); // length = 3
  21673. frame += "abc";
  21674. strm.write(frame.data(), frame.size());
  21675. ws::Opcode opcode;
  21676. std::string payload;
  21677. bool fin;
  21678. EXPECT_EQ(
  21679. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21680. ws::impl::FrameRead::Ok);
  21681. EXPECT_EQ(ws::Opcode::Text, opcode);
  21682. EXPECT_EQ("abc", payload);
  21683. }
  21684. }
  21685. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  21686. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  21687. // Valid UTF-8
  21688. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  21689. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  21690. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  21691. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  21692. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  21693. // Invalid UTF-8
  21694. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  21695. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  21696. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  21697. EXPECT_FALSE(
  21698. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  21699. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  21700. }
  21701. TEST(WebSocketTest, ConnectAndDisconnect) {
  21702. Server svr;
  21703. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21704. std::string msg;
  21705. while (ws.read(msg)) {}
  21706. });
  21707. auto port = svr.bind_to_any_port(HOST);
  21708. std::thread t([&]() { svr.listen_after_bind(); });
  21709. svr.wait_until_ready();
  21710. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21711. auto res = client.connect();
  21712. ASSERT_TRUE(res);
  21713. EXPECT_EQ(Error::Success, res.error());
  21714. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  21715. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  21716. EXPECT_TRUE(client.is_open());
  21717. client.close();
  21718. EXPECT_FALSE(client.is_open());
  21719. svr.stop();
  21720. t.join();
  21721. }
  21722. TEST(WebSocketTest, ValidURL) {
  21723. ws::WebSocketClient ws1("ws://localhost:8080/path");
  21724. EXPECT_TRUE(ws1.is_valid());
  21725. ws::WebSocketClient ws2("ws://example.com/path");
  21726. EXPECT_TRUE(ws2.is_valid());
  21727. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  21728. EXPECT_TRUE(ws3.is_valid());
  21729. #ifdef CPPHTTPLIB_SSL_ENABLED
  21730. ws::WebSocketClient wss1("wss://example.com/path");
  21731. EXPECT_TRUE(wss1.is_valid());
  21732. ws::WebSocketClient wss2("wss://example.com:443/path");
  21733. EXPECT_TRUE(wss2.is_valid());
  21734. #endif
  21735. }
  21736. TEST(WebSocketTest, InvalidURL) {
  21737. // No scheme
  21738. ws::WebSocketClient ws1("localhost:8080/path");
  21739. EXPECT_FALSE(ws1.is_valid());
  21740. // No path
  21741. ws::WebSocketClient ws2("ws://localhost:8080");
  21742. EXPECT_FALSE(ws2.is_valid());
  21743. // Empty string
  21744. ws::WebSocketClient ws3("");
  21745. EXPECT_FALSE(ws3.is_valid());
  21746. // Missing host
  21747. ws::WebSocketClient ws4("ws://:8080/path");
  21748. EXPECT_FALSE(ws4.is_valid());
  21749. // Port number overflow — should not crash
  21750. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  21751. EXPECT_FALSE(ws5.is_valid());
  21752. // Port out of range
  21753. ws::WebSocketClient ws6("ws://localhost:99999/path");
  21754. EXPECT_FALSE(ws6.is_valid());
  21755. }
  21756. TEST(WebSocketTest, UnsupportedScheme) {
  21757. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  21758. ws::WebSocketClient ws1("http://localhost:8080/path");
  21759. EXPECT_FALSE(ws1.is_valid());
  21760. ws::WebSocketClient ws2("https://localhost:8080/path");
  21761. EXPECT_FALSE(ws2.is_valid());
  21762. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  21763. EXPECT_FALSE(ws3.is_valid());
  21764. #else
  21765. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  21766. std::invalid_argument);
  21767. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  21768. std::invalid_argument);
  21769. #endif
  21770. }
  21771. TEST(WebSocketTest, ConnectWhenInvalid) {
  21772. ws::WebSocketClient ws("not a valid url");
  21773. EXPECT_FALSE(ws.is_valid());
  21774. auto res = ws.connect();
  21775. EXPECT_FALSE(res);
  21776. EXPECT_EQ(Error::Connection, res.error());
  21777. EXPECT_EQ(-1, res.status());
  21778. }
  21779. TEST(WebSocketTest, ConnectRefusedReportsError) {
  21780. // Grab a port that is free, then close it again so nothing listens there
  21781. Server svr;
  21782. auto port = svr.bind_to_any_port(HOST);
  21783. svr.stop();
  21784. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21785. auto res = client.connect();
  21786. ASSERT_FALSE(res);
  21787. EXPECT_EQ(Error::Connection, res.error());
  21788. EXPECT_EQ(-1, res.status());
  21789. }
  21790. TEST(WebSocketTest, DefaultPort) {
  21791. ws::WebSocketClient ws1("ws://example.com/path");
  21792. EXPECT_TRUE(ws1.is_valid());
  21793. // ws:// defaults to port 80 (verified by successful parse)
  21794. #ifdef CPPHTTPLIB_SSL_ENABLED
  21795. ws::WebSocketClient ws2("wss://example.com/path");
  21796. EXPECT_TRUE(ws2.is_valid());
  21797. // wss:// defaults to port 443 (verified by successful parse)
  21798. #endif
  21799. }
  21800. TEST(WebSocketTest, IPv6LiteralAddress) {
  21801. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  21802. EXPECT_TRUE(ws1.is_valid());
  21803. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  21804. EXPECT_TRUE(ws2.is_valid());
  21805. }
  21806. TEST(WebSocketTest, ComplexPath) {
  21807. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  21808. EXPECT_TRUE(ws1.is_valid());
  21809. ws::WebSocketClient ws2("ws://localhost:8080/");
  21810. EXPECT_TRUE(ws2.is_valid());
  21811. }
  21812. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  21813. Server svr;
  21814. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21815. std::string msg;
  21816. while (ws.read(msg)) {}
  21817. });
  21818. auto port = svr.bind_to_any_port(HOST);
  21819. std::thread t([&]() { svr.listen_after_bind(); });
  21820. svr.wait_until_ready();
  21821. auto another_host = "example.com";
  21822. auto wrong_ip = "192.0.2.1";
  21823. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21824. client.set_hostname_addr_map({{another_host, wrong_ip}});
  21825. ASSERT_TRUE(client.connect());
  21826. EXPECT_TRUE(client.is_open());
  21827. client.close();
  21828. svr.stop();
  21829. t.join();
  21830. }
  21831. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  21832. Server svr;
  21833. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21834. std::string msg;
  21835. while (ws.read(msg)) {}
  21836. });
  21837. auto port = svr.bind_to_any_port(HOST);
  21838. std::thread t([&]() { svr.listen_after_bind(); });
  21839. svr.wait_until_ready();
  21840. auto wrong_ip = "192.0.2.1";
  21841. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21842. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  21843. client.set_connection_timeout(1);
  21844. client.set_read_timeout(1);
  21845. client.set_write_timeout(1);
  21846. EXPECT_FALSE(client.connect());
  21847. EXPECT_FALSE(client.is_open());
  21848. svr.stop();
  21849. t.join();
  21850. }
  21851. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  21852. // A mapped value that is not an IP literal must be resolved. HOST resolves
  21853. // from the hosts file, so this test needs no external DNS. "target.invalid"
  21854. // (RFC 6761) is only a map key and the Host header value.
  21855. auto host = "target.invalid";
  21856. Server svr;
  21857. std::string received_host;
  21858. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21859. received_host = req.get_header_value("Host");
  21860. std::string msg;
  21861. while (ws.read(msg)) {}
  21862. });
  21863. auto port = svr.bind_to_any_port(HOST);
  21864. std::thread t([&]() { svr.listen_after_bind(); });
  21865. // ASSERT_* below returns from the test body, which would leave t joinable
  21866. // and make ~thread call std::terminate.
  21867. auto se = detail::scope_exit([&] {
  21868. svr.stop();
  21869. if (t.joinable()) { t.join(); }
  21870. });
  21871. svr.wait_until_ready();
  21872. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  21873. std::to_string(port) + "/ws");
  21874. client.set_hostname_addr_map({{host, HOST}});
  21875. ASSERT_TRUE(client.connect());
  21876. EXPECT_TRUE(client.is_open());
  21877. client.close();
  21878. svr.stop();
  21879. t.join();
  21880. // The mapping only redirects the connection; the identity stays host_.
  21881. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  21882. }
  21883. class WebSocketIntegrationTest : public ::testing::Test {
  21884. protected:
  21885. void SetUp() override {
  21886. server_ = httplib::detail::make_unique<Server>();
  21887. setup_server();
  21888. start_server();
  21889. }
  21890. void TearDown() override {
  21891. server_->stop();
  21892. if (server_thread_.joinable()) { server_thread_.join(); }
  21893. }
  21894. void setup_server() {
  21895. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21896. std::string msg;
  21897. ws::ReadResult ret;
  21898. while ((ret = ws.read(msg))) {
  21899. if (ret == ws::Binary) {
  21900. ws.send(msg.data(), msg.size());
  21901. } else {
  21902. ws.send(msg);
  21903. }
  21904. }
  21905. });
  21906. server_->WebSocket("/ws-echo-string",
  21907. [](const Request &, ws::WebSocket &ws) {
  21908. std::string msg;
  21909. while (ws.read(msg)) {
  21910. ws.send("echo: " + msg);
  21911. }
  21912. });
  21913. server_->WebSocket(
  21914. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  21915. // Echo back request metadata
  21916. ws.send("path:" + req.path);
  21917. ws.send("header:" + req.get_header_value("X-Test-Header"));
  21918. std::string msg;
  21919. while (ws.read(msg)) {}
  21920. });
  21921. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  21922. std::string msg;
  21923. ws.read(msg); // wait for a message
  21924. ws.close();
  21925. });
  21926. server_->WebSocket("/ws-close-status",
  21927. [](const Request &, ws::WebSocket &ws) {
  21928. std::string msg;
  21929. ws.read(msg); // wait for a message
  21930. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  21931. });
  21932. server_->WebSocket(
  21933. "/ws-subprotocol",
  21934. [](const Request &, ws::WebSocket &ws) {
  21935. std::string msg;
  21936. while (ws.read(msg)) {
  21937. ws.send(msg);
  21938. }
  21939. },
  21940. [](const std::vector<std::string> &protocols) -> std::string {
  21941. for (const auto &p : protocols) {
  21942. if (p == "graphql-ws") { return p; }
  21943. }
  21944. return "";
  21945. });
  21946. server_->WebSocket(
  21947. "/ws-subprotocol-unoffered",
  21948. [](const Request &, ws::WebSocket &ws) {
  21949. std::string msg;
  21950. while (ws.read(msg)) {
  21951. ws.send(msg);
  21952. }
  21953. },
  21954. [](const std::vector<std::string> &) -> std::string {
  21955. return "admin";
  21956. });
  21957. }
  21958. void start_server() {
  21959. port_ = server_->bind_to_any_port(HOST);
  21960. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21961. server_->wait_until_ready();
  21962. }
  21963. std::unique_ptr<Server> server_;
  21964. std::thread server_thread_;
  21965. int port_ = 0;
  21966. };
  21967. TEST_F(WebSocketIntegrationTest, TextEcho) {
  21968. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21969. "/ws-echo");
  21970. ASSERT_TRUE(client.connect());
  21971. ASSERT_TRUE(client.is_open());
  21972. ASSERT_TRUE(client.send("Hello WebSocket"));
  21973. std::string msg;
  21974. EXPECT_EQ(ws::Text, client.read(msg));
  21975. EXPECT_EQ("Hello WebSocket", msg);
  21976. client.close();
  21977. }
  21978. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  21979. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21980. "/ws-echo");
  21981. ASSERT_TRUE(client.connect());
  21982. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  21983. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  21984. std::string msg;
  21985. EXPECT_EQ(ws::Binary, client.read(msg));
  21986. EXPECT_EQ(binary_data, msg);
  21987. client.close();
  21988. }
  21989. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  21990. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21991. "/ws-echo");
  21992. ASSERT_TRUE(client.connect());
  21993. for (int i = 0; i < 10; i++) {
  21994. auto text = "message " + std::to_string(i);
  21995. ASSERT_TRUE(client.send(text));
  21996. std::string msg;
  21997. ASSERT_TRUE(client.read(msg));
  21998. EXPECT_EQ(text, msg);
  21999. }
  22000. client.close();
  22001. }
  22002. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  22003. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22004. "/ws-close");
  22005. ASSERT_TRUE(client.connect());
  22006. // Send a message to trigger the server to close
  22007. ASSERT_TRUE(client.send("trigger close"));
  22008. // The server will close, so read should return false
  22009. std::string msg;
  22010. EXPECT_FALSE(client.read(msg));
  22011. EXPECT_FALSE(client.is_open());
  22012. }
  22013. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  22014. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22015. "/ws-echo");
  22016. ASSERT_TRUE(client.connect());
  22017. // 128KB message
  22018. std::string large_data(128 * 1024, 'X');
  22019. ASSERT_TRUE(client.send(large_data));
  22020. std::string msg;
  22021. ASSERT_TRUE(client.read(msg));
  22022. EXPECT_EQ(large_data, msg);
  22023. client.close();
  22024. }
  22025. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  22026. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22027. "/ws-echo");
  22028. ASSERT_TRUE(client.connect());
  22029. const int num_threads = 4;
  22030. std::vector<std::thread> threads;
  22031. std::atomic<int> send_count{0};
  22032. for (int t = 0; t < num_threads; t++) {
  22033. threads.emplace_back([&client, &send_count, t]() {
  22034. for (int i = 0; i < 5; i++) {
  22035. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  22036. if (client.send(text)) { send_count++; }
  22037. }
  22038. });
  22039. }
  22040. for (auto &th : threads) {
  22041. th.join();
  22042. }
  22043. int received = 0;
  22044. std::string msg;
  22045. while (received < send_count.load()) {
  22046. if (!client.read(msg)) { break; }
  22047. received++;
  22048. }
  22049. EXPECT_EQ(send_count.load(), received);
  22050. client.close();
  22051. }
  22052. TEST_F(WebSocketIntegrationTest, ReadString) {
  22053. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22054. "/ws-echo-string");
  22055. ASSERT_TRUE(client.connect());
  22056. ASSERT_TRUE(client.send("hello"));
  22057. std::string msg;
  22058. ASSERT_TRUE(client.read(msg));
  22059. EXPECT_EQ("echo: hello", msg);
  22060. ASSERT_TRUE(client.send("world"));
  22061. ASSERT_TRUE(client.read(msg));
  22062. EXPECT_EQ("echo: world", msg);
  22063. client.close();
  22064. }
  22065. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  22066. Headers headers = {{"X-Test-Header", "test-value"}};
  22067. ws::WebSocketClient client(
  22068. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  22069. ASSERT_TRUE(client.connect());
  22070. std::string msg;
  22071. ASSERT_TRUE(client.read(msg));
  22072. EXPECT_EQ("path:/ws-request-info", msg);
  22073. ASSERT_TRUE(client.read(msg));
  22074. EXPECT_EQ("header:test-value", msg);
  22075. client.close();
  22076. }
  22077. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  22078. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22079. "/ws-echo");
  22080. client.set_read_timeout(1, 0); // 1 second
  22081. ASSERT_TRUE(client.connect());
  22082. // Don't send anything — server echo handler waits for a message, so read()
  22083. // should time out. The connection survives it: nothing was consumed.
  22084. std::string msg;
  22085. EXPECT_EQ(client.read(msg), ws::Timeout);
  22086. EXPECT_TRUE(client.is_open());
  22087. // And it is still usable afterwards.
  22088. EXPECT_TRUE(client.send("after timeout"));
  22089. EXPECT_EQ(client.read(msg), ws::Text);
  22090. EXPECT_EQ(msg, "after timeout");
  22091. }
  22092. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  22093. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22094. "/ws-echo");
  22095. client.set_read_timeout(1, 0);
  22096. ASSERT_TRUE(client.connect());
  22097. ASSERT_TRUE(client.send("first"));
  22098. std::string msg;
  22099. ASSERT_EQ(client.read(msg), ws::Text);
  22100. ASSERT_EQ(msg, "first");
  22101. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  22102. // not be used with a read timeout: it would reprocess the previous message.
  22103. EXPECT_EQ(client.read(msg), ws::Timeout);
  22104. EXPECT_EQ(msg, "first");
  22105. }
  22106. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  22107. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22108. "/ws-echo");
  22109. ASSERT_TRUE(client.connect());
  22110. // Setting it once the connection is open reaches the live stream, not just
  22111. // the seed for the next connect().
  22112. client.set_read_timeout(1, 0);
  22113. std::string msg;
  22114. EXPECT_EQ(client.read(msg), ws::Timeout);
  22115. EXPECT_TRUE(client.is_open());
  22116. }
  22117. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  22118. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22119. "/ws-echo");
  22120. client.set_read_timeout(5, 0);
  22121. ASSERT_TRUE(client.connect());
  22122. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  22123. // The server should reject it and close the connection.
  22124. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  22125. client.send(oversized);
  22126. // The server's read() should have failed due to payload limit,
  22127. // so our read() should return false (connection closed).
  22128. std::string msg;
  22129. EXPECT_FALSE(client.read(msg));
  22130. }
  22131. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  22132. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22133. "/ws-echo");
  22134. client.set_read_timeout(10, 0);
  22135. ASSERT_TRUE(client.connect());
  22136. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  22137. // This should succeed.
  22138. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  22139. ASSERT_TRUE(client.send(at_limit));
  22140. std::string msg;
  22141. ASSERT_TRUE(client.read(msg));
  22142. EXPECT_EQ(at_limit.size(), msg.size());
  22143. client.close();
  22144. }
  22145. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  22146. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22147. "/nonexistent");
  22148. auto res = client.connect();
  22149. EXPECT_FALSE(res);
  22150. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22151. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  22152. EXPECT_FALSE(client.is_open());
  22153. }
  22154. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  22155. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22156. "/ws-echo");
  22157. ASSERT_TRUE(client.connect());
  22158. ASSERT_TRUE(client.send(""));
  22159. std::string msg;
  22160. EXPECT_EQ(ws::Text, client.read(msg));
  22161. EXPECT_EQ("", msg);
  22162. client.close();
  22163. }
  22164. TEST_F(WebSocketIntegrationTest, Reconnect) {
  22165. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22166. "/ws-echo");
  22167. // First connection
  22168. ASSERT_TRUE(client.connect());
  22169. ASSERT_TRUE(client.send("first"));
  22170. std::string msg;
  22171. ASSERT_TRUE(client.read(msg));
  22172. EXPECT_EQ("first", msg);
  22173. client.close();
  22174. EXPECT_FALSE(client.is_open());
  22175. // Reconnect using the same client object
  22176. ASSERT_TRUE(client.connect());
  22177. ASSERT_TRUE(client.is_open());
  22178. ASSERT_TRUE(client.send("second"));
  22179. ASSERT_TRUE(client.read(msg));
  22180. EXPECT_EQ("second", msg);
  22181. client.close();
  22182. }
  22183. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  22184. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22185. "/ws-close-status");
  22186. ASSERT_TRUE(client.connect());
  22187. // Trigger the server to close with GoingAway status
  22188. ASSERT_TRUE(client.send("trigger"));
  22189. // read() should return false after receiving the close frame
  22190. std::string msg;
  22191. EXPECT_FALSE(client.read(msg));
  22192. EXPECT_FALSE(client.is_open());
  22193. }
  22194. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  22195. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22196. "/ws-echo");
  22197. ASSERT_TRUE(client.connect());
  22198. client.close(ws::CloseStatus::GoingAway, "client leaving");
  22199. EXPECT_FALSE(client.is_open());
  22200. }
  22201. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  22202. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  22203. ws::WebSocketClient client(
  22204. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22205. ASSERT_TRUE(client.connect());
  22206. // Server should have selected graphql-ws
  22207. EXPECT_EQ("graphql-ws", client.subprotocol());
  22208. client.close();
  22209. }
  22210. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  22211. Headers headers;
  22212. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  22213. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  22214. ws::WebSocketClient client(
  22215. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22216. ASSERT_TRUE(client.connect());
  22217. // The offer on the second field line counts too, so graphql-ws is selected
  22218. EXPECT_EQ("graphql-ws", client.subprotocol());
  22219. client.close();
  22220. }
  22221. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  22222. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  22223. ws::WebSocketClient client(
  22224. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22225. ASSERT_TRUE(client.connect());
  22226. // Server should not have selected any subprotocol
  22227. EXPECT_TRUE(client.subprotocol().empty());
  22228. client.close();
  22229. }
  22230. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  22231. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22232. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22233. "/ws-subprotocol-unoffered",
  22234. headers);
  22235. ASSERT_TRUE(client.connect());
  22236. EXPECT_TRUE(client.subprotocol().empty());
  22237. client.close();
  22238. }
  22239. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  22240. // Connect without requesting any subprotocol
  22241. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22242. "/ws-subprotocol");
  22243. ASSERT_TRUE(client.connect());
  22244. EXPECT_TRUE(client.subprotocol().empty());
  22245. client.close();
  22246. }
  22247. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  22248. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22249. "/ws-echo");
  22250. client.set_tcp_nodelay(true);
  22251. client.set_connection_timeout(3, 0);
  22252. bool socket_options_called = false;
  22253. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  22254. ASSERT_TRUE(client.connect());
  22255. ASSERT_TRUE(client.is_open());
  22256. EXPECT_TRUE(socket_options_called);
  22257. ASSERT_TRUE(client.send("hello"));
  22258. std::string msg;
  22259. auto result = client.read(msg);
  22260. EXPECT_EQ(result, ws::ReadResult::Text);
  22261. EXPECT_EQ(msg, "hello");
  22262. client.close();
  22263. }
  22264. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  22265. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22266. "/ws-echo");
  22267. client.set_connection_timeout(std::chrono::seconds(3));
  22268. client.set_write_timeout(std::chrono::seconds(3));
  22269. // A sub-second remainder exercises the seconds/microseconds split.
  22270. client.set_read_timeout(std::chrono::milliseconds(1500));
  22271. ASSERT_TRUE(client.connect());
  22272. auto start = std::chrono::steady_clock::now();
  22273. std::string msg;
  22274. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  22275. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  22276. std::chrono::steady_clock::now() - start)
  22277. .count();
  22278. // Above 1s so that dropping the microseconds half of the split fails here.
  22279. // Ignoring the setter altogether would not reach this line at all: a client
  22280. // waits forever by default.
  22281. EXPECT_GE(elapsed, 1400);
  22282. EXPECT_LT(elapsed, 30000);
  22283. }
  22284. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  22285. Server svr;
  22286. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  22287. if (!req.has_header("Authorization")) {
  22288. res.status = StatusCode::Unauthorized_401;
  22289. res.set_content("Unauthorized", "text/plain");
  22290. return Server::HandlerResponse::Handled;
  22291. }
  22292. return Server::HandlerResponse::Unhandled;
  22293. });
  22294. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22295. std::string msg;
  22296. while (ws.read(msg)) {
  22297. ws.send(msg);
  22298. }
  22299. });
  22300. auto port = svr.bind_to_any_port("localhost");
  22301. std::thread t([&]() { svr.listen_after_bind(); });
  22302. svr.wait_until_ready();
  22303. // Without Authorization header - should be rejected before upgrade
  22304. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  22305. EXPECT_FALSE(client1.connect());
  22306. // The rejection is framed like any other HTTP response
  22307. {
  22308. Client cli("localhost", port);
  22309. Headers headers = {{"Upgrade", "websocket"},
  22310. {"Connection", "Upgrade"},
  22311. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22312. {"Sec-WebSocket-Version", "13"}};
  22313. auto res = cli.Get("/ws", headers);
  22314. ASSERT_TRUE(res);
  22315. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  22316. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  22317. EXPECT_EQ("Unauthorized", res->body);
  22318. }
  22319. // With Authorization header - should succeed
  22320. Headers headers = {{"Authorization", "Bearer token123"}};
  22321. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  22322. headers);
  22323. ASSERT_TRUE(client2.connect());
  22324. ASSERT_TRUE(client2.send("hello"));
  22325. std::string msg;
  22326. ASSERT_TRUE(client2.read(msg));
  22327. EXPECT_EQ("hello", msg);
  22328. client2.close();
  22329. svr.stop();
  22330. t.join();
  22331. }
  22332. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  22333. Server svr;
  22334. std::atomic<int> pre_request_calls{0};
  22335. std::atomic<bool> route_matched{false};
  22336. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  22337. pre_request_calls++;
  22338. if (req.matched_route == "/ws/:id") { route_matched = true; }
  22339. if (req.get_header_value("Authorization") != "Bearer token123") {
  22340. res.status = StatusCode::Unauthorized_401;
  22341. res.set_content("Unauthorized", "text/plain");
  22342. return Server::HandlerResponse::Handled;
  22343. }
  22344. return Server::HandlerResponse::Unhandled;
  22345. });
  22346. std::atomic<bool> handler_called{false};
  22347. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  22348. handler_called = true;
  22349. ws.send(req.matched_route + " " + req.path_params.at("id"));
  22350. });
  22351. auto port = svr.bind_to_any_port("localhost");
  22352. std::thread t([&]() { svr.listen_after_bind(); });
  22353. svr.wait_until_ready();
  22354. // Without Authorization header - should be rejected before upgrade
  22355. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  22356. "/ws/1");
  22357. EXPECT_FALSE(client1.connect());
  22358. EXPECT_FALSE(handler_called);
  22359. EXPECT_EQ(1, pre_request_calls);
  22360. EXPECT_TRUE(route_matched);
  22361. // The rejection is an ordinary HTTP response, not a protocol switch
  22362. {
  22363. Client cli("localhost", port);
  22364. Headers headers = {{"Upgrade", "websocket"},
  22365. {"Connection", "Upgrade"},
  22366. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22367. {"Sec-WebSocket-Version", "13"}};
  22368. auto res = cli.Get("/ws/1", headers);
  22369. ASSERT_TRUE(res);
  22370. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  22371. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  22372. EXPECT_EQ("Unauthorized", res->body);
  22373. }
  22374. EXPECT_FALSE(handler_called);
  22375. // With Authorization header - should succeed
  22376. Headers headers = {{"Authorization", "Bearer token123"}};
  22377. ws::WebSocketClient client2(
  22378. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  22379. ASSERT_TRUE(client2.connect());
  22380. std::string msg;
  22381. ASSERT_TRUE(client2.read(msg));
  22382. EXPECT_EQ("/ws/:id 2", msg);
  22383. EXPECT_TRUE(handler_called);
  22384. client2.close();
  22385. svr.stop();
  22386. t.join();
  22387. }
  22388. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  22389. Server svr;
  22390. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22391. // A read timeout is how a handler gets control back. Without it, a handler
  22392. // parked in read() can never write on the connection it is reading.
  22393. ws.set_read_timeout(std::chrono::milliseconds(100));
  22394. std::string msg;
  22395. while (ws.is_open()) {
  22396. auto r = ws.read(msg);
  22397. if (r == httplib::ws::Timeout) {
  22398. ws.send("tick");
  22399. continue;
  22400. }
  22401. if (r == httplib::ws::Fail) { break; }
  22402. ws.send(msg);
  22403. }
  22404. });
  22405. auto port = svr.bind_to_any_port("localhost");
  22406. std::thread t([&]() { svr.listen_after_bind(); });
  22407. svr.wait_until_ready();
  22408. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22409. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  22410. ASSERT_TRUE(client.connect());
  22411. // The client sends nothing, so anything it receives came out of the
  22412. // handler's timeout path.
  22413. std::string msg;
  22414. ASSERT_EQ(client.read(msg), ws::Text);
  22415. EXPECT_EQ("tick", msg);
  22416. client.close();
  22417. svr.stop();
  22418. t.join();
  22419. }
  22420. // Stream::read may return fewer bytes than asked for. This is that contract at
  22421. // its worst -- one byte per call -- which is what a frame header straddling a
  22422. // read buffer's boundary looks like to the frame parser.
  22423. class WsByteAtATimeStream : public Stream {
  22424. public:
  22425. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  22426. bool is_readable() const override { return true; }
  22427. bool wait_readable() const override { return true; }
  22428. bool wait_writable() const override { return true; }
  22429. ssize_t read(char *ptr, size_t size) override {
  22430. if (size == 0 || pos_ >= data_.size()) { return 0; }
  22431. *ptr = data_[pos_++];
  22432. return 1;
  22433. }
  22434. ssize_t write(const char *, size_t size) override {
  22435. return static_cast<ssize_t>(size);
  22436. }
  22437. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  22438. ip = "127.0.0.1";
  22439. port = 0;
  22440. }
  22441. void get_local_ip_and_port(std::string &ip, int &port) const override {
  22442. ip = "127.0.0.1";
  22443. port = 0;
  22444. }
  22445. socket_t socket() const override { return INVALID_SOCKET; }
  22446. time_t duration() const override { return 0; }
  22447. private:
  22448. std::string data_;
  22449. size_t pos_ = 0;
  22450. };
  22451. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  22452. // The payload uses the 16-bit extended length, so the header, the length
  22453. // and the mask key are all multi-byte fields here. Each used to be read
  22454. // with a single read() call, which fails as soon as one is split. The
  22455. // payload is also a little over one read chunk, so it is read in two.
  22456. std::string body;
  22457. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  22458. body += static_cast<char>(i % 251);
  22459. }
  22460. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  22461. std::string frame;
  22462. frame += static_cast<char>(0x81); // FIN + Text
  22463. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  22464. frame += static_cast<char>(body.size() >> 8);
  22465. frame += static_cast<char>(body.size() & 0xff);
  22466. for (size_t i = 0; i < 4; i++) {
  22467. frame += static_cast<char>(mask[i]);
  22468. }
  22469. for (size_t i = 0; i < body.size(); i++) {
  22470. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  22471. }
  22472. WsByteAtATimeStream strm(frame);
  22473. ws::Opcode opcode;
  22474. std::string payload;
  22475. bool fin = false;
  22476. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  22477. /*expect_masked=*/true, body.size()),
  22478. ws::impl::FrameRead::Ok);
  22479. EXPECT_TRUE(fin);
  22480. EXPECT_EQ(opcode, ws::Opcode::Text);
  22481. EXPECT_EQ(payload, body);
  22482. }
  22483. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  22484. std::string body(2000, 'x');
  22485. std::string frame;
  22486. frame += static_cast<char>(0x82); // FIN + Binary
  22487. frame += static_cast<char>(126); // 16-bit length follows
  22488. frame += static_cast<char>(body.size() >> 8);
  22489. frame += static_cast<char>(body.size() & 0xff);
  22490. frame += body;
  22491. detail::BufferStream strm;
  22492. strm.write(frame.data(), frame.size());
  22493. ws::Opcode opcode;
  22494. std::string payload;
  22495. bool fin;
  22496. EXPECT_EQ(
  22497. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  22498. ws::impl::FrameRead::Ok);
  22499. EXPECT_EQ(body, payload);
  22500. }
  22501. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  22502. // The header announces the largest payload allowed, and only 3 bytes of it
  22503. // ever arrive.
  22504. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  22505. std::string frame;
  22506. frame += static_cast<char>(0x82); // FIN + Binary
  22507. frame += static_cast<char>(127); // 64-bit length follows
  22508. for (int shift = 56; shift >= 0; shift -= 8) {
  22509. frame += static_cast<char>((len >> shift) & 0xff);
  22510. }
  22511. frame += "abc";
  22512. detail::BufferStream strm;
  22513. strm.write(frame.data(), frame.size());
  22514. ws::Opcode opcode;
  22515. std::string payload;
  22516. bool fin;
  22517. EXPECT_EQ(
  22518. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  22519. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  22520. ws::impl::FrameRead::Fail);
  22521. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  22522. }
  22523. TEST(WebSocketTest, QueryStringInHandshake) {
  22524. Server svr;
  22525. std::mutex mtx;
  22526. std::string received_target;
  22527. std::string received_token;
  22528. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22529. {
  22530. std::lock_guard<std::mutex> lock(mtx);
  22531. received_target = req.target;
  22532. if (req.has_param("token")) {
  22533. received_token = req.get_param_value("token");
  22534. }
  22535. }
  22536. std::string msg;
  22537. while (ws.read(msg)) {
  22538. ws.send(msg);
  22539. }
  22540. });
  22541. auto port = svr.bind_to_any_port("localhost");
  22542. std::thread t([&]() { svr.listen_after_bind(); });
  22543. svr.wait_until_ready();
  22544. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  22545. "/ws?token=ABC&session=123");
  22546. ASSERT_TRUE(client.connect());
  22547. // Round-trip ensures the handler has run and captured the request.
  22548. ASSERT_TRUE(client.send("hello"));
  22549. std::string msg;
  22550. ASSERT_TRUE(client.read(msg));
  22551. EXPECT_EQ("hello", msg);
  22552. client.close();
  22553. {
  22554. std::lock_guard<std::mutex> lock(mtx);
  22555. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  22556. EXPECT_EQ("ABC", received_token);
  22557. }
  22558. svr.stop();
  22559. t.join();
  22560. }
  22561. // Run a handshake against a throwaway server and hand the request the server
  22562. // received back to the caller, so tests can assert on the headers the client
  22563. // actually put on the wire.
  22564. static void capture_websocket_handshake_request(
  22565. const Headers &client_headers,
  22566. std::function<void(const Request &, int port)> verify) {
  22567. Server svr;
  22568. std::mutex mtx;
  22569. Request received;
  22570. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22571. {
  22572. std::lock_guard<std::mutex> lock(mtx);
  22573. received = req;
  22574. }
  22575. std::string msg;
  22576. while (ws.read(msg)) {
  22577. ws.send(msg);
  22578. }
  22579. });
  22580. auto port = svr.bind_to_any_port("localhost");
  22581. std::thread t([&]() { svr.listen_after_bind(); });
  22582. auto se = detail::scope_exit([&] {
  22583. svr.stop();
  22584. t.join();
  22585. });
  22586. svr.wait_until_ready();
  22587. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  22588. client_headers);
  22589. ASSERT_TRUE(client.connect());
  22590. ASSERT_TRUE(client.send("hello"));
  22591. std::string msg;
  22592. ASSERT_TRUE(client.read(msg));
  22593. client.close();
  22594. {
  22595. std::lock_guard<std::mutex> lock(mtx);
  22596. verify(received, port);
  22597. }
  22598. }
  22599. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  22600. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  22601. // Non-default port must be present in the Host header. Default ports
  22602. // (80/443) are omitted; that logic is covered by
  22603. // MakeHostAndPortStringTest.
  22604. EXPECT_EQ("localhost:" + std::to_string(port),
  22605. req.get_header_value("Host"));
  22606. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  22607. req.get_header_value("User-Agent"));
  22608. EXPECT_FALSE(req.has_header("Accept"));
  22609. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  22610. EXPECT_FALSE(req.has_header("Content-Length"));
  22611. });
  22612. }
  22613. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  22614. capture_websocket_handshake_request(
  22615. {{"Host", "example.com"},
  22616. {"User-Agent", "custom-agent"},
  22617. {"X-Custom", "value"}},
  22618. [](const Request &req, int) {
  22619. EXPECT_EQ("example.com", req.get_header_value("Host"));
  22620. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  22621. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  22622. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  22623. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  22624. });
  22625. }
  22626. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  22627. capture_websocket_handshake_request(
  22628. {{"Upgrade", "bogus"},
  22629. {"Connection", "close"},
  22630. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  22631. {"Sec-WebSocket-Version", "8"}},
  22632. [](const Request &req, int) {
  22633. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  22634. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  22635. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  22636. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  22637. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  22638. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  22639. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  22640. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  22641. req.get_header_value("Sec-WebSocket-Key"));
  22642. });
  22643. }
  22644. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  22645. // A header the client refuses to send must abort the handshake before any
  22646. // part of it reaches the wire; a lone request line would otherwise sit in
  22647. // the peer's buffer as a truncated request.
  22648. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  22649. ASSERT_NE(INVALID_SOCKET, srv);
  22650. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  22651. sockaddr_in addr{};
  22652. addr.sin_family = AF_INET;
  22653. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  22654. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22655. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  22656. ASSERT_EQ(0, ::listen(srv, 1));
  22657. sockaddr_in bound{};
  22658. socklen_t bound_len = sizeof(bound);
  22659. ASSERT_EQ(
  22660. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  22661. auto port = ntohs(bound.sin_port);
  22662. ssize_t received = -1;
  22663. std::thread t([&] {
  22664. // Bound every blocking call so a regression fails the test with a bad
  22665. // value instead of hanging the suite.
  22666. fd_set rfds;
  22667. FD_ZERO(&rfds);
  22668. FD_SET(srv, &rfds);
  22669. timeval tv{5, 0};
  22670. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  22671. 0) {
  22672. return;
  22673. }
  22674. sockaddr_in cli_addr{};
  22675. socklen_t cli_len = sizeof(cli_addr);
  22676. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  22677. if (cli == INVALID_SOCKET) { return; }
  22678. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  22679. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22680. char buf[4096];
  22681. received = ::recv(cli, buf, sizeof(buf), 0);
  22682. });
  22683. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  22684. // connect() has already shut the socket down by the time it returns false,
  22685. // so the peer sees EOF without waiting for the client to be destroyed.
  22686. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  22687. {{"X-Bad", "a\r\nInjected: 1"}});
  22688. EXPECT_FALSE(client.connect());
  22689. t.join();
  22690. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  22691. EXPECT_EQ(0, received);
  22692. }
  22693. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  22694. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  22695. // contains "upgrade" as a substring is a different token and must not
  22696. // start a WebSocket handshake.
  22697. auto make_request = [](const std::vector<std::string> &connection_values) {
  22698. Request req;
  22699. req.method = "GET";
  22700. req.headers.emplace("Upgrade", "websocket");
  22701. for (const auto &value : connection_values) {
  22702. req.headers.emplace("Connection", value);
  22703. }
  22704. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22705. req.headers.emplace("Sec-WebSocket-Version", "13");
  22706. return req;
  22707. };
  22708. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  22709. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  22710. EXPECT_TRUE(
  22711. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  22712. EXPECT_TRUE(
  22713. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  22714. EXPECT_TRUE(
  22715. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  22716. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  22717. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  22718. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  22719. EXPECT_FALSE(
  22720. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  22721. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  22722. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22723. }
  22724. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  22725. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  22726. // asks recipients to match each protocol-name case-insensitively, and RFC
  22727. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  22728. // client naming websocket alongside another protocol, or on a second field
  22729. // line, is offering websocket; a value that merely contains "websocket" as a
  22730. // substring is a different protocol name and is not.
  22731. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  22732. Request req;
  22733. req.method = "GET";
  22734. for (const auto &value : upgrade_values) {
  22735. req.headers.emplace("Upgrade", value);
  22736. }
  22737. req.headers.emplace("Connection", "Upgrade");
  22738. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22739. req.headers.emplace("Sec-WebSocket-Version", "13");
  22740. return req;
  22741. };
  22742. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  22743. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  22744. EXPECT_TRUE(
  22745. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  22746. EXPECT_TRUE(
  22747. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  22748. EXPECT_TRUE(
  22749. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  22750. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  22751. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  22752. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  22753. EXPECT_FALSE(
  22754. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  22755. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  22756. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22757. }
  22758. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  22759. Server svr;
  22760. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  22761. auto port = svr.bind_to_any_port("localhost");
  22762. std::thread t([&]() { svr.listen_after_bind(); });
  22763. auto se = detail::scope_exit([&] {
  22764. svr.stop();
  22765. t.join();
  22766. });
  22767. svr.wait_until_ready();
  22768. Headers headers = {{"Upgrade", "websocket"},
  22769. {"Connection", "notupgrade"},
  22770. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22771. {"Sec-WebSocket-Version", "13"}};
  22772. Client cli("localhost", port);
  22773. auto res = cli.Get("/ws", headers);
  22774. // The route exists only as a WebSocket route, so a request that fails the
  22775. // handshake check falls through to ordinary routing.
  22776. ASSERT_TRUE(res);
  22777. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  22778. }
  22779. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  22780. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  22781. // Connection value is the only thing left for the client to reject.
  22782. Server svr;
  22783. svr.Get("/ws", [](const Request &req, Response &res) {
  22784. res.status = StatusCode::SwitchingProtocol_101;
  22785. res.set_header("Upgrade", "websocket");
  22786. res.set_header("Connection", "notupgrade");
  22787. res.set_header("Sec-WebSocket-Accept",
  22788. detail::websocket_accept_key(
  22789. req.get_header_value("Sec-WebSocket-Key")));
  22790. });
  22791. auto port = svr.bind_to_any_port("localhost");
  22792. std::thread t([&]() { svr.listen_after_bind(); });
  22793. auto se = detail::scope_exit([&] {
  22794. svr.stop();
  22795. t.join();
  22796. });
  22797. svr.wait_until_ready();
  22798. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22799. auto res = client.connect();
  22800. EXPECT_FALSE(res);
  22801. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22802. EXPECT_FALSE(client.is_open());
  22803. }
  22804. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  22805. Server svr;
  22806. svr.Get("/ws", [](const Request &req, Response &res) {
  22807. res.status = StatusCode::SwitchingProtocol_101;
  22808. res.set_header("Upgrade", "websocket");
  22809. res.set_header("Connection", "Upgrade");
  22810. res.set_header("Sec-WebSocket-Accept",
  22811. detail::websocket_accept_key(
  22812. req.get_header_value("Sec-WebSocket-Key")));
  22813. res.set_header("Sec-WebSocket-Protocol", "admin");
  22814. });
  22815. auto port = svr.bind_to_any_port("localhost");
  22816. std::thread t([&]() { svr.listen_after_bind(); });
  22817. auto se = detail::scope_exit([&] {
  22818. svr.stop();
  22819. t.join();
  22820. });
  22821. svr.wait_until_ready();
  22822. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  22823. // Server selects a subprotocol the client never offered
  22824. {
  22825. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22826. ws::WebSocketClient client(url, headers);
  22827. auto res = client.connect();
  22828. EXPECT_FALSE(res);
  22829. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22830. EXPECT_FALSE(client.is_open());
  22831. EXPECT_TRUE(client.subprotocol().empty());
  22832. }
  22833. // Client offered none but the server named one anyway
  22834. {
  22835. ws::WebSocketClient client(url);
  22836. auto res = client.connect();
  22837. EXPECT_FALSE(res);
  22838. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22839. EXPECT_FALSE(client.is_open());
  22840. EXPECT_TRUE(client.subprotocol().empty());
  22841. }
  22842. }
  22843. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  22844. // The socket path doubles as the URL host, so it must not contain '/'.
  22845. const char *shard = getenv("GTEST_SHARD_INDEX");
  22846. const std::string sock_path =
  22847. shard ? std::string("httplib-ws-") + shard + ".sock"
  22848. : std::string("httplib-ws.sock");
  22849. std::remove(sock_path.c_str());
  22850. Server svr;
  22851. std::mutex mtx;
  22852. std::string received_host;
  22853. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22854. {
  22855. std::lock_guard<std::mutex> lock(mtx);
  22856. received_host = req.get_header_value("Host");
  22857. }
  22858. std::string msg;
  22859. while (ws.read(msg)) {
  22860. ws.send(msg);
  22861. }
  22862. });
  22863. svr.set_address_family(AF_UNIX);
  22864. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  22865. auto se = detail::scope_exit([&] {
  22866. svr.stop();
  22867. t.join();
  22868. std::remove(sock_path.c_str());
  22869. });
  22870. svr.wait_until_ready();
  22871. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  22872. client.set_address_family(AF_UNIX);
  22873. ASSERT_TRUE(client.connect());
  22874. ASSERT_TRUE(client.send("hello"));
  22875. std::string msg;
  22876. ASSERT_TRUE(client.read(msg));
  22877. client.close();
  22878. {
  22879. std::lock_guard<std::mutex> lock(mtx);
  22880. // There is no host:port for a Unix socket, so the same "localhost"
  22881. // placeholder the HTTP client uses is expected.
  22882. EXPECT_EQ("localhost", received_host);
  22883. }
  22884. }
  22885. // Two threads must never parse WebSocket frames from the same stream.
  22886. // close() used to read the peer's Close reply with its own frame read, so it
  22887. // raced a reader thread that was in the middle of a payload: the payload loop
  22888. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  22889. // so bytes taken by close() were replaced with bytes from further along the
  22890. // stream. The message kept its length and silently changed content.
  22891. //
  22892. // The raw peer below sends a frame header plus part of the payload, waits for
  22893. // the handler to call close(), and only then sends the rest. Whichever thread
  22894. // would win the race for those bytes, the message must arrive intact, because
  22895. // close() must not touch the stream while read() owns it.
  22896. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  22897. #ifndef _WIN32
  22898. signal(SIGPIPE, SIG_IGN);
  22899. #endif
  22900. const size_t payload_len = 120; // fits the 7-bit length field
  22901. const size_t prefix_len = 8;
  22902. const int attempts = 8;
  22903. std::string expected(payload_len, '\0');
  22904. for (size_t i = 0; i < payload_len; i++) {
  22905. expected[i] = static_cast<char>('a' + i % 26);
  22906. }
  22907. std::atomic<bool> peer_stalled{false};
  22908. std::atomic<bool> handler_done{false};
  22909. std::mutex received_mutex;
  22910. std::vector<std::string> received;
  22911. // Bound every wait, so a regression fails the test instead of hanging the
  22912. // suite.
  22913. auto wait_for = [](const std::atomic<bool> &flag) {
  22914. for (int i = 0; i < 500 && !flag; i++) {
  22915. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22916. }
  22917. };
  22918. Server svr;
  22919. svr.set_websocket_ping_interval(0);
  22920. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22921. std::thread reader([&]() {
  22922. std::string msg;
  22923. while (ws.read(msg)) {
  22924. std::lock_guard<std::mutex> guard(received_mutex);
  22925. received.push_back(msg);
  22926. }
  22927. });
  22928. // Wait until the peer stalls mid-payload, so the reader thread is parked
  22929. // inside read_websocket_frame() when close() runs.
  22930. wait_for(peer_stalled);
  22931. ws.close();
  22932. reader.join();
  22933. handler_done = true;
  22934. });
  22935. auto port = svr.bind_to_any_port("127.0.0.1");
  22936. std::thread t([&]() { svr.listen_after_bind(); });
  22937. auto se = detail::scope_exit([&] {
  22938. svr.stop();
  22939. t.join();
  22940. });
  22941. svr.wait_until_ready();
  22942. auto send_bytes = [](socket_t s, const std::string &data) {
  22943. #ifdef _WIN32
  22944. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  22945. #else
  22946. auto n = ::send(s, data.data(), data.size(), 0);
  22947. #endif
  22948. return n == static_cast<decltype(n)>(data.size());
  22949. };
  22950. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  22951. // Every length used here fits the 7-bit length field.
  22952. auto masked_header = [](uint8_t first_byte, size_t len) {
  22953. std::string h;
  22954. h += static_cast<char>(first_byte);
  22955. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  22956. h.append(4, '\0'); // mask key
  22957. return h;
  22958. };
  22959. for (int attempt = 0; attempt < attempts; attempt++) {
  22960. peer_stalled = false;
  22961. handler_done = false;
  22962. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22963. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  22964. auto se_sock = detail::scope_exit([&] {
  22965. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  22966. });
  22967. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22968. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  22969. sockaddr_in addr{};
  22970. addr.sin_family = AF_INET;
  22971. addr.sin_port = htons(static_cast<uint16_t>(port));
  22972. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22973. ASSERT_EQ(
  22974. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  22975. << "attempt " << attempt;
  22976. ASSERT_TRUE(send_bytes(sock,
  22977. "GET /ws HTTP/1.1\r\n"
  22978. "Host: 127.0.0.1\r\n"
  22979. "Upgrade: websocket\r\n"
  22980. "Connection: Upgrade\r\n"
  22981. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22982. "Sec-WebSocket-Version: 13\r\n"
  22983. "\r\n"))
  22984. << "attempt " << attempt;
  22985. std::string response;
  22986. while (response.find("\r\n\r\n") == std::string::npos) {
  22987. char buf[512];
  22988. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  22989. if (n <= 0) { break; }
  22990. response.append(buf, static_cast<size_t>(n));
  22991. }
  22992. ASSERT_NE(std::string::npos, response.find(" 101 "))
  22993. << "attempt " << attempt;
  22994. // Send the header of a Binary message but only the first prefix_len bytes
  22995. // of its payload, leaving the reader thread stalled inside the payload.
  22996. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  22997. expected.substr(0, prefix_len)))
  22998. << "attempt " << attempt;
  22999. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23000. peer_stalled = true;
  23001. // Let close() send its Close frame and park in its own read before the
  23002. // rest of the payload arrives, so both threads are waiting for it.
  23003. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23004. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  23005. close_frame += static_cast<char>(0x03); // status 1000
  23006. close_frame += static_cast<char>(0xE8);
  23007. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  23008. << "attempt " << attempt;
  23009. // Closing the peer releases the reader thread even on the buggy path,
  23010. // where it waits for bytes another thread already consumed.
  23011. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23012. detail::close_socket(sock);
  23013. sock = INVALID_SOCKET;
  23014. wait_for(handler_done);
  23015. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  23016. }
  23017. std::lock_guard<std::mutex> guard(received_mutex);
  23018. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  23019. << "a message in flight when close() ran was dropped";
  23020. for (size_t i = 0; i < received.size(); i++) {
  23021. EXPECT_EQ(expected, received[i]) << "message " << i;
  23022. }
  23023. }
  23024. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  23025. // returning the socket, or INVALID_SOCKET.
  23026. static socket_t connect_raw_websocket(int port, const std::string &path) {
  23027. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  23028. if (sock == INVALID_SOCKET) { return sock; }
  23029. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23030. sockaddr_in addr{};
  23031. addr.sin_family = AF_INET;
  23032. addr.sin_port = htons(static_cast<uint16_t>(port));
  23033. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23034. std::string req = "GET " + path +
  23035. " HTTP/1.1\r\n"
  23036. "Host: 127.0.0.1\r\n"
  23037. "Upgrade: websocket\r\n"
  23038. "Connection: Upgrade\r\n"
  23039. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  23040. "Sec-WebSocket-Version: 13\r\n"
  23041. "\r\n";
  23042. std::string res;
  23043. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  23044. ::send(sock, req.data(), static_cast<int>(req.size()), 0) ==
  23045. static_cast<int>(req.size())) {
  23046. char c;
  23047. while (res.find("\r\n\r\n") == std::string::npos &&
  23048. ::recv(sock, &c, 1, 0) == 1) {
  23049. res += c;
  23050. }
  23051. }
  23052. if (res.find(" 101 ") == std::string::npos) {
  23053. detail::close_socket(sock);
  23054. return INVALID_SOCKET;
  23055. }
  23056. return sock;
  23057. }
  23058. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  23059. // The payload must fit the 7-bit length field.
  23060. static std::string masked_frame(uint8_t first_byte,
  23061. const std::string &payload) {
  23062. std::string f;
  23063. f += static_cast<char>(first_byte);
  23064. f += static_cast<char>(0x80 | payload.size());
  23065. f.append(4, '\0');
  23066. return f + payload;
  23067. }
  23068. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  23069. std::atomic<bool> done{false};
  23070. std::string received;
  23071. Server svr;
  23072. svr.set_websocket_ping_interval(0);
  23073. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23074. std::string msg;
  23075. if (ws.read(msg) == ws::Binary) { received = msg; }
  23076. done = true;
  23077. });
  23078. auto port = svr.bind_to_any_port("127.0.0.1");
  23079. std::thread t([&]() { svr.listen_after_bind(); });
  23080. auto se = detail::scope_exit([&] {
  23081. svr.stop();
  23082. t.join();
  23083. });
  23084. svr.wait_until_ready();
  23085. auto sock = connect_raw_websocket(port, "/ws");
  23086. ASSERT_NE(INVALID_SOCKET, sock);
  23087. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  23088. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  23089. masked_frame(0x89, "p") + // FIN + Ping
  23090. masked_frame(0x80, "lo"); // FIN + Continuation
  23091. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  23092. for (int i = 0; i < 500 && !done; i++) {
  23093. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23094. }
  23095. ASSERT_TRUE(done);
  23096. EXPECT_EQ("Hello", received);
  23097. // The Ping between the fragments is answered with a Pong.
  23098. char pong[3];
  23099. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  23100. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  23101. }
  23102. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  23103. Server svr;
  23104. svr.set_websocket_ping_interval(-1);
  23105. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23106. std::string msg;
  23107. while (ws.read(msg)) {}
  23108. });
  23109. auto port = svr.bind_to_any_port("127.0.0.1");
  23110. std::thread t([&]() { svr.listen_after_bind(); });
  23111. auto se = detail::scope_exit([&] {
  23112. svr.stop();
  23113. t.join();
  23114. });
  23115. svr.wait_until_ready();
  23116. auto sock = connect_raw_websocket(port, "/ws");
  23117. ASSERT_NE(INVALID_SOCKET, sock);
  23118. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  23119. // Nothing comes while the client stays quiet.
  23120. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  23121. char c;
  23122. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  23123. }
  23124. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  23125. Server svr;
  23126. svr.set_websocket_ping_interval(0);
  23127. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23128. std::string msg;
  23129. while (ws.read(msg)) {}
  23130. });
  23131. auto port = svr.bind_to_any_port("127.0.0.1");
  23132. std::thread t([&]() { svr.listen_after_bind(); });
  23133. auto se = detail::scope_exit([&] {
  23134. svr.stop();
  23135. t.join();
  23136. });
  23137. svr.wait_until_ready();
  23138. // Each Close payload and the reply it should get: an echo when valid, 1002
  23139. // otherwise.
  23140. std::vector<std::pair<std::string, std::string>> cases = {
  23141. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  23142. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  23143. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  23144. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  23145. };
  23146. // Also between the fragments of a message.
  23147. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  23148. for (const auto &c : cases) {
  23149. auto sock = connect_raw_websocket(port, "/ws");
  23150. ASSERT_NE(INVALID_SOCKET, sock);
  23151. auto frames = prefix + masked_frame(0x88, c.first);
  23152. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  23153. std::string reply;
  23154. char buf[256];
  23155. while (reply.size() < 2 + c.second.size()) {
  23156. auto n = ::recv(sock, buf, sizeof(buf), 0);
  23157. if (n <= 0) { break; }
  23158. reply.append(buf, static_cast<size_t>(n));
  23159. }
  23160. detail::close_socket(sock);
  23161. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  23162. c.second,
  23163. reply);
  23164. }
  23165. }
  23166. }
  23167. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  23168. class WebSocketSSLIntegrationTest : public ::testing::Test {
  23169. protected:
  23170. void SetUp() override {
  23171. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  23172. SERVER_PRIVATE_KEY_FILE);
  23173. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23174. std::string msg;
  23175. ws::ReadResult ret;
  23176. while ((ret = ws.read(msg))) {
  23177. if (ret == ws::Binary) {
  23178. ws.send(msg.data(), msg.size());
  23179. } else {
  23180. ws.send(msg);
  23181. }
  23182. }
  23183. });
  23184. port_ = server_->bind_to_any_port(HOST);
  23185. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23186. server_->wait_until_ready();
  23187. }
  23188. void TearDown() override {
  23189. server_->stop();
  23190. if (server_thread_.joinable()) { server_thread_.join(); }
  23191. }
  23192. std::unique_ptr<SSLServer> server_;
  23193. std::thread server_thread_;
  23194. int port_ = 0;
  23195. };
  23196. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  23197. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  23198. {
  23199. ws::WebSocketClient client(url);
  23200. client.enable_server_certificate_verification(false);
  23201. auto calls = 0;
  23202. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  23203. calls++;
  23204. return false;
  23205. });
  23206. EXPECT_FALSE(client.connect());
  23207. EXPECT_GT(calls, 0);
  23208. }
  23209. {
  23210. ws::WebSocketClient client(url);
  23211. client.enable_server_certificate_verification(false);
  23212. client.set_session_verifier([](tls::session_t) {
  23213. return SSLVerifierResponse::CertificateRejected;
  23214. });
  23215. EXPECT_FALSE(client.connect());
  23216. }
  23217. {
  23218. ws::WebSocketClient client(url);
  23219. client.enable_server_certificate_verification(false);
  23220. client.set_session_verifier([](tls::session_t) {
  23221. return SSLVerifierResponse::CertificateAccepted;
  23222. });
  23223. EXPECT_TRUE(client.connect());
  23224. }
  23225. }
  23226. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  23227. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23228. "/ws-echo");
  23229. client.enable_server_certificate_verification(false);
  23230. ASSERT_TRUE(client.connect());
  23231. ASSERT_TRUE(client.is_open());
  23232. ASSERT_TRUE(client.send("Hello WSS"));
  23233. std::string msg;
  23234. EXPECT_EQ(ws::Text, client.read(msg));
  23235. EXPECT_EQ("Hello WSS", msg);
  23236. client.close();
  23237. }
  23238. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  23239. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  23240. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  23241. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  23242. // client (without calling close() first) is the only path that runs
  23243. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  23244. // bug exactly.
  23245. //
  23246. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  23247. // when linked against an instrumented libssl; run under Valgrind to catch it
  23248. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  23249. // suite (the freed session otherwise stalls on the close handshake) — this test
  23250. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  23251. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  23252. {
  23253. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23254. "/ws-echo");
  23255. client.enable_server_certificate_verification(false);
  23256. client.set_read_timeout(2, 0);
  23257. client.set_write_timeout(2, 0);
  23258. ASSERT_TRUE(client.connect());
  23259. ASSERT_TRUE(client.is_open());
  23260. ASSERT_TRUE(client.send("still open"));
  23261. // Intentionally do NOT call client.close(): leaving scope runs
  23262. // shutdown_and_close() with the WebSocket still open, which must send the
  23263. // close frame while the TLS session is still alive.
  23264. }
  23265. }
  23266. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  23267. // shutdown_and_close() at the start of connect(), reproducing the same
  23268. // use-after-free within the test body rather than at scope exit. The second
  23269. // connect must succeed and echo, proving the close handshake ran over a live
  23270. // session. See the note above about memory-tool requirements.
  23271. TEST_F(WebSocketSSLIntegrationTest,
  23272. ReconnectWhileOpenSendsCloseOverLiveSession) {
  23273. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23274. "/ws-echo");
  23275. client.enable_server_certificate_verification(false);
  23276. client.set_read_timeout(2, 0);
  23277. client.set_write_timeout(2, 0);
  23278. ASSERT_TRUE(client.connect());
  23279. ASSERT_TRUE(client.is_open());
  23280. ASSERT_TRUE(client.send("still open"));
  23281. // Reconnect without closing first: connect() calls shutdown_and_close() on
  23282. // the still-open connection, which must not touch a freed TLS session.
  23283. ASSERT_TRUE(client.connect());
  23284. ASSERT_TRUE(client.is_open());
  23285. ASSERT_TRUE(client.send("after reconnect"));
  23286. std::string msg;
  23287. EXPECT_EQ(ws::Text, client.read(msg));
  23288. EXPECT_EQ("after reconnect", msg);
  23289. client.close();
  23290. }
  23291. #endif
  23292. #ifdef CPPHTTPLIB_SSL_ENABLED
  23293. class WebSocketSSLCATest : public ::testing::Test {
  23294. protected:
  23295. void SetUp() override {
  23296. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  23297. SERVER_PRIVATE_KEY_FILE);
  23298. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23299. std::string msg;
  23300. while (ws.read(msg)) {
  23301. ws.send(msg);
  23302. }
  23303. });
  23304. port_ = server_->bind_to_any_port("127.0.0.1");
  23305. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23306. server_->wait_until_ready();
  23307. }
  23308. void TearDown() override {
  23309. server_->stop();
  23310. if (server_thread_.joinable()) { server_thread_.join(); }
  23311. }
  23312. std::string url() const {
  23313. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  23314. }
  23315. std::unique_ptr<SSLServer> server_;
  23316. std::thread server_thread_;
  23317. int port_ = 0;
  23318. };
  23319. // A custom CA loaded as PEM verifies the server with full certificate
  23320. // verification enabled
  23321. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  23322. ws::WebSocketClient client(url());
  23323. std::string cert;
  23324. read_file(SERVER_CERT2_FILE, cert);
  23325. client.load_ca_cert_store(cert.c_str(), cert.size());
  23326. ASSERT_TRUE(client.connect());
  23327. ASSERT_TRUE(client.send("hello"));
  23328. std::string msg;
  23329. EXPECT_EQ(ws::Text, client.read(msg));
  23330. EXPECT_EQ("hello", msg);
  23331. client.close();
  23332. }
  23333. // A custom CA that does not cover the server must fail verification (the
  23334. // custom CA is exclusive; system certs are not loaded alongside it)
  23335. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  23336. ws::WebSocketClient client(url());
  23337. std::string cert;
  23338. read_file(CLIENT_CA_CERT_FILE, cert);
  23339. client.load_ca_cert_store(cert.c_str(), cert.size());
  23340. auto res = client.connect();
  23341. ASSERT_FALSE(res);
  23342. EXPECT_EQ(Error::SSLServerVerification, res.error());
  23343. EXPECT_EQ(-1, res.status());
  23344. EXPECT_NE(0u, res.ssl_backend_error());
  23345. }
  23346. // The same CA as a file path rather than PEM in memory
  23347. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  23348. ws::WebSocketClient client(url());
  23349. client.set_ca_cert_path(SERVER_CERT2_FILE);
  23350. ASSERT_TRUE(client.connect());
  23351. ASSERT_TRUE(client.send("hello"));
  23352. std::string msg;
  23353. EXPECT_EQ(ws::Text, client.read(msg));
  23354. EXPECT_EQ("hello", msg);
  23355. client.close();
  23356. }
  23357. // ...and a CA file that does not cover the server still fails, so it is the
  23358. // path above that decides the outcome
  23359. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  23360. ws::WebSocketClient client(url());
  23361. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  23362. ASSERT_FALSE(client.connect());
  23363. }
  23364. // Regression test: reconnecting with a native custom CA store used to reuse
  23365. // a store handle the previous TLS context had already freed (use-after-free
  23366. // under the OpenSSL backend). The context now lives as long as the client.
  23367. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  23368. ws::WebSocketClient client(url());
  23369. std::string cert;
  23370. read_file(SERVER_CERT2_FILE, cert);
  23371. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  23372. ASSERT_TRUE(client.connect());
  23373. client.close();
  23374. ASSERT_TRUE(client.connect());
  23375. ASSERT_TRUE(client.send("again"));
  23376. std::string msg;
  23377. EXPECT_EQ(ws::Text, client.read(msg));
  23378. EXPECT_EQ("again", msg);
  23379. client.close();
  23380. }
  23381. // Regression test: a certificate with a trusted chain but no identity match
  23382. // for the server IP must be rejected. The Mbed TLS backend used to skip
  23383. // verification entirely for IP hosts, so this connection succeeded there.
  23384. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  23385. // chain verification while the identity check must still fail.
  23386. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  23387. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23388. ASSERT_TRUE(svr.is_valid());
  23389. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23390. std::string msg;
  23391. while (ws.read(msg)) {
  23392. ws.send(msg);
  23393. }
  23394. });
  23395. auto port = svr.bind_to_any_port("127.0.0.1");
  23396. auto t = std::thread([&]() { svr.listen_after_bind(); });
  23397. auto se = detail::scope_exit([&] {
  23398. svr.stop();
  23399. t.join();
  23400. });
  23401. svr.wait_until_ready();
  23402. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  23403. "/echo");
  23404. std::string cert;
  23405. read_file(SERVER_CERT_FILE, cert);
  23406. client.load_ca_cert_store(cert.c_str(), cert.size());
  23407. ASSERT_FALSE(client.connect());
  23408. }
  23409. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  23410. // SNI, so nothing binds the host name to the TLS session. These bind the
  23411. // server to "localhost" instead, the only shape that exercises the SNI and
  23412. // hostname-verification path with certificate verification left enabled.
  23413. class WebSocketSSLDnsHostTest : public ::testing::Test {
  23414. protected:
  23415. void Start(const char *cert_file) {
  23416. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  23417. SERVER_PRIVATE_KEY_FILE);
  23418. ASSERT_TRUE(server_->is_valid());
  23419. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23420. std::string msg;
  23421. while (ws.read(msg)) {
  23422. ws.send(msg);
  23423. }
  23424. });
  23425. port_ = server_->bind_to_any_port("localhost");
  23426. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23427. server_->wait_until_ready();
  23428. }
  23429. void TearDown() override {
  23430. if (server_) { server_->stop(); }
  23431. if (server_thread_.joinable()) { server_thread_.join(); }
  23432. }
  23433. std::string url() const {
  23434. return "wss://localhost:" + std::to_string(port_) + "/echo";
  23435. }
  23436. std::unique_ptr<SSLServer> server_;
  23437. std::thread server_thread_;
  23438. int port_ = 0;
  23439. };
  23440. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  23441. // out and the connection is usable
  23442. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  23443. Start(SERVER_CERT2_FILE);
  23444. ws::WebSocketClient client(url());
  23445. client.set_ca_cert_path(SERVER_CERT2_FILE);
  23446. ASSERT_TRUE(client.connect());
  23447. ASSERT_TRUE(client.send("hello"));
  23448. std::string msg;
  23449. EXPECT_EQ(ws::Text, client.read(msg));
  23450. EXPECT_EQ("hello", msg);
  23451. client.close();
  23452. }
  23453. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  23454. // while the identity check must still reject "localhost"
  23455. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  23456. Start(SERVER_CERT_FILE);
  23457. ws::WebSocketClient client(url());
  23458. client.set_ca_cert_path(SERVER_CERT_FILE);
  23459. auto res = client.connect();
  23460. ASSERT_FALSE(res);
  23461. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  23462. EXPECT_EQ(-1, res.status());
  23463. }
  23464. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  23465. // disabled: the chain is still checked, only the identity check is skipped
  23466. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  23467. Start(SERVER_CERT_FILE);
  23468. ws::WebSocketClient client(url());
  23469. client.set_ca_cert_path(SERVER_CERT_FILE);
  23470. client.enable_server_hostname_verification(false);
  23471. ASSERT_TRUE(client.connect());
  23472. ASSERT_TRUE(client.send("hello"));
  23473. std::string msg;
  23474. EXPECT_EQ(ws::Text, client.read(msg));
  23475. EXPECT_EQ("hello", msg);
  23476. client.close();
  23477. }
  23478. // A CA that did not sign the server certificate fails the chain, even though
  23479. // the name would match
  23480. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  23481. Start(SERVER_CERT2_FILE);
  23482. ws::WebSocketClient client(url());
  23483. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  23484. ASSERT_FALSE(client.connect());
  23485. }
  23486. // With verification disabled, neither the chain nor the name is checked
  23487. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  23488. Start(SERVER_CERT_FILE);
  23489. ws::WebSocketClient client(url());
  23490. client.enable_server_certificate_verification(false);
  23491. ASSERT_TRUE(client.connect());
  23492. ASSERT_TRUE(client.send("hello"));
  23493. std::string msg;
  23494. EXPECT_EQ(ws::Text, client.read(msg));
  23495. EXPECT_EQ("hello", msg);
  23496. client.close();
  23497. }
  23498. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  23499. protected:
  23500. void SetUp() override {
  23501. server_ = httplib::detail::make_unique<SSLServer>(
  23502. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23503. ASSERT_TRUE(server_->is_valid());
  23504. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23505. std::string msg;
  23506. while (ws.read(msg)) {
  23507. ws.send(msg);
  23508. }
  23509. });
  23510. port_ = server_->bind_to_any_port("localhost");
  23511. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23512. server_->wait_until_ready();
  23513. }
  23514. void TearDown() override {
  23515. server_->stop();
  23516. if (server_thread_.joinable()) { server_thread_.join(); }
  23517. }
  23518. std::string url() const {
  23519. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  23520. }
  23521. void ConnectWithClientCert(const std::string &client_cert_file,
  23522. const std::string &client_private_key_file,
  23523. const char *private_key_password) {
  23524. std::string cert_pem, key_pem;
  23525. read_file(client_cert_file, cert_pem);
  23526. read_file(client_private_key_file, key_pem);
  23527. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  23528. key_pem.c_str(), key_pem.size(),
  23529. private_key_password};
  23530. ws::WebSocketClient client(url(), pem);
  23531. ASSERT_TRUE(client.is_valid());
  23532. client.enable_server_certificate_verification(false);
  23533. ASSERT_TRUE(client.connect());
  23534. ASSERT_TRUE(client.send("hello"));
  23535. std::string msg;
  23536. EXPECT_EQ(ws::Text, client.read(msg));
  23537. EXPECT_EQ("hello", msg);
  23538. client.close();
  23539. }
  23540. std::unique_ptr<SSLServer> server_;
  23541. std::thread server_thread_;
  23542. int port_ = 0;
  23543. };
  23544. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  23545. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  23546. }
  23547. // Control for the tests above: the fixture's server really does require a
  23548. // client certificate, so it is the PEM the constructor installed that decides
  23549. // the outcome.
  23550. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  23551. ws::WebSocketClient client(url());
  23552. ASSERT_TRUE(client.is_valid());
  23553. client.enable_server_certificate_verification(false);
  23554. EXPECT_FALSE(client.connect());
  23555. }
  23556. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  23557. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  23558. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  23559. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  23560. }
  23561. #endif
  23562. #if !defined(_WIN32)
  23563. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  23564. auto secret_dir = std::string("./symlink_test_secret");
  23565. auto served_dir = std::string("./symlink_test_served");
  23566. auto secret_file = secret_dir + "/secret.txt";
  23567. auto symlink_path = served_dir + "/escape";
  23568. // Setup: create directories and files
  23569. mkdir(secret_dir.c_str(), 0755);
  23570. mkdir(served_dir.c_str(), 0755);
  23571. {
  23572. std::ofstream ofs(secret_file);
  23573. ofs << "SECRET_DATA";
  23574. }
  23575. // Create symlink using absolute path so it resolves correctly
  23576. #ifdef PATH_MAX
  23577. char abs_secret[PATH_MAX];
  23578. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  23579. #else
  23580. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  23581. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  23582. ASSERT_NE(nullptr, abs_secret);
  23583. #endif
  23584. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  23585. auto se = detail::scope_exit([&] {
  23586. unlink(symlink_path.c_str());
  23587. unlink(secret_file.c_str());
  23588. rmdir(served_dir.c_str());
  23589. rmdir(secret_dir.c_str());
  23590. });
  23591. Server svr;
  23592. svr.set_mount_point("/", served_dir);
  23593. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  23594. auto se2 = detail::scope_exit([&] {
  23595. svr.stop();
  23596. listen_thread.join();
  23597. });
  23598. svr.wait_until_ready();
  23599. Client cli("localhost", PORT);
  23600. // Symlink pointing outside base dir should be blocked
  23601. auto res = cli.Get("/escape/secret.txt");
  23602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23603. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  23604. }
  23605. #endif
  23606. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  23607. // "GET /smuggled" request), reads the first response, and only then sends the
  23608. // embedded request as the body. Returns how many times /smuggled ran.
  23609. //
  23610. // The body is sent AFTER receiving the first response (as in the original
  23611. // PoC) so that the stream_line_reader cannot buffer it together with the
  23612. // headers of the first request.
  23613. static int count_smuggled_requests(const std::string &outer_head,
  23614. std::string &first_response) {
  23615. Server svr;
  23616. svr.set_mount_point("/", "./www");
  23617. std::atomic<int> smuggled_count(0);
  23618. svr.Get("/smuggled", [&](const Request &, Response &res) {
  23619. smuggled_count++;
  23620. res.set_content("oops", "text/plain");
  23621. });
  23622. svr.Post("/post", [&](const Request &req, Response &res) {
  23623. res.set_content(req.body, "text/plain");
  23624. });
  23625. auto port = svr.bind_to_any_port("localhost");
  23626. thread t = thread([&] { svr.listen_after_bind(); });
  23627. auto se = detail::scope_exit([&] {
  23628. svr.stop();
  23629. t.join();
  23630. });
  23631. svr.wait_until_ready();
  23632. auto error = Error::Success;
  23633. auto sock = detail::create_client_socket(
  23634. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  23635. /*connection_timeout_sec=*/2, 0,
  23636. /*read_timeout_sec=*/2, 0,
  23637. /*write_timeout_sec=*/2, 0, std::string(), error);
  23638. EXPECT_NE(INVALID_SOCKET, sock);
  23639. if (sock == INVALID_SOCKET) { return -1; }
  23640. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23641. // The "smuggled" request will be sent as the body of the outer request
  23642. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  23643. "Host: localhost\r\n"
  23644. "Connection: close\r\n"
  23645. "\r\n";
  23646. auto head = outer_head;
  23647. auto len = std::to_string(smuggled.size());
  23648. for (auto pos = head.find("{len}"); pos != std::string::npos;
  23649. pos = head.find("{len}", pos + len.size())) {
  23650. head.replace(pos, 5, len);
  23651. }
  23652. // Step 1: Send only the outer request headers (no body yet)
  23653. auto sent = send(sock, head.data(), head.size(), 0);
  23654. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  23655. // Step 2: Read the first response
  23656. char buf[4096];
  23657. for (;;) {
  23658. auto n = recv(sock, buf, sizeof(buf), 0);
  23659. if (n <= 0) break;
  23660. first_response.append(buf, static_cast<size_t>(n));
  23661. // Stop once we have a complete response (headers + body)
  23662. auto hdr_end = first_response.find("\r\n\r\n");
  23663. if (hdr_end != std::string::npos) {
  23664. // Check for Content-Length to know when the body is complete
  23665. auto cl_pos = first_response.find("Content-Length:");
  23666. if (cl_pos != std::string::npos) {
  23667. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  23668. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  23669. auto cl = std::stoul(
  23670. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  23671. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  23672. } else {
  23673. break; // No Content-Length, assume headers-only response
  23674. }
  23675. }
  23676. }
  23677. // Step 3: Now send the body, which looks like a new HTTP request. On a
  23678. // vulnerable server the keep-alive loop reads this as a second request. The
  23679. // server may already have closed the connection, so the result is ignored.
  23680. send(sock, smuggled.data(), smuggled.size(), 0);
  23681. // Half-close so that a server which drained the body sees EOF and closes,
  23682. // instead of the read below waiting for the read timeout.
  23683. #ifdef _WIN32
  23684. ::shutdown(sock, SD_SEND);
  23685. #else
  23686. ::shutdown(sock, SHUT_WR);
  23687. #endif
  23688. // Step 4: Read until the server closes the connection
  23689. for (;;) {
  23690. auto n = recv(sock, buf, sizeof(buf), 0);
  23691. if (n <= 0) break;
  23692. }
  23693. return smuggled_count.load();
  23694. }
  23695. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  23696. // A GET request with Content-Length to a static file handler must have its
  23697. // body drained before the keep-alive connection is reused. Otherwise the
  23698. // unread body bytes are interpreted as the next HTTP request.
  23699. std::string first_response;
  23700. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23701. "Host: localhost\r\n"
  23702. "Content-Length: {len}\r\n"
  23703. "\r\n",
  23704. first_response));
  23705. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  23706. }
  23707. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  23708. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  23709. // be answered with 400 and the connection closed. Treating it as "no body"
  23710. // leaves the body to be parsed as the next request.
  23711. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  23712. const char *targets[] = {
  23713. "GET /file", // handler that never reads the body
  23714. "GET /not-found", // no handler matches (404)
  23715. "POST /post", // handler that reads the body
  23716. };
  23717. for (auto target : targets) {
  23718. for (auto value : values) {
  23719. std::string first_response;
  23720. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  23721. " HTTP/1.1\r\n"
  23722. "Host: localhost\r\n"
  23723. "Content-Length: " +
  23724. value + "\r\n\r\n",
  23725. first_response))
  23726. << target << " with Content-Length: " << value;
  23727. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  23728. << target << " with Content-Length: " << value;
  23729. }
  23730. }
  23731. }
  23732. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  23733. // A 400 for an unparseable request line leaves the rest of the message
  23734. // unread, so the connection must be closed rather than reused.
  23735. std::string first_response;
  23736. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  23737. "Host: localhost\r\n"
  23738. "Content-Length: {len}\r\n"
  23739. "\r\n",
  23740. first_response));
  23741. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  23742. }
  23743. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  23744. // Same as above for a header block that fails to parse.
  23745. std::string first_response;
  23746. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23747. "Host: localhost\r\n"
  23748. "Bad Header\r\n"
  23749. "Content-Length: {len}\r\n"
  23750. "\r\n",
  23751. first_response));
  23752. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  23753. }
  23754. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  23755. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  23756. // server must not read another request on that connection, even when the
  23757. // request had no body to drain.
  23758. std::string first_response;
  23759. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  23760. "Host: localhost\r\n"
  23761. "\r\n",
  23762. first_response));
  23763. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  23764. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  23765. }
  23766. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  23767. // A content reader that stops early leaves the stream inside the body.
  23768. // Draining the whole Content-Length from there, or reading the body again,
  23769. // reads into the next request, and whatever follows is parsed as a request
  23770. // of its own.
  23771. Server svr;
  23772. std::atomic<int> smuggled_count(0);
  23773. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  23774. svr.Post("/upload", [](const Request &req, Response &res,
  23775. const ContentReader &content_reader) {
  23776. // Stop at the last chunk, so the whole body has been read however it
  23777. // arrives.
  23778. auto length = req.get_header_value_u64("Content-Length");
  23779. size_t total = 0;
  23780. auto consumed = content_reader([&](const char *, size_t n) {
  23781. total += n;
  23782. return total < length;
  23783. });
  23784. EXPECT_FALSE(consumed);
  23785. if (req.has_param("retry")) {
  23786. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  23787. }
  23788. // Replace the 400 the aborted read set, which would close the connection.
  23789. res.set_redirect("/done");
  23790. });
  23791. auto port = svr.bind_to_any_port(HOST);
  23792. thread t = thread([&] { svr.listen_after_bind(); });
  23793. auto se = detail::scope_exit([&] {
  23794. svr.stop();
  23795. t.join();
  23796. });
  23797. svr.wait_until_ready();
  23798. // A front end sees the second request as a POST whose body is the GET. The
  23799. // first body is as long as the POST's headers, so draining it again reads
  23800. // exactly those and leaves the GET to be parsed next.
  23801. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  23802. "Host: localhost\r\n"
  23803. "\r\n";
  23804. std::string second_head = "POST /post HTTP/1.1\r\n"
  23805. "Host: localhost\r\n"
  23806. "Content-Length: " +
  23807. std::to_string(inner.size()) +
  23808. "\r\n"
  23809. "\r\n";
  23810. for (auto target : {"/upload", "/upload?retry"}) {
  23811. smuggled_count = 0;
  23812. std::string request = "POST " + std::string(target) +
  23813. " HTTP/1.1\r\n"
  23814. "Host: localhost\r\n"
  23815. "Content-Length: " +
  23816. std::to_string(second_head.size()) +
  23817. "\r\n"
  23818. "\r\n" +
  23819. std::string(second_head.size(), 'A') + second_head +
  23820. inner;
  23821. std::string response;
  23822. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  23823. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  23824. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  23825. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  23826. EXPECT_EQ(0, smuggled_count.load()) << target;
  23827. }
  23828. }
  23829. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  23830. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  23831. // must be rejected with 400 Bad Request.
  23832. Server svr;
  23833. svr.Post("/test", [&](const Request &, Response &res) {
  23834. res.set_content("ok", "text/plain");
  23835. });
  23836. thread t = thread([&] { svr.listen(HOST, PORT); });
  23837. auto se = detail::scope_exit([&] {
  23838. svr.stop();
  23839. t.join();
  23840. ASSERT_FALSE(svr.is_running());
  23841. });
  23842. svr.wait_until_ready();
  23843. // Exact "chunked"
  23844. {
  23845. auto req = "POST /test HTTP/1.1\r\n"
  23846. "Host: localhost\r\n"
  23847. "Content-Length: 5\r\n"
  23848. "Transfer-Encoding: chunked\r\n"
  23849. "Connection: close\r\n"
  23850. "\r\n"
  23851. "hello";
  23852. std::string response;
  23853. ASSERT_TRUE(send_request(1, req, &response));
  23854. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23855. response.substr(0, response.find("\r\n")));
  23856. }
  23857. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  23858. {
  23859. auto req = "POST /test HTTP/1.1\r\n"
  23860. "Host: localhost\r\n"
  23861. "Content-Length: 5\r\n"
  23862. "Transfer-Encoding: gzip, chunked\r\n"
  23863. "Connection: close\r\n"
  23864. "\r\n"
  23865. "hello";
  23866. std::string response;
  23867. ASSERT_TRUE(send_request(1, req, &response));
  23868. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23869. response.substr(0, response.find("\r\n")));
  23870. }
  23871. }
  23872. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  23873. Server svr;
  23874. svr.Post("/test", [&](const Request &, Response &res) {
  23875. res.set_content("ok", "text/plain");
  23876. });
  23877. thread t = thread([&] { svr.listen(HOST, PORT); });
  23878. auto se = detail::scope_exit([&] {
  23879. svr.stop();
  23880. t.join();
  23881. ASSERT_FALSE(svr.is_running());
  23882. });
  23883. svr.wait_until_ready();
  23884. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  23885. // length cannot be determined, so the server must answer 400 and close
  23886. // rather than treat the request as bodyless and leave the body in the
  23887. // socket for the next request to pick up.
  23888. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  23889. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  23890. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  23891. std::string response;
  23892. ASSERT_TRUE(send_request(1, req, &response));
  23893. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23894. response.substr(0, response.find("\r\n")))
  23895. << transfer_encoding;
  23896. }
  23897. // RFC 9110 5.3: the codings may also be split across several
  23898. // Transfer-Encoding lines, which combine in the order they were received.
  23899. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  23900. // just like the single-line "chunked, gzip" above.
  23901. {
  23902. auto req = "POST /test HTTP/1.1\r\n"
  23903. "Host: localhost\r\n"
  23904. "Transfer-Encoding: chunked\r\n"
  23905. "Transfer-Encoding: gzip\r\n"
  23906. "\r\n"
  23907. "0\r\n\r\n";
  23908. std::string response;
  23909. ASSERT_TRUE(send_request(1, req, &response));
  23910. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23911. response.substr(0, response.find("\r\n")));
  23912. }
  23913. // A sequence ending in chunked stays valid.
  23914. auto req = "POST /test HTTP/1.1\r\n"
  23915. "Host: localhost\r\n"
  23916. "Transfer-Encoding: gzip, chunked\r\n"
  23917. "Connection: close\r\n"
  23918. "\r\n"
  23919. "0\r\n\r\n";
  23920. std::string response;
  23921. ASSERT_TRUE(send_request(1, req, &response));
  23922. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  23923. // ...including when it is spread over several lines.
  23924. auto split_req = "POST /test HTTP/1.1\r\n"
  23925. "Host: localhost\r\n"
  23926. "Transfer-Encoding: gzip\r\n"
  23927. "Transfer-Encoding: chunked\r\n"
  23928. "Connection: close\r\n"
  23929. "\r\n"
  23930. "0\r\n\r\n";
  23931. std::string split_response;
  23932. ASSERT_TRUE(send_request(1, split_req, &split_response));
  23933. EXPECT_EQ("HTTP/1.1 200 OK",
  23934. split_response.substr(0, split_response.find("\r\n")));
  23935. }
  23936. // Regression for issue #2450: a DELETE without Content-Length on a
  23937. // keep-alive connection must not let the post-response drain consume the
  23938. // next request's bytes.
  23939. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  23940. Server svr;
  23941. std::atomic<int> delete_count(0);
  23942. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  23943. delete_count++;
  23944. res.status = StatusCode::NoContent_204;
  23945. });
  23946. auto port = svr.bind_to_any_port(HOST);
  23947. thread t = thread([&] { svr.listen_after_bind(); });
  23948. auto se = detail::scope_exit([&] {
  23949. svr.stop();
  23950. t.join();
  23951. });
  23952. svr.wait_until_ready();
  23953. auto error = Error::Success;
  23954. auto sock = detail::create_client_socket(
  23955. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23956. /*connection_timeout_sec=*/2, 0,
  23957. /*read_timeout_sec=*/2, 0,
  23958. /*write_timeout_sec=*/2, 0, std::string(), error);
  23959. ASSERT_NE(INVALID_SOCKET, sock);
  23960. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23961. auto send_request_and_read_response = [&](const std::string &req,
  23962. std::string &out) -> bool {
  23963. auto sent = send(sock, req.data(), req.size(), 0);
  23964. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  23965. char buf[4096];
  23966. for (;;) {
  23967. auto n = recv(sock, buf, sizeof(buf), 0);
  23968. if (n <= 0) { return !out.empty(); }
  23969. out.append(buf, static_cast<size_t>(n));
  23970. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  23971. }
  23972. };
  23973. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  23974. "Host: localhost\r\n"
  23975. "\r\n";
  23976. std::string resp1;
  23977. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  23978. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  23979. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  23980. "Host: localhost\r\n"
  23981. "Connection: close\r\n"
  23982. "\r\n";
  23983. std::string resp2;
  23984. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  23985. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  23986. EXPECT_EQ(2, delete_count.load());
  23987. }
  23988. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  23989. Server svr;
  23990. svr.Post("/ingest", [&](const Request &, Response &res,
  23991. const ContentReader &content_reader) {
  23992. auto consumed = content_reader([](const char *, size_t) { return false; });
  23993. EXPECT_FALSE(consumed);
  23994. res.status = StatusCode::Conflict_409;
  23995. res.set_header("Connection", "close");
  23996. });
  23997. auto port = svr.bind_to_any_port(HOST);
  23998. thread t = thread([&] { svr.listen_after_bind(); });
  23999. auto se = detail::scope_exit([&] {
  24000. svr.stop();
  24001. t.join();
  24002. });
  24003. svr.wait_until_ready();
  24004. auto error = Error::Success;
  24005. auto sock = detail::create_client_socket(
  24006. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  24007. /*connection_timeout_sec=*/2, 0,
  24008. /*read_timeout_sec=*/1, 0,
  24009. /*write_timeout_sec=*/2, 0, std::string(), error);
  24010. ASSERT_NE(INVALID_SOCKET, sock);
  24011. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24012. std::string request = "POST /ingest HTTP/1.1\r\n"
  24013. "Host: localhost\r\n"
  24014. "Transfer-Encoding: chunked\r\n"
  24015. "\r\n"
  24016. "4\r\n"
  24017. "data\r\n";
  24018. auto sent = send(sock, request.data(), request.size(), 0);
  24019. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  24020. std::string response;
  24021. ssize_t received = 0;
  24022. do {
  24023. char buf[4096];
  24024. received = recv(sock, buf, sizeof(buf), 0);
  24025. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  24026. } while (received > 0);
  24027. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  24028. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  24029. EXPECT_EQ(0, received);
  24030. }
  24031. namespace no_proxy_test {
  24032. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  24033. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  24034. // calling listen().
  24035. class ScopedServer {
  24036. public:
  24037. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  24038. ~ScopedServer() {
  24039. svr_.stop();
  24040. if (th_.joinable()) { th_.join(); }
  24041. }
  24042. Server &svr() { return svr_; }
  24043. int port() const { return port_; }
  24044. void listen() {
  24045. th_ = std::thread([this] { svr_.listen_after_bind(); });
  24046. svr_.wait_until_ready();
  24047. }
  24048. private:
  24049. Server svr_;
  24050. std::thread th_;
  24051. int port_ = 0;
  24052. };
  24053. class ProxyAndTargetServers {
  24054. public:
  24055. ProxyAndTargetServers() {
  24056. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  24057. proxy_hits_++;
  24058. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  24059. res.set_content("via-proxy", "text/plain");
  24060. });
  24061. target_.Get(".*", [this](const Request &req, Response &res) {
  24062. target_hits_++;
  24063. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  24064. res.set_content("direct", "text/plain");
  24065. });
  24066. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  24067. target_port_ = target_.bind_to_any_port("127.0.0.1");
  24068. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  24069. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  24070. proxy_mock_.wait_until_ready();
  24071. target_.wait_until_ready();
  24072. }
  24073. ~ProxyAndTargetServers() {
  24074. proxy_mock_.stop();
  24075. target_.stop();
  24076. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  24077. if (target_thread_.joinable()) { target_thread_.join(); }
  24078. }
  24079. Server &proxy_mock() { return proxy_mock_; }
  24080. Server &target() { return target_; }
  24081. int proxy_port() const { return proxy_port_; }
  24082. int target_port() const { return target_port_; }
  24083. int proxy_hits() const { return proxy_hits_.load(); }
  24084. int target_hits() const { return target_hits_.load(); }
  24085. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  24086. void reset_counters() {
  24087. proxy_hits_ = 0;
  24088. target_hits_ = 0;
  24089. last_had_proxy_authz_ = false;
  24090. }
  24091. private:
  24092. Server proxy_mock_;
  24093. Server target_;
  24094. std::thread proxy_thread_;
  24095. std::thread target_thread_;
  24096. int proxy_port_ = 0;
  24097. int target_port_ = 0;
  24098. std::atomic<int> proxy_hits_{0};
  24099. std::atomic<int> target_hits_{0};
  24100. std::atomic<bool> last_had_proxy_authz_{false};
  24101. };
  24102. inline std::unique_ptr<Client> make_client(const std::string &host,
  24103. ProxyAndTargetServers &s) {
  24104. auto cli = detail::make_unique<Client>(host, s.target_port());
  24105. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  24106. cli->set_proxy("127.0.0.1", s.proxy_port());
  24107. return cli;
  24108. }
  24109. } // namespace no_proxy_test
  24110. using no_proxy_test::make_client;
  24111. using no_proxy_test::ProxyAndTargetServers;
  24112. TEST(NoProxyTest, ExactHostnameBypasses) {
  24113. ProxyAndTargetServers s;
  24114. auto cli = make_client("example.com", s);
  24115. cli->set_no_proxy({"example.com"});
  24116. auto res = cli->Get("/");
  24117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24118. EXPECT_EQ(0, s.proxy_hits());
  24119. EXPECT_EQ(1, s.target_hits());
  24120. }
  24121. TEST(NoProxyTest, SubdomainBypasses) {
  24122. ProxyAndTargetServers s;
  24123. auto cli = make_client("foo.example.com", s);
  24124. cli->set_no_proxy({"example.com"});
  24125. auto res = cli->Get("/");
  24126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24127. EXPECT_EQ(0, s.proxy_hits());
  24128. EXPECT_EQ(1, s.target_hits());
  24129. }
  24130. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  24131. // Regression guard: "evilexample.com" must not be considered a subdomain
  24132. // of "example.com". Without the dot-boundary rule, a naive endsWith
  24133. // check would let traffic bypass the proxy and leak credentials direct
  24134. // to the attacker host.
  24135. ProxyAndTargetServers s;
  24136. auto cli = make_client("evilexample.com", s);
  24137. cli->set_no_proxy({"example.com"});
  24138. auto res = cli->Get("/");
  24139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24140. EXPECT_GE(s.proxy_hits(), 1);
  24141. EXPECT_EQ(0, s.target_hits());
  24142. }
  24143. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  24144. ProxyAndTargetServers s;
  24145. auto cli = make_client("example.com.evil.com", s);
  24146. cli->set_no_proxy({"example.com"});
  24147. auto res = cli->Get("/");
  24148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24149. EXPECT_GE(s.proxy_hits(), 1);
  24150. EXPECT_EQ(0, s.target_hits());
  24151. }
  24152. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  24153. ProxyAndTargetServers s;
  24154. auto cli = make_client("example.com", s);
  24155. cli->set_no_proxy({".example.com"});
  24156. auto res = cli->Get("/");
  24157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24158. EXPECT_EQ(0, s.proxy_hits());
  24159. EXPECT_EQ(1, s.target_hits());
  24160. }
  24161. TEST(NoProxyTest, CaseInsensitiveHostname) {
  24162. ProxyAndTargetServers s;
  24163. auto cli = make_client("Example.COM", s);
  24164. cli->set_no_proxy({"EXAMPLE.com"});
  24165. auto res = cli->Get("/");
  24166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24167. EXPECT_EQ(0, s.proxy_hits());
  24168. EXPECT_EQ(1, s.target_hits());
  24169. }
  24170. TEST(NoProxyTest, TrailingDotIsNormalized) {
  24171. ProxyAndTargetServers s;
  24172. auto cli = make_client("example.com.", s);
  24173. cli->set_no_proxy({"example.com"});
  24174. auto res = cli->Get("/");
  24175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24176. EXPECT_EQ(0, s.proxy_hits());
  24177. EXPECT_EQ(1, s.target_hits());
  24178. }
  24179. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  24180. // Trailing dots must be normalized on BOTH sides — host and entry.
  24181. // An implementation that only strips the host-side trailing dot would
  24182. // fail to match host "example.com" against entry "example.com." because
  24183. // a literal substring search would compare 11 chars against 12.
  24184. ProxyAndTargetServers s;
  24185. auto cli = make_client("example.com", s);
  24186. cli->set_no_proxy({"example.com."});
  24187. auto res = cli->Get("/");
  24188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24189. EXPECT_EQ(0, s.proxy_hits());
  24190. EXPECT_EQ(1, s.target_hits());
  24191. }
  24192. TEST(NoProxyTest, WildcardBypassesEverything) {
  24193. ProxyAndTargetServers s;
  24194. auto cli = make_client("anything.invalid.test", s);
  24195. cli->set_no_proxy({"*"});
  24196. auto res = cli->Get("/");
  24197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24198. EXPECT_EQ(0, s.proxy_hits());
  24199. EXPECT_EQ(1, s.target_hits());
  24200. }
  24201. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  24202. ProxyAndTargetServers s;
  24203. Client cli("127.0.0.1", s.target_port());
  24204. cli.set_proxy("127.0.0.1", s.proxy_port());
  24205. cli.set_no_proxy({"127.0.0.1"});
  24206. auto res = cli.Get("/");
  24207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24208. EXPECT_EQ(0, s.proxy_hits());
  24209. EXPECT_EQ(1, s.target_hits());
  24210. }
  24211. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  24212. ProxyAndTargetServers s;
  24213. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  24214. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  24215. cli.set_proxy("127.0.0.1", s.proxy_port());
  24216. cli.set_no_proxy({"::1"});
  24217. auto res = cli.Get("/");
  24218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24219. EXPECT_EQ(0, s.proxy_hits());
  24220. EXPECT_EQ(1, s.target_hits());
  24221. }
  24222. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  24223. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  24224. // must still be recognized as IPv6 for CIDR matching. Implementations
  24225. // that detect IPv6 only when the host begins with '[' would parse the
  24226. // host as a hostname and miss the match.
  24227. ProxyAndTargetServers s;
  24228. Client cli("fe80::1", s.target_port());
  24229. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  24230. cli.set_proxy("127.0.0.1", s.proxy_port());
  24231. cli.set_no_proxy({"fe80::/10"});
  24232. auto res = cli.Get("/");
  24233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24234. EXPECT_EQ(0, s.proxy_hits());
  24235. EXPECT_EQ(1, s.target_hits());
  24236. }
  24237. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  24238. ProxyAndTargetServers s;
  24239. Client cli("::1", s.target_port());
  24240. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  24241. cli.set_proxy("127.0.0.1", s.proxy_port());
  24242. cli.set_no_proxy({"[::1]"});
  24243. auto res = cli.Get("/");
  24244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24245. EXPECT_EQ(0, s.proxy_hits());
  24246. EXPECT_EQ(1, s.target_hits());
  24247. }
  24248. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  24249. ProxyAndTargetServers s;
  24250. Client cli("fe80::1", s.target_port());
  24251. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  24252. cli.set_proxy("127.0.0.1", s.proxy_port());
  24253. cli.set_no_proxy({"[fe80::]/10"});
  24254. auto res = cli.Get("/");
  24255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24256. EXPECT_EQ(0, s.proxy_hits());
  24257. EXPECT_EQ(1, s.target_hits());
  24258. }
  24259. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  24260. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  24261. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  24262. // tricks via address-family conversion.
  24263. ProxyAndTargetServers s;
  24264. Client cli("::ffff:127.0.0.1", s.target_port());
  24265. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  24266. cli.set_proxy("127.0.0.1", s.proxy_port());
  24267. cli.set_no_proxy({"127.0.0.1"});
  24268. auto res = cli.Get("/");
  24269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24270. EXPECT_GE(s.proxy_hits(), 1);
  24271. EXPECT_EQ(0, s.target_hits());
  24272. }
  24273. TEST(NoProxyTest, IPv4CidrMatch) {
  24274. ProxyAndTargetServers s;
  24275. Client cli("127.0.0.1", s.target_port());
  24276. cli.set_proxy("127.0.0.1", s.proxy_port());
  24277. cli.set_no_proxy({"127.0.0.0/8"});
  24278. auto res = cli.Get("/");
  24279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24280. EXPECT_EQ(0, s.proxy_hits());
  24281. EXPECT_EQ(1, s.target_hits());
  24282. }
  24283. TEST(NoProxyTest, IPv4CidrNonMatch) {
  24284. ProxyAndTargetServers s;
  24285. Client cli("127.0.0.1", s.target_port());
  24286. cli.set_proxy("127.0.0.1", s.proxy_port());
  24287. cli.set_no_proxy({"10.0.0.0/8"});
  24288. auto res = cli.Get("/");
  24289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24290. EXPECT_GE(s.proxy_hits(), 1);
  24291. EXPECT_EQ(0, s.target_hits());
  24292. }
  24293. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  24294. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  24295. // IPv4 target matches.
  24296. ProxyAndTargetServers s;
  24297. Client cli("127.0.0.1", s.target_port());
  24298. cli.set_proxy("127.0.0.1", s.proxy_port());
  24299. cli.set_no_proxy({"0.0.0.0/0"});
  24300. auto res = cli.Get("/");
  24301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24302. EXPECT_EQ(0, s.proxy_hits());
  24303. EXPECT_EQ(1, s.target_hits());
  24304. }
  24305. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  24306. ProxyAndTargetServers s;
  24307. Client cli("127.0.0.1", s.target_port());
  24308. cli.set_proxy("127.0.0.1", s.proxy_port());
  24309. cli.set_no_proxy({"127.0.0.1"});
  24310. auto res = cli.Get("/");
  24311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24312. EXPECT_EQ(0, s.proxy_hits());
  24313. EXPECT_EQ(1, s.target_hits());
  24314. }
  24315. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  24316. ProxyAndTargetServers s;
  24317. Client cli("127.0.0.1", s.target_port());
  24318. cli.set_proxy("127.0.0.1", s.proxy_port());
  24319. cli.set_no_proxy({"127.0.0.0/33"});
  24320. auto res = cli.Get("/");
  24321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24322. EXPECT_GE(s.proxy_hits(), 1);
  24323. EXPECT_EQ(0, s.target_hits());
  24324. }
  24325. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  24326. // Empty prefix after the slash must be rejected, not silently treated as /32.
  24327. ProxyAndTargetServers s;
  24328. Client cli("127.0.0.1", s.target_port());
  24329. cli.set_proxy("127.0.0.1", s.proxy_port());
  24330. cli.set_no_proxy({"127.0.0.1/"});
  24331. auto res = cli.Get("/");
  24332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24333. EXPECT_GE(s.proxy_hits(), 1);
  24334. EXPECT_EQ(0, s.target_hits());
  24335. }
  24336. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  24337. ProxyAndTargetServers s;
  24338. auto cli = make_client("internal.corp", s);
  24339. cli->set_proxy_basic_auth("u", "p");
  24340. cli->set_no_proxy({"internal.corp"});
  24341. auto res = cli->Get("/");
  24342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24343. EXPECT_EQ(1, s.target_hits());
  24344. EXPECT_EQ(0, s.proxy_hits());
  24345. EXPECT_FALSE(s.last_had_proxy_authz())
  24346. << "Proxy-Authorization must not be sent direct to the target";
  24347. }
  24348. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  24349. ProxyAndTargetServers s;
  24350. auto cli = make_client("public.example", s);
  24351. cli->set_proxy_basic_auth("u", "p");
  24352. cli->set_no_proxy({"internal.corp"}); // does not match
  24353. auto res = cli->Get("/");
  24354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24355. EXPECT_GE(s.proxy_hits(), 1);
  24356. EXPECT_TRUE(s.last_had_proxy_authz());
  24357. }
  24358. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  24359. std::atomic<int> hits{0};
  24360. std::atomic<int> hits_with_authz{0};
  24361. no_proxy_test::ScopedServer proxy_mock;
  24362. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  24363. hits++;
  24364. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  24365. if (req.target.find("/redir") != std::string::npos) {
  24366. res.set_redirect("http://other.example/landed");
  24367. } else {
  24368. res.set_content("via-proxy", "text/plain");
  24369. }
  24370. });
  24371. proxy_mock.listen();
  24372. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  24373. hits = 0;
  24374. hits_with_authz = 0;
  24375. Client cli("public.example", 80);
  24376. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24377. cli.set_proxy_basic_auth(c.first, c.second);
  24378. cli.set_follow_location(true);
  24379. // The redirect to another host goes through the proxy as well
  24380. auto res = cli.Get("/redir");
  24381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24382. EXPECT_EQ(2, hits.load());
  24383. EXPECT_EQ(2, hits_with_authz.load());
  24384. }
  24385. }
  24386. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  24387. ProxyAndTargetServers s;
  24388. auto cli = make_client("anything.test", s);
  24389. auto res = cli->Get("/");
  24390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24391. EXPECT_GE(s.proxy_hits(), 1);
  24392. EXPECT_EQ(0, s.target_hits());
  24393. }
  24394. TEST(NoProxyTest, PortSpecificEntryRejected) {
  24395. ProxyAndTargetServers s;
  24396. auto cli = make_client("example.com", s);
  24397. cli->set_no_proxy({"example.com:8080"});
  24398. auto res = cli->Get("/");
  24399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24400. EXPECT_GE(s.proxy_hits(), 1);
  24401. EXPECT_EQ(0, s.target_hits());
  24402. }
  24403. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  24404. ProxyAndTargetServers s;
  24405. auto cli = make_client("anything.test", s);
  24406. cli->set_no_proxy({"", " ", "\t"});
  24407. auto res = cli->Get("/");
  24408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24409. EXPECT_GE(s.proxy_hits(), 1);
  24410. EXPECT_EQ(0, s.target_hits());
  24411. }
  24412. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  24413. // An entry with leading/trailing whitespace must still match — env-style
  24414. // values are commonly pasted with stray spaces and an implementation
  24415. // that feeds the raw token directly to inet_pton would fail to match
  24416. // valid CIDRs because of the spaces.
  24417. ProxyAndTargetServers s;
  24418. Client cli("127.0.0.1", s.target_port());
  24419. cli.set_proxy("127.0.0.1", s.proxy_port());
  24420. cli.set_no_proxy({" 127.0.0.0/8 "});
  24421. auto res = cli.Get("/");
  24422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24423. EXPECT_EQ(0, s.proxy_hits());
  24424. EXPECT_EQ(1, s.target_hits());
  24425. }
  24426. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  24427. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  24428. // go direct and must NOT carry Proxy-Authorization.
  24429. std::atomic<int> proxy_hits{0};
  24430. std::atomic<int> target_hits{0};
  24431. std::atomic<bool> target_saw_authz{false};
  24432. no_proxy_test::ScopedServer proxy_mock, target;
  24433. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  24434. proxy_hits++;
  24435. res.status = 302;
  24436. res.set_header("Location", "http://127.0.0.1:" +
  24437. std::to_string(target.port()) + "/landed");
  24438. });
  24439. target.svr().Get(".*", [&](const Request &req, Response &res) {
  24440. target_hits++;
  24441. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  24442. res.set_content("direct", "text/plain");
  24443. });
  24444. proxy_mock.listen();
  24445. target.listen();
  24446. Client cli("public.example", target.port());
  24447. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24448. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24449. cli.set_proxy_basic_auth("u", "p");
  24450. cli.set_no_proxy({"127.0.0.1"});
  24451. cli.set_follow_location(true);
  24452. auto res = cli.Get("/redir");
  24453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24454. EXPECT_GE(proxy_hits.load(), 1);
  24455. EXPECT_GE(target_hits.load(), 1);
  24456. EXPECT_FALSE(target_saw_authz.load());
  24457. }
  24458. #ifdef CPPHTTPLIB_SSL_ENABLED
  24459. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  24460. // Direct origin replying 407 must not trigger the digest retry; otherwise
  24461. // proxy creds would be sent to the (possibly hostile) origin.
  24462. std::atomic<int> target_hits{0};
  24463. std::atomic<bool> target_saw_proxy_authz{false};
  24464. no_proxy_test::ScopedServer target;
  24465. target.svr().Get(".*", [&](const Request &req, Response &res) {
  24466. target_hits++;
  24467. if (req.has_header("Proxy-Authorization")) {
  24468. target_saw_proxy_authz = true;
  24469. }
  24470. res.status = StatusCode::ProxyAuthenticationRequired_407;
  24471. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  24472. "nonce=\"abc\", algorithm=MD5");
  24473. });
  24474. target.listen();
  24475. // The proxy address is set to the target's port: the bypass MUST kick in;
  24476. // if it doesn't, the test still routes "via proxy" to the same server and
  24477. // the Proxy-Authorization assertion below catches the leak.
  24478. Client cli("evil.example", target.port());
  24479. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  24480. cli.set_proxy("127.0.0.1", target.port());
  24481. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  24482. cli.set_no_proxy({"evil.example"});
  24483. auto res = cli.Get("/x");
  24484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24485. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  24486. EXPECT_EQ(1, target_hits.load());
  24487. EXPECT_FALSE(target_saw_proxy_authz.load());
  24488. }
  24489. #endif
  24490. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  24491. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  24492. std::atomic<int> proxy_hits{0};
  24493. std::atomic<int> bypass_hits{0};
  24494. std::atomic<bool> proxy_saw_c_url{false};
  24495. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  24496. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  24497. proxy_hits++;
  24498. if (req.path.find("/start") != std::string::npos) {
  24499. res.status = 302;
  24500. res.set_header("Location", "http://127.0.0.1:" +
  24501. std::to_string(bypass_server.port()) +
  24502. "/middle");
  24503. return;
  24504. }
  24505. if (req.path.find("/end") != std::string::npos) {
  24506. proxy_saw_c_url = true;
  24507. res.set_content("c-via-proxy", "text/plain");
  24508. return;
  24509. }
  24510. res.set_content("unexpected", "text/plain");
  24511. });
  24512. // public.example's "advertised" port is arbitrary (the request never lands
  24513. // there — it goes through the proxy), but use a dynamic value to stay
  24514. // friendly with sharded parallel runs.
  24515. int public_port = bypass_server.port();
  24516. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  24517. bypass_hits++;
  24518. res.status = 302;
  24519. res.set_header("Location", "http://public.example:" +
  24520. std::to_string(public_port) + "/end");
  24521. });
  24522. proxy_mock.listen();
  24523. bypass_server.listen();
  24524. Client cli("public.example", public_port);
  24525. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24526. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24527. cli.set_no_proxy({"127.0.0.1"});
  24528. cli.set_follow_location(true);
  24529. auto res = cli.Get("/start");
  24530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24531. EXPECT_EQ(StatusCode::OK_200, res->status);
  24532. EXPECT_EQ("c-via-proxy", res->body);
  24533. EXPECT_GE(proxy_hits.load(), 2);
  24534. EXPECT_GE(bypass_hits.load(), 1);
  24535. EXPECT_TRUE(proxy_saw_c_url.load());
  24536. }
  24537. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  24538. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  24539. // request reconnects to the correct endpoint.
  24540. std::atomic<int> proxy_hits{0};
  24541. std::atomic<int> target_hits{0};
  24542. no_proxy_test::ScopedServer proxy_mock, target;
  24543. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  24544. proxy_hits++;
  24545. res.set_content("via-proxy", "text/plain");
  24546. });
  24547. target.svr().Get(".*", [&](const Request &, Response &res) {
  24548. target_hits++;
  24549. res.set_content("direct", "text/plain");
  24550. });
  24551. proxy_mock.listen();
  24552. target.listen();
  24553. Client cli("public.example", target.port());
  24554. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24555. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24556. cli.set_keep_alive(true);
  24557. auto res1 = cli.Get("/a");
  24558. ASSERT_TRUE(res1);
  24559. EXPECT_EQ("via-proxy", res1->body);
  24560. EXPECT_EQ(1, proxy_hits.load());
  24561. EXPECT_EQ(0, target_hits.load());
  24562. cli.set_no_proxy({"public.example"});
  24563. auto res2 = cli.Get("/b");
  24564. ASSERT_TRUE(res2);
  24565. EXPECT_EQ("direct", res2->body);
  24566. EXPECT_EQ(1, proxy_hits.load());
  24567. EXPECT_EQ(1, target_hits.load());
  24568. }
  24569. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  24570. namespace proxy_tunnel_test {
  24571. // SSLServer counterpart to no_proxy_test::ScopedServer.
  24572. class ScopedSSLServer {
  24573. public:
  24574. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  24575. port_ = svr_.bind_to_any_port("127.0.0.1");
  24576. }
  24577. ~ScopedSSLServer() {
  24578. svr_.stop();
  24579. if (th_.joinable()) { th_.join(); }
  24580. }
  24581. SSLServer &svr() { return svr_; }
  24582. int port() const { return port_; }
  24583. void listen() {
  24584. th_ = std::thread([this] { svr_.listen_after_bind(); });
  24585. svr_.wait_until_ready();
  24586. }
  24587. private:
  24588. SSLServer svr_;
  24589. std::thread th_;
  24590. int port_ = 0;
  24591. };
  24592. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  24593. class ScopedConnectProxy {
  24594. public:
  24595. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  24596. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  24597. if (listen_fd_ < 0) { return; }
  24598. int yes = 1;
  24599. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  24600. sockaddr_in a{};
  24601. a.sin_family = AF_INET;
  24602. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24603. a.sin_port = 0;
  24604. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  24605. return;
  24606. }
  24607. socklen_t alen = sizeof(a);
  24608. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  24609. 0) {
  24610. return;
  24611. }
  24612. port_ = ntohs(a.sin_port);
  24613. if (::listen(listen_fd_, 1) != 0) { return; }
  24614. th_ = std::thread([this] { run(); });
  24615. }
  24616. ~ScopedConnectProxy() {
  24617. stop_ = true;
  24618. if (listen_fd_ >= 0) {
  24619. ::shutdown(listen_fd_, SHUT_RDWR);
  24620. ::close(listen_fd_);
  24621. }
  24622. if (th_.joinable()) { th_.join(); }
  24623. }
  24624. int port() const { return port_; }
  24625. int connect_hits() const { return connect_hits_.load(); }
  24626. // Head of the last CONNECT request, as the proxy saw it on the wire.
  24627. std::string connect_request() const {
  24628. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24629. return connect_request_;
  24630. }
  24631. private:
  24632. void run() {
  24633. while (!stop_.load()) {
  24634. fd_set rfds;
  24635. FD_ZERO(&rfds);
  24636. FD_SET(listen_fd_, &rfds);
  24637. timeval tv{0, 100 * 1000};
  24638. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  24639. if (sel <= 0) { continue; }
  24640. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  24641. if (client_fd < 0) { continue; }
  24642. std::string req;
  24643. char buf[2048];
  24644. while (req.find("\r\n\r\n") == std::string::npos) {
  24645. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  24646. if (n <= 0) { break; }
  24647. req.append(buf, static_cast<size_t>(n));
  24648. }
  24649. if (req.compare(0, 7, "CONNECT") != 0) {
  24650. ::close(client_fd);
  24651. continue;
  24652. }
  24653. connect_hits_++;
  24654. {
  24655. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24656. connect_request_ = req;
  24657. }
  24658. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  24659. ::send(client_fd, ok, std::strlen(ok), 0);
  24660. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  24661. sockaddr_in o{};
  24662. o.sin_family = AF_INET;
  24663. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24664. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  24665. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  24666. 0) {
  24667. ::close(client_fd);
  24668. ::close(origin_fd);
  24669. continue;
  24670. }
  24671. auto forward = [](int from, int to) {
  24672. char b[8192];
  24673. for (;;) {
  24674. ssize_t n = ::recv(from, b, sizeof(b), 0);
  24675. if (n <= 0) { break; }
  24676. ssize_t off = 0;
  24677. while (off < n) {
  24678. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  24679. if (s <= 0) {
  24680. off = n;
  24681. break;
  24682. }
  24683. off += s;
  24684. }
  24685. }
  24686. ::shutdown(to, SHUT_WR);
  24687. };
  24688. std::thread t1([&] { forward(client_fd, origin_fd); });
  24689. std::thread t2([&] { forward(origin_fd, client_fd); });
  24690. t1.join();
  24691. t2.join();
  24692. ::close(client_fd);
  24693. ::close(origin_fd);
  24694. }
  24695. }
  24696. int forward_port_ = -1;
  24697. int listen_fd_ = -1;
  24698. int port_ = 0;
  24699. std::thread th_;
  24700. std::atomic<bool> stop_{false};
  24701. std::atomic<int> connect_hits_{0};
  24702. mutable std::mutex connect_request_mutex_;
  24703. std::string connect_request_;
  24704. };
  24705. // Sends one request through the CONNECT proxy to the TLS origin with a
  24706. // credential configured for each hop, and checks that each credential reaches
  24707. // only the hop it was configured for: the proxy's on the CONNECT request, the
  24708. // origin's (every header in origin_headers) on the tunnelled request.
  24709. void CredentialsStayWithTheirHop(
  24710. const std::function<void(SSLClient &)> &set_credentials,
  24711. const std::string &scheme,
  24712. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  24713. std::atomic<int> origin_hits{0};
  24714. std::atomic<bool> origin_saw_proxy_authz{false};
  24715. std::atomic<bool> origin_saw_headers{false};
  24716. ScopedSSLServer origin;
  24717. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24718. origin_hits++;
  24719. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  24720. origin_saw_headers =
  24721. std::all_of(origin_headers.begin(), origin_headers.end(),
  24722. [&](const std::string &h) { return req.has_header(h); });
  24723. res.set_content("ok", "text/plain");
  24724. });
  24725. origin.listen();
  24726. ScopedConnectProxy proxy(origin.port());
  24727. ASSERT_NE(0, proxy.port());
  24728. // Pinned to 127.0.0.1 for the same reason as the test below.
  24729. SSLClient cli("127.0.0.1", origin.port());
  24730. cli.enable_server_certificate_verification(false);
  24731. cli.set_proxy("127.0.0.1", proxy.port());
  24732. set_credentials(cli);
  24733. auto res = cli.Get("/x");
  24734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24735. EXPECT_EQ(StatusCode::OK_200, res->status);
  24736. EXPECT_EQ(1, origin_hits.load());
  24737. EXPECT_EQ(1, proxy.connect_hits());
  24738. EXPECT_TRUE(origin_saw_headers.load());
  24739. EXPECT_FALSE(origin_saw_proxy_authz.load())
  24740. << "Proxy-Authorization must not be sent inside the tunnel";
  24741. auto connect_req = proxy.connect_request();
  24742. EXPECT_NE(std::string::npos,
  24743. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  24744. for (const auto &h : origin_headers) {
  24745. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  24746. << h << " must not be sent to the proxy on CONNECT";
  24747. }
  24748. }
  24749. } // namespace proxy_tunnel_test
  24750. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  24751. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24752. [](SSLClient &cli) {
  24753. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  24754. cli.set_basic_auth("origin-user", "origin-pass");
  24755. },
  24756. "Basic");
  24757. }
  24758. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  24759. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24760. [](SSLClient &cli) {
  24761. cli.set_proxy_bearer_token_auth("proxy-token");
  24762. cli.set_bearer_token_auth("origin-token");
  24763. },
  24764. "Bearer");
  24765. }
  24766. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  24767. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24768. [](SSLClient &cli) {
  24769. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  24770. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  24771. {"Cookie", "sid=origin-session"},
  24772. {"X-Api-Key", "origin-key"}});
  24773. },
  24774. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  24775. }
  24776. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  24777. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  24778. // retry; otherwise proxy creds would be sent to the origin.
  24779. std::atomic<int> origin_hits{0};
  24780. std::atomic<bool> origin_saw_proxy_authz{false};
  24781. proxy_tunnel_test::ScopedSSLServer origin;
  24782. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24783. origin_hits++;
  24784. if (req.has_header("Proxy-Authorization")) {
  24785. origin_saw_proxy_authz = true;
  24786. }
  24787. res.status = StatusCode::ProxyAuthenticationRequired_407;
  24788. res.set_header("Proxy-Authenticate",
  24789. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  24790. "algorithm=MD5");
  24791. });
  24792. origin.listen();
  24793. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  24794. ASSERT_NE(0, proxy.port());
  24795. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  24796. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  24797. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  24798. // and answer with its own status, making this test flaky.
  24799. SSLClient cli("127.0.0.1", origin.port());
  24800. cli.enable_server_certificate_verification(false);
  24801. cli.set_proxy("127.0.0.1", proxy.port());
  24802. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  24803. auto res = cli.Get("/x");
  24804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24805. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  24806. EXPECT_EQ(1, origin_hits.load());
  24807. EXPECT_FALSE(origin_saw_proxy_authz.load());
  24808. EXPECT_EQ(1, proxy.connect_hits());
  24809. }
  24810. #endif