test.cc 898 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definition is linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. } // namespace tls
  68. } // namespace httplib
  69. #endif
  70. using namespace std;
  71. using namespace httplib;
  72. const char *HOST = "localhost";
  73. static int get_base_port() {
  74. const char *shard = getenv("GTEST_SHARD_INDEX");
  75. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  76. }
  77. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  78. // New standalone tests MUST use svr.bind_to_any_port() instead.
  79. const int PORT = get_base_port();
  80. const string LONG_QUERY_VALUE = string(25000, '@');
  81. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  82. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  83. const string TOO_LONG_QUERY_URL =
  84. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  85. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  86. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  87. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  88. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  89. return file.name == key;
  90. });
  91. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  92. return *it;
  93. #else
  94. if (it != items.end()) { return *it; }
  95. throw std::runtime_error("invalid multipart form data name error");
  96. #endif
  97. }
  98. static void read_file(const std::string &path, std::string &out) {
  99. std::ifstream fs(path, std::ios_base::binary);
  100. if (!fs) {
  101. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  102. return;
  103. #else
  104. throw std::runtime_error("File not found: " + path);
  105. #endif
  106. }
  107. fs.seekg(0, std::ios_base::end);
  108. auto size = fs.tellg();
  109. fs.seekg(0);
  110. out.resize(static_cast<size_t>(size));
  111. fs.read(&out[0], static_cast<std::streamsize>(size));
  112. }
  113. class UnixSocketTest : public ::testing::Test {
  114. protected:
  115. void TearDown() override { std::remove(pathname_.c_str()); }
  116. void client_GET(const std::string &addr) {
  117. httplib::Client cli{addr};
  118. cli.set_address_family(AF_UNIX);
  119. ASSERT_TRUE(cli.is_valid());
  120. const auto &result = cli.Get(pattern_);
  121. ASSERT_TRUE(result) << "error: " << result.error();
  122. const auto &resp = result.value();
  123. EXPECT_EQ(resp.status, StatusCode::OK_200);
  124. EXPECT_EQ(resp.body, content_);
  125. }
  126. static std::string make_sock_path() {
  127. const char *shard = getenv("GTEST_SHARD_INDEX");
  128. return shard ? std::string("./httplib-server-") + shard + ".sock"
  129. : "./httplib-server.sock";
  130. }
  131. const std::string pathname_{make_sock_path()};
  132. const std::string pattern_{"/hi"};
  133. const std::string content_{"Hello World!"};
  134. };
  135. TEST_F(UnixSocketTest, pathname) {
  136. httplib::Server svr;
  137. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  138. res.set_content(content_, "text/plain");
  139. });
  140. std::thread t{[&] {
  141. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  142. }};
  143. auto se = detail::scope_exit([&] {
  144. svr.stop();
  145. t.join();
  146. ASSERT_FALSE(svr.is_running());
  147. });
  148. svr.wait_until_ready();
  149. ASSERT_TRUE(svr.is_running());
  150. client_GET(pathname_);
  151. }
  152. #if defined(__linux__) || \
  153. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  154. TEST_F(UnixSocketTest, PeerPid) {
  155. httplib::Server svr;
  156. std::string remote_port_val;
  157. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  158. res.set_content(content_, "text/plain");
  159. remote_port_val = std::to_string(req.remote_port);
  160. });
  161. std::thread t{[&] {
  162. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  163. }};
  164. auto se = detail::scope_exit([&] {
  165. svr.stop();
  166. t.join();
  167. ASSERT_FALSE(svr.is_running());
  168. });
  169. svr.wait_until_ready();
  170. ASSERT_TRUE(svr.is_running());
  171. client_GET(pathname_);
  172. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  173. }
  174. #endif
  175. #ifdef __linux__
  176. TEST_F(UnixSocketTest, abstract) {
  177. constexpr char svr_path[]{"\x00httplib-server.sock"};
  178. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  179. httplib::Server svr;
  180. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  181. res.set_content(content_, "text/plain");
  182. });
  183. std::thread t{[&] {
  184. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  185. }};
  186. auto se = detail::scope_exit([&] {
  187. svr.stop();
  188. t.join();
  189. ASSERT_FALSE(svr.is_running());
  190. });
  191. svr.wait_until_ready();
  192. ASSERT_TRUE(svr.is_running());
  193. client_GET(abstract_addr);
  194. }
  195. #endif
  196. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  197. httplib::Server svr;
  198. std::string received_host_header;
  199. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  200. // Capture the Host header sent by the client
  201. auto host_iter = req.headers.find("Host");
  202. if (host_iter != req.headers.end()) {
  203. received_host_header = host_iter->second;
  204. }
  205. res.set_content(content_, "text/plain");
  206. });
  207. std::thread t{[&] {
  208. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  209. }};
  210. auto se = detail::scope_exit([&] {
  211. svr.stop();
  212. t.join();
  213. ASSERT_FALSE(svr.is_running());
  214. });
  215. svr.wait_until_ready();
  216. ASSERT_TRUE(svr.is_running());
  217. // Test that Host header is automatically set to "localhost" for Unix socket
  218. // connections
  219. httplib::Client cli{pathname_};
  220. cli.set_address_family(AF_UNIX);
  221. ASSERT_TRUE(cli.is_valid());
  222. const auto &result = cli.Get(pattern_);
  223. ASSERT_TRUE(result) << "error: " << result.error();
  224. const auto &resp = result.value();
  225. EXPECT_EQ(resp.status, StatusCode::OK_200);
  226. EXPECT_EQ(resp.body, content_);
  227. // Verify that Host header was automatically set to "localhost"
  228. EXPECT_EQ(received_host_header, "localhost");
  229. }
  230. #ifndef _WIN32
  231. TEST(SocketStream, wait_writable_UNIX) {
  232. int fds[2];
  233. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  234. const auto asSocketStream = [&](socket_t fd,
  235. std::function<bool(Stream &)> func) {
  236. return detail::process_client_socket(
  237. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  238. };
  239. asSocketStream(fds[0], [&](Stream &s0) {
  240. EXPECT_EQ(s0.socket(), fds[0]);
  241. EXPECT_TRUE(s0.wait_writable());
  242. EXPECT_TRUE(s0.is_peer_alive());
  243. EXPECT_EQ(0, close(fds[1]));
  244. EXPECT_FALSE(s0.is_peer_alive());
  245. return true;
  246. });
  247. EXPECT_EQ(0, close(fds[0]));
  248. }
  249. TEST(SocketStream, wait_writable_INET) {
  250. sockaddr_in addr;
  251. memset(&addr, 0, sizeof(addr));
  252. addr.sin_family = AF_INET;
  253. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  254. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  255. int disconnected_svr_sock = -1;
  256. std::thread svr{[&] {
  257. const int s = socket(AF_INET, SOCK_STREAM, 0);
  258. ASSERT_LE(0, s);
  259. // PORT + 1 is shared with the SSL redirect tests and with
  260. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  261. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  262. // because that happens on a worker thread the ASSERT does not stop the
  263. // test: it runs on and fails at the disconnected_svr_sock check instead.
  264. default_socket_options(s);
  265. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  266. ASSERT_EQ(0, listen(s, 1));
  267. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  268. ASSERT_EQ(0, close(s));
  269. }};
  270. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  271. std::thread cli{[&] {
  272. const int s = socket(AF_INET, SOCK_STREAM, 0);
  273. ASSERT_LE(0, s);
  274. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  275. ASSERT_EQ(0, close(s));
  276. }};
  277. cli.join();
  278. svr.join();
  279. ASSERT_NE(disconnected_svr_sock, -1);
  280. const auto asSocketStream = [&](socket_t fd,
  281. std::function<bool(Stream &)> func) {
  282. return detail::process_client_socket(
  283. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  284. };
  285. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  286. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  287. // wait_writable() returns true because select_write() only checks if the
  288. // send buffer has space. Peer disconnection is detected later by send().
  289. EXPECT_TRUE(ss.wait_writable());
  290. return true;
  291. });
  292. ASSERT_EQ(0, close(disconnected_svr_sock));
  293. }
  294. #endif // #ifndef _WIN32
  295. TEST(SetSocketOptTest, TcpNoDelay) {
  296. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  297. ASSERT_NE(sock, INVALID_SOCKET);
  298. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  299. int val = 0;
  300. socklen_t len = sizeof(val);
  301. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  302. reinterpret_cast<char *>(&val), &len));
  303. EXPECT_NE(val, 0);
  304. detail::close_socket(sock);
  305. }
  306. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  307. // accept() reports failures through WSAGetLastError() on Windows and through
  308. // errno everywhere else. Asking the wrong one is what made the accept loop
  309. // treat every recoverable failure as fatal on Windows.
  310. struct Classification {
  311. bool resource;
  312. bool transient;
  313. };
  314. auto classify = [](int err) {
  315. #ifdef _WIN32
  316. WSASetLastError(err);
  317. #else
  318. errno = err;
  319. #endif
  320. // Read both before asserting: an assertion may clobber the error slot.
  321. Classification c;
  322. c.resource = detail::is_accept_resource_error();
  323. c.transient = detail::is_accept_transient_error();
  324. return c;
  325. };
  326. #ifdef _WIN32
  327. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  328. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  329. WSAECONNRESET, WSAECONNABORTED};
  330. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  331. #else
  332. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  333. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  334. ECONNABORTED};
  335. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  336. #endif
  337. for (auto err : resource_errors) {
  338. const auto c = classify(err);
  339. EXPECT_TRUE(c.resource) << "error " << err;
  340. EXPECT_FALSE(c.transient) << "error " << err;
  341. }
  342. for (auto err : transient_errors) {
  343. const auto c = classify(err);
  344. EXPECT_TRUE(c.transient) << "error " << err;
  345. EXPECT_FALSE(c.resource) << "error " << err;
  346. }
  347. for (auto err : fatal_errors) {
  348. const auto c = classify(err);
  349. EXPECT_FALSE(c.resource) << "error " << err;
  350. EXPECT_FALSE(c.transient) << "error " << err;
  351. }
  352. #ifdef _WIN32
  353. WSASetLastError(0);
  354. #else
  355. errno = 0;
  356. #endif
  357. }
  358. TEST(ClientTest, MoveConstructible) {
  359. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  360. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  361. }
  362. TEST(ClientTest, MoveAssignable) {
  363. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  364. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  365. }
  366. #ifdef _WIN32
  367. TEST(StartupTest, WSAStartup) {
  368. WSADATA wsaData;
  369. int ret = WSAStartup(0x0002, &wsaData);
  370. ASSERT_EQ(0, ret);
  371. }
  372. #endif
  373. TEST(DecodePathTest, PercentCharacter) {
  374. EXPECT_EQ(
  375. decode_path_component(
  376. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  377. U8("descrip=Gastos áéíóúñÑ 6"));
  378. }
  379. TEST(DecodePathTest, PercentCharacterNUL) {
  380. string expected;
  381. expected.push_back('x');
  382. expected.push_back('\0');
  383. expected.push_back('x');
  384. EXPECT_EQ(decode_path_component("x%00x"), expected);
  385. }
  386. TEST(DecodePathTest, UnicodeEncoding) {
  387. // %u0041 = 'A' (1-byte UTF-8)
  388. EXPECT_EQ("A", decode_path_component("%u0041"));
  389. // %u00E9 = 'é' (2-byte UTF-8)
  390. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  391. // %u3042 = 'あ' (3-byte UTF-8)
  392. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  393. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  394. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  395. // %uD800 = surrogate (invalid, silently dropped)
  396. EXPECT_EQ("", decode_path_component("%uD800"));
  397. }
  398. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  399. // A sign or whitespace inside the two-character escape window must not be
  400. // accepted as a valid percent-encoding; the sequence is passed through
  401. // literally, matching decode_uri_component / decode_path_component.
  402. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  403. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  404. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  405. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  406. // Well-formed escapes still decode.
  407. EXPECT_EQ("-", decode_query_component("%2D", false));
  408. EXPECT_EQ("A", decode_query_component("%41", false));
  409. }
  410. TEST(SanitizeFilenameTest, VariousPatterns) {
  411. // Path traversal
  412. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  413. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  414. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  415. // Normal and edge cases
  416. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  417. EXPECT_EQ("filename.txt",
  418. httplib::sanitize_filename("/path/to/filename.txt"));
  419. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  420. EXPECT_EQ("", httplib::sanitize_filename(".."));
  421. EXPECT_EQ("", httplib::sanitize_filename(""));
  422. // Null bytes stripped
  423. EXPECT_EQ("safe.txt",
  424. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  425. // Whitespace-only rejected
  426. EXPECT_EQ("", httplib::sanitize_filename(" "));
  427. }
  428. // Forward declaration (see the base64_encode note below): split builds move the
  429. // definition into httplib.cc, so re-declaring it here lets the test link.
  430. namespace httplib {
  431. namespace detail {
  432. bool is_chunked_transfer_encoding(const Headers &headers);
  433. } // namespace detail
  434. } // namespace httplib
  435. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  436. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  437. auto make = [](std::initializer_list<const char *> lines) {
  438. Headers h;
  439. for (auto te : lines) {
  440. if (te) { h.emplace("Transfer-Encoding", te); }
  441. }
  442. return h;
  443. };
  444. // Sole coding, matched case-insensitively.
  445. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  446. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  448. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  450. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  452. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  453. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  454. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  455. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  456. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  457. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  458. // were received, into one list. Headers preserves that order, so the answer
  459. // is decided by the last coding of the last line and the order the lines
  460. // arrived in is significant.
  461. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  462. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  463. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  464. // The split can fall anywhere in the list.
  465. EXPECT_TRUE(
  466. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  467. EXPECT_FALSE(
  468. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  469. // A trailing line naming no coding leaves the list ending in nothing, so it
  470. // must not inherit the chunked from the line before it.
  471. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  472. }
  473. // Forward declaration: in split builds split.py strips `inline` and moves the
  474. // definition into httplib.cc, so detail::base64_encode is not visible from the
  475. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  476. // in both header-only and split builds.
  477. namespace httplib {
  478. namespace detail {
  479. std::string base64_encode(const std::string &in);
  480. } // namespace detail
  481. } // namespace httplib
  482. TEST(Base64EncodeTest, KnownAnswers) {
  483. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  484. // where the accumulator's top bit is already set before the next shift.
  485. EXPECT_EQ("", detail::base64_encode(""));
  486. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  487. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  488. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  489. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  490. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  491. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  492. // High bytes keep the top bit set across several rounds.
  493. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  494. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  495. }
  496. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  497. string unescapedCharacters = "-_.!~*'()";
  498. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  499. }
  500. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  501. string reservedCharacters = ";,/?:@&=+$";
  502. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  503. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  504. }
  505. TEST(ClientQueryOrder, PreserveOrder) {
  506. // This test reproduces Issue #2259: client may reorder query parameters
  507. // when sending a GET request. The expected behavior is that the client
  508. // preserves the original query string order when the caller supplied it
  509. // as part of the path.
  510. Server svr;
  511. svr.Get("/", [&](const Request &req, Response &res) {
  512. // Echo back the raw target so the test can assert ordering
  513. res.set_content(req.target, "text/plain");
  514. });
  515. std::thread t{[&] { svr.listen(HOST, PORT); }};
  516. auto se = detail::scope_exit([&] {
  517. svr.stop();
  518. t.join();
  519. ASSERT_FALSE(svr.is_running());
  520. });
  521. svr.wait_until_ready();
  522. Client cli(HOST, PORT);
  523. ASSERT_TRUE(cli.is_valid());
  524. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  525. auto res = cli.Get(original);
  526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  527. // Expect the echoed target to exactly match the original path (order
  528. // preserved)
  529. EXPECT_EQ(res->body, original);
  530. }
  531. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  532. string chineseCharacters = U8("中国語");
  533. string russianCharacters = U8("дом");
  534. string brazilianCharacters = U8("óculos");
  535. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  536. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  537. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  538. "%D0%B4%D0%BE%D0%BC");
  539. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  540. }
  541. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  542. string unescapedCharacters = "-_.!~*'()";
  543. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  544. }
  545. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  546. string reservedCharacters = ";,/?:@&=+$";
  547. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  548. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  549. }
  550. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  551. string chineseCharacters = U8("中国語");
  552. string russianCharacters = U8("дом");
  553. string brazilianCharacters = U8("óculos");
  554. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  555. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  556. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  557. "%D0%B4%D0%BE%D0%BC");
  558. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  559. }
  560. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  561. // Issue #2082 use case: encoding path component with ampersand
  562. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  563. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  564. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  565. }
  566. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  567. string unescapedCharacters = "-_.!~*'()";
  568. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  569. }
  570. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  571. string reservedCharacters = ";,/?:@&=+$#";
  572. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  573. }
  574. TEST(EncodeUriTest, TestUTF8Characters) {
  575. string chineseCharacters = U8("中国語");
  576. string russianCharacters = U8("дом");
  577. string brazilianCharacters = U8("óculos");
  578. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  579. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  580. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  581. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  582. }
  583. TEST(EncodeUriTest, TestCompleteUri) {
  584. string uri =
  585. "https://example.com/path/to/resource?query=value&param=test#fragment";
  586. EXPECT_EQ(
  587. httplib::encode_uri(uri),
  588. "https://example.com/path/to/resource?query=value&param=test#fragment");
  589. }
  590. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  591. string uri =
  592. "https://example.com/path with spaces/file name.html?q=hello world";
  593. EXPECT_EQ(httplib::encode_uri(uri),
  594. "https://example.com/path%20with%20spaces/"
  595. "file%20name.html?q=hello%20world");
  596. }
  597. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  598. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  599. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  600. }
  601. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  602. string unescapedCharacters = "-_.!~*'()";
  603. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  604. }
  605. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  606. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  607. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  608. string encodedBrazilian = "%C3%B3culos";
  609. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  610. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  611. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  612. }
  613. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  614. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  615. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  616. "Piri Tommy Villiers - on & on");
  617. }
  618. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  619. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  620. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  621. }
  622. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  623. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  624. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  625. }
  626. TEST(DecodeUriTest, TestUTF8Characters) {
  627. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  628. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  629. string encodedBrazilian = "%C3%B3culos";
  630. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  631. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  632. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  633. }
  634. TEST(DecodeUriTest, TestCompleteUri) {
  635. string encodedUri = "https://example.com/path%20with%20spaces/"
  636. "file%20name.html?q=hello%20world";
  637. EXPECT_EQ(
  638. httplib::decode_uri(encodedUri),
  639. "https://example.com/path with spaces/file name.html?q=hello world");
  640. }
  641. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  642. string original =
  643. "https://example.com/path with spaces/file name.html?q=hello world";
  644. string encoded = httplib::encode_uri(original);
  645. string decoded = httplib::decode_uri(encoded);
  646. EXPECT_EQ(decoded, original);
  647. }
  648. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  649. // decode_uri is the inverse of encode_uri: an escaped reserved character
  650. // stays encoded so it is not promoted into a real delimiter, while
  651. // non-reserved escapes still decode (like JS decodeURI).
  652. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  653. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  654. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  655. "%3F%3A%40%26%3D%2B%24%2C%3B");
  656. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  657. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  658. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  659. "http://example.com/a%2Fb");
  660. // decode_uri_component still decodes the reserved character.
  661. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  662. }
  663. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  664. string original = "Piri Tommy Villiers - on & on";
  665. string encoded = httplib::encode_uri_component(original);
  666. string decoded = httplib::decode_uri_component(encoded);
  667. EXPECT_EQ(decoded, original);
  668. }
  669. TEST(TrimTests, TrimStringTests) {
  670. EXPECT_EQ("abc", detail::trim_copy("abc"));
  671. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  672. EXPECT_TRUE(detail::trim_copy("").empty());
  673. }
  674. TEST(AsciiTest, LocaleIndependentClassification) {
  675. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  676. // which consult the global C locale: std::isalnum(0xC5) can return true
  677. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  678. // helpers must classify every byte by the ASCII grammar alone.
  679. for (int i = 0; i < 256; i++) {
  680. auto c = static_cast<char>(i);
  681. auto is_digit = i >= '0' && i <= '9';
  682. auto is_upper = i >= 'A' && i <= 'Z';
  683. auto is_lower = i >= 'a' && i <= 'z';
  684. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  685. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  686. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  687. << "byte " << i;
  688. }
  689. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  690. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  691. // Non-ASCII bytes must be percent-encoded, never passed through as
  692. // alphanumeric.
  693. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  694. }
  695. TEST(FromCharsTest, Double) {
  696. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  697. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  698. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  699. auto parse = [](const std::string &s, double &v) {
  700. return detail::from_chars(s.data(), s.data() + s.size(), v);
  701. };
  702. double v = -1.0;
  703. // Representative quality values.
  704. EXPECT_EQ(parse("0", v).ec, std::errc{});
  705. EXPECT_DOUBLE_EQ(v, 0.0);
  706. EXPECT_EQ(parse("1", v).ec, std::errc{});
  707. EXPECT_DOUBLE_EQ(v, 1.0);
  708. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  709. EXPECT_DOUBLE_EQ(v, 0.8);
  710. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  711. EXPECT_DOUBLE_EQ(v, 0.001);
  712. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  713. EXPECT_DOUBLE_EQ(v, 1.0);
  714. // A missing integer or fractional part is tolerated.
  715. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  716. EXPECT_DOUBLE_EQ(v, 0.5);
  717. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  718. EXPECT_DOUBLE_EQ(v, 5.0);
  719. // Values outside [0, 1] still parse; the caller range-checks them.
  720. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  721. EXPECT_DOUBLE_EQ(v, 123.456);
  722. // Stops at the first byte that is not part of the number and reports where.
  723. std::string trailing = "0.9, text/html";
  724. auto r = parse(trailing, v);
  725. EXPECT_EQ(r.ec, std::errc{});
  726. EXPECT_DOUBLE_EQ(v, 0.9);
  727. EXPECT_EQ(*r.ptr, ',');
  728. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  729. // outright, and an 'e'/'E' simply ends the number.
  730. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  731. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  732. std::string exp_input = "1.5e3";
  733. r = parse(exp_input, v);
  734. EXPECT_EQ(r.ec, std::errc{});
  735. EXPECT_DOUBLE_EQ(v, 1.5);
  736. EXPECT_EQ(*r.ptr, 'e');
  737. // Invalid inputs.
  738. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  739. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  740. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  741. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  742. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  743. // Pathological but well-formed inputs must stay bounded (no overflow, no
  744. // out-of-bounds table access) and stay within [0, 1] for the caller.
  745. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  746. std::errc{});
  747. EXPECT_DOUBLE_EQ(v, 0.0);
  748. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  749. std::errc{});
  750. EXPECT_GE(v, 0.0);
  751. EXPECT_LE(v, 1.0);
  752. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  753. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  754. }
  755. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  756. // Simple case without quality values
  757. std::vector<std::string> result1;
  758. EXPECT_TRUE(detail::parse_accept_header(
  759. "text/html,application/json,text/plain", result1));
  760. EXPECT_EQ(result1.size(), 3U);
  761. EXPECT_EQ(result1[0], "text/html");
  762. EXPECT_EQ(result1[1], "application/json");
  763. EXPECT_EQ(result1[2], "text/plain");
  764. // With quality values
  765. std::vector<std::string> result2;
  766. EXPECT_TRUE(detail::parse_accept_header(
  767. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  768. EXPECT_EQ(result2.size(), 3U);
  769. EXPECT_EQ(result2[0], "application/json"); // highest q value
  770. EXPECT_EQ(result2[1], "text/html");
  771. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  772. }
  773. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  774. // Mixed with and without quality values
  775. std::vector<std::string> result;
  776. EXPECT_TRUE(detail::parse_accept_header(
  777. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  778. EXPECT_EQ(result.size(), 3U);
  779. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  780. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  781. EXPECT_EQ(result[2], "application/json"); // q=0.5
  782. }
  783. TEST(ParseAcceptHeaderTest, EdgeCases) {
  784. // Empty header
  785. std::vector<std::string> empty_result;
  786. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  787. EXPECT_TRUE(empty_result.empty());
  788. // Single type
  789. std::vector<std::string> single_result;
  790. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  791. EXPECT_EQ(single_result.size(), 1U);
  792. EXPECT_EQ(single_result[0], "application/json");
  793. // Wildcard types
  794. std::vector<std::string> wildcard_result;
  795. EXPECT_TRUE(detail::parse_accept_header(
  796. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  797. EXPECT_EQ(wildcard_result.size(), 3U);
  798. EXPECT_EQ(wildcard_result[0], "application/json");
  799. EXPECT_EQ(wildcard_result[1], "text/*");
  800. EXPECT_EQ(wildcard_result[2], "*/*");
  801. }
  802. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  803. // Common browser Accept header
  804. std::vector<std::string> browser_result;
  805. EXPECT_TRUE(
  806. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  807. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  808. browser_result));
  809. EXPECT_EQ(browser_result.size(), 6U);
  810. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  811. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  812. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  813. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  814. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  815. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  816. // API client header
  817. std::vector<std::string> api_result;
  818. EXPECT_TRUE(detail::parse_accept_header(
  819. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  820. api_result));
  821. EXPECT_EQ(api_result.size(), 3U);
  822. EXPECT_EQ(api_result[0], "application/json");
  823. EXPECT_EQ(api_result[1], "application/xml");
  824. EXPECT_EQ(api_result[2], "text/plain");
  825. }
  826. TEST(ParseAcceptHeaderTest, SpecialCases) {
  827. // Quality value with 3 decimal places
  828. std::vector<std::string> decimal_result;
  829. EXPECT_TRUE(detail::parse_accept_header(
  830. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  831. EXPECT_EQ(decimal_result.size(), 2U);
  832. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  833. EXPECT_EQ(decimal_result[1], "text/html");
  834. // Zero quality (should still be included but with lowest priority)
  835. std::vector<std::string> zero_q_result;
  836. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  837. zero_q_result));
  838. EXPECT_EQ(zero_q_result.size(), 2U);
  839. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  840. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  841. // No spaces around commas
  842. std::vector<std::string> no_space_result;
  843. EXPECT_TRUE(detail::parse_accept_header(
  844. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  845. no_space_result));
  846. EXPECT_EQ(no_space_result.size(), 3U);
  847. EXPECT_EQ(no_space_result[0], "text/html");
  848. EXPECT_EQ(no_space_result[1], "application/json");
  849. EXPECT_EQ(no_space_result[2], "text/plain");
  850. }
  851. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  852. // Quality values always use '.' as the decimal separator, so parsing must
  853. // not depend on the process locale. An embedding application may have
  854. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  855. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  856. std::string saved = cur ? cur : "C";
  857. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  858. "fr_FR.UTF-8"};
  859. bool switched = false;
  860. for (const auto loc : comma_locales) {
  861. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  862. std::localeconv()->decimal_point[0] == ',') {
  863. switched = true;
  864. break;
  865. }
  866. }
  867. if (!switched) {
  868. std::setlocale(LC_NUMERIC, saved.c_str());
  869. GTEST_SKIP() << "no comma-decimal locale available on this host";
  870. }
  871. // The higher-weighted type appears later in the list, so a correct parse
  872. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  873. // sensitive parse reads both weights as 0 and leaves the original order.
  874. std::vector<std::string> result;
  875. EXPECT_TRUE(detail::parse_accept_header(
  876. "application/json;q=0.1,text/html;q=0.9", result));
  877. ASSERT_EQ(result.size(), 2U);
  878. EXPECT_EQ(result[0], "text/html");
  879. EXPECT_EQ(result[1], "application/json");
  880. std::setlocale(LC_NUMERIC, saved.c_str());
  881. }
  882. TEST(ParseAcceptHeaderTest, InvalidCases) {
  883. std::vector<std::string> result;
  884. // Invalid quality value (> 1.0)
  885. EXPECT_FALSE(
  886. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  887. // Invalid quality value (< 0.0)
  888. EXPECT_FALSE(
  889. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  890. // Invalid quality value (not a number)
  891. EXPECT_FALSE(detail::parse_accept_header(
  892. "text/html;q=invalid,application/json", result));
  893. // A valid numeric prefix does not make the entire quality value valid.
  894. EXPECT_FALSE(detail::parse_accept_header(
  895. "text/html;q=0.5junk,application/json", result));
  896. // Empty quality value
  897. EXPECT_FALSE(
  898. detail::parse_accept_header("text/html;q=,application/json", result));
  899. // Invalid media type format (no slash and not wildcard)
  900. EXPECT_FALSE(
  901. detail::parse_accept_header("invalidtype,application/json", result));
  902. // Valid cases should still work
  903. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  904. EXPECT_EQ(result.size(), 1U);
  905. EXPECT_EQ(result[0], "*/*");
  906. EXPECT_TRUE(detail::parse_accept_header("*", result));
  907. EXPECT_EQ(result.size(), 1U);
  908. EXPECT_EQ(result[0], "*");
  909. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  910. EXPECT_EQ(result.size(), 1U);
  911. EXPECT_EQ(result[0], "text/*");
  912. }
  913. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  914. // elements, so a leading, trailing or doubled comma is a legal Accept value
  915. // and must not be answered with 400 Bad Request.
  916. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  917. struct {
  918. const char *value;
  919. std::vector<std::string> expected;
  920. } cases[] = {
  921. {",application/json", {"application/json"}},
  922. {"text/html,", {"text/html"}},
  923. {"text/html,,*/*", {"text/html", "*/*"}},
  924. // An empty element may be spelled with whitespace in it
  925. {"text/html, , application/json", {"text/html", "application/json"}},
  926. // Nothing but empty elements is an empty list, which means the same
  927. // thing as no Accept header at all
  928. {",,,", {}},
  929. // Quality values still apply across ignored empty elements
  930. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  931. };
  932. for (const auto &c : cases) {
  933. std::vector<std::string> result;
  934. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  935. << "value: " << c.value;
  936. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  937. }
  938. // An invalid entry is still rejected when empty elements surround it
  939. std::vector<std::string> result;
  940. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  941. }
  942. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  943. // or ';' inside one does not end the list element or the parameter. Section
  944. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  945. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  946. struct {
  947. const char *value;
  948. std::vector<std::string> expected;
  949. } cases[] = {
  950. {"text/html;profile=\"a,b\",application/json",
  951. {"text/html", "application/json"}},
  952. // A "q=" inside a quoted value is not the weight
  953. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  954. {"text/html", "application/json"}},
  955. // The weight after a quoted value still applies
  956. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  957. {"application/json", "text/html"}},
  958. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  959. {"application/json", "text/html"}},
  960. {"text/html;profile=\"a\\\"b\",application/json",
  961. {"text/html", "application/json"}},
  962. // An escaped backslash does not escape the '"' after it
  963. {"text/html;profile=\"a\\\\\",application/json",
  964. {"text/html", "application/json"}},
  965. };
  966. for (const auto &c : cases) {
  967. std::vector<std::string> result;
  968. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  969. << "value: " << c.value;
  970. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  971. }
  972. }
  973. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  974. Server svr;
  975. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  976. EXPECT_EQ(req.accept_content_types.size(), 3U);
  977. EXPECT_EQ(req.accept_content_types[0], "application/json");
  978. EXPECT_EQ(req.accept_content_types[1], "text/html");
  979. EXPECT_EQ(req.accept_content_types[2], "*/*");
  980. res.set_content("ok", "text/plain");
  981. });
  982. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  983. EXPECT_TRUE(false);
  984. res.set_content("bad request", "text/plain");
  985. });
  986. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  987. auto se = detail::scope_exit([&] {
  988. svr.stop();
  989. listen_thread.join();
  990. ASSERT_FALSE(svr.is_running());
  991. });
  992. svr.wait_until_ready();
  993. Client cli("localhost", PORT);
  994. {
  995. auto res = cli.Get(
  996. "/accept_ok",
  997. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  999. EXPECT_EQ(StatusCode::OK_200, res->status);
  1000. }
  1001. {
  1002. auto res = cli.Get("/accept_bad_request",
  1003. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1005. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1006. }
  1007. }
  1008. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1009. Server svr;
  1010. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1011. res.set_content("ok", "text/plain");
  1012. });
  1013. std::atomic<int> start_count{0};
  1014. std::atomic<bool> running_when_called{false};
  1015. svr.set_start_handler([&]() {
  1016. running_when_called = svr.is_running();
  1017. start_count++;
  1018. });
  1019. auto port = svr.bind_to_any_port(HOST);
  1020. std::thread t([&]() { svr.listen_after_bind(); });
  1021. auto se = detail::scope_exit([&] {
  1022. svr.stop();
  1023. t.join();
  1024. ASSERT_FALSE(svr.is_running());
  1025. });
  1026. svr.wait_until_ready();
  1027. // A successful request proves the accept loop is running, which the start
  1028. // handler precedes; so by now the handler must have run exactly once.
  1029. Client cli(HOST, port);
  1030. cli.set_connection_timeout(std::chrono::seconds(5));
  1031. auto res = cli.Get("/");
  1032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1033. EXPECT_EQ(StatusCode::OK_200, res->status);
  1034. EXPECT_EQ(1, start_count.load());
  1035. EXPECT_TRUE(running_when_called.load());
  1036. }
  1037. TEST(DivideTest, DivideStringTests) {
  1038. auto divide = [](const std::string &str, char d) {
  1039. std::string lhs;
  1040. std::string rhs;
  1041. detail::divide(str, d,
  1042. [&](const char *lhs_data, std::size_t lhs_size,
  1043. const char *rhs_data, std::size_t rhs_size) {
  1044. lhs.assign(lhs_data, lhs_size);
  1045. rhs.assign(rhs_data, rhs_size);
  1046. });
  1047. return std::make_pair(std::move(lhs), std::move(rhs));
  1048. };
  1049. {
  1050. const auto res = divide("", '=');
  1051. EXPECT_EQ(res.first, "");
  1052. EXPECT_EQ(res.second, "");
  1053. }
  1054. {
  1055. const auto res = divide("=", '=');
  1056. EXPECT_EQ(res.first, "");
  1057. EXPECT_EQ(res.second, "");
  1058. }
  1059. {
  1060. const auto res = divide(" ", '=');
  1061. EXPECT_EQ(res.first, " ");
  1062. EXPECT_EQ(res.second, "");
  1063. }
  1064. {
  1065. const auto res = divide("a", '=');
  1066. EXPECT_EQ(res.first, "a");
  1067. EXPECT_EQ(res.second, "");
  1068. }
  1069. {
  1070. const auto res = divide("a=", '=');
  1071. EXPECT_EQ(res.first, "a");
  1072. EXPECT_EQ(res.second, "");
  1073. }
  1074. {
  1075. const auto res = divide("=b", '=');
  1076. EXPECT_EQ(res.first, "");
  1077. EXPECT_EQ(res.second, "b");
  1078. }
  1079. {
  1080. const auto res = divide("a=b", '=');
  1081. EXPECT_EQ(res.first, "a");
  1082. EXPECT_EQ(res.second, "b");
  1083. }
  1084. {
  1085. const auto res = divide("a=b=", '=');
  1086. EXPECT_EQ(res.first, "a");
  1087. EXPECT_EQ(res.second, "b=");
  1088. }
  1089. {
  1090. const auto res = divide("a=b=c", '=');
  1091. EXPECT_EQ(res.first, "a");
  1092. EXPECT_EQ(res.second, "b=c");
  1093. }
  1094. }
  1095. TEST(SplitTest, ParseQueryString) {
  1096. string s = "key1=val1&key2=val2&key3=val3";
  1097. Params dic;
  1098. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1099. [&](const char *b, const char *e) {
  1100. string key, val;
  1101. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1102. if (key.empty()) {
  1103. key.assign(b2, e2);
  1104. } else {
  1105. val.assign(b2, e2);
  1106. }
  1107. });
  1108. dic.emplace(key, val);
  1109. });
  1110. EXPECT_EQ("val1", dic.find("key1")->second);
  1111. EXPECT_EQ("val2", dic.find("key2")->second);
  1112. EXPECT_EQ("val3", dic.find("key3")->second);
  1113. }
  1114. TEST(SplitTest, ParseInvalidQueryTests) {
  1115. {
  1116. string s = " ";
  1117. Params dict;
  1118. detail::parse_query_text(s, dict);
  1119. EXPECT_TRUE(dict.empty());
  1120. }
  1121. {
  1122. string s = " = =";
  1123. Params dict;
  1124. detail::parse_query_text(s, dict);
  1125. EXPECT_TRUE(dict.empty());
  1126. }
  1127. }
  1128. TEST(ParseQueryTest, ParseQueryString) {
  1129. {
  1130. std::string s = "key1=val1&key2=val2&key3=val3";
  1131. Params dic;
  1132. detail::parse_query_text(s, dic);
  1133. EXPECT_EQ("val1", dic.find("key1")->second);
  1134. EXPECT_EQ("val2", dic.find("key2")->second);
  1135. EXPECT_EQ("val3", dic.find("key3")->second);
  1136. }
  1137. {
  1138. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1139. Params dic;
  1140. detail::parse_query_text(s, dic);
  1141. EXPECT_EQ("", dic.find("key1")->second);
  1142. EXPECT_EQ("val1", dic.find("key2")->second);
  1143. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1144. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1145. }
  1146. }
  1147. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1148. Params dic;
  1149. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1150. dic.emplace("key1", "val1");
  1151. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1152. dic.emplace("key2", "val2");
  1153. dic.emplace("key3", "val3");
  1154. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1155. }
  1156. // Joins every entry of a Headers or Params into "key=value " so a whole
  1157. // traversal can be compared in one assertion. Both are instantiations of the
  1158. // same insertion-ordered container, so one helper serves both.
  1159. template <typename Map> static std::string entries_to_string(const Map &m) {
  1160. std::string s;
  1161. for (const auto &entry : m) {
  1162. s += entry.first + "=" + entry.second + " ";
  1163. }
  1164. return s;
  1165. }
  1166. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1167. // Params used to be a std::multimap, which sorted by name and handed the
  1168. // caller's query back alphabetised. A client signing its query string could
  1169. // not reproduce the order it asked for.
  1170. Params dic;
  1171. dic.emplace("zulu", "1");
  1172. dic.emplace("alpha", "2");
  1173. dic.emplace("mike", "3");
  1174. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1175. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1176. }
  1177. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1178. Params dic;
  1179. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1180. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1181. }
  1182. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1183. Request req;
  1184. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1185. req.params);
  1186. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1187. EXPECT_EQ("first", req.get_param_value("tag"));
  1188. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1189. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1190. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1191. EXPECT_EQ("", req.get_param_value("tag", 3));
  1192. }
  1193. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1194. // Params shares its container with Headers, which matches field names
  1195. // case-insensitively. Parameter names must not pick that up.
  1196. Params dic;
  1197. dic.emplace("Key", "upper");
  1198. dic.emplace("key", "lower");
  1199. EXPECT_EQ(2U, dic.size());
  1200. EXPECT_EQ(1U, dic.count("Key"));
  1201. EXPECT_EQ(1U, dic.count("key"));
  1202. EXPECT_EQ("upper", dic.find("Key")->second);
  1203. EXPECT_EQ("lower", dic.find("key")->second);
  1204. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1205. }
  1206. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1207. Server svr;
  1208. std::string order;
  1209. svr.Get("/order", [&](const Request &req, Response &res) {
  1210. order = entries_to_string(req.params);
  1211. res.set_content("ok", "text/plain");
  1212. });
  1213. auto port = svr.bind_to_any_port(HOST);
  1214. thread t = thread([&] { svr.listen_after_bind(); });
  1215. auto se = detail::scope_exit([&] {
  1216. svr.stop();
  1217. t.join();
  1218. ASSERT_FALSE(svr.is_running());
  1219. });
  1220. svr.wait_until_ready();
  1221. Client cli(HOST, port);
  1222. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1223. ASSERT_TRUE(res);
  1224. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1225. }
  1226. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1227. Server svr;
  1228. std::string field_order, file_order;
  1229. svr.Post("/order", [&](const Request &req, Response &res) {
  1230. for (const auto &field : req.form.fields) {
  1231. field_order += field.first + "=" + field.second.content + " ";
  1232. }
  1233. for (const auto &file : req.form.files) {
  1234. file_order += file.first + "=" + file.second.filename + " ";
  1235. }
  1236. res.set_content("ok", "text/plain");
  1237. });
  1238. auto port = svr.bind_to_any_port(HOST);
  1239. thread t = thread([&] { svr.listen_after_bind(); });
  1240. auto se = detail::scope_exit([&] {
  1241. svr.stop();
  1242. t.join();
  1243. ASSERT_FALSE(svr.is_running());
  1244. });
  1245. svr.wait_until_ready();
  1246. UploadFormDataItems items = {
  1247. {"zulu", "1", "", ""},
  1248. {"alpha", "2", "", ""},
  1249. {"mike", "3", "", ""},
  1250. {"zebra", "z", "z.txt", "text/plain"},
  1251. {"apple", "a", "a.txt", "text/plain"},
  1252. };
  1253. Client cli(HOST, port);
  1254. auto res = cli.Post("/order", items);
  1255. ASSERT_TRUE(res);
  1256. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1257. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1258. }
  1259. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1260. Server svr;
  1261. std::vector<std::string> values;
  1262. std::string first, second, out_of_range, order;
  1263. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1264. values = req.form.get_fields("tag");
  1265. first = req.form.get_field("tag", 0);
  1266. second = req.form.get_field("tag", 1);
  1267. out_of_range = req.form.get_field("tag", 2);
  1268. for (const auto &field : req.form.fields) {
  1269. order += field.first + "=" + field.second.content + " ";
  1270. }
  1271. res.set_content("ok", "text/plain");
  1272. });
  1273. auto port = svr.bind_to_any_port(HOST);
  1274. thread t = thread([&] { svr.listen_after_bind(); });
  1275. auto se = detail::scope_exit([&] {
  1276. svr.stop();
  1277. t.join();
  1278. ASSERT_FALSE(svr.is_running());
  1279. });
  1280. svr.wait_until_ready();
  1281. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1282. // not adjacent in the container.
  1283. UploadFormDataItems items = {
  1284. {"tag", "first", "", ""},
  1285. {"other", "x", "", ""},
  1286. {"tag", "second", "", ""},
  1287. };
  1288. Client cli(HOST, port);
  1289. auto res = cli.Post("/repeated", items);
  1290. ASSERT_TRUE(res);
  1291. ASSERT_EQ(2U, values.size());
  1292. EXPECT_EQ("first", values[0]);
  1293. EXPECT_EQ("second", values[1]);
  1294. EXPECT_EQ("first", first);
  1295. EXPECT_EQ("second", second);
  1296. // std::multimap already kept entries sharing a name in insertion order, so
  1297. // everything above passes without this change too. The whole traversal is
  1298. // what tells the two apart: sorting by name would hoist "other" to the front
  1299. // and the two "tag" parts would end up adjacent.
  1300. EXPECT_EQ("tag=first other=x tag=second ", order);
  1301. // Advancing past the last entry of a name used to run off the container;
  1302. // the container's saturating increment makes it return the default instead.
  1303. EXPECT_EQ("", out_of_range);
  1304. }
  1305. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1306. // Server::read_content() keeps a FormFields::iterator alive across the
  1307. // content callbacks that fill the part it points at. The container is
  1308. // vector-backed, so a later emplace can reallocate and invalidate an older
  1309. // iterator; 64 parts grow the vector through seven reallocations, which
  1310. // checks that every part's content still lands in its own entry.
  1311. const size_t part_count = 64;
  1312. // One formula for both the parts sent and the values expected back, so the
  1313. // two cannot drift apart.
  1314. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1315. auto content_of = [](size_t i) {
  1316. return std::string(64, static_cast<char>('a' + (i % 26)));
  1317. };
  1318. Server svr;
  1319. std::vector<std::pair<std::string, std::string>> received;
  1320. svr.Post("/many", [&](const Request &req, Response &res) {
  1321. for (const auto &field : req.form.fields) {
  1322. received.emplace_back(field.first, field.second.content);
  1323. }
  1324. res.set_content("ok", "text/plain");
  1325. });
  1326. auto port = svr.bind_to_any_port(HOST);
  1327. thread t = thread([&] { svr.listen_after_bind(); });
  1328. auto se = detail::scope_exit([&] {
  1329. svr.stop();
  1330. t.join();
  1331. ASSERT_FALSE(svr.is_running());
  1332. });
  1333. svr.wait_until_ready();
  1334. UploadFormDataItems items;
  1335. for (size_t i = 0; i < part_count; i++) {
  1336. items.push_back({name_of(i), content_of(i), "", ""});
  1337. }
  1338. Client cli(HOST, port);
  1339. auto res = cli.Post("/many", items);
  1340. ASSERT_TRUE(res);
  1341. ASSERT_EQ(part_count, received.size());
  1342. for (size_t i = 0; i < part_count; i++) {
  1343. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1344. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1345. }
  1346. }
  1347. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1348. string content_type = "multipart/form-data; boundary=something";
  1349. string boundary;
  1350. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1351. EXPECT_TRUE(ret);
  1352. EXPECT_EQ(boundary, "something");
  1353. }
  1354. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1355. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1356. string boundary;
  1357. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1358. EXPECT_TRUE(ret);
  1359. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1360. }
  1361. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1362. string content_type =
  1363. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1364. string boundary;
  1365. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1366. EXPECT_TRUE(ret);
  1367. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1368. }
  1369. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1370. string content_type =
  1371. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1372. string boundary;
  1373. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1374. EXPECT_TRUE(ret);
  1375. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1376. }
  1377. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1378. const string boundary(70, 'a');
  1379. string content_type = "multipart/form-data; boundary=" + boundary;
  1380. string parsed;
  1381. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1382. EXPECT_TRUE(ret);
  1383. EXPECT_EQ(parsed, boundary);
  1384. }
  1385. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1386. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1387. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1388. string parsed;
  1389. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1390. EXPECT_FALSE(ret);
  1391. }
  1392. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1393. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1394. // is 72 characters on the wire and still valid.
  1395. const string boundary(70, 'a');
  1396. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1397. string parsed;
  1398. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1399. EXPECT_EQ(parsed, boundary);
  1400. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1401. parsed.clear();
  1402. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1403. }
  1404. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1405. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1406. // The parameter parser must not treat that '=' as the key/value separator.
  1407. string content_type =
  1408. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1409. "charset=UTF-8";
  1410. string parsed;
  1411. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1412. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1413. }
  1414. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1415. // A ';' inside the quoted-string is part of the value, not a parameter
  1416. // separator, so it must not truncate the boundary.
  1417. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1418. string parsed;
  1419. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1420. EXPECT_EQ(parsed, "a;b");
  1421. }
  1422. TEST(ParseDispositionParamsTest, QuotedValues) {
  1423. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1424. // ';' and '=' are ordinary characters inside one.
  1425. struct {
  1426. const char *value;
  1427. std::vector<std::pair<const char *, const char *>> expected;
  1428. } cases[] = {
  1429. {"name=\"file1\"; filename=\"a.txt\"",
  1430. {{"name", "file1"}, {"filename", "a.txt"}}},
  1431. // Whitespace around '=' and ';' is still trimmed
  1432. {"name=\"file2\" ;filename = \"a.html\"",
  1433. {{"name", "file2"}, {"filename", "a.html"}}},
  1434. // '=' inside the value used to leave only the text after the last one
  1435. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1436. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1437. {"name=\"x=y\"", {{"name", "x=y"}}},
  1438. // ';' inside the value used to truncate the pair and leave a bogus one
  1439. {"name=\"file3\"; filename=\"a;b.txt\"",
  1440. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1441. // An unquoted value keeps working, and so does filename*
  1442. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1443. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1444. // A parameter with no key is dropped rather than turned into one whose
  1445. // key is the value
  1446. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1447. };
  1448. for (const auto &c : cases) {
  1449. Params params;
  1450. detail::parse_disposition_params(c.value, params);
  1451. for (const auto &kv : c.expected) {
  1452. auto it = params.find(kv.first);
  1453. ASSERT_NE(it, params.end())
  1454. << "value: " << c.value << ", key: " << kv.first;
  1455. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1456. }
  1457. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1458. }
  1459. }
  1460. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1461. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1462. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1463. Server svr;
  1464. std::string field_value, file_name, file_filename;
  1465. bool has_field = false, has_file = false;
  1466. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1467. has_field = req.form.has_field("x=y");
  1468. field_value = req.form.get_field("x=y");
  1469. has_file = req.form.has_file("file1");
  1470. const auto &file = req.form.get_file("file1");
  1471. file_name = file.name;
  1472. file_filename = file.filename;
  1473. res.set_content("ok", "text/plain");
  1474. });
  1475. auto port = svr.bind_to_any_port(HOST);
  1476. thread t = thread([&] { svr.listen_after_bind(); });
  1477. auto se = detail::scope_exit([&] {
  1478. svr.stop();
  1479. t.join();
  1480. ASSERT_FALSE(svr.is_running());
  1481. });
  1482. svr.wait_until_ready();
  1483. UploadFormDataItems items = {
  1484. {"x=y", "field-value", "", ""},
  1485. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1486. };
  1487. Client cli(HOST, port);
  1488. auto res = cli.Post("/quoted", items);
  1489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1490. ASSERT_EQ(StatusCode::OK_200, res->status);
  1491. EXPECT_TRUE(has_field);
  1492. EXPECT_EQ("field-value", field_value);
  1493. EXPECT_TRUE(has_file);
  1494. EXPECT_EQ("file1", file_name);
  1495. EXPECT_EQ("a;b=report.pdf", file_filename);
  1496. }
  1497. TEST(GetHeaderValueTest, DefaultValue) {
  1498. Headers headers = {{"Dummy", "Dummy"}};
  1499. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1500. EXPECT_STREQ("text/plain", val);
  1501. }
  1502. TEST(GetHeaderValueTest, DefaultValueInt) {
  1503. Headers headers = {{"Dummy", "Dummy"}};
  1504. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1505. EXPECT_EQ(100ull, val);
  1506. }
  1507. TEST(GetHeaderValueTest, RegularValue) {
  1508. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1509. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1510. EXPECT_STREQ("text/html", val);
  1511. }
  1512. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1513. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1514. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1515. EXPECT_STREQ("text/html", val);
  1516. }
  1517. TEST(GetHeaderValueTest, SetContent) {
  1518. Response res;
  1519. res.set_content("html", "text/html");
  1520. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1521. res.set_content("text", "text/plain");
  1522. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1523. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1524. }
  1525. TEST(GetHeaderValueTest, RegularValueInt) {
  1526. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1527. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1528. EXPECT_EQ(100ull, val);
  1529. }
  1530. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1531. Headers headers = {{"Content-Length", "x"}};
  1532. auto is_invalid_value = false;
  1533. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1534. is_invalid_value);
  1535. EXPECT_EQ(0ull, val);
  1536. EXPECT_TRUE(is_invalid_value);
  1537. }
  1538. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1539. // An all-digit value that overflows size_t must be reported as invalid, not
  1540. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1541. // a large length to a small one on 32-bit builds, leaving the framing length
  1542. // wrong while is_invalid_value stayed false.
  1543. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1544. auto is_invalid_value = false;
  1545. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1546. is_invalid_value);
  1547. EXPECT_TRUE(is_invalid_value);
  1548. // A well-formed length is unaffected.
  1549. Headers ok = {{"Content-Length", "1234"}};
  1550. is_invalid_value = false;
  1551. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1552. is_invalid_value);
  1553. EXPECT_EQ(1234ull, val);
  1554. EXPECT_FALSE(is_invalid_value);
  1555. }
  1556. TEST(GetHeaderValueTest, Range) {
  1557. {
  1558. Headers headers = {make_range_header({{1, -1}})};
  1559. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1560. EXPECT_STREQ("bytes=1-", val);
  1561. }
  1562. {
  1563. Headers headers = {make_range_header({{-1, 1}})};
  1564. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1565. EXPECT_STREQ("bytes=-1", val);
  1566. }
  1567. {
  1568. Headers headers = {make_range_header({{1, 10}})};
  1569. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1570. EXPECT_STREQ("bytes=1-10", val);
  1571. }
  1572. {
  1573. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1574. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1575. EXPECT_STREQ("bytes=1-10, 100-", val);
  1576. }
  1577. {
  1578. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1579. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1580. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1581. }
  1582. {
  1583. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1584. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1585. EXPECT_STREQ("bytes=0-0, -1", val);
  1586. }
  1587. }
  1588. TEST(BearerTokenAuthTest, SchemeValidation) {
  1589. // A value shorter than "Bearer " must not throw from the fixed-length
  1590. // substr, and a non-Bearer scheme must not be reported as a token.
  1591. struct {
  1592. const char *value;
  1593. const char *expected;
  1594. } cases[] = {
  1595. {"x", ""},
  1596. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1597. {"Bearer abc123", "abc123"},
  1598. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1599. };
  1600. for (const auto &c : cases) {
  1601. Request req;
  1602. req.set_header("Authorization", c.value);
  1603. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1604. }
  1605. }
  1606. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1607. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1608. // to depend on the standard library (libstdc++ handed back duplicates in
  1609. // reverse insertion order, libc++ in insertion order).
  1610. Request req;
  1611. req.set_header("Accept-Encoding", "gzip");
  1612. req.set_header("Accept-Encoding", "deflate");
  1613. req.set_header("Accept-Encoding", "br");
  1614. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1615. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1616. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1617. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1618. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1619. }
  1620. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1621. Request req;
  1622. req.set_header("X-Test", "only");
  1623. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1624. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1625. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1626. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1627. }
  1628. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1629. Request req;
  1630. req.set_header("X-First", "1");
  1631. req.set_header("X-Test", "2");
  1632. req.params.emplace("first", "1");
  1633. req.params.emplace("test", "2");
  1634. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1635. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1636. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1637. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1638. // The second one is negative when read as a signed value
  1639. const auto max_id = (std::numeric_limits<size_t>::max)();
  1640. for (auto id : {max_id / 2, max_id}) {
  1641. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1642. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1643. EXPECT_EQ("", req.get_param_value("test", id));
  1644. EXPECT_EQ("", req.form.get_field("test", id));
  1645. EXPECT_EQ("", req.form.get_file("test", id).content);
  1646. }
  1647. }
  1648. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1649. Headers headers;
  1650. headers.emplace("Host", "example.com");
  1651. headers.emplace("Accept-Encoding", "gzip");
  1652. headers.emplace("User-Agent", "test");
  1653. headers.emplace("Accept-Encoding", "deflate");
  1654. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1655. "Accept-Encoding=deflate ",
  1656. entries_to_string(headers));
  1657. }
  1658. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1659. Headers headers = {{"Content-Type", "text/html"},
  1660. {"CONTENT-TYPE", "text/xml"}};
  1661. EXPECT_EQ(2U, headers.count("content-type"));
  1662. auto it = headers.find("content-type");
  1663. ASSERT_TRUE(it != headers.end());
  1664. EXPECT_EQ("text/html", it->second);
  1665. }
  1666. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1667. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1668. // drop only those fields and leave everything positioned between them.
  1669. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1670. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1671. auto rng = headers.equal_range("a");
  1672. headers.erase(rng.first, rng.second);
  1673. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1674. }
  1675. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1676. Headers headers = {
  1677. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1678. EXPECT_EQ(3U, headers.erase("A"));
  1679. EXPECT_EQ(0U, headers.count("A"));
  1680. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1681. }
  1682. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1683. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1684. headers.emplace_front("Host", "example.com");
  1685. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1686. entries_to_string(headers));
  1687. }
  1688. TEST(ParseHeaderValueTest, Range) {
  1689. {
  1690. Ranges ranges;
  1691. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1692. EXPECT_TRUE(ret);
  1693. EXPECT_EQ(1u, ranges.size());
  1694. EXPECT_EQ(1u, ranges[0].first);
  1695. EXPECT_EQ(-1, ranges[0].second);
  1696. }
  1697. {
  1698. Ranges ranges;
  1699. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1700. EXPECT_TRUE(ret);
  1701. EXPECT_EQ(1u, ranges.size());
  1702. EXPECT_EQ(-1, ranges[0].first);
  1703. EXPECT_EQ(1u, ranges[0].second);
  1704. }
  1705. {
  1706. Ranges ranges;
  1707. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1708. EXPECT_TRUE(ret);
  1709. EXPECT_EQ(1u, ranges.size());
  1710. EXPECT_EQ(1u, ranges[0].first);
  1711. EXPECT_EQ(10u, ranges[0].second);
  1712. }
  1713. {
  1714. Ranges ranges;
  1715. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1716. EXPECT_FALSE(ret);
  1717. }
  1718. {
  1719. Ranges ranges;
  1720. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1721. EXPECT_TRUE(ret);
  1722. EXPECT_EQ(2u, ranges.size());
  1723. EXPECT_EQ(1u, ranges[0].first);
  1724. EXPECT_EQ(10u, ranges[0].second);
  1725. EXPECT_EQ(100u, ranges[1].first);
  1726. EXPECT_EQ(-1, ranges[1].second);
  1727. }
  1728. {
  1729. Ranges ranges;
  1730. auto ret =
  1731. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1732. EXPECT_TRUE(ret);
  1733. EXPECT_EQ(3u, ranges.size());
  1734. EXPECT_EQ(1u, ranges[0].first);
  1735. EXPECT_EQ(10u, ranges[0].second);
  1736. EXPECT_EQ(100u, ranges[1].first);
  1737. EXPECT_EQ(200u, ranges[1].second);
  1738. EXPECT_EQ(300u, ranges[2].first);
  1739. EXPECT_EQ(400u, ranges[2].second);
  1740. }
  1741. {
  1742. Ranges ranges;
  1743. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1744. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1745. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1746. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1747. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1748. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1749. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1750. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1751. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1752. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1753. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1754. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1755. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1756. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1757. EXPECT_FALSE(
  1758. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1759. EXPECT_TRUE(ranges.empty());
  1760. }
  1761. {
  1762. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1763. // remainder of the representation, so it stays accepted.
  1764. Ranges ranges;
  1765. auto ret =
  1766. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1767. EXPECT_TRUE(ret);
  1768. ASSERT_EQ(1u, ranges.size());
  1769. EXPECT_EQ(0, ranges[0].first);
  1770. EXPECT_EQ(-1, ranges[0].second);
  1771. }
  1772. // RFC 9110 14.1: range unit names are case-insensitive.
  1773. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  1774. Ranges ranges;
  1775. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  1776. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  1777. }
  1778. }
  1779. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1780. Request req;
  1781. req.set_header("Accept-Encoding", "gzip");
  1782. Response res;
  1783. res.set_header("Content-Type", "text/plain");
  1784. auto ret = detail::encoding_type(req, res);
  1785. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1786. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1787. #else
  1788. EXPECT_TRUE(ret == detail::EncodingType::None);
  1789. #endif
  1790. }
  1791. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1792. Request req;
  1793. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1794. Response res;
  1795. res.set_header("Content-Type", "text/plain");
  1796. auto ret = detail::encoding_type(req, res);
  1797. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1798. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1799. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1800. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1801. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1802. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1803. #else
  1804. EXPECT_TRUE(ret == detail::EncodingType::None);
  1805. #endif
  1806. }
  1807. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1808. Request req;
  1809. req.set_header("Accept-Encoding",
  1810. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1811. Response res;
  1812. res.set_header("Content-Type", "text/plain");
  1813. auto ret = detail::encoding_type(req, res);
  1814. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1815. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1816. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1817. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1818. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1819. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1820. #else
  1821. EXPECT_TRUE(ret == detail::EncodingType::None);
  1822. #endif
  1823. }
  1824. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1825. // All supported encodings rejected with q=0 should return None
  1826. Request req;
  1827. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1828. Response res;
  1829. res.set_header("Content-Type", "text/plain");
  1830. auto ret = detail::encoding_type(req, res);
  1831. EXPECT_TRUE(ret == detail::EncodingType::None);
  1832. }
  1833. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1834. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1835. Request req;
  1836. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1837. Response res;
  1838. res.set_header("Content-Type", "text/plain");
  1839. auto ret = detail::encoding_type(req, res);
  1840. EXPECT_TRUE(ret == detail::EncodingType::None);
  1841. }
  1842. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  1843. Request req;
  1844. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  1845. Response res;
  1846. res.set_header("Content-Type", "text/plain");
  1847. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  1848. }
  1849. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1850. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1851. Request req;
  1852. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1853. Response res;
  1854. res.set_header("Content-Type", "text/plain");
  1855. auto ret = detail::encoding_type(req, res);
  1856. EXPECT_TRUE(ret == detail::EncodingType::None);
  1857. }
  1858. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1859. // RFC 7231: Accept-Encoding values are case-insensitive
  1860. Request req;
  1861. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1862. Response res;
  1863. res.set_header("Content-Type", "text/plain");
  1864. auto ret = detail::encoding_type(req, res);
  1865. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1866. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1867. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1868. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1869. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1870. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1871. #else
  1872. EXPECT_TRUE(ret == detail::EncodingType::None);
  1873. #endif
  1874. }
  1875. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1876. // q value should determine priority, not hardcoded order
  1877. Request req;
  1878. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1879. Response res;
  1880. res.set_header("Content-Type", "text/plain");
  1881. auto ret = detail::encoding_type(req, res);
  1882. // gzip has highest q=1.0, so it should be selected even though
  1883. // br and zstd are also supported
  1884. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1885. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1886. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1887. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1888. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1889. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1890. #else
  1891. EXPECT_TRUE(ret == detail::EncodingType::None);
  1892. #endif
  1893. }
  1894. TEST(BufferStreamTest, read) {
  1895. detail::BufferStream strm1;
  1896. Stream &strm = strm1;
  1897. EXPECT_EQ(5, strm.write("hello"));
  1898. char buf[512];
  1899. EXPECT_EQ(2, strm.read(buf, 2));
  1900. EXPECT_EQ('h', buf[0]);
  1901. EXPECT_EQ('e', buf[1]);
  1902. EXPECT_EQ(2, strm.read(buf, 2));
  1903. EXPECT_EQ('l', buf[0]);
  1904. EXPECT_EQ('l', buf[1]);
  1905. EXPECT_EQ(1, strm.read(buf, 1));
  1906. EXPECT_EQ('o', buf[0]);
  1907. EXPECT_EQ(0, strm.read(buf, 1));
  1908. }
  1909. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1910. auto host = "www.httpwatch.com";
  1911. auto ip = hosted_at(host);
  1912. EXPECT_EQ("23.96.13.243", ip);
  1913. std::vector<std::string> addrs;
  1914. hosted_at(host, addrs);
  1915. EXPECT_EQ(1u, addrs.size());
  1916. }
  1917. #if 0 // It depends on each test environment...
  1918. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1919. auto host = "www.youtube.com";
  1920. std::vector<std::string> addrs;
  1921. hosted_at(host, addrs);
  1922. EXPECT_EQ(20u, addrs.size());
  1923. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1924. EXPECT_TRUE(it != addrs.end());
  1925. }
  1926. #endif
  1927. class ChunkedEncodingTest : public ::testing::Test {
  1928. protected:
  1929. ChunkedEncodingTest()
  1930. : cli_(HOST, PORT)
  1931. #ifdef CPPHTTPLIB_SSL_ENABLED
  1932. ,
  1933. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1934. #endif
  1935. {
  1936. cli_.set_connection_timeout(2);
  1937. #ifdef CPPHTTPLIB_SSL_ENABLED
  1938. cli_.enable_server_certificate_verification(false);
  1939. #endif
  1940. }
  1941. virtual void SetUp() {
  1942. read_file("./image.jpg", image_data_);
  1943. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1944. res.set_content("Hello World!", "text/plain");
  1945. });
  1946. svr_.Get(
  1947. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1948. res.set_chunked_content_provider(
  1949. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1950. size_t remaining = image_data_.size() - offset;
  1951. if (remaining == 0) {
  1952. sink.done();
  1953. } else {
  1954. constexpr size_t CHUNK_SIZE = 1024;
  1955. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1956. sink.write(&image_data_[offset], send_size);
  1957. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1958. }
  1959. return true;
  1960. });
  1961. });
  1962. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1963. svr_.wait_until_ready();
  1964. }
  1965. virtual void TearDown() {
  1966. svr_.stop();
  1967. if (!request_threads_.empty()) {
  1968. std::this_thread::sleep_for(std::chrono::seconds(1));
  1969. for (auto &t : request_threads_) {
  1970. t.join();
  1971. }
  1972. }
  1973. t_.join();
  1974. }
  1975. #ifdef CPPHTTPLIB_SSL_ENABLED
  1976. SSLClient cli_;
  1977. SSLServer svr_;
  1978. #else
  1979. Client cli_;
  1980. Server svr_;
  1981. #endif
  1982. thread t_;
  1983. std::vector<thread> request_threads_;
  1984. std::string image_data_;
  1985. };
  1986. TEST_F(ChunkedEncodingTest, NormalGet) {
  1987. auto res = cli_.Get("/chunked");
  1988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1989. std::string out;
  1990. read_file("./image.jpg", out);
  1991. EXPECT_EQ(StatusCode::OK_200, res->status);
  1992. EXPECT_EQ(out, res->body);
  1993. }
  1994. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1995. std::string body;
  1996. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1997. body.append(data, data_length);
  1998. return true;
  1999. });
  2000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2001. std::string out;
  2002. read_file("./image.jpg", out);
  2003. EXPECT_EQ(StatusCode::OK_200, res->status);
  2004. EXPECT_EQ(out, body);
  2005. }
  2006. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2007. std::string body;
  2008. auto res = cli_.Get(
  2009. "/chunked",
  2010. [&](const Response &response) {
  2011. EXPECT_EQ(StatusCode::OK_200, response.status);
  2012. return true;
  2013. },
  2014. [&](const char *data, size_t data_length) {
  2015. body.append(data, data_length);
  2016. return true;
  2017. });
  2018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2019. std::string out;
  2020. read_file("./image.jpg", out);
  2021. EXPECT_EQ(StatusCode::OK_200, res->status);
  2022. EXPECT_EQ(out, body);
  2023. }
  2024. TEST(RangeTest, FromHTTPBin_Online) {
  2025. auto host = "httpbingo.org";
  2026. auto path = std::string{"/range/32"};
  2027. #ifdef CPPHTTPLIB_SSL_ENABLED
  2028. auto port = 443;
  2029. SSLClient cli(host, port);
  2030. #else
  2031. auto port = 80;
  2032. Client cli(host, port);
  2033. #endif
  2034. cli.set_connection_timeout(5);
  2035. {
  2036. auto res = cli.Get(path);
  2037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2038. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2039. EXPECT_EQ(StatusCode::OK_200, res->status);
  2040. }
  2041. {
  2042. Headers headers = {make_range_header({{1, -1}})};
  2043. auto res = cli.Get(path, headers);
  2044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2045. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2046. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2047. }
  2048. {
  2049. Headers headers = {make_range_header({{1, 10}})};
  2050. auto res = cli.Get(path, headers);
  2051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2052. EXPECT_EQ("bcdefghijk", res->body);
  2053. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2054. }
  2055. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2056. // entire resource, while the original httpbin returned 200. Both are
  2057. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2058. {
  2059. Headers headers = {make_range_header({{0, 31}})};
  2060. auto res = cli.Get(path, headers);
  2061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2062. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2063. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2064. res->status == StatusCode::PartialContent_206);
  2065. }
  2066. {
  2067. Headers headers = {make_range_header({{0, -1}})};
  2068. auto res = cli.Get(path, headers);
  2069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2070. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2071. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2072. res->status == StatusCode::PartialContent_206);
  2073. }
  2074. // go-httpbin returns 206 with clamped range for over-range requests,
  2075. // while the original httpbin returned 416. Both behaviors are observed
  2076. // in real servers, so we only verify the request succeeds.
  2077. {
  2078. Headers headers = {make_range_header({{0, 32}})};
  2079. auto res = cli.Get(path, headers);
  2080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2081. }
  2082. }
  2083. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2084. auto host = "unresolvableaddress.local";
  2085. auto path = std::string{"/"};
  2086. #ifdef CPPHTTPLIB_SSL_ENABLED
  2087. auto port = 443;
  2088. SSLClient cli(host, port);
  2089. #else
  2090. auto port = 80;
  2091. Client cli(host, port);
  2092. #endif
  2093. cli.set_connection_timeout(1);
  2094. {
  2095. auto res = cli.Get(path);
  2096. ASSERT_FALSE(res);
  2097. }
  2098. std::this_thread::sleep_for(std::chrono::seconds(8));
  2099. }
  2100. #if defined(__linux__) && defined(__GLIBC__) && \
  2101. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2102. // Forward declaration: in split builds split.py strips `inline` and moves the
  2103. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2104. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2105. // against the symbol in both header-only and split builds.
  2106. namespace httplib {
  2107. namespace detail {
  2108. int getaddrinfo_with_timeout(const char *node, const char *service,
  2109. const struct addrinfo *hints,
  2110. struct addrinfo **res, time_t timeout_sec);
  2111. } // namespace detail
  2112. } // namespace httplib
  2113. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2114. //
  2115. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2116. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2117. // gai_suspend() call hits the connection timeout the function calls
  2118. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2119. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2120. // still alive and still references the now-destroyed stack frame.
  2121. //
  2122. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2123. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2124. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2125. // and runs them in a container.
  2126. namespace {
  2127. bool should_run_issue_2431_tests() {
  2128. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2129. return v && *v && std::string(v) != "0";
  2130. }
  2131. std::string unique_unresolvable_host(int n) {
  2132. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2133. // glibc still asks the configured nameserver — which is exactly the path
  2134. // we want to exercise. A unique label per call avoids the resolver cache.
  2135. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2136. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2137. std::to_string(n) + ".invalid";
  2138. }
  2139. } // namespace
  2140. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2141. if (!should_run_issue_2431_tests()) {
  2142. GTEST_SKIP()
  2143. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2144. }
  2145. for (int i = 0; i < 8; ++i) {
  2146. struct addrinfo hints;
  2147. memset(&hints, 0, sizeof(hints));
  2148. hints.ai_family = AF_UNSPEC;
  2149. hints.ai_socktype = SOCK_STREAM;
  2150. auto host = unique_unresolvable_host(i);
  2151. struct addrinfo *result = nullptr;
  2152. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2153. &result, /*timeout_sec=*/1);
  2154. if (rc == 0 && result) { freeaddrinfo(result); }
  2155. }
  2156. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2157. // stack region they still believe holds their gaicb.
  2158. std::this_thread::sleep_for(std::chrono::seconds(3));
  2159. }
  2160. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2161. if (!should_run_issue_2431_tests()) {
  2162. GTEST_SKIP()
  2163. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2164. }
  2165. std::atomic<bool> stop{false};
  2166. std::vector<std::thread> threads;
  2167. for (int t = 0; t < 8; ++t) {
  2168. threads.emplace_back([t, &stop] {
  2169. int i = 0;
  2170. while (!stop.load(std::memory_order_relaxed)) {
  2171. struct addrinfo hints;
  2172. memset(&hints, 0, sizeof(hints));
  2173. hints.ai_family = AF_UNSPEC;
  2174. hints.ai_socktype = SOCK_STREAM;
  2175. auto host = unique_unresolvable_host(t * 100000 + i++);
  2176. struct addrinfo *result = nullptr;
  2177. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2178. &result, /*timeout_sec=*/1);
  2179. if (rc == 0 && result) { freeaddrinfo(result); }
  2180. }
  2181. });
  2182. }
  2183. std::this_thread::sleep_for(std::chrono::seconds(8));
  2184. stop.store(true, std::memory_order_relaxed);
  2185. for (auto &th : threads) {
  2186. th.join();
  2187. }
  2188. std::this_thread::sleep_for(std::chrono::seconds(3));
  2189. }
  2190. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2191. if (!should_run_issue_2431_tests()) {
  2192. GTEST_SKIP()
  2193. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2194. }
  2195. std::atomic<bool> stop{false};
  2196. std::vector<std::thread> threads;
  2197. for (int t = 0; t < 8; ++t) {
  2198. threads.emplace_back([t, &stop] {
  2199. int i = 0;
  2200. while (!stop.load(std::memory_order_relaxed)) {
  2201. auto host = unique_unresolvable_host(t * 100000 + i++);
  2202. Client cli(host, 80);
  2203. cli.set_connection_timeout(1, 0);
  2204. cli.set_read_timeout(1, 0);
  2205. cli.set_write_timeout(1, 0);
  2206. (void)cli.Get("/");
  2207. }
  2208. });
  2209. }
  2210. std::this_thread::sleep_for(std::chrono::seconds(8));
  2211. stop.store(true, std::memory_order_relaxed);
  2212. for (auto &th : threads) {
  2213. th.join();
  2214. }
  2215. std::this_thread::sleep_for(std::chrono::seconds(3));
  2216. }
  2217. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2218. TEST(ConnectionErrorTest, InvalidHost) {
  2219. auto host = "-abcde.com";
  2220. #ifdef CPPHTTPLIB_SSL_ENABLED
  2221. auto port = 443;
  2222. SSLClient cli(host, port);
  2223. #else
  2224. auto port = 80;
  2225. Client cli(host, port);
  2226. #endif
  2227. cli.set_connection_timeout(std::chrono::seconds(2));
  2228. auto res = cli.Get("/");
  2229. ASSERT_TRUE(!res);
  2230. EXPECT_EQ(Error::Connection, res.error());
  2231. }
  2232. TEST(ConnectionErrorTest, InvalidHost2) {
  2233. auto host = "httpcan.org/";
  2234. #ifdef CPPHTTPLIB_SSL_ENABLED
  2235. SSLClient cli(host);
  2236. #else
  2237. Client cli(host);
  2238. #endif
  2239. cli.set_connection_timeout(std::chrono::seconds(2));
  2240. auto res = cli.Get("/");
  2241. ASSERT_TRUE(!res);
  2242. EXPECT_EQ(Error::Connection, res.error());
  2243. }
  2244. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2245. auto host = "httpcan.org/";
  2246. #ifdef CPPHTTPLIB_SSL_ENABLED
  2247. SSLClient cli(host);
  2248. #else
  2249. Client cli(host);
  2250. #endif
  2251. cli.set_connection_timeout(std::chrono::seconds(2));
  2252. auto res = cli.Get("/");
  2253. ASSERT_TRUE(!res);
  2254. stringstream s;
  2255. s << "error code: " << res.error();
  2256. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2257. }
  2258. TEST(ConnectionErrorTest, InvalidPort) {
  2259. auto host = "localhost";
  2260. auto port = 44380;
  2261. #ifdef CPPHTTPLIB_SSL_ENABLED
  2262. SSLClient cli(host, port);
  2263. #else
  2264. Client cli(host, port);
  2265. #endif
  2266. cli.set_connection_timeout(std::chrono::seconds(2));
  2267. auto res = cli.Get("/");
  2268. ASSERT_TRUE(!res);
  2269. EXPECT_TRUE(Error::Connection == res.error() ||
  2270. Error::ConnectionTimeout == res.error());
  2271. }
  2272. TEST(ConnectionErrorTest, Timeout_Online) {
  2273. auto host = "google.com";
  2274. #ifdef CPPHTTPLIB_SSL_ENABLED
  2275. auto port = 44380;
  2276. SSLClient cli(host, port);
  2277. #else
  2278. auto port = 8080;
  2279. Client cli(host, port);
  2280. #endif
  2281. cli.set_connection_timeout(std::chrono::seconds(2));
  2282. // only probe one address type so that the error reason
  2283. // correlates to the timed-out IPv4, not the unsupported
  2284. // IPv6 connection attempt
  2285. cli.set_address_family(AF_INET);
  2286. auto res = cli.Get("/");
  2287. ASSERT_TRUE(!res);
  2288. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2289. }
  2290. TEST(CancelTest, NoCancel_Online) {
  2291. auto host = "httpbingo.org";
  2292. auto path = std::string{"/range/32"};
  2293. #ifdef CPPHTTPLIB_SSL_ENABLED
  2294. auto port = 443;
  2295. SSLClient cli(host, port);
  2296. #else
  2297. auto port = 80;
  2298. Client cli(host, port);
  2299. #endif
  2300. cli.set_connection_timeout(std::chrono::seconds(5));
  2301. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2303. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2304. EXPECT_EQ(StatusCode::OK_200, res->status);
  2305. }
  2306. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2307. // Use /bytes with a large payload so that the DownloadProgress callback
  2308. // (which only fires for Content-Length responses) is invoked before the
  2309. // entire body is received, giving cancellation a chance to fire.
  2310. auto host = "httpbingo.org";
  2311. auto path = std::string{"/bytes/524288"};
  2312. #ifdef CPPHTTPLIB_SSL_ENABLED
  2313. auto port = 443;
  2314. SSLClient cli(host, port);
  2315. #else
  2316. auto port = 80;
  2317. Client cli(host, port);
  2318. #endif
  2319. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2320. cli.set_connection_timeout(std::chrono::seconds(5));
  2321. ASSERT_TRUE(!res);
  2322. EXPECT_EQ(Error::Canceled, res.error());
  2323. }
  2324. TEST(CancelTest, WithCancelLargePayload_Online) {
  2325. auto host = "httpbingo.org";
  2326. auto path = std::string{"/bytes/524288"};
  2327. #ifdef CPPHTTPLIB_SSL_ENABLED
  2328. auto port = 443;
  2329. SSLClient cli(host, port);
  2330. #else
  2331. auto port = 80;
  2332. Client cli(host, port);
  2333. #endif
  2334. cli.set_connection_timeout(std::chrono::seconds(5));
  2335. uint32_t count = 0;
  2336. auto res =
  2337. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2338. ASSERT_TRUE(!res);
  2339. EXPECT_EQ(Error::Canceled, res.error());
  2340. }
  2341. TEST(CancelTest, NoCancelPost) {
  2342. Server svr;
  2343. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2344. res.set_content("Hello World!", "text/plain");
  2345. });
  2346. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2347. auto se = detail::scope_exit([&] {
  2348. svr.stop();
  2349. thread.join();
  2350. ASSERT_FALSE(svr.is_running());
  2351. });
  2352. svr.wait_until_ready();
  2353. Client cli(HOST, PORT);
  2354. cli.set_connection_timeout(std::chrono::seconds(5));
  2355. auto res =
  2356. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2357. "application/json", [](uint64_t, uint64_t) { return true; });
  2358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2359. EXPECT_EQ("Hello World!", res->body);
  2360. EXPECT_EQ(StatusCode::OK_200, res->status);
  2361. }
  2362. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2363. Server svr;
  2364. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2365. res.set_content("Hello World!", "text/plain");
  2366. });
  2367. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2368. auto se = detail::scope_exit([&] {
  2369. svr.stop();
  2370. thread.join();
  2371. ASSERT_FALSE(svr.is_running());
  2372. });
  2373. svr.wait_until_ready();
  2374. Client cli(HOST, PORT);
  2375. cli.set_connection_timeout(std::chrono::seconds(5));
  2376. auto res =
  2377. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2378. "application/json", [](uint64_t, uint64_t) { return false; });
  2379. ASSERT_TRUE(!res);
  2380. EXPECT_EQ(Error::Canceled, res.error());
  2381. }
  2382. TEST(CancelTest, WithCancelLargePayloadPost) {
  2383. Server svr;
  2384. svr.set_payload_max_length(200 * 1024 * 1024);
  2385. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2386. res.set_content(LARGE_DATA, "text/plain");
  2387. });
  2388. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2389. auto se = detail::scope_exit([&] {
  2390. svr.stop();
  2391. thread.join();
  2392. ASSERT_FALSE(svr.is_running());
  2393. });
  2394. svr.wait_until_ready();
  2395. Client cli(HOST, PORT);
  2396. cli.set_payload_max_length(200 * 1024 * 1024);
  2397. cli.set_connection_timeout(std::chrono::seconds(5));
  2398. auto res =
  2399. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2400. "application/json", [](uint64_t, uint64_t) { return false; });
  2401. ASSERT_TRUE(!res);
  2402. EXPECT_EQ(Error::Canceled, res.error());
  2403. }
  2404. TEST(CancelTest, NoCancelPut) {
  2405. Server svr;
  2406. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2407. res.set_content("Hello World!", "text/plain");
  2408. });
  2409. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2410. auto se = detail::scope_exit([&] {
  2411. svr.stop();
  2412. thread.join();
  2413. ASSERT_FALSE(svr.is_running());
  2414. });
  2415. svr.wait_until_ready();
  2416. Client cli(HOST, PORT);
  2417. cli.set_connection_timeout(std::chrono::seconds(5));
  2418. auto res =
  2419. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2420. "application/json", [](uint64_t, uint64_t) { return true; });
  2421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2422. EXPECT_EQ("Hello World!", res->body);
  2423. EXPECT_EQ(StatusCode::OK_200, res->status);
  2424. }
  2425. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2426. Server svr;
  2427. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2428. res.set_content("Hello World!", "text/plain");
  2429. });
  2430. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2431. auto se = detail::scope_exit([&] {
  2432. svr.stop();
  2433. thread.join();
  2434. ASSERT_FALSE(svr.is_running());
  2435. });
  2436. svr.wait_until_ready();
  2437. Client cli(HOST, PORT);
  2438. cli.set_connection_timeout(std::chrono::seconds(5));
  2439. auto res =
  2440. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2441. "application/json", [](uint64_t, uint64_t) { return false; });
  2442. ASSERT_TRUE(!res);
  2443. EXPECT_EQ(Error::Canceled, res.error());
  2444. }
  2445. TEST(CancelTest, WithCancelLargePayloadPut) {
  2446. Server svr;
  2447. svr.set_payload_max_length(200 * 1024 * 1024);
  2448. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2449. res.set_content(LARGE_DATA, "text/plain");
  2450. });
  2451. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2452. auto se = detail::scope_exit([&] {
  2453. svr.stop();
  2454. thread.join();
  2455. ASSERT_FALSE(svr.is_running());
  2456. });
  2457. svr.wait_until_ready();
  2458. Client cli(HOST, PORT);
  2459. cli.set_payload_max_length(200 * 1024 * 1024);
  2460. cli.set_connection_timeout(std::chrono::seconds(5));
  2461. auto res =
  2462. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2463. "application/json", [](uint64_t, uint64_t) { return false; });
  2464. ASSERT_TRUE(!res);
  2465. EXPECT_EQ(Error::Canceled, res.error());
  2466. }
  2467. TEST(CancelTest, NoCancelPatch) {
  2468. Server svr;
  2469. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2470. res.set_content("Hello World!", "text/plain");
  2471. });
  2472. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2473. auto se = detail::scope_exit([&] {
  2474. svr.stop();
  2475. thread.join();
  2476. ASSERT_FALSE(svr.is_running());
  2477. });
  2478. svr.wait_until_ready();
  2479. Client cli(HOST, PORT);
  2480. cli.set_connection_timeout(std::chrono::seconds(5));
  2481. auto res =
  2482. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2483. "application/json", [](uint64_t, uint64_t) { return true; });
  2484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2485. EXPECT_EQ("Hello World!", res->body);
  2486. EXPECT_EQ(StatusCode::OK_200, res->status);
  2487. }
  2488. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2489. Server svr;
  2490. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2491. res.set_content("Hello World!", "text/plain");
  2492. });
  2493. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2494. auto se = detail::scope_exit([&] {
  2495. svr.stop();
  2496. thread.join();
  2497. ASSERT_FALSE(svr.is_running());
  2498. });
  2499. svr.wait_until_ready();
  2500. Client cli(HOST, PORT);
  2501. cli.set_connection_timeout(std::chrono::seconds(5));
  2502. auto res =
  2503. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2504. "application/json", [](uint64_t, uint64_t) { return false; });
  2505. ASSERT_TRUE(!res);
  2506. EXPECT_EQ(Error::Canceled, res.error());
  2507. }
  2508. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2509. Server svr;
  2510. svr.set_payload_max_length(200 * 1024 * 1024);
  2511. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2512. res.set_content(LARGE_DATA, "text/plain");
  2513. });
  2514. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2515. auto se = detail::scope_exit([&] {
  2516. svr.stop();
  2517. thread.join();
  2518. ASSERT_FALSE(svr.is_running());
  2519. });
  2520. svr.wait_until_ready();
  2521. Client cli(HOST, PORT);
  2522. cli.set_payload_max_length(200 * 1024 * 1024);
  2523. cli.set_connection_timeout(std::chrono::seconds(5));
  2524. auto res =
  2525. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2526. "application/json", [](uint64_t, uint64_t) { return false; });
  2527. ASSERT_TRUE(!res);
  2528. EXPECT_EQ(Error::Canceled, res.error());
  2529. }
  2530. TEST(CancelTest, NoCancelDelete) {
  2531. Server svr;
  2532. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2533. res.set_content("Hello World!", "text/plain");
  2534. });
  2535. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2536. auto se = detail::scope_exit([&] {
  2537. svr.stop();
  2538. thread.join();
  2539. ASSERT_FALSE(svr.is_running());
  2540. });
  2541. svr.wait_until_ready();
  2542. Client cli(HOST, PORT);
  2543. cli.set_connection_timeout(std::chrono::seconds(5));
  2544. auto res =
  2545. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2546. "application/json", [](uint64_t, uint64_t) { return true; });
  2547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2548. EXPECT_EQ("Hello World!", res->body);
  2549. EXPECT_EQ(StatusCode::OK_200, res->status);
  2550. }
  2551. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2552. Server svr;
  2553. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2554. res.set_content("Hello World!", "text/plain");
  2555. });
  2556. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2557. auto se = detail::scope_exit([&] {
  2558. svr.stop();
  2559. thread.join();
  2560. ASSERT_FALSE(svr.is_running());
  2561. });
  2562. svr.wait_until_ready();
  2563. Client cli(HOST, PORT);
  2564. cli.set_connection_timeout(std::chrono::seconds(5));
  2565. auto res =
  2566. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2567. "application/json", [](uint64_t, uint64_t) { return false; });
  2568. ASSERT_TRUE(!res);
  2569. EXPECT_EQ(Error::Canceled, res.error());
  2570. }
  2571. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2572. Server svr;
  2573. svr.set_payload_max_length(200 * 1024 * 1024);
  2574. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2575. res.set_content(LARGE_DATA, "text/plain");
  2576. });
  2577. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2578. auto se = detail::scope_exit([&] {
  2579. svr.stop();
  2580. thread.join();
  2581. ASSERT_FALSE(svr.is_running());
  2582. });
  2583. svr.wait_until_ready();
  2584. Client cli(HOST, PORT);
  2585. cli.set_payload_max_length(200 * 1024 * 1024);
  2586. cli.set_connection_timeout(std::chrono::seconds(5));
  2587. auto res =
  2588. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2589. "application/json", [](uint64_t, uint64_t) { return false; });
  2590. ASSERT_TRUE(!res);
  2591. EXPECT_EQ(Error::Canceled, res.error());
  2592. }
  2593. static std::string remove_whitespace(const std::string &input) {
  2594. std::string output;
  2595. output.reserve(input.size());
  2596. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2597. [](unsigned char c) { return !std::isspace(c); });
  2598. return output;
  2599. }
  2600. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2601. auto host = "httpbingo.org";
  2602. auto path = std::string{"/basic-auth/hello/world"};
  2603. #ifdef CPPHTTPLIB_SSL_ENABLED
  2604. auto port = 443;
  2605. SSLClient cli(host, port);
  2606. #else
  2607. auto port = 80;
  2608. Client cli(host, port);
  2609. #endif
  2610. {
  2611. auto res = cli.Get(path);
  2612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2613. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2614. }
  2615. {
  2616. auto res = cli.Get(
  2617. path, Headers{make_basic_authentication_header("hello", "world")});
  2618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2619. auto body = remove_whitespace(res->body);
  2620. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2621. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2622. EXPECT_EQ(StatusCode::OK_200, res->status);
  2623. }
  2624. {
  2625. cli.set_basic_auth("hello", "world");
  2626. auto res = cli.Get(path);
  2627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2628. auto body = remove_whitespace(res->body);
  2629. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2630. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2631. EXPECT_EQ(StatusCode::OK_200, res->status);
  2632. }
  2633. {
  2634. cli.set_basic_auth("hello", "bad");
  2635. auto res = cli.Get(path);
  2636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2637. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2638. }
  2639. {
  2640. cli.set_basic_auth("bad", "world");
  2641. auto res = cli.Get(path);
  2642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2643. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2644. }
  2645. }
  2646. #ifdef CPPHTTPLIB_SSL_ENABLED
  2647. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2648. auto host = "httpbingo.org";
  2649. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2650. auto paths = std::vector<std::string>{
  2651. "/digest-auth/auth/hello/world/MD5",
  2652. "/digest-auth/auth/hello/world/SHA-256",
  2653. };
  2654. auto port = 443;
  2655. SSLClient cli(host, port);
  2656. {
  2657. auto res = cli.Get(unauth_path);
  2658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2659. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2660. }
  2661. {
  2662. cli.set_digest_auth("hello", "world");
  2663. for (const auto &path : paths) {
  2664. auto res = cli.Get(path.c_str());
  2665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2666. auto body = remove_whitespace(res->body);
  2667. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2668. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2669. EXPECT_EQ(StatusCode::OK_200, res->status);
  2670. }
  2671. cli.set_digest_auth("hello", "bad");
  2672. for (const auto &path : paths) {
  2673. auto res = cli.Get(path.c_str());
  2674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2675. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2676. }
  2677. }
  2678. }
  2679. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2680. // comma-separated list of challenges, and each challenge may itself carry a
  2681. // comma-separated auth-param list, so a server can legally offer Basic
  2682. // before Digest, either as two field lines or packed into one. Runs one 401
  2683. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2684. // value() joins them in receipt order) and checks that the retry carries a
  2685. // well-formed Digest Authorization header naming expected_realm.
  2686. static void
  2687. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2688. const std::string &expected_realm) {
  2689. std::atomic<int> hits{0};
  2690. Server svr;
  2691. svr.Get("/x", [&](const Request &req, Response &res) {
  2692. if (++hits == 1) {
  2693. res.status = StatusCode::Unauthorized_401;
  2694. for (const auto &challenge : challenges) {
  2695. res.set_header("WWW-Authenticate", challenge);
  2696. }
  2697. } else {
  2698. auto authorization = req.get_header_value("Authorization");
  2699. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2700. EXPECT_NE(std::string::npos,
  2701. authorization.find("realm=\"" + expected_realm + "\""));
  2702. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2703. res.set_content("ok", "text/plain");
  2704. }
  2705. });
  2706. auto port = svr.bind_to_any_port(HOST);
  2707. std::thread t([&]() { svr.listen_after_bind(); });
  2708. auto se = detail::scope_exit([&] {
  2709. svr.stop();
  2710. t.join();
  2711. });
  2712. svr.wait_until_ready();
  2713. Client cli(HOST, port);
  2714. cli.set_digest_auth("hello", "world");
  2715. auto res = cli.Get("/x");
  2716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2717. EXPECT_EQ(2, hits.load());
  2718. }
  2719. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2720. static const char *kDigestChallenge =
  2721. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2722. "algorithm=MD5";
  2723. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2724. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2725. "testrealm");
  2726. }
  2727. // Same challenge list with the schemes in the opposite order, to make sure
  2728. // the fix above didn't just special-case "Basic first".
  2729. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2730. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2731. "testrealm");
  2732. }
  2733. // A comma inside a quoted auth-param value must not be mistaken for the
  2734. // separator between two challenges (or two auth-params).
  2735. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2736. run_digest_challenge_list_test(
  2737. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2738. "algorithm=MD5"},
  2739. "test,realm");
  2740. }
  2741. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2742. // make_digest_authentication_header() dereferences both unconditionally, so
  2743. // a server sending a challenge missing either one must not be treated as
  2744. // usable -- doing so used to crash the client with std::out_of_range.
  2745. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2746. Server svr;
  2747. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2748. res.status = StatusCode::Unauthorized_401;
  2749. res.set_header("WWW-Authenticate", challenge);
  2750. });
  2751. auto port = svr.bind_to_any_port(HOST);
  2752. std::thread t([&]() { svr.listen_after_bind(); });
  2753. auto se = detail::scope_exit([&] {
  2754. svr.stop();
  2755. t.join();
  2756. });
  2757. svr.wait_until_ready();
  2758. Client cli(HOST, port);
  2759. cli.set_digest_auth("hello", "world");
  2760. auto res = cli.Get("/x");
  2761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2762. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2763. }
  2764. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2765. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2766. }
  2767. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2768. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2769. }
  2770. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2771. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2772. }
  2773. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  2774. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  2775. // when storing the values, so the header builder has to re-escape them (and
  2776. // keep algorithm a bare token); otherwise the value breaks out of its
  2777. // quoted-string and injects extra auth-params into the client's Authorization.
  2778. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  2779. std::atomic<int> hits{0};
  2780. std::string authorization;
  2781. Server svr;
  2782. svr.Get("/x", [&](const Request &req, Response &res) {
  2783. if (++hits == 1) {
  2784. res.status = StatusCode::Unauthorized_401;
  2785. // On the wire the quotes embedded in the values are backslash-escaped.
  2786. res.set_header("WWW-Authenticate",
  2787. "Digest realm=\"testrealm\", "
  2788. "nonce=\"n\\\"; injected=\\\"x\", "
  2789. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  2790. } else {
  2791. authorization = req.get_header_value("Authorization");
  2792. res.set_content("ok", "text/plain");
  2793. }
  2794. });
  2795. auto port = svr.bind_to_any_port(HOST);
  2796. std::thread t([&]() { svr.listen_after_bind(); });
  2797. auto se = detail::scope_exit([&] {
  2798. svr.stop();
  2799. t.join();
  2800. });
  2801. svr.wait_until_ready();
  2802. Client cli(HOST, port);
  2803. cli.set_digest_auth("hello", "world");
  2804. auto res = cli.Get("/x");
  2805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2806. EXPECT_EQ(2, hits.load());
  2807. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2808. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  2809. // inside its quoted-string rather than starting an "injected" auth-param.
  2810. EXPECT_NE(std::string::npos,
  2811. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  2812. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  2813. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  2814. }
  2815. #endif
  2816. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2817. auto host = "google.com";
  2818. auto another_host = "example.com";
  2819. auto wrong_ip = "0.0.0.0";
  2820. #ifdef CPPHTTPLIB_SSL_ENABLED
  2821. SSLClient cli(host);
  2822. #else
  2823. Client cli(host);
  2824. #endif
  2825. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2826. auto res = cli.Get("/");
  2827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2828. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2829. }
  2830. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2831. auto host = "google.com";
  2832. auto wrong_ip = "0.0.0.0";
  2833. #ifdef CPPHTTPLIB_SSL_ENABLED
  2834. SSLClient cli(host);
  2835. #else
  2836. Client cli(host);
  2837. #endif
  2838. cli.set_hostname_addr_map({{host, wrong_ip}});
  2839. auto res = cli.Get("/");
  2840. ASSERT_TRUE(!res);
  2841. EXPECT_EQ(Error::Connection, res.error());
  2842. }
  2843. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2844. // A mapped value that is not an IP literal must be resolved. "localhost"
  2845. // resolves from the hosts file, so this test needs no external DNS.
  2846. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2847. auto host = "target.invalid";
  2848. Server svr;
  2849. std::string received_host;
  2850. svr.Get("/hi", [&](const Request &req, Response &res) {
  2851. received_host = req.get_header_value("Host");
  2852. res.set_content("Hello World!", "text/plain");
  2853. });
  2854. auto port = svr.bind_to_any_port(HOST);
  2855. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2856. auto se = detail::scope_exit([&] {
  2857. svr.stop();
  2858. thread.join();
  2859. ASSERT_FALSE(svr.is_running());
  2860. });
  2861. svr.wait_until_ready();
  2862. Client cli(host, port);
  2863. cli.set_hostname_addr_map({{host, HOST}});
  2864. auto res = cli.Get("/hi");
  2865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2866. EXPECT_EQ(StatusCode::OK_200, res->status);
  2867. // The mapping only redirects the connection; the identity stays host_.
  2868. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2869. }
  2870. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2871. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2872. auto host = "target.invalid";
  2873. Server svr;
  2874. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2875. res.set_content("Hello World!", "text/plain");
  2876. });
  2877. auto port = svr.bind_to_any_port("127.0.0.1");
  2878. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2879. auto se = detail::scope_exit([&] {
  2880. svr.stop();
  2881. thread.join();
  2882. ASSERT_FALSE(svr.is_running());
  2883. });
  2884. svr.wait_until_ready();
  2885. Client cli(host, port);
  2886. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2887. auto res = cli.Get("/hi");
  2888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2889. EXPECT_EQ(StatusCode::OK_200, res->status);
  2890. }
  2891. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2892. // An empty mapped value must leave host_ as the connection target. Without
  2893. // that guard the empty value would become the host argument, getaddrinfo
  2894. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2895. // loopback - silently connecting somewhere the caller never asked for.
  2896. // The server listens on loopback, so such a fallback would succeed and is
  2897. // therefore observable as a failure of this test.
  2898. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2899. Server svr;
  2900. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2901. res.set_content("Hello World!", "text/plain");
  2902. });
  2903. auto port = svr.bind_to_any_port(HOST);
  2904. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2905. auto se = detail::scope_exit([&] {
  2906. svr.stop();
  2907. thread.join();
  2908. ASSERT_FALSE(svr.is_running());
  2909. });
  2910. svr.wait_until_ready();
  2911. Client cli(blackhole, port);
  2912. cli.set_hostname_addr_map({{blackhole, ""}});
  2913. cli.set_connection_timeout(1);
  2914. auto res = cli.Get("/hi");
  2915. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2916. }
  2917. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2918. auto host = "httpbingo.org";
  2919. auto path = std::string{"/absolute-redirect/3"};
  2920. #ifdef CPPHTTPLIB_SSL_ENABLED
  2921. SSLClient cli(host);
  2922. #else
  2923. Client cli(host);
  2924. #endif
  2925. cli.set_follow_location(true);
  2926. auto res = cli.Get(path);
  2927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2928. EXPECT_EQ(StatusCode::OK_200, res->status);
  2929. }
  2930. TEST(RedirectTest, Redirect_Online) {
  2931. auto host = "httpbingo.org";
  2932. auto path = std::string{"/redirect/3"};
  2933. #ifdef CPPHTTPLIB_SSL_ENABLED
  2934. SSLClient cli(host);
  2935. #else
  2936. Client cli(host);
  2937. #endif
  2938. cli.set_follow_location(true);
  2939. auto res = cli.Get(path);
  2940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2941. EXPECT_EQ(StatusCode::OK_200, res->status);
  2942. }
  2943. TEST(RelativeRedirectTest, Redirect_Online) {
  2944. auto host = "httpbingo.org";
  2945. auto path = std::string{"/relative-redirect/3"};
  2946. #ifdef CPPHTTPLIB_SSL_ENABLED
  2947. SSLClient cli(host);
  2948. #else
  2949. Client cli(host);
  2950. #endif
  2951. cli.set_follow_location(true);
  2952. auto res = cli.Get(path);
  2953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2954. EXPECT_EQ(StatusCode::OK_200, res->status);
  2955. }
  2956. TEST(TooManyRedirectTest, Redirect_Online) {
  2957. auto host = "httpbingo.org";
  2958. auto path = std::string{"/redirect/21"};
  2959. #ifdef CPPHTTPLIB_SSL_ENABLED
  2960. SSLClient cli(host);
  2961. #else
  2962. Client cli(host);
  2963. #endif
  2964. cli.set_follow_location(true);
  2965. auto res = cli.Get(path);
  2966. ASSERT_TRUE(!res);
  2967. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2968. }
  2969. #ifdef CPPHTTPLIB_SSL_ENABLED
  2970. TEST(YahooRedirectTest, Redirect_Online) {
  2971. Client cli("yahoo.com");
  2972. auto res = cli.Get("/");
  2973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2974. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2975. cli.set_follow_location(true);
  2976. res = cli.Get("/");
  2977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2978. EXPECT_EQ(StatusCode::OK_200, res->status);
  2979. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2980. }
  2981. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2982. #define REDIR_HOST "httpbingo.org"
  2983. #define REDIR_PATH "/redirect-to"
  2984. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2985. SSLClient cli(REDIR_HOST);
  2986. cli.set_follow_location(true);
  2987. auto res =
  2988. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2990. EXPECT_EQ(StatusCode::OK_200, res->status);
  2991. }
  2992. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2993. SSLClient cli(REDIR_HOST);
  2994. cli.set_follow_location(true);
  2995. Params params;
  2996. params.emplace("url", "http://example.com");
  2997. params.emplace("status_code", "302");
  2998. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3000. EXPECT_EQ(StatusCode::OK_200, res->status);
  3001. }
  3002. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3003. SSLClient cli(REDIR_HOST);
  3004. cli.set_follow_location(true);
  3005. Params params;
  3006. params.emplace("url", "http://example.com");
  3007. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3009. EXPECT_EQ(StatusCode::OK_200, res->status);
  3010. }
  3011. TEST(UrlWithSpace, Redirect_Online) {
  3012. SSLClient cli("edge.forgecdn.net");
  3013. cli.set_follow_location(true);
  3014. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3016. EXPECT_EQ(StatusCode::OK_200, res->status);
  3017. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3018. }
  3019. #endif
  3020. #if !defined(_WIN32) && !defined(_WIN64)
  3021. TEST(ReceiveSignals, Signal) {
  3022. auto setupSignalHandlers = []() {
  3023. struct sigaction act;
  3024. sigemptyset(&act.sa_mask);
  3025. act.sa_flags = SA_SIGINFO;
  3026. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3027. switch (sig) {
  3028. case SIGINT:
  3029. default: break;
  3030. }
  3031. };
  3032. ::sigaction(SIGINT, &act, nullptr);
  3033. };
  3034. Server svr;
  3035. int port = 0;
  3036. auto thread = std::thread([&]() {
  3037. setupSignalHandlers();
  3038. port = svr.bind_to_any_port(HOST);
  3039. svr.listen_after_bind();
  3040. });
  3041. auto se = detail::scope_exit([&] {
  3042. svr.stop();
  3043. thread.join();
  3044. ASSERT_FALSE(svr.is_running());
  3045. });
  3046. svr.wait_until_ready();
  3047. ASSERT_TRUE(svr.is_running());
  3048. pthread_kill(thread.native_handle(), SIGINT);
  3049. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3050. ASSERT_TRUE(svr.is_running());
  3051. }
  3052. #endif
  3053. TEST(RedirectToDifferentPort, Redirect) {
  3054. Server svr1;
  3055. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3056. res.set_content("Hello World!", "text/plain");
  3057. });
  3058. int svr1_port = 0;
  3059. auto thread1 = std::thread([&]() {
  3060. svr1_port = svr1.bind_to_any_port(HOST);
  3061. svr1.listen_after_bind();
  3062. });
  3063. Server svr2;
  3064. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3065. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3066. });
  3067. int svr2_port = 0;
  3068. auto thread2 = std::thread([&]() {
  3069. svr2_port = svr2.bind_to_any_port(HOST);
  3070. svr2.listen_after_bind();
  3071. });
  3072. auto se = detail::scope_exit([&] {
  3073. svr2.stop();
  3074. thread2.join();
  3075. svr1.stop();
  3076. thread1.join();
  3077. ASSERT_FALSE(svr2.is_running());
  3078. ASSERT_FALSE(svr1.is_running());
  3079. });
  3080. svr1.wait_until_ready();
  3081. svr2.wait_until_ready();
  3082. Client cli("localhost", svr2_port);
  3083. cli.set_follow_location(true);
  3084. auto res = cli.Get("/2");
  3085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3086. EXPECT_EQ(StatusCode::OK_200, res->status);
  3087. EXPECT_EQ("Hello World!", res->body);
  3088. }
  3089. static void
  3090. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3091. Server svr1;
  3092. std::string captured_authorization;
  3093. svr1.Get("/target", [&](const Request &req, Response &res) {
  3094. captured_authorization = req.get_header_value("Authorization");
  3095. res.set_content("OK", "text/plain");
  3096. });
  3097. int svr1_port = 0;
  3098. auto thread1 = std::thread([&]() {
  3099. svr1_port = svr1.bind_to_any_port(HOST);
  3100. svr1.listen_after_bind();
  3101. });
  3102. Server svr2;
  3103. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3104. res.set_redirect(
  3105. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3106. });
  3107. int svr2_port = 0;
  3108. auto thread2 = std::thread([&]() {
  3109. svr2_port = svr2.bind_to_any_port(HOST);
  3110. svr2.listen_after_bind();
  3111. });
  3112. auto se = detail::scope_exit([&] {
  3113. svr2.stop();
  3114. thread2.join();
  3115. svr1.stop();
  3116. thread1.join();
  3117. ASSERT_FALSE(svr2.is_running());
  3118. ASSERT_FALSE(svr1.is_running());
  3119. });
  3120. svr1.wait_until_ready();
  3121. svr2.wait_until_ready();
  3122. Client cli("localhost", svr2_port);
  3123. cli.set_follow_location(true);
  3124. set_auth(cli);
  3125. auto res = cli.Get("/redir");
  3126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3127. EXPECT_EQ(StatusCode::OK_200, res->status);
  3128. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3129. EXPECT_TRUE(captured_authorization.empty());
  3130. }
  3131. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3132. TestDoNotForwardCredentialsOnRedirect(
  3133. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3134. }
  3135. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3136. TestDoNotForwardCredentialsOnRedirect(
  3137. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3138. }
  3139. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3140. Server svr1;
  3141. std::string captured_cookie;
  3142. bool target_hit = false;
  3143. svr1.Get("/target", [&](const Request &req, Response &res) {
  3144. captured_cookie = req.get_header_value("Cookie");
  3145. target_hit = true;
  3146. res.set_content("OK", "text/plain");
  3147. });
  3148. int svr1_port = 0;
  3149. auto thread1 = std::thread([&]() {
  3150. svr1_port = svr1.bind_to_any_port(HOST);
  3151. svr1.listen_after_bind();
  3152. });
  3153. Server svr2;
  3154. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3155. res.set_redirect(
  3156. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3157. });
  3158. int svr2_port = 0;
  3159. auto thread2 = std::thread([&]() {
  3160. svr2_port = svr2.bind_to_any_port(HOST);
  3161. svr2.listen_after_bind();
  3162. });
  3163. auto se = detail::scope_exit([&] {
  3164. svr2.stop();
  3165. thread2.join();
  3166. svr1.stop();
  3167. thread1.join();
  3168. ASSERT_FALSE(svr2.is_running());
  3169. ASSERT_FALSE(svr1.is_running());
  3170. });
  3171. svr1.wait_until_ready();
  3172. svr2.wait_until_ready();
  3173. Client cli("localhost", svr2_port);
  3174. cli.set_follow_location(true);
  3175. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  3176. auto res = cli.Get("/redir", headers);
  3177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3178. EXPECT_EQ(StatusCode::OK_200, res->status);
  3179. EXPECT_TRUE(target_hit);
  3180. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3181. EXPECT_TRUE(captured_cookie.empty());
  3182. }
  3183. TEST(RedirectToSamePort, ForwardCookie) {
  3184. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3185. // header so that ordinary session flows keep working.
  3186. Server svr;
  3187. std::string captured_cookie;
  3188. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3189. res.set_redirect("/target", 302);
  3190. });
  3191. svr.Get("/target", [&](const Request &req, Response &res) {
  3192. captured_cookie = req.get_header_value("Cookie");
  3193. res.set_content("OK", "text/plain");
  3194. });
  3195. auto port = svr.bind_to_any_port(HOST);
  3196. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3197. auto se = detail::scope_exit([&] {
  3198. svr.stop();
  3199. thread.join();
  3200. ASSERT_FALSE(svr.is_running());
  3201. });
  3202. svr.wait_until_ready();
  3203. Client cli(HOST, port);
  3204. cli.set_follow_location(true);
  3205. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3206. auto res = cli.Get("/redir", headers);
  3207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3208. EXPECT_EQ(StatusCode::OK_200, res->status);
  3209. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3210. }
  3211. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3212. Server svr;
  3213. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3214. // Port number that overflows int — should not crash
  3215. res.set_redirect("http://localhost:99999999999999999999/target");
  3216. });
  3217. auto port = svr.bind_to_any_port(HOST);
  3218. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3219. auto se = detail::scope_exit([&] {
  3220. svr.stop();
  3221. thread.join();
  3222. ASSERT_FALSE(svr.is_running());
  3223. });
  3224. svr.wait_until_ready();
  3225. Client cli(HOST, port);
  3226. cli.set_follow_location(true);
  3227. auto res = cli.Get("/redir");
  3228. // Should fail gracefully, not crash (no valid response due to bad port)
  3229. EXPECT_FALSE(res);
  3230. }
  3231. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3232. Server svr;
  3233. auto port = svr.bind_to_any_port(HOST);
  3234. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3235. // The server's own port followed by junk must not be followed
  3236. res.set_redirect("http://" + std::string(HOST) + ":" +
  3237. std::to_string(port) + "junk/target");
  3238. });
  3239. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3240. res.set_content("target", "text/plain");
  3241. });
  3242. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3243. auto se = detail::scope_exit([&] {
  3244. svr.stop();
  3245. thread.join();
  3246. ASSERT_FALSE(svr.is_running());
  3247. });
  3248. svr.wait_until_ready();
  3249. Client cli(HOST, port);
  3250. cli.set_follow_location(true);
  3251. auto res = cli.Get("/redir");
  3252. EXPECT_FALSE(res);
  3253. }
  3254. TEST(RedirectFromPageWithContent, Redirect) {
  3255. Server svr;
  3256. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3257. res.set_content("___", "text/plain");
  3258. res.set_redirect("/2");
  3259. });
  3260. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3261. res.set_content("Hello World!", "text/plain");
  3262. });
  3263. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3264. auto se = detail::scope_exit([&] {
  3265. svr.stop();
  3266. th.join();
  3267. ASSERT_FALSE(svr.is_running());
  3268. });
  3269. svr.wait_until_ready();
  3270. {
  3271. Client cli("localhost", PORT);
  3272. cli.set_follow_location(true);
  3273. std::string body;
  3274. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3275. body.append(data, data_length);
  3276. return true;
  3277. });
  3278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3279. EXPECT_EQ(StatusCode::OK_200, res->status);
  3280. EXPECT_EQ("Hello World!", body);
  3281. }
  3282. {
  3283. Client cli("localhost", PORT);
  3284. std::string body;
  3285. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3286. body.append(data, data_length);
  3287. return true;
  3288. });
  3289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3290. EXPECT_EQ(StatusCode::Found_302, res->status);
  3291. EXPECT_EQ("___", body);
  3292. }
  3293. }
  3294. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3295. Server svr;
  3296. auto port_str = std::to_string(PORT);
  3297. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3298. auto expected_host = "[::1]:" + port_str;
  3299. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3300. res.set_content("___", "text/plain");
  3301. // res.set_redirect("/2");
  3302. res.set_redirect(redirect_url);
  3303. });
  3304. svr.Get("/2", [&](const Request &req, Response &res) {
  3305. auto host_header = req.headers.find("Host");
  3306. ASSERT_TRUE(host_header != req.headers.end());
  3307. EXPECT_EQ(expected_host, host_header->second);
  3308. res.set_content("Hello World!", "text/plain");
  3309. });
  3310. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3311. auto se = detail::scope_exit([&] {
  3312. svr.stop();
  3313. th.join();
  3314. ASSERT_FALSE(svr.is_running());
  3315. });
  3316. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3317. // actually starts anything, so the condition !svr.is_running() will
  3318. // always remain true, and the loop never stops.
  3319. // This basically counts how many milliseconds have passed since the
  3320. // call to svr.listen(), and if after 5 seconds nothing started yet
  3321. // aborts the test.
  3322. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3323. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3324. ASSERT_LT(milliseconds, 5000U);
  3325. }
  3326. {
  3327. Client cli("::1", PORT);
  3328. cli.set_follow_location(true);
  3329. std::string body;
  3330. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3331. body.append(data, data_length);
  3332. return true;
  3333. });
  3334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3335. EXPECT_EQ(StatusCode::OK_200, res->status);
  3336. EXPECT_EQ("Hello World!", body);
  3337. }
  3338. {
  3339. Client cli("::1", PORT);
  3340. std::string body;
  3341. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3342. body.append(data, data_length);
  3343. return true;
  3344. });
  3345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3346. EXPECT_EQ(StatusCode::Found_302, res->status);
  3347. EXPECT_EQ("___", body);
  3348. }
  3349. }
  3350. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3351. Server svr;
  3352. svr.Get("/foo", [](const Request &req, Response &res) {
  3353. auto a = req.params.find("a");
  3354. if (a != req.params.end()) {
  3355. res.set_content((*a).second, "text/plain");
  3356. res.status = StatusCode::OK_200;
  3357. } else {
  3358. res.status = StatusCode::BadRequest_400;
  3359. }
  3360. });
  3361. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3362. auto se = detail::scope_exit([&] {
  3363. svr.stop();
  3364. thread.join();
  3365. ASSERT_FALSE(svr.is_running());
  3366. });
  3367. svr.wait_until_ready();
  3368. {
  3369. Client cli(HOST, PORT);
  3370. cli.set_path_encode(false);
  3371. auto res = cli.Get("/foo?a=explicitly+encoded");
  3372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3373. EXPECT_EQ(StatusCode::OK_200, res->status);
  3374. // This expects it back with a space, as the `+` won't have been
  3375. // url-encoded, and server-side the params get decoded turning `+`
  3376. // into spaces.
  3377. EXPECT_EQ("explicitly encoded", res->body);
  3378. }
  3379. }
  3380. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3381. // When path encoding is disabled the client must transmit the supplied
  3382. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3383. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3384. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3385. // than a space (0x20). Assert on the raw wire target to catch this.
  3386. Server svr;
  3387. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3388. svr.Get("/foo", [&](const Request &req, Response &res) {
  3389. EXPECT_EQ(expected_target, req.target);
  3390. res.status = StatusCode::OK_200;
  3391. });
  3392. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3393. auto se = detail::scope_exit([&] {
  3394. svr.stop();
  3395. thread.join();
  3396. ASSERT_FALSE(svr.is_running());
  3397. });
  3398. svr.wait_until_ready();
  3399. {
  3400. Client cli(HOST, PORT);
  3401. cli.set_path_encode(false);
  3402. auto res = cli.Get(expected_target.c_str());
  3403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3404. EXPECT_EQ(StatusCode::OK_200, res->status);
  3405. }
  3406. }
  3407. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3408. // `open_stream()` used to skip the path encoding that the buffered send
  3409. // path applies, so the same `path` produced different bytes in the request
  3410. // line depending on which API was used. Assert the two agree.
  3411. Server svr;
  3412. std::string target;
  3413. svr.Get(".*", [&](const Request &req, Response &res) {
  3414. target = req.target;
  3415. res.status = StatusCode::OK_200;
  3416. });
  3417. auto port = svr.bind_to_any_port(HOST);
  3418. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3419. auto se = detail::scope_exit([&] {
  3420. svr.stop();
  3421. thread.join();
  3422. ASSERT_FALSE(svr.is_running());
  3423. });
  3424. svr.wait_until_ready();
  3425. struct {
  3426. const char *path;
  3427. const char *expected;
  3428. } cases[] = {
  3429. {"/a b?x=1", "/a%20b?x=1"},
  3430. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3431. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3432. };
  3433. for (const auto &c : cases) {
  3434. Client cli(HOST, port);
  3435. target.clear();
  3436. auto res = cli.Get(c.path);
  3437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3438. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3439. auto buffered_target = target;
  3440. target.clear();
  3441. auto handle = cli.open_stream("GET", c.path);
  3442. EXPECT_TRUE(handle.is_valid())
  3443. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3444. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3445. }
  3446. }
  3447. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3448. // The `set_path_encode(false)` contract — transmit the supplied target
  3449. // verbatim — must hold for the streaming API too.
  3450. Server svr;
  3451. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3452. std::string target;
  3453. svr.Get("/foo", [&](const Request &req, Response &res) {
  3454. target = req.target;
  3455. res.status = StatusCode::OK_200;
  3456. });
  3457. auto port = svr.bind_to_any_port(HOST);
  3458. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3459. auto se = detail::scope_exit([&] {
  3460. svr.stop();
  3461. thread.join();
  3462. ASSERT_FALSE(svr.is_running());
  3463. });
  3464. svr.wait_until_ready();
  3465. {
  3466. Client cli(HOST, port);
  3467. cli.set_path_encode(false);
  3468. auto handle = cli.open_stream("GET", expected_target);
  3469. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3470. EXPECT_EQ(expected_target, target);
  3471. }
  3472. }
  3473. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3474. // With path encoding enabled a CR/LF in the target is percent-encoded
  3475. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3476. // write_request_line still backstops `set_path_encode(false)`, which is
  3477. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3478. Server svr;
  3479. // Captured before routing: the decoded path contains a newline, which a
  3480. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3481. std::string target;
  3482. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3483. target = req.target;
  3484. res.status = StatusCode::OK_200;
  3485. return Server::HandlerResponse::Handled;
  3486. });
  3487. auto port = svr.bind_to_any_port(HOST);
  3488. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3489. auto se = detail::scope_exit([&] {
  3490. svr.stop();
  3491. thread.join();
  3492. ASSERT_FALSE(svr.is_running());
  3493. });
  3494. svr.wait_until_ready();
  3495. {
  3496. Client cli(HOST, port);
  3497. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3498. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3499. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3500. }
  3501. }
  3502. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3503. // Every control character is percent-encoded, not just CR/LF, so the target
  3504. // passes the request-target check in write_request_line.
  3505. Server svr;
  3506. std::string target;
  3507. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3508. target = req.target;
  3509. res.status = StatusCode::OK_200;
  3510. return Server::HandlerResponse::Handled;
  3511. });
  3512. auto port = svr.bind_to_any_port(HOST);
  3513. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3514. auto se = detail::scope_exit([&] {
  3515. svr.stop();
  3516. thread.join();
  3517. ASSERT_FALSE(svr.is_running());
  3518. });
  3519. svr.wait_until_ready();
  3520. {
  3521. Client cli(HOST, port);
  3522. auto res = cli.Get("/a\tb\x1b\x7f");
  3523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3524. EXPECT_EQ("/a%09b%1B%7F", target);
  3525. }
  3526. }
  3527. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3528. // Nothing may reach the wire: a raw CR/LF target would split the request
  3529. // line and inject headers.
  3530. Server svr;
  3531. // Pre-routing so that "not called" means nothing reached the server at all,
  3532. // rather than merely failing to match a handler pattern.
  3533. auto handler_called = false;
  3534. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3535. handler_called = true;
  3536. res.status = StatusCode::OK_200;
  3537. return Server::HandlerResponse::Handled;
  3538. });
  3539. auto port = svr.bind_to_any_port(HOST);
  3540. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3541. auto se = detail::scope_exit([&] {
  3542. svr.stop();
  3543. thread.join();
  3544. ASSERT_FALSE(svr.is_running());
  3545. });
  3546. svr.wait_until_ready();
  3547. {
  3548. Client cli(HOST, port);
  3549. cli.set_path_encode(false);
  3550. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3551. EXPECT_FALSE(handle.is_valid());
  3552. EXPECT_EQ(Error::Write, handle.error);
  3553. EXPECT_FALSE(handler_called);
  3554. }
  3555. }
  3556. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3557. // Which of the two branches runs is decided by whether the query component
  3558. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3559. // an empty query and must still fall back to building one from
  3560. // `req.params`, while a non-empty query must win over `req.params`.
  3561. Server svr;
  3562. std::string target;
  3563. svr.Get("/foo", [&](const Request &req, Response &res) {
  3564. target = req.target;
  3565. res.status = StatusCode::OK_200;
  3566. });
  3567. auto port = svr.bind_to_any_port(HOST);
  3568. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3569. auto se = detail::scope_exit([&] {
  3570. svr.stop();
  3571. thread.join();
  3572. ASSERT_FALSE(svr.is_running());
  3573. });
  3574. svr.wait_until_ready();
  3575. {
  3576. // Trailing `?` -> empty query component -> `req.params` is used.
  3577. Client cli(HOST, port);
  3578. Request req;
  3579. req.method = "GET";
  3580. req.path = "/foo?";
  3581. req.params.emplace("a", "1");
  3582. target.clear();
  3583. auto res = cli.send(req);
  3584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3585. EXPECT_EQ("/foo?a=1", target);
  3586. }
  3587. {
  3588. // Non-empty query in `req.path` -> `req.params` is not appended.
  3589. Client cli(HOST, port);
  3590. Request req;
  3591. req.method = "GET";
  3592. req.path = "/foo?b=2";
  3593. req.params.emplace("a", "1");
  3594. target.clear();
  3595. auto res = cli.send(req);
  3596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3597. EXPECT_EQ("/foo?b=2", target);
  3598. }
  3599. }
  3600. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3601. Server svr;
  3602. svr.Get("/", [](const Request &req, Response &) {
  3603. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3604. });
  3605. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3606. auto se = detail::scope_exit([&] {
  3607. svr.stop();
  3608. thread.join();
  3609. ASSERT_FALSE(svr.is_running());
  3610. });
  3611. svr.wait_until_ready();
  3612. {
  3613. Client cli(HOST, PORT);
  3614. cli.set_path_encode(false);
  3615. auto res = cli.Get("/?something=%0A");
  3616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3617. EXPECT_EQ(StatusCode::OK_200, res->status);
  3618. }
  3619. }
  3620. TEST(BindServerTest, BindDualStack) {
  3621. Server svr;
  3622. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3623. res.set_content("Hello World!", "text/plain");
  3624. });
  3625. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3626. auto se = detail::scope_exit([&] {
  3627. svr.stop();
  3628. thread.join();
  3629. ASSERT_FALSE(svr.is_running());
  3630. });
  3631. svr.wait_until_ready();
  3632. {
  3633. Client cli("127.0.0.1", PORT);
  3634. auto res = cli.Get("/1");
  3635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3636. EXPECT_EQ(StatusCode::OK_200, res->status);
  3637. EXPECT_EQ("Hello World!", res->body);
  3638. }
  3639. {
  3640. Client cli("::1", PORT);
  3641. auto res = cli.Get("/1");
  3642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3643. EXPECT_EQ(StatusCode::OK_200, res->status);
  3644. EXPECT_EQ("Hello World!", res->body);
  3645. }
  3646. }
  3647. TEST(BindServerTest, BindAndListenSeparately) {
  3648. Server svr;
  3649. int port = svr.bind_to_any_port("0.0.0.0");
  3650. ASSERT_TRUE(svr.is_valid());
  3651. ASSERT_TRUE(port > 0);
  3652. svr.stop();
  3653. }
  3654. // Reports whether anything is still listening on a loopback port. A plain
  3655. // connect() is used instead of a Client request because a socket left bound by
  3656. // mistake accepts the connection into its backlog and never answers, which
  3657. // would hang the test instead of failing it.
  3658. static bool is_loopback_port_accepting(int port) {
  3659. sockaddr_in addr{};
  3660. addr.sin_family = AF_INET;
  3661. addr.sin_port = htons(static_cast<uint16_t>(port));
  3662. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3663. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3664. EXPECT_NE(sock, INVALID_SOCKET);
  3665. if (sock == INVALID_SOCKET) { return false; }
  3666. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3667. static_cast<socklen_t>(sizeof(addr)));
  3668. detail::close_socket(sock);
  3669. return ret == 0;
  3670. }
  3671. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3672. Server svr;
  3673. auto port = svr.bind_to_any_port("127.0.0.1");
  3674. ASSERT_TRUE(port > 0);
  3675. svr.stop();
  3676. // bind_to_any_port() already called listen(2), so until stop() closed the
  3677. // descriptor the port kept accepting connections into the backlog. ASSERT
  3678. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3679. // below blocks forever in the accept loop.
  3680. ASSERT_FALSE(is_loopback_port_accepting(port));
  3681. // Nothing is left to accept on, so listen_after_bind() must report failure
  3682. // instead of returning success without ever serving.
  3683. EXPECT_FALSE(svr.listen_after_bind());
  3684. // The failed listen marks the server decommissioned, so a waiter returns
  3685. // instead of spinning forever.
  3686. svr.wait_until_ready();
  3687. }
  3688. #ifdef CPPHTTPLIB_SSL_ENABLED
  3689. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3690. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3691. CLIENT_CA_CERT_DIR);
  3692. int port = svr.bind_to_any_port("0.0.0.0");
  3693. ASSERT_TRUE(svr.is_valid());
  3694. ASSERT_TRUE(port > 0);
  3695. svr.stop();
  3696. }
  3697. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3698. // or a rejected CustomRoute() registration would not stop the server binding.
  3699. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3700. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3701. CLIENT_CA_CERT_DIR);
  3702. ASSERT_TRUE(svr.is_valid());
  3703. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3704. EXPECT_FALSE(svr.is_valid());
  3705. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3706. }
  3707. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3708. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3709. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3710. int port = svr.bind_to_any_port("0.0.0.0");
  3711. ASSERT_TRUE(svr.is_valid());
  3712. ASSERT_TRUE(port > 0);
  3713. svr.stop();
  3714. }
  3715. TEST(BindServerTest, UpdateCertsPem) {
  3716. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3717. int port = svr.bind_to_any_port("0.0.0.0");
  3718. ASSERT_TRUE(svr.is_valid());
  3719. ASSERT_TRUE(port > 0);
  3720. // Read PEM files
  3721. std::string cert_pem, key_pem, ca_pem;
  3722. read_file(SERVER_CERT_FILE, cert_pem);
  3723. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3724. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3725. // Update server certificates using PEM API
  3726. ASSERT_TRUE(
  3727. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3728. ASSERT_TRUE(svr.is_valid());
  3729. svr.stop();
  3730. }
  3731. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3732. // Start server with client CA (enables client auth)
  3733. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3734. ASSERT_TRUE(svr.is_valid());
  3735. bool handler_called = false;
  3736. svr.Get("/test", [&](const Request &req, Response &res) {
  3737. handler_called = true;
  3738. // Verify client certificate is present
  3739. auto cert = req.peer_cert();
  3740. EXPECT_TRUE(static_cast<bool>(cert));
  3741. res.set_content("ok", "text/plain");
  3742. });
  3743. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3744. auto se = detail::scope_exit([&] {
  3745. svr.stop();
  3746. t.join();
  3747. ASSERT_FALSE(svr.is_running());
  3748. });
  3749. svr.wait_until_ready();
  3750. // Read PEM files
  3751. std::string cert_pem, key_pem, ca_pem;
  3752. read_file(SERVER_CERT_FILE, cert_pem);
  3753. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3754. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3755. // Update server certificates and client CA using PEM API while server running
  3756. ASSERT_TRUE(
  3757. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3758. // Connect with client certificate
  3759. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3760. cli.enable_server_certificate_verification(false);
  3761. cli.set_connection_timeout(30);
  3762. auto res = cli.Get("/test");
  3763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3764. ASSERT_EQ(StatusCode::OK_200, res->status);
  3765. ASSERT_TRUE(handler_called);
  3766. EXPECT_EQ("ok", res->body);
  3767. }
  3768. #endif
  3769. TEST(ErrorHandlerTest, ContentLength) {
  3770. Server svr;
  3771. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3772. res.status = StatusCode::OK_200;
  3773. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3774. "text/html"); // <= Content-Length still 13
  3775. });
  3776. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3777. res.set_content("Hello World!\n", "text/plain");
  3778. res.status = 524;
  3779. });
  3780. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3781. auto se = detail::scope_exit([&] {
  3782. svr.stop();
  3783. thread.join();
  3784. ASSERT_FALSE(svr.is_running());
  3785. });
  3786. svr.wait_until_ready();
  3787. {
  3788. Client cli(HOST, PORT);
  3789. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3791. EXPECT_EQ(StatusCode::OK_200, res->status);
  3792. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3793. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3794. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3795. }
  3796. }
  3797. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3798. TEST(ExceptionTest, WithoutExceptionHandler) {
  3799. Server svr;
  3800. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3801. throw std::runtime_error("exception...");
  3802. });
  3803. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3804. throw std::runtime_error("exception\r\n...");
  3805. });
  3806. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3807. auto se = detail::scope_exit([&] {
  3808. svr.stop();
  3809. listen_thread.join();
  3810. ASSERT_FALSE(svr.is_running());
  3811. });
  3812. svr.wait_until_ready();
  3813. Client cli("localhost", PORT);
  3814. {
  3815. auto res = cli.Get("/exception");
  3816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3817. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3818. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3819. }
  3820. {
  3821. auto res = cli.Get("/unknown");
  3822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3823. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3824. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3825. }
  3826. }
  3827. TEST(ExceptionTest, WithExceptionHandler) {
  3828. Server svr;
  3829. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3830. std::exception_ptr ep) {
  3831. EXPECT_FALSE(ep == nullptr);
  3832. try {
  3833. std::rethrow_exception(ep);
  3834. } catch (std::exception &e) {
  3835. EXPECT_EQ("abc", std::string(e.what()));
  3836. } catch (...) {}
  3837. res.status = StatusCode::InternalServerError_500;
  3838. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3839. "text/html"); // <= Content-Length still 13 at this point
  3840. });
  3841. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3842. res.set_content("Hello World!\n", "text/plain");
  3843. throw std::runtime_error("abc");
  3844. });
  3845. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3846. auto se = detail::scope_exit([&] {
  3847. svr.stop();
  3848. thread.join();
  3849. ASSERT_FALSE(svr.is_running());
  3850. });
  3851. svr.wait_until_ready();
  3852. for (size_t i = 0; i < 10; i++) {
  3853. Client cli(HOST, PORT);
  3854. for (size_t j = 0; j < 100; j++) {
  3855. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3857. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3858. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3859. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3860. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3861. }
  3862. cli.set_keep_alive(true);
  3863. for (size_t j = 0; j < 100; j++) {
  3864. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3866. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3867. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3868. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3869. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3870. }
  3871. }
  3872. }
  3873. TEST(ExceptionTest, AndErrorHandler) {
  3874. Server svr;
  3875. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3876. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3877. });
  3878. svr.set_exception_handler(
  3879. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3880. EXPECT_FALSE(ep == nullptr);
  3881. try {
  3882. std::rethrow_exception(ep);
  3883. } catch (std::exception &e) {
  3884. res.set_content(e.what(), "text/html");
  3885. } catch (...) {}
  3886. res.status = StatusCode::InternalServerError_500;
  3887. });
  3888. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3889. throw std::runtime_error("EXCEPTION");
  3890. });
  3891. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3892. res.set_content("ERROR", "text/html");
  3893. res.status = StatusCode::InternalServerError_500;
  3894. });
  3895. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3896. auto se = detail::scope_exit([&] {
  3897. svr.stop();
  3898. thread.join();
  3899. ASSERT_FALSE(svr.is_running());
  3900. });
  3901. svr.wait_until_ready();
  3902. Client cli(HOST, PORT);
  3903. {
  3904. auto res = cli.Get("/exception");
  3905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3906. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3907. EXPECT_EQ("EXCEPTION", res->body);
  3908. }
  3909. {
  3910. auto res = cli.Get("/error");
  3911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3912. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3913. EXPECT_EQ("ERROR", res->body);
  3914. }
  3915. {
  3916. auto res = cli.Get("/invalid");
  3917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3918. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3919. EXPECT_EQ("NOT_FOUND", res->body);
  3920. }
  3921. }
  3922. #endif
  3923. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3924. // process_request() wraps only routing() in a try/catch, so an exception from
  3925. // any other user callback used to unwind into the task queue - which does not
  3926. // catch - and terminate the process. Each test below runs the server on a
  3927. // single worker thread: a guard that catches the exception but still loses the
  3928. // thread would otherwise be hidden by a spare worker serving the follow-up
  3929. // request. Note that a regression here aborts the whole test binary rather
  3930. // than failing one test.
  3931. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  3932. Server svr;
  3933. svr.new_task_queue = [] { return new ThreadPool(1); };
  3934. std::atomic<int> reported{0};
  3935. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3936. if (err == Error::UserCallbackException) { reported++; }
  3937. });
  3938. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3939. res.set_content_provider(
  3940. 1024, "text/plain",
  3941. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3942. sink.write("hello", 5);
  3943. throw std::runtime_error("from the content provider");
  3944. });
  3945. });
  3946. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3947. res.set_content("ok", "text/plain");
  3948. });
  3949. auto port = svr.bind_to_any_port(HOST);
  3950. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3951. auto se = detail::scope_exit([&] {
  3952. svr.stop();
  3953. listen_thread.join();
  3954. ASSERT_FALSE(svr.is_running());
  3955. });
  3956. svr.wait_until_ready();
  3957. {
  3958. Client cli(HOST, port);
  3959. cli.set_read_timeout(5, 0);
  3960. EXPECT_FALSE(cli.Get("/throw"));
  3961. }
  3962. EXPECT_TRUE(svr.is_running());
  3963. EXPECT_EQ(1, reported.load());
  3964. // A request on a fresh connection is still served.
  3965. {
  3966. Client cli(HOST, port);
  3967. auto res = cli.Get("/ok");
  3968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3969. EXPECT_EQ(StatusCode::OK_200, res->status);
  3970. EXPECT_EQ("ok", res->body);
  3971. }
  3972. }
  3973. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  3974. Server svr;
  3975. svr.new_task_queue = [] { return new ThreadPool(1); };
  3976. std::atomic<bool> should_throw{true};
  3977. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3978. res.set_content("hi", "text/plain");
  3979. });
  3980. svr.set_post_routing_handler(
  3981. [&](const Request & /*req*/, Response & /*res*/) {
  3982. if (should_throw) {
  3983. throw std::runtime_error("from the post-routing handler");
  3984. }
  3985. });
  3986. auto port = svr.bind_to_any_port(HOST);
  3987. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3988. auto se = detail::scope_exit([&] {
  3989. svr.stop();
  3990. listen_thread.join();
  3991. ASSERT_FALSE(svr.is_running());
  3992. });
  3993. svr.wait_until_ready();
  3994. {
  3995. Client cli(HOST, port);
  3996. cli.set_read_timeout(5, 0);
  3997. EXPECT_FALSE(cli.Get("/hi"));
  3998. }
  3999. EXPECT_TRUE(svr.is_running());
  4000. should_throw = false;
  4001. {
  4002. Client cli(HOST, port);
  4003. auto res = cli.Get("/hi");
  4004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4005. EXPECT_EQ(StatusCode::OK_200, res->status);
  4006. EXPECT_EQ("hi", res->body);
  4007. }
  4008. }
  4009. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4010. // The guard reports the caught exception through the error logger, which is
  4011. // a user callback too. A logger that throws has to be contained as well, or
  4012. // the process would terminate from inside the catch.
  4013. Server svr;
  4014. svr.new_task_queue = [] { return new ThreadPool(1); };
  4015. std::atomic<int> reported{0};
  4016. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4017. if (err == Error::UserCallbackException) {
  4018. reported++;
  4019. throw std::runtime_error("from the error logger");
  4020. }
  4021. });
  4022. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4023. res.set_content_provider(
  4024. 1024, "text/plain",
  4025. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4026. sink.write("hello", 5);
  4027. throw std::runtime_error("from the content provider");
  4028. });
  4029. });
  4030. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4031. res.set_content("ok", "text/plain");
  4032. });
  4033. auto port = svr.bind_to_any_port(HOST);
  4034. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4035. auto se = detail::scope_exit([&] {
  4036. svr.stop();
  4037. listen_thread.join();
  4038. ASSERT_FALSE(svr.is_running());
  4039. });
  4040. svr.wait_until_ready();
  4041. {
  4042. Client cli(HOST, port);
  4043. cli.set_read_timeout(5, 0);
  4044. EXPECT_FALSE(cli.Get("/throw"));
  4045. }
  4046. EXPECT_TRUE(svr.is_running());
  4047. EXPECT_EQ(1, reported.load());
  4048. {
  4049. Client cli(HOST, port);
  4050. auto res = cli.Get("/ok");
  4051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4052. EXPECT_EQ(StatusCode::OK_200, res->status);
  4053. EXPECT_EQ("ok", res->body);
  4054. }
  4055. }
  4056. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4057. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4058. // so the exception unwinds through the ws::WebSocket object on its way to
  4059. // the guard. None of the HTTP cases above cross that.
  4060. Server svr;
  4061. svr.new_task_queue = [] { return new ThreadPool(1); };
  4062. std::atomic<int> reported{0};
  4063. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4064. if (err == Error::UserCallbackException) { reported++; }
  4065. });
  4066. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4067. throw std::runtime_error("from the WebSocket handler");
  4068. });
  4069. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4070. res.set_content("ok", "text/plain");
  4071. });
  4072. auto port = svr.bind_to_any_port(HOST);
  4073. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4074. auto se = detail::scope_exit([&] {
  4075. svr.stop();
  4076. listen_thread.join();
  4077. ASSERT_FALSE(svr.is_running());
  4078. });
  4079. svr.wait_until_ready();
  4080. {
  4081. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4082. "/ws");
  4083. auto res = client.connect();
  4084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4085. // The server dropped the connection instead of dying.
  4086. std::string msg;
  4087. EXPECT_FALSE(client.read(msg));
  4088. client.close();
  4089. }
  4090. EXPECT_TRUE(svr.is_running());
  4091. EXPECT_EQ(1, reported.load());
  4092. {
  4093. Client cli(HOST, port);
  4094. auto res = cli.Get("/ok");
  4095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4096. EXPECT_EQ(StatusCode::OK_200, res->status);
  4097. EXPECT_EQ("ok", res->body);
  4098. }
  4099. }
  4100. #ifdef CPPHTTPLIB_SSL_ENABLED
  4101. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4102. // SSLServer::process_and_close_socket() is a separate overload with its own
  4103. // guard, so it is exercised on its own.
  4104. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4105. ASSERT_TRUE(svr.is_valid());
  4106. svr.new_task_queue = [] { return new ThreadPool(1); };
  4107. std::atomic<int> reported{0};
  4108. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4109. if (err == Error::UserCallbackException) { reported++; }
  4110. });
  4111. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4112. res.set_content_provider(
  4113. 1024, "text/plain",
  4114. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4115. sink.write("hello", 5);
  4116. throw std::runtime_error("from the content provider");
  4117. });
  4118. });
  4119. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4120. res.set_content("ok", "text/plain");
  4121. });
  4122. auto port = svr.bind_to_any_port(HOST);
  4123. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4124. auto se = detail::scope_exit([&] {
  4125. svr.stop();
  4126. listen_thread.join();
  4127. ASSERT_FALSE(svr.is_running());
  4128. });
  4129. svr.wait_until_ready();
  4130. {
  4131. SSLClient cli(HOST, port);
  4132. cli.enable_server_certificate_verification(false);
  4133. cli.set_read_timeout(5, 0);
  4134. EXPECT_FALSE(cli.Get("/throw"));
  4135. }
  4136. EXPECT_TRUE(svr.is_running());
  4137. EXPECT_EQ(1, reported.load());
  4138. {
  4139. SSLClient cli(HOST, port);
  4140. cli.enable_server_certificate_verification(false);
  4141. auto res = cli.Get("/ok");
  4142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4143. EXPECT_EQ(StatusCode::OK_200, res->status);
  4144. EXPECT_EQ("ok", res->body);
  4145. }
  4146. }
  4147. #endif
  4148. #endif
  4149. TEST(NoContentTest, ContentLength) {
  4150. Server svr;
  4151. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4152. res.status = StatusCode::NoContent_204;
  4153. });
  4154. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4155. auto se = detail::scope_exit([&] {
  4156. svr.stop();
  4157. thread.join();
  4158. ASSERT_FALSE(svr.is_running());
  4159. });
  4160. svr.wait_until_ready();
  4161. {
  4162. Client cli(HOST, PORT);
  4163. auto res = cli.Get("/hi");
  4164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4165. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4166. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4167. }
  4168. }
  4169. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4170. #ifdef CPPHTTPLIB_SSL_ENABLED
  4171. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4172. ASSERT_TRUE(svr.is_valid());
  4173. #else
  4174. Server svr;
  4175. #endif
  4176. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4177. if (req.path == "/routing_handler") {
  4178. res.set_header("PRE_ROUTING", "on");
  4179. res.set_content("Routing Handler", "text/plain");
  4180. return httplib::Server::HandlerResponse::Handled;
  4181. }
  4182. return httplib::Server::HandlerResponse::Unhandled;
  4183. });
  4184. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4185. res.set_content("Error", "text/html");
  4186. });
  4187. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4188. if (req.path == "/routing_handler") {
  4189. res.set_header("POST_ROUTING", "on");
  4190. }
  4191. });
  4192. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4193. res.set_content("Hello World!\n", "text/plain");
  4194. });
  4195. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4196. auto se = detail::scope_exit([&] {
  4197. svr.stop();
  4198. thread.join();
  4199. ASSERT_FALSE(svr.is_running());
  4200. });
  4201. svr.wait_until_ready();
  4202. {
  4203. #ifdef CPPHTTPLIB_SSL_ENABLED
  4204. SSLClient cli(HOST, PORT);
  4205. cli.enable_server_certificate_verification(false);
  4206. #else
  4207. Client cli(HOST, PORT);
  4208. #endif
  4209. auto res = cli.Get("/routing_handler");
  4210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4211. EXPECT_EQ(StatusCode::OK_200, res->status);
  4212. EXPECT_EQ("Routing Handler", res->body);
  4213. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4214. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4215. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4216. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4217. }
  4218. {
  4219. #ifdef CPPHTTPLIB_SSL_ENABLED
  4220. SSLClient cli(HOST, PORT);
  4221. cli.enable_server_certificate_verification(false);
  4222. #else
  4223. Client cli(HOST, PORT);
  4224. #endif
  4225. auto res = cli.Get("/hi");
  4226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4227. EXPECT_EQ(StatusCode::OK_200, res->status);
  4228. EXPECT_EQ("Hello World!\n", res->body);
  4229. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4230. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4231. }
  4232. {
  4233. #ifdef CPPHTTPLIB_SSL_ENABLED
  4234. SSLClient cli(HOST, PORT);
  4235. cli.enable_server_certificate_verification(false);
  4236. #else
  4237. Client cli(HOST, PORT);
  4238. #endif
  4239. auto res = cli.Get("/aaa");
  4240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4241. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4242. EXPECT_EQ("Error", res->body);
  4243. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4244. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4245. }
  4246. }
  4247. TEST(RequestHandlerTest, PreRequestHandler) {
  4248. auto route_path = "/user/:user";
  4249. Server svr;
  4250. svr.Get("/hi", [](const Request &, Response &res) {
  4251. res.set_content("hi", "text/plain");
  4252. });
  4253. svr.Get(route_path, [](const Request &req, Response &res) {
  4254. res.set_content(req.path_params.at("user"), "text/plain");
  4255. });
  4256. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4257. if (req.matched_route == route_path) {
  4258. auto user = req.path_params.at("user");
  4259. if (user != "john") {
  4260. res.status = StatusCode::Forbidden_403;
  4261. res.set_content("error", "text/html");
  4262. return Server::HandlerResponse::Handled;
  4263. }
  4264. }
  4265. return Server::HandlerResponse::Unhandled;
  4266. });
  4267. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4268. auto se = detail::scope_exit([&] {
  4269. svr.stop();
  4270. thread.join();
  4271. ASSERT_FALSE(svr.is_running());
  4272. });
  4273. svr.wait_until_ready();
  4274. Client cli(HOST, PORT);
  4275. {
  4276. auto res = cli.Get("/hi");
  4277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4278. EXPECT_EQ(StatusCode::OK_200, res->status);
  4279. EXPECT_EQ("hi", res->body);
  4280. }
  4281. {
  4282. auto res = cli.Get("/user/john");
  4283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4284. EXPECT_EQ(StatusCode::OK_200, res->status);
  4285. EXPECT_EQ("john", res->body);
  4286. }
  4287. {
  4288. auto res = cli.Get("/user/invalid-user");
  4289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4290. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4291. EXPECT_EQ("error", res->body);
  4292. }
  4293. }
  4294. // The pre-request handler must run before the request body is read, so a
  4295. // rejected request never forces the server to buffer a (potentially large)
  4296. // body. Here the posted body is larger than the payload limit: if the body
  4297. // were read first the server would answer 413, but because the pre-request
  4298. // handler runs first it answers 403 and the body is never read.
  4299. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4300. Server svr;
  4301. svr.set_payload_max_length(8);
  4302. auto handler_ran = false;
  4303. svr.Post("/reject", [&](const Request &req, Response &res) {
  4304. handler_ran = true;
  4305. res.set_content(req.body, "text/plain");
  4306. });
  4307. svr.Post("/accept", [](const Request &req, Response &res) {
  4308. res.set_content(req.body, "text/plain");
  4309. });
  4310. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4311. if (req.matched_route == "/reject") {
  4312. res.status = StatusCode::Forbidden_403;
  4313. res.set_content("denied", "text/plain");
  4314. return Server::HandlerResponse::Handled;
  4315. }
  4316. return Server::HandlerResponse::Unhandled;
  4317. });
  4318. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4319. auto se = detail::scope_exit([&] {
  4320. svr.stop();
  4321. thread.join();
  4322. ASSERT_FALSE(svr.is_running());
  4323. });
  4324. svr.wait_until_ready();
  4325. Client cli(HOST, PORT);
  4326. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4327. // rejects with 403 before the body is read, so 413 is never reached.
  4328. {
  4329. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4331. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4332. EXPECT_EQ("denied", res->body);
  4333. EXPECT_FALSE(handler_ran);
  4334. }
  4335. // An approved route still reads the body and enforces the payload limit.
  4336. {
  4337. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4339. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4340. }
  4341. }
  4342. TEST(UserDataTest, BasicOperations) {
  4343. httplib::UserData ud;
  4344. // Initially empty
  4345. EXPECT_FALSE(ud.has("key"));
  4346. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4347. // set and get
  4348. ud.set("key", 42);
  4349. EXPECT_TRUE(ud.has("key"));
  4350. auto *p = ud.get<int>("key");
  4351. ASSERT_NE(nullptr, p);
  4352. EXPECT_EQ(42, *p);
  4353. // Type mismatch → nullptr
  4354. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4355. // Overwrite with different type
  4356. ud.set("key", std::string("hello"));
  4357. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4358. auto *s = ud.get<std::string>("key");
  4359. ASSERT_NE(nullptr, s);
  4360. EXPECT_EQ("hello", *s);
  4361. // erase
  4362. ud.erase("key");
  4363. EXPECT_FALSE(ud.has("key"));
  4364. // clear
  4365. ud.set("a", 1);
  4366. ud.set("b", 2);
  4367. ud.clear();
  4368. EXPECT_FALSE(ud.has("a"));
  4369. EXPECT_FALSE(ud.has("b"));
  4370. }
  4371. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4372. struct AuthCtx {
  4373. std::string user_id;
  4374. };
  4375. Server svr;
  4376. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4377. res.user_data.set("auth", AuthCtx{"alice"});
  4378. return Server::HandlerResponse::Unhandled;
  4379. });
  4380. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4381. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4382. ASSERT_NE(nullptr, ctx);
  4383. res.set_content("Hello " + ctx->user_id, "text/plain");
  4384. });
  4385. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4386. auto se = detail::scope_exit([&] {
  4387. svr.stop();
  4388. thread.join();
  4389. ASSERT_FALSE(svr.is_running());
  4390. });
  4391. svr.wait_until_ready();
  4392. Client cli(HOST, PORT);
  4393. auto res = cli.Get("/me");
  4394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4395. EXPECT_EQ(StatusCode::OK_200, res->status);
  4396. EXPECT_EQ("Hello alice", res->body);
  4397. }
  4398. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4399. struct RoleCtx {
  4400. std::string role;
  4401. };
  4402. Server svr;
  4403. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4404. res.user_data.set("role", RoleCtx{"admin"});
  4405. return Server::HandlerResponse::Unhandled;
  4406. });
  4407. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4408. auto *ctx = res.user_data.get<RoleCtx>("role");
  4409. ASSERT_NE(nullptr, ctx);
  4410. res.set_content(ctx->role, "text/plain");
  4411. });
  4412. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4413. auto se = detail::scope_exit([&] {
  4414. svr.stop();
  4415. thread.join();
  4416. ASSERT_FALSE(svr.is_running());
  4417. });
  4418. svr.wait_until_ready();
  4419. Client cli(HOST, PORT);
  4420. auto res = cli.Get("/role");
  4421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4422. EXPECT_EQ(StatusCode::OK_200, res->status);
  4423. EXPECT_EQ("admin", res->body);
  4424. }
  4425. TEST(InvalidFormatTest, StatusCode) {
  4426. Server svr;
  4427. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4428. res.set_content("Hello World!\n", "text/plain");
  4429. res.status = 9999; // Status should be a three-digit code...
  4430. });
  4431. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4432. auto se = detail::scope_exit([&] {
  4433. svr.stop();
  4434. thread.join();
  4435. ASSERT_FALSE(svr.is_running());
  4436. });
  4437. svr.wait_until_ready();
  4438. {
  4439. Client cli(HOST, PORT);
  4440. auto res = cli.Get("/hi");
  4441. ASSERT_FALSE(res);
  4442. }
  4443. }
  4444. TEST(URLFragmentTest, WithFragment) {
  4445. Server svr;
  4446. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4447. EXPECT_TRUE(req.target == "/hi");
  4448. });
  4449. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4450. auto se = detail::scope_exit([&] {
  4451. svr.stop();
  4452. thread.join();
  4453. ASSERT_FALSE(svr.is_running());
  4454. });
  4455. svr.wait_until_ready();
  4456. {
  4457. Client cli(HOST, PORT);
  4458. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4459. EXPECT_TRUE(res);
  4460. EXPECT_EQ(StatusCode::OK_200, res->status);
  4461. res = cli.Get("/hi%23key1=val1=key2=val2");
  4462. EXPECT_TRUE(res);
  4463. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4464. }
  4465. }
  4466. TEST(HeaderWriter, SetHeaderWriter) {
  4467. Server svr;
  4468. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4469. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4470. return detail::write_headers(strm, hdrs);
  4471. });
  4472. svr.Get("/hi", [](const Request &req, Response &res) {
  4473. auto it = req.headers.find("CustomClientHeader");
  4474. EXPECT_TRUE(it != req.headers.end());
  4475. EXPECT_EQ(it->second, "CustomClientValue");
  4476. res.set_content("Hello World!\n", "text/plain");
  4477. });
  4478. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4479. auto se = detail::scope_exit([&] {
  4480. svr.stop();
  4481. thread.join();
  4482. ASSERT_FALSE(svr.is_running());
  4483. });
  4484. svr.wait_until_ready();
  4485. {
  4486. Client cli(HOST, PORT);
  4487. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4488. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4489. return detail::write_headers(strm, hdrs);
  4490. });
  4491. auto res = cli.Get("/hi");
  4492. EXPECT_TRUE(res);
  4493. EXPECT_EQ(StatusCode::OK_200, res->status);
  4494. auto it = res->headers.find("CustomServerHeader");
  4495. EXPECT_TRUE(it != res->headers.end());
  4496. EXPECT_EQ(it->second, "CustomServerValue");
  4497. }
  4498. }
  4499. class ServerTest : public ::testing::Test {
  4500. protected:
  4501. ServerTest()
  4502. : cli_(HOST, PORT)
  4503. #ifdef CPPHTTPLIB_SSL_ENABLED
  4504. ,
  4505. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4506. #endif
  4507. {
  4508. #ifdef CPPHTTPLIB_SSL_ENABLED
  4509. cli_.enable_server_certificate_verification(false);
  4510. #endif
  4511. // Allow LARGE_DATA (100MB) responses
  4512. cli_.set_payload_max_length(200 * 1024 * 1024);
  4513. }
  4514. virtual void SetUp() {
  4515. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4516. svr_.set_payload_max_length(200 * 1024 * 1024);
  4517. svr_.set_mount_point("/", "./www");
  4518. svr_.set_mount_point("/mount", "./www2");
  4519. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4520. svr_.Get("/hi",
  4521. [&](const Request & /*req*/, Response &res) {
  4522. res.set_content("Hello World!", "text/plain");
  4523. })
  4524. .Get("/file_content",
  4525. [&](const Request & /*req*/, Response &res) {
  4526. res.set_file_content("./www/dir/test.html");
  4527. })
  4528. .Get("/file_content_with_content_type",
  4529. [&](const Request & /*req*/, Response &res) {
  4530. res.set_file_content("./www/file", "text/plain");
  4531. })
  4532. .Get("/invalid_file_content",
  4533. [&](const Request & /*req*/, Response &res) {
  4534. res.set_file_content("./www/dir/invalid_file_path");
  4535. })
  4536. .Get("/http_response_splitting",
  4537. [&](const Request & /*req*/, Response &res) {
  4538. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4539. EXPECT_EQ(0U, res.headers.size());
  4540. EXPECT_FALSE(res.has_header("a"));
  4541. res.set_header("a", "1\nSet-Cookie: a=1");
  4542. EXPECT_EQ(0U, res.headers.size());
  4543. EXPECT_FALSE(res.has_header("a"));
  4544. res.set_header("a", "1\rSet-Cookie: a=1");
  4545. EXPECT_EQ(0U, res.headers.size());
  4546. EXPECT_FALSE(res.has_header("a"));
  4547. res.set_header("a\r\nb", "0");
  4548. EXPECT_EQ(0U, res.headers.size());
  4549. EXPECT_FALSE(res.has_header("a"));
  4550. res.set_header("a\rb", "0");
  4551. EXPECT_EQ(0U, res.headers.size());
  4552. EXPECT_FALSE(res.has_header("a"));
  4553. res.set_header("a\nb", "0");
  4554. EXPECT_EQ(0U, res.headers.size());
  4555. EXPECT_FALSE(res.has_header("a"));
  4556. res.set_redirect("1\r\nSet-Cookie: a=1");
  4557. EXPECT_EQ(0U, res.headers.size());
  4558. EXPECT_FALSE(res.has_header("Location"));
  4559. })
  4560. .Get("/slow",
  4561. [&](const Request & /*req*/, Response &res) {
  4562. std::this_thread::sleep_for(std::chrono::seconds(4));
  4563. res.set_content("slow", "text/plain");
  4564. })
  4565. #if 0
  4566. .Post("/slowpost",
  4567. [&](const Request & /*req*/, Response &res) {
  4568. std::this_thread::sleep_for(std::chrono::seconds(2));
  4569. res.set_content("slow", "text/plain");
  4570. })
  4571. #endif
  4572. .Get("/remote_addr",
  4573. [&](const Request &req, Response &res) {
  4574. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4575. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4576. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4577. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4578. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4579. #endif
  4580. res.set_content(req.remote_addr, "text/plain");
  4581. })
  4582. .Get("/local_addr",
  4583. [&](const Request &req, Response &res) {
  4584. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4585. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4586. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4587. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4588. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4589. #endif
  4590. auto local_addr = req.local_addr;
  4591. auto local_port = std::to_string(req.local_port);
  4592. res.set_content(local_addr.append(":").append(local_port),
  4593. "text/plain");
  4594. })
  4595. .Get("/endwith%",
  4596. [&](const Request & /*req*/, Response &res) {
  4597. res.set_content("Hello World!", "text/plain");
  4598. })
  4599. .Get("/a\\+\\+b",
  4600. [&](const Request &req, Response &res) {
  4601. ASSERT_TRUE(req.has_param("a +b"));
  4602. auto val = req.get_param_value("a +b");
  4603. res.set_content(val, "text/plain");
  4604. })
  4605. .Get("/", [&](const Request & /*req*/,
  4606. Response &res) { res.set_redirect("/hi"); })
  4607. .Post("/1",
  4608. [](const Request & /*req*/, Response &res) {
  4609. res.set_redirect("/2", StatusCode::SeeOther_303);
  4610. })
  4611. .Get("/2",
  4612. [](const Request & /*req*/, Response &res) {
  4613. res.set_content("redirected.", "text/plain");
  4614. res.status = StatusCode::OK_200;
  4615. })
  4616. .Post("/person",
  4617. [&](const Request &req, Response &res) {
  4618. if (req.has_param("name") && req.has_param("note")) {
  4619. persons_[req.get_param_value("name")] =
  4620. req.get_param_value("note");
  4621. } else {
  4622. res.status = StatusCode::BadRequest_400;
  4623. }
  4624. })
  4625. .Put("/person",
  4626. [&](const Request &req, Response &res) {
  4627. if (req.has_param("name") && req.has_param("note")) {
  4628. persons_[req.get_param_value("name")] =
  4629. req.get_param_value("note");
  4630. } else {
  4631. res.status = StatusCode::BadRequest_400;
  4632. }
  4633. })
  4634. .Get("/person/(.*)",
  4635. [&](const Request &req, Response &res) {
  4636. string name = req.matches[1];
  4637. if (persons_.find(name) != persons_.end()) {
  4638. auto note = persons_[name];
  4639. res.set_content(note, "text/plain");
  4640. } else {
  4641. res.status = StatusCode::NotFound_404;
  4642. }
  4643. })
  4644. .Delete("/person",
  4645. [&](const Request &req, Response &res) {
  4646. if (req.has_param("name")) {
  4647. string name = req.get_param_value("name");
  4648. if (persons_.find(name) != persons_.end()) {
  4649. persons_.erase(name);
  4650. res.set_content("DELETED", "text/plain");
  4651. } else {
  4652. res.status = StatusCode::NotFound_404;
  4653. }
  4654. } else {
  4655. res.status = StatusCode::BadRequest_400;
  4656. }
  4657. })
  4658. .Post("/x-www-form-urlencoded-json",
  4659. [&](const Request &req, Response &res) {
  4660. auto json = req.get_param_value("json");
  4661. ASSERT_EQ(JSON_DATA, json);
  4662. res.set_content(json, "appliation/json");
  4663. res.status = StatusCode::OK_200;
  4664. })
  4665. .Get("/streamed-chunked",
  4666. [&](const Request & /*req*/, Response &res) {
  4667. res.set_chunked_content_provider(
  4668. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4669. sink.os << "123";
  4670. sink.os << "456";
  4671. sink.os << "789";
  4672. sink.done();
  4673. return true;
  4674. });
  4675. })
  4676. .Get("/streamed-chunked-with-prohibited-trailer",
  4677. [&](const Request & /*req*/, Response &res) {
  4678. auto i = new int(0);
  4679. // Declare both a prohibited trailer (Content-Length) and an
  4680. // allowed one
  4681. res.set_header("Trailer", "Content-Length, X-Allowed");
  4682. res.set_chunked_content_provider(
  4683. "text/plain",
  4684. [i](size_t /*offset*/, DataSink &sink) {
  4685. switch (*i) {
  4686. case 0: sink.os << "123"; break;
  4687. case 1: sink.os << "456"; break;
  4688. case 2: sink.os << "789"; break;
  4689. case 3: {
  4690. sink.done_with_trailer(
  4691. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4692. } break;
  4693. }
  4694. (*i)++;
  4695. return true;
  4696. },
  4697. [i](bool success) {
  4698. EXPECT_TRUE(success);
  4699. delete i;
  4700. });
  4701. })
  4702. .Get("/streamed-chunked2",
  4703. [&](const Request & /*req*/, Response &res) {
  4704. auto i = new int(0);
  4705. res.set_chunked_content_provider(
  4706. "text/plain",
  4707. [i](size_t /*offset*/, DataSink &sink) {
  4708. switch (*i) {
  4709. case 0: sink.os << "123"; break;
  4710. case 1: sink.os << "456"; break;
  4711. case 2: sink.os << "789"; break;
  4712. case 3: sink.done(); break;
  4713. }
  4714. (*i)++;
  4715. return true;
  4716. },
  4717. [i](bool success) {
  4718. EXPECT_TRUE(success);
  4719. delete i;
  4720. });
  4721. })
  4722. .Get("/streamed-chunked-with-trailer",
  4723. [&](const Request & /*req*/, Response &res) {
  4724. auto i = new int(0);
  4725. res.set_header("Trailer", "Dummy1, Dummy2");
  4726. res.set_chunked_content_provider(
  4727. "text/plain",
  4728. [i](size_t /*offset*/, DataSink &sink) {
  4729. switch (*i) {
  4730. case 0: sink.os << "123"; break;
  4731. case 1: sink.os << "456"; break;
  4732. case 2: sink.os << "789"; break;
  4733. case 3: {
  4734. sink.done_with_trailer(
  4735. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4736. } break;
  4737. }
  4738. (*i)++;
  4739. return true;
  4740. },
  4741. [i](bool success) {
  4742. EXPECT_TRUE(success);
  4743. delete i;
  4744. });
  4745. })
  4746. .Get("/streamed",
  4747. [&](const Request & /*req*/, Response &res) {
  4748. res.set_content_provider(
  4749. 6, "text/plain",
  4750. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4751. sink.os << (offset < 3 ? "a" : "b");
  4752. return true;
  4753. });
  4754. })
  4755. .Get("/streamed-without-length",
  4756. [&](const Request & /*req*/, Response &res) {
  4757. auto data = new std::string("abcdefg");
  4758. res.set_content_provider(
  4759. "text/plain",
  4760. [data](size_t offset, DataSink &sink) {
  4761. if (offset < data->size()) {
  4762. sink.os << data->substr(offset);
  4763. }
  4764. sink.done();
  4765. return true;
  4766. },
  4767. [data](bool success) {
  4768. EXPECT_TRUE(success);
  4769. delete data;
  4770. });
  4771. })
  4772. .Get("/streamed-with-range",
  4773. [&](const Request &req, Response &res) {
  4774. auto data = new std::string("abcdefg");
  4775. // An explicit status keeps the server from picking the 206 it
  4776. // would otherwise choose for a ranged request, so the response
  4777. // is not a partial representation.
  4778. auto status = req.get_param_value("status");
  4779. if (status == "200") {
  4780. res.status = StatusCode::OK_200;
  4781. } else if (status == "403") {
  4782. res.status = StatusCode::Forbidden_403;
  4783. }
  4784. res.set_content_provider(
  4785. data->size(), "text/plain",
  4786. [data](size_t offset, size_t length, DataSink &sink) {
  4787. size_t DATA_CHUNK_SIZE = 4;
  4788. const auto &d = *data;
  4789. auto out_len =
  4790. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4791. auto ret =
  4792. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4793. EXPECT_TRUE(ret);
  4794. return true;
  4795. },
  4796. [data, &req](bool success) {
  4797. EXPECT_EQ(success, !req.has_param("error"));
  4798. delete data;
  4799. });
  4800. })
  4801. .Get("/streamed-cancel",
  4802. [&](const Request & /*req*/, Response &res) {
  4803. res.set_content_provider(
  4804. size_t(-1), "text/plain",
  4805. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4806. sink.os << "data_chunk";
  4807. return true;
  4808. });
  4809. })
  4810. .Get("/regex-with-delimiter",
  4811. [&](const Request &req, Response & /*res*/) {
  4812. ASSERT_TRUE(req.has_param("key"));
  4813. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4814. })
  4815. .Get("/with-range",
  4816. [&](const Request & /*req*/, Response &res) {
  4817. res.set_content("abcdefg", "text/plain");
  4818. })
  4819. .Get("/test-start-time",
  4820. [&](const Request &req, Response & /*res*/) {
  4821. EXPECT_NE(req.start_time_,
  4822. std::chrono::steady_clock::time_point::min());
  4823. })
  4824. .Get("/with-range-customized-response",
  4825. [&](const Request & /*req*/, Response &res) {
  4826. res.status = StatusCode::BadRequest_400;
  4827. res.set_content(JSON_DATA, "application/json");
  4828. })
  4829. .Post("/chunked",
  4830. [&](const Request &req, Response & /*res*/) {
  4831. EXPECT_EQ(req.body, "dechunked post body");
  4832. })
  4833. .Post("/large-chunked",
  4834. [&](const Request &req, Response & /*res*/) {
  4835. std::string expected(6 * 30 * 1024u, 'a');
  4836. EXPECT_EQ(req.body, expected);
  4837. })
  4838. .Post("/multipart",
  4839. [&](const Request &req, Response & /*res*/) {
  4840. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4841. req.form.get_field_count("text2") +
  4842. req.form.get_field_count("file3") +
  4843. req.form.get_field_count("file4"));
  4844. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4845. req.form.get_file_count("file2"));
  4846. ASSERT_TRUE(!req.form.has_file("???"));
  4847. ASSERT_TRUE(!req.form.has_field("???"));
  4848. ASSERT_TRUE(req.body.empty());
  4849. {
  4850. const auto &text = req.form.get_field("text1");
  4851. EXPECT_EQ("text default", text);
  4852. }
  4853. {
  4854. const auto &text = req.form.get_field("text2");
  4855. EXPECT_EQ("aωb", text);
  4856. }
  4857. {
  4858. const auto &file = req.form.get_file("file1");
  4859. EXPECT_EQ("hello.txt", file.filename);
  4860. EXPECT_EQ("text/plain", file.content_type);
  4861. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4862. }
  4863. {
  4864. const auto &file = req.form.get_file("file2");
  4865. EXPECT_EQ("world.json", file.filename);
  4866. EXPECT_EQ("application/json", file.content_type);
  4867. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4868. }
  4869. {
  4870. const auto &text = req.form.get_field("file3");
  4871. EXPECT_EQ(0u, text.size());
  4872. }
  4873. {
  4874. const auto &text = req.form.get_field("file4");
  4875. EXPECT_EQ(0u, text.size());
  4876. }
  4877. })
  4878. .Post("/multipart/multi_file_values",
  4879. [&](const Request &req, Response & /*res*/) {
  4880. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4881. req.form.get_field_count("multi_text1"));
  4882. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4883. ASSERT_TRUE(!req.form.has_file("???"));
  4884. ASSERT_TRUE(!req.form.has_field("???"));
  4885. ASSERT_TRUE(req.body.empty());
  4886. {
  4887. const auto &text = req.form.get_field("text");
  4888. EXPECT_EQ("default text", text);
  4889. }
  4890. {
  4891. const auto &text1_values = req.form.get_fields("multi_text1");
  4892. EXPECT_EQ(2u, text1_values.size());
  4893. EXPECT_EQ("aaaaa", text1_values[0]);
  4894. EXPECT_EQ("bbbbb", text1_values[1]);
  4895. }
  4896. {
  4897. const auto &file1_values = req.form.get_files("multi_file1");
  4898. EXPECT_EQ(2u, file1_values.size());
  4899. auto file1 = file1_values[0];
  4900. EXPECT_EQ(file1.filename, "hello.txt");
  4901. EXPECT_EQ(file1.content_type, "text/plain");
  4902. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4903. auto file2 = file1_values[1];
  4904. EXPECT_EQ(file2.filename, "world.json");
  4905. EXPECT_EQ(file2.content_type, "application/json");
  4906. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4907. }
  4908. })
  4909. .Post("/empty",
  4910. [&](const Request &req, Response &res) {
  4911. EXPECT_EQ(req.body, "");
  4912. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4913. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4914. res.set_content("empty", "text/plain");
  4915. })
  4916. .Post("/empty-no-content-type",
  4917. [&](const Request &req, Response &res) {
  4918. EXPECT_EQ(req.body, "");
  4919. EXPECT_FALSE(req.has_header("Content-Type"));
  4920. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4921. res.set_content("empty-no-content-type", "text/plain");
  4922. })
  4923. .Post("/path-only",
  4924. [&](const Request &req, Response &res) {
  4925. EXPECT_EQ(req.body, "");
  4926. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4927. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4928. res.set_content("path-only", "text/plain");
  4929. })
  4930. .Post("/path-headers-only",
  4931. [&](const Request &req, Response &res) {
  4932. EXPECT_EQ(req.body, "");
  4933. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4934. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4935. EXPECT_EQ("world", req.get_header_value("hello"));
  4936. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4937. res.set_content("path-headers-only", "text/plain");
  4938. })
  4939. .Post("/post-large",
  4940. [&](const Request &req, Response &res) {
  4941. EXPECT_EQ(req.body, LARGE_DATA);
  4942. res.set_content(req.body, "text/plain");
  4943. })
  4944. .Post("/post-loopback",
  4945. [&](const Request &, Response &res,
  4946. ContentReader const &content_reader) {
  4947. std::string body;
  4948. content_reader([&](const char *data, size_t data_length) {
  4949. body.append(data, data_length);
  4950. return true;
  4951. });
  4952. res.set_content(body, "text/plain");
  4953. })
  4954. .Put("/put-loopback",
  4955. [&](const Request &, Response &res,
  4956. ContentReader const &content_reader) {
  4957. std::string body;
  4958. content_reader([&](const char *data, size_t data_length) {
  4959. body.append(data, data_length);
  4960. return true;
  4961. });
  4962. res.set_content(body, "text/plain");
  4963. })
  4964. .Patch("/patch-loopback",
  4965. [&](const Request &, Response &res,
  4966. ContentReader const &content_reader) {
  4967. std::string body;
  4968. content_reader([&](const char *data, size_t data_length) {
  4969. body.append(data, data_length);
  4970. return true;
  4971. });
  4972. res.set_content(body, "text/plain");
  4973. })
  4974. .Put("/empty-no-content-type",
  4975. [&](const Request &req, Response &res) {
  4976. EXPECT_EQ(req.body, "");
  4977. EXPECT_FALSE(req.has_header("Content-Type"));
  4978. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4979. res.set_content("empty-no-content-type", "text/plain");
  4980. })
  4981. .Put("/put",
  4982. [&](const Request &req, Response &res) {
  4983. EXPECT_EQ(req.body, "PUT");
  4984. res.set_content(req.body, "text/plain");
  4985. })
  4986. .Put("/put-large",
  4987. [&](const Request &req, Response &res) {
  4988. EXPECT_EQ(req.body, LARGE_DATA);
  4989. res.set_content(req.body, "text/plain");
  4990. })
  4991. .Patch("/patch",
  4992. [&](const Request &req, Response &res) {
  4993. EXPECT_EQ(req.body, "PATCH");
  4994. res.set_content(req.body, "text/plain");
  4995. })
  4996. .Delete("/delete",
  4997. [&](const Request & /*req*/, Response &res) {
  4998. res.set_content("DELETE", "text/plain");
  4999. })
  5000. .Delete("/delete-body",
  5001. [&](const Request &req, Response &res) {
  5002. EXPECT_EQ(req.body, "content");
  5003. res.set_content(req.body, "text/plain");
  5004. })
  5005. .Options(R"(\*)",
  5006. [&](const Request & /*req*/, Response &res) {
  5007. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5008. })
  5009. .CustomRoute("PROPFIND", "/dav/:id",
  5010. [&](const Request &req, Response &res) {
  5011. res.set_header("x-body-size",
  5012. std::to_string(req.body.size()));
  5013. res.set_header("x-matched-route", req.matched_route);
  5014. res.set_header("x-dav-id", req.path_params.at("id"));
  5015. res.status = StatusCode::MultiStatus_207;
  5016. res.set_content(req.body, "application/xml");
  5017. })
  5018. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5019. [&](const Request &req, Response &res) {
  5020. res.set_header("x-dav-match", req.matches[1]);
  5021. res.status = StatusCode::MultiStatus_207;
  5022. })
  5023. .CustomRoute("MKCOL", "/dav-mkcol",
  5024. [&](const Request &req, Response &res) {
  5025. EXPECT_TRUE(req.body.empty());
  5026. res.status = StatusCode::Created_201;
  5027. })
  5028. .CustomRoute(
  5029. "REPORT", "/dav-report",
  5030. [&](const Request & /*req*/, Response &res,
  5031. const ContentReader &content_reader) {
  5032. std::string body;
  5033. content_reader([&](const char *data, size_t data_length) {
  5034. body.append(data, data_length);
  5035. return true;
  5036. });
  5037. res.set_header("x-body-size", std::to_string(body.size()));
  5038. res.status = StatusCode::MultiStatus_207;
  5039. res.set_content(body, "application/xml");
  5040. })
  5041. .Get("/request-target",
  5042. [&](const Request &req, Response & /*res*/) {
  5043. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5044. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5045. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5046. })
  5047. .Get("/long-query-value",
  5048. [&](const Request &req, Response & /*res*/) {
  5049. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5050. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5051. })
  5052. .Get("/too-long-query-value",
  5053. [&](const Request &req, Response & /*res*/) {
  5054. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5055. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5056. })
  5057. .Get("/array-param",
  5058. [&](const Request &req, Response & /*res*/) {
  5059. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5060. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5061. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5062. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5063. })
  5064. .Get("/array-param-values",
  5065. [&](const Request &req, Response & /*res*/) {
  5066. auto values = req.get_param_values("array");
  5067. EXPECT_EQ(3u, values.size());
  5068. EXPECT_EQ("value1", values[0]);
  5069. EXPECT_EQ("value2", values[1]);
  5070. EXPECT_EQ("value3", values[2]);
  5071. auto empty = req.get_param_values("nonexistent");
  5072. EXPECT_TRUE(empty.empty());
  5073. })
  5074. .Post("/validate-no-multiple-headers",
  5075. [&](const Request &req, Response & /*res*/) {
  5076. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5077. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5078. })
  5079. .Post("/content_receiver",
  5080. [&](const Request &req, Response &res,
  5081. const ContentReader &content_reader) {
  5082. if (req.is_multipart_form_data()) {
  5083. std::vector<FormData> items;
  5084. content_reader(
  5085. [&](const FormData &file) {
  5086. items.push_back(file);
  5087. return true;
  5088. },
  5089. [&](const char *data, size_t data_length) {
  5090. items.back().content.append(data, data_length);
  5091. return true;
  5092. });
  5093. EXPECT_EQ(5u, items.size());
  5094. {
  5095. const auto &file = get_file_value(items, "text1");
  5096. EXPECT_TRUE(file.filename.empty());
  5097. EXPECT_EQ("text default", file.content);
  5098. }
  5099. {
  5100. const auto &file = get_file_value(items, "text2");
  5101. EXPECT_TRUE(file.filename.empty());
  5102. EXPECT_EQ("aωb", file.content);
  5103. }
  5104. {
  5105. const auto &file = get_file_value(items, "file1");
  5106. EXPECT_EQ("hello.txt", file.filename);
  5107. EXPECT_EQ("text/plain", file.content_type);
  5108. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5109. }
  5110. {
  5111. const auto &file = get_file_value(items, "file2");
  5112. EXPECT_EQ("world.json", file.filename);
  5113. EXPECT_EQ("application/json", file.content_type);
  5114. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5115. }
  5116. {
  5117. const auto &file = get_file_value(items, "file3");
  5118. EXPECT_TRUE(file.filename.empty());
  5119. EXPECT_EQ("application/octet-stream", file.content_type);
  5120. EXPECT_EQ(0u, file.content.size());
  5121. }
  5122. } else {
  5123. std::string body;
  5124. content_reader([&](const char *data, size_t data_length) {
  5125. EXPECT_EQ(7U, data_length);
  5126. body.append(data, data_length);
  5127. return true;
  5128. });
  5129. EXPECT_EQ(body, "content");
  5130. res.set_content(body, "text/plain");
  5131. }
  5132. })
  5133. .Put("/content_receiver",
  5134. [&](const Request & /*req*/, Response &res,
  5135. const ContentReader &content_reader) {
  5136. std::string body;
  5137. content_reader([&](const char *data, size_t data_length) {
  5138. body.append(data, data_length);
  5139. return true;
  5140. });
  5141. EXPECT_EQ(body, "content");
  5142. res.set_content(body, "text/plain");
  5143. })
  5144. .Patch("/content_receiver",
  5145. [&](const Request & /*req*/, Response &res,
  5146. const ContentReader &content_reader) {
  5147. std::string body;
  5148. content_reader([&](const char *data, size_t data_length) {
  5149. body.append(data, data_length);
  5150. return true;
  5151. });
  5152. EXPECT_EQ(body, "content");
  5153. res.set_content(body, "text/plain");
  5154. })
  5155. .Post("/query-string-and-body",
  5156. [&](const Request &req, Response & /*res*/) {
  5157. ASSERT_TRUE(req.has_param("key"));
  5158. EXPECT_EQ(req.get_param_value("key"), "value");
  5159. EXPECT_EQ(req.body, "content");
  5160. })
  5161. .Get("/last-request",
  5162. [&](const Request &req, Response & /*res*/) {
  5163. EXPECT_EQ("close", req.get_header_value("Connection"));
  5164. })
  5165. .Get(R"(/redirect/(\d+))",
  5166. [&](const Request &req, Response &res) {
  5167. auto num = std::stoi(req.matches[1]) + 1;
  5168. std::string url = "/redirect/" + std::to_string(num);
  5169. res.set_redirect(url);
  5170. })
  5171. .Post("/binary",
  5172. [&](const Request &req, Response &res) {
  5173. EXPECT_EQ(4U, req.body.size());
  5174. EXPECT_EQ("application/octet-stream",
  5175. req.get_header_value("Content-Type"));
  5176. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5177. res.set_content(req.body, "application/octet-stream");
  5178. })
  5179. .Put("/binary",
  5180. [&](const Request &req, Response &res) {
  5181. EXPECT_EQ(4U, req.body.size());
  5182. EXPECT_EQ("application/octet-stream",
  5183. req.get_header_value("Content-Type"));
  5184. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5185. res.set_content(req.body, "application/octet-stream");
  5186. })
  5187. .Patch("/binary",
  5188. [&](const Request &req, Response &res) {
  5189. EXPECT_EQ(4U, req.body.size());
  5190. EXPECT_EQ("application/octet-stream",
  5191. req.get_header_value("Content-Type"));
  5192. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5193. res.set_content(req.body, "application/octet-stream");
  5194. })
  5195. .Delete("/binary",
  5196. [&](const Request &req, Response &res) {
  5197. EXPECT_EQ(4U, req.body.size());
  5198. EXPECT_EQ("application/octet-stream",
  5199. req.get_header_value("Content-Type"));
  5200. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5201. res.set_content(req.body, "application/octet-stream");
  5202. })
  5203. .Get("/issue1772",
  5204. [&](const Request & /*req*/, Response &res) {
  5205. res.status = 401;
  5206. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5207. })
  5208. .Delete("/issue609",
  5209. [](const httplib::Request &, httplib::Response &res,
  5210. const httplib::ContentReader &) {
  5211. res.set_content("ok", "text/plain");
  5212. })
  5213. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5214. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5215. .Get("/compress",
  5216. [&](const Request & /*req*/, Response &res) {
  5217. res.set_content(
  5218. "12345678901234567890123456789012345678901234567890123456789"
  5219. "01234567890123456789012345678901234567890",
  5220. "text/plain");
  5221. })
  5222. .Get("/compress-with-charset",
  5223. [&](const Request & /*req*/, Response &res) {
  5224. res.set_content(
  5225. "12345678901234567890123456789012345678901234567890123456789"
  5226. "01234567890123456789012345678901234567890",
  5227. "application/json; charset=utf-8");
  5228. })
  5229. .Get("/nocompress",
  5230. [&](const Request & /*req*/, Response &res) {
  5231. res.set_content(
  5232. "12345678901234567890123456789012345678901234567890123456789"
  5233. "01234567890123456789012345678901234567890",
  5234. "application/octet-stream");
  5235. })
  5236. .Post("/compress-multipart",
  5237. [&](const Request &req, Response & /*res*/) {
  5238. EXPECT_EQ(2u, req.form.fields.size());
  5239. ASSERT_TRUE(!req.form.has_field("???"));
  5240. {
  5241. const auto &text = req.form.get_field("key1");
  5242. EXPECT_EQ("test", text);
  5243. }
  5244. {
  5245. const auto &text = req.form.get_field("key2");
  5246. EXPECT_EQ("--abcdefg123", text);
  5247. }
  5248. })
  5249. #endif
  5250. ;
  5251. persons_["john"] = "programmer";
  5252. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5253. svr_.wait_until_ready();
  5254. }
  5255. virtual void TearDown() {
  5256. svr_.stop();
  5257. if (!request_threads_.empty()) {
  5258. std::this_thread::sleep_for(std::chrono::seconds(1));
  5259. for (auto &t : request_threads_) {
  5260. t.join();
  5261. }
  5262. }
  5263. t_.join();
  5264. }
  5265. map<string, string> persons_;
  5266. #ifdef CPPHTTPLIB_SSL_ENABLED
  5267. SSLClient cli_;
  5268. SSLServer svr_;
  5269. #else
  5270. Client cli_;
  5271. Server svr_;
  5272. #endif
  5273. thread t_;
  5274. std::vector<thread> request_threads_;
  5275. };
  5276. TEST_F(ServerTest, GetMethod200) {
  5277. auto res = cli_.Get("/hi");
  5278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5279. EXPECT_EQ("HTTP/1.1", res->version);
  5280. EXPECT_EQ(StatusCode::OK_200, res->status);
  5281. EXPECT_EQ("OK", res->reason);
  5282. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5283. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5284. EXPECT_EQ("Hello World!", res->body);
  5285. }
  5286. TEST_F(ServerTest, GetEmptyFile) {
  5287. auto res = cli_.Get("/empty_file");
  5288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5289. EXPECT_EQ(StatusCode::OK_200, res->status);
  5290. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5291. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5292. EXPECT_EQ("", res->body);
  5293. }
  5294. TEST_F(ServerTest, GetFileContent) {
  5295. auto res = cli_.Get("/file_content");
  5296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5297. EXPECT_EQ(StatusCode::OK_200, res->status);
  5298. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5299. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5300. EXPECT_EQ("test.html", res->body);
  5301. }
  5302. TEST_F(ServerTest, GetFileContentWithRange) {
  5303. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5305. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5306. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5307. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5308. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5309. EXPECT_EQ("est", res->body);
  5310. }
  5311. TEST_F(ServerTest, GetFileContentWithContentType) {
  5312. auto res = cli_.Get("/file_content_with_content_type");
  5313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5314. EXPECT_EQ(StatusCode::OK_200, res->status);
  5315. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5316. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5317. EXPECT_EQ("file\n", res->body);
  5318. }
  5319. TEST_F(ServerTest, GetInvalidFileContent) {
  5320. auto res = cli_.Get("/invalid_file_content");
  5321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5322. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5323. }
  5324. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5325. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5327. EXPECT_EQ("HTTP/1.1", res->version);
  5328. EXPECT_EQ(StatusCode::OK_200, res->status);
  5329. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5330. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5331. EXPECT_EQ("Hello World!", res->body);
  5332. }
  5333. TEST_F(ServerTest, GetMethod302) {
  5334. auto res = cli_.Get("/");
  5335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5336. EXPECT_EQ(StatusCode::Found_302, res->status);
  5337. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5338. }
  5339. TEST_F(ServerTest, GetMethod302Redirect) {
  5340. cli_.set_follow_location(true);
  5341. auto res = cli_.Get("/");
  5342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5343. EXPECT_EQ(StatusCode::OK_200, res->status);
  5344. EXPECT_EQ("Hello World!", res->body);
  5345. EXPECT_EQ("/hi", res->location);
  5346. }
  5347. TEST_F(ServerTest, GetMethod404) {
  5348. auto res = cli_.Get("/invalid");
  5349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5350. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5351. }
  5352. TEST_F(ServerTest, HeadMethod200) {
  5353. auto res = cli_.Head("/hi");
  5354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5355. EXPECT_EQ(StatusCode::OK_200, res->status);
  5356. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5357. EXPECT_TRUE(res->body.empty());
  5358. }
  5359. TEST_F(ServerTest, HeadMethod200Static) {
  5360. auto res = cli_.Head("/mount/dir/index.html");
  5361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5362. EXPECT_EQ(StatusCode::OK_200, res->status);
  5363. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5364. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5365. EXPECT_TRUE(res->body.empty());
  5366. }
  5367. TEST_F(ServerTest, HeadMethod404) {
  5368. auto res = cli_.Head("/invalid");
  5369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5370. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5371. EXPECT_TRUE(res->body.empty());
  5372. }
  5373. TEST_F(ServerTest, GetMethodPersonJohn) {
  5374. auto res = cli_.Get("/person/john");
  5375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5376. EXPECT_EQ(StatusCode::OK_200, res->status);
  5377. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5378. EXPECT_EQ("programmer", res->body);
  5379. }
  5380. TEST_F(ServerTest, PostMethod1) {
  5381. auto res = cli_.Get("/person/john1");
  5382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5383. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5384. res = cli_.Post("/person", "name=john1&note=coder",
  5385. "application/x-www-form-urlencoded");
  5386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5387. ASSERT_EQ(StatusCode::OK_200, res->status);
  5388. res = cli_.Get("/person/john1");
  5389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5390. ASSERT_EQ(StatusCode::OK_200, res->status);
  5391. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5392. ASSERT_EQ("coder", res->body);
  5393. }
  5394. TEST_F(ServerTest, PostMethod2) {
  5395. auto res = cli_.Get("/person/john2");
  5396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5397. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5398. Params params;
  5399. params.emplace("name", "john2");
  5400. params.emplace("note", "coder");
  5401. res = cli_.Post("/person", params);
  5402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5403. ASSERT_EQ(StatusCode::OK_200, res->status);
  5404. res = cli_.Get("/person/john2");
  5405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5406. ASSERT_EQ(StatusCode::OK_200, res->status);
  5407. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5408. ASSERT_EQ("coder", res->body);
  5409. }
  5410. TEST_F(ServerTest, PutMethod3) {
  5411. auto res = cli_.Get("/person/john3");
  5412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5413. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5414. Params params;
  5415. params.emplace("name", "john3");
  5416. params.emplace("note", "coder");
  5417. res = cli_.Put("/person", params);
  5418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5419. ASSERT_EQ(StatusCode::OK_200, res->status);
  5420. res = cli_.Get("/person/john3");
  5421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5422. ASSERT_EQ(StatusCode::OK_200, res->status);
  5423. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5424. ASSERT_EQ("coder", res->body);
  5425. }
  5426. TEST_F(ServerTest, DeleteMethod1) {
  5427. auto res = cli_.Get("/person/john4");
  5428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5429. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5430. Params params;
  5431. params.emplace("name", "john4");
  5432. params.emplace("note", "coder");
  5433. res = cli_.Post("/person", params);
  5434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5435. ASSERT_EQ(StatusCode::OK_200, res->status);
  5436. res = cli_.Get("/person/john4");
  5437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5438. ASSERT_EQ(StatusCode::OK_200, res->status);
  5439. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5440. ASSERT_EQ("coder", res->body);
  5441. Params delete_params;
  5442. delete_params.emplace("name", "john4");
  5443. res = cli_.Delete("/person", delete_params);
  5444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5445. ASSERT_EQ(StatusCode::OK_200, res->status);
  5446. ASSERT_EQ("DELETED", res->body);
  5447. res = cli_.Get("/person/john4");
  5448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5449. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5450. }
  5451. TEST_F(ServerTest, DeleteMethod2) {
  5452. auto res = cli_.Get("/person/john5");
  5453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5454. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5455. Params params;
  5456. params.emplace("name", "john5");
  5457. params.emplace("note", "developer");
  5458. res = cli_.Post("/person", params);
  5459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5460. ASSERT_EQ(StatusCode::OK_200, res->status);
  5461. res = cli_.Get("/person/john5");
  5462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5463. ASSERT_EQ(StatusCode::OK_200, res->status);
  5464. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5465. ASSERT_EQ("developer", res->body);
  5466. Params delete_params;
  5467. delete_params.emplace("name", "john5");
  5468. Headers headers;
  5469. headers.emplace("Custom-Header", "test-value");
  5470. res = cli_.Delete("/person", headers, delete_params);
  5471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5472. ASSERT_EQ(StatusCode::OK_200, res->status);
  5473. ASSERT_EQ("DELETED", res->body);
  5474. res = cli_.Get("/person/john5");
  5475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5476. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5477. }
  5478. TEST_F(ServerTest, DeleteMethod3) {
  5479. auto res = cli_.Get("/person/john6");
  5480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5481. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5482. Params params;
  5483. params.emplace("name", "john6");
  5484. params.emplace("note", "tester");
  5485. res = cli_.Post("/person", params);
  5486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5487. ASSERT_EQ(StatusCode::OK_200, res->status);
  5488. res = cli_.Get("/person/john6");
  5489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5490. ASSERT_EQ(StatusCode::OK_200, res->status);
  5491. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5492. ASSERT_EQ("tester", res->body);
  5493. Params delete_params;
  5494. delete_params.emplace("name", "john6");
  5495. Headers headers;
  5496. headers.emplace("Custom-Header", "test-value");
  5497. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5499. ASSERT_EQ(StatusCode::OK_200, res->status);
  5500. ASSERT_EQ("DELETED", res->body);
  5501. res = cli_.Get("/person/john6");
  5502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5503. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5504. }
  5505. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5506. Params params;
  5507. params.emplace("json", JSON_DATA);
  5508. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5510. ASSERT_EQ(StatusCode::OK_200, res->status);
  5511. ASSERT_EQ(JSON_DATA, res->body);
  5512. }
  5513. TEST_F(ServerTest, PostEmptyContent) {
  5514. auto res = cli_.Post("/empty", "", "text/plain");
  5515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5516. ASSERT_EQ(StatusCode::OK_200, res->status);
  5517. ASSERT_EQ("empty", res->body);
  5518. }
  5519. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5520. auto res = cli_.Post("/empty-no-content-type");
  5521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5522. ASSERT_EQ(StatusCode::OK_200, res->status);
  5523. ASSERT_EQ("empty-no-content-type", res->body);
  5524. }
  5525. TEST_F(ServerTest, PostPathOnly) {
  5526. auto res = cli_.Post("/path-only");
  5527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5528. ASSERT_EQ(StatusCode::OK_200, res->status);
  5529. ASSERT_EQ("path-only", res->body);
  5530. }
  5531. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5532. auto res = cli_.Post("/path-headers-only",
  5533. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5535. ASSERT_EQ(StatusCode::OK_200, res->status);
  5536. ASSERT_EQ("path-headers-only", res->body);
  5537. }
  5538. TEST_F(ServerTest, PostLarge) {
  5539. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5541. ASSERT_EQ(StatusCode::OK_200, res->status);
  5542. EXPECT_EQ(LARGE_DATA, res->body);
  5543. }
  5544. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5545. auto res = cli_.Put("/empty-no-content-type");
  5546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5547. ASSERT_EQ(StatusCode::OK_200, res->status);
  5548. ASSERT_EQ("empty-no-content-type", res->body);
  5549. }
  5550. TEST_F(ServerTest, GetMethodDir) {
  5551. auto res = cli_.Get("/dir/");
  5552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5553. EXPECT_EQ(StatusCode::OK_200, res->status);
  5554. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5555. auto body = R"(<html>
  5556. <head>
  5557. </head>
  5558. <body>
  5559. <a href="/dir/test.html">Test</a>
  5560. <a href="/hi">hi</a>
  5561. </body>
  5562. </html>
  5563. )";
  5564. EXPECT_EQ(body, res->body);
  5565. }
  5566. TEST_F(ServerTest, GetMethodDirTest) {
  5567. auto res = cli_.Get("/dir/test.html");
  5568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5569. EXPECT_EQ(StatusCode::OK_200, res->status);
  5570. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5571. EXPECT_EQ("test.html", res->body);
  5572. }
  5573. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5574. auto res = cli_.Get("/dir/../dir/test.html");
  5575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5576. EXPECT_EQ(StatusCode::OK_200, res->status);
  5577. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5578. EXPECT_EQ("test.html", res->body);
  5579. }
  5580. TEST_F(ServerTest, GetMethodInvalidPath) {
  5581. auto res = cli_.Get("/dir/../test.html");
  5582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5583. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5584. }
  5585. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5586. auto res = cli_.Get("/../www/dir/test.html");
  5587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5588. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5589. }
  5590. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5591. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5593. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5594. }
  5595. TEST_F(ServerTest, GetMethodDirMountTest) {
  5596. auto res = cli_.Get("/mount/dir/test.html");
  5597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5598. EXPECT_EQ(StatusCode::OK_200, res->status);
  5599. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5600. EXPECT_EQ("test.html", res->body);
  5601. }
  5602. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5603. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5605. EXPECT_EQ(StatusCode::OK_200, res->status);
  5606. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5607. EXPECT_EQ("test.html", res->body);
  5608. }
  5609. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5610. auto res = cli_.Get("/mount/dir/../test.html");
  5611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5612. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5613. }
  5614. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5615. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5617. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5618. }
  5619. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5620. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5622. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5623. }
  5624. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5625. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5627. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5628. }
  5629. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5630. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5632. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5633. }
  5634. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  5635. auto res = cli_.Get("/mount/dir");
  5636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5637. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5638. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5639. }
  5640. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  5641. auto res = cli_.Get("//dir");
  5642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5643. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5644. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5645. }
  5646. TEST_F(ServerTest, PostMethod303) {
  5647. auto res = cli_.Post("/1", "body", "text/plain");
  5648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5649. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5650. EXPECT_EQ("/2", res->get_header_value("Location"));
  5651. }
  5652. TEST_F(ServerTest, PostMethod303Redirect) {
  5653. cli_.set_follow_location(true);
  5654. auto res = cli_.Post("/1", "body", "text/plain");
  5655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5656. EXPECT_EQ(StatusCode::OK_200, res->status);
  5657. EXPECT_EQ("redirected.", res->body);
  5658. EXPECT_EQ("/2", res->location);
  5659. }
  5660. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5661. auto res = cli_.Get("/dir/test.abcde");
  5662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5663. EXPECT_EQ(StatusCode::OK_200, res->status);
  5664. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5665. EXPECT_EQ("abcde", res->body);
  5666. }
  5667. TEST_F(ServerTest, StaticFileRange) {
  5668. auto res =
  5669. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5671. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5672. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5673. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5674. EXPECT_EQ(true, res->has_header("Content-Range"));
  5675. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5676. EXPECT_EQ(std::string("cd"), res->body);
  5677. }
  5678. TEST_F(ServerTest, StaticFileRanges) {
  5679. auto res = cli_.Get("/dir/test.abcde",
  5680. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5682. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5683. EXPECT_TRUE(
  5684. res->get_header_value("Content-Type")
  5685. .find(
  5686. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5687. 0);
  5688. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5689. }
  5690. TEST_F(ServerTest, StaticFileRangeHead) {
  5691. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5693. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5694. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5695. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5696. EXPECT_EQ(true, res->has_header("Content-Range"));
  5697. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5698. }
  5699. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5700. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5702. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5703. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5704. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5705. EXPECT_EQ(true, res->has_header("Content-Range"));
  5706. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5707. res->get_header_value("Content-Range"));
  5708. EXPECT_EQ("LAST\n", res->body);
  5709. }
  5710. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5711. auto res =
  5712. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5714. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5715. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5716. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5717. EXPECT_EQ(true, res->has_header("Content-Range"));
  5718. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5719. }
  5720. TEST_F(ServerTest, StaticFileBigFile) {
  5721. auto res = cli_.Get("/dir/1MB.txt");
  5722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5723. EXPECT_EQ(StatusCode::OK_200, res->status);
  5724. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5725. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5726. }
  5727. TEST_F(ServerTest, InvalidBaseDirMount) {
  5728. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5729. }
  5730. TEST_F(ServerTest, Binary) {
  5731. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5732. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5733. "application/octet-stream");
  5734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5735. ASSERT_EQ(StatusCode::OK_200, res->status);
  5736. ASSERT_EQ(4U, res->body.size());
  5737. res = cli_.Put("/binary", binary.data(), binary.size(),
  5738. "application/octet-stream");
  5739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5740. ASSERT_EQ(StatusCode::OK_200, res->status);
  5741. ASSERT_EQ(4U, res->body.size());
  5742. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5743. "application/octet-stream");
  5744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5745. ASSERT_EQ(StatusCode::OK_200, res->status);
  5746. ASSERT_EQ(4U, res->body.size());
  5747. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5748. "application/octet-stream");
  5749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5750. ASSERT_EQ(StatusCode::OK_200, res->status);
  5751. ASSERT_EQ(4U, res->body.size());
  5752. }
  5753. TEST_F(ServerTest, BinaryString) {
  5754. auto binary = std::string("\x00\x01\x02\x03", 4);
  5755. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5757. ASSERT_EQ(StatusCode::OK_200, res->status);
  5758. ASSERT_EQ(4U, res->body.size());
  5759. res = cli_.Put("/binary", binary, "application/octet-stream");
  5760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5761. ASSERT_EQ(StatusCode::OK_200, res->status);
  5762. ASSERT_EQ(4U, res->body.size());
  5763. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5765. ASSERT_EQ(StatusCode::OK_200, res->status);
  5766. ASSERT_EQ(4U, res->body.size());
  5767. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5769. ASSERT_EQ(StatusCode::OK_200, res->status);
  5770. ASSERT_EQ(4U, res->body.size());
  5771. }
  5772. TEST_F(ServerTest, EmptyRequest) {
  5773. auto res = cli_.Get("");
  5774. ASSERT_TRUE(!res);
  5775. EXPECT_EQ(Error::Connection, res.error());
  5776. }
  5777. TEST_F(ServerTest, LongRequest) {
  5778. std::string request;
  5779. for (size_t i = 0; i < 545; i++) {
  5780. request += "/TooLongRequest";
  5781. }
  5782. request += "OK";
  5783. auto res = cli_.Get(request.c_str());
  5784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5785. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5786. }
  5787. TEST_F(ServerTest, TooLongRequest) {
  5788. std::string request;
  5789. for (size_t i = 0; i < 546; i++) {
  5790. request += "/TooLongRequest";
  5791. }
  5792. request += "_NG";
  5793. auto start = std::chrono::high_resolution_clock::now();
  5794. cli_.set_keep_alive(true);
  5795. auto res = cli_.Get(request.c_str());
  5796. auto end = std::chrono::high_resolution_clock::now();
  5797. auto elapsed =
  5798. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5799. .count();
  5800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5801. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5802. EXPECT_LE(elapsed, 1000);
  5803. EXPECT_EQ("close", res->get_header_value("Connection"));
  5804. EXPECT_FALSE(cli_.is_socket_open());
  5805. }
  5806. TEST_F(ServerTest, AlmostTooLongRequest) {
  5807. // test for #2046 - URI length check shouldn't include other content on req
  5808. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5809. // leading /, space, HTTP/1.1)
  5810. std::string request =
  5811. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5812. auto res = cli_.Get(request.c_str());
  5813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5814. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5815. }
  5816. TEST_F(ServerTest, LongHeader) {
  5817. Request req;
  5818. req.method = "GET";
  5819. req.path = "/hi";
  5820. std::string host_and_port;
  5821. host_and_port += HOST;
  5822. host_and_port += ":";
  5823. host_and_port += std::to_string(PORT);
  5824. req.headers.emplace("Host", host_and_port.c_str());
  5825. req.headers.emplace("Accept", "*/*");
  5826. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5827. req.headers.emplace(
  5828. "Header-Name",
  5829. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5830. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5831. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5832. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5833. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5834. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5835. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5836. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5837. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5838. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5839. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5840. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5841. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5842. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5843. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5844. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5845. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5846. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5847. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5848. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5849. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5850. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5851. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5852. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5853. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5854. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5855. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5856. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5857. "@@@@@@@@@@@@@@@@");
  5858. auto res = std::make_shared<Response>();
  5859. auto error = Error::Success;
  5860. auto ret = cli_.send(req, *res, error);
  5861. ASSERT_TRUE(ret);
  5862. EXPECT_EQ(StatusCode::OK_200, res->status);
  5863. }
  5864. TEST_F(ServerTest, LongQueryValue) {
  5865. auto start = std::chrono::high_resolution_clock::now();
  5866. cli_.set_keep_alive(true);
  5867. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5868. auto end = std::chrono::high_resolution_clock::now();
  5869. auto elapsed =
  5870. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5871. .count();
  5872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5873. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5874. EXPECT_LE(elapsed, 1000);
  5875. EXPECT_EQ("close", res->get_header_value("Connection"));
  5876. EXPECT_FALSE(cli_.is_socket_open());
  5877. }
  5878. TEST_F(ServerTest, TooLongQueryValue) {
  5879. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5880. ASSERT_FALSE(res);
  5881. EXPECT_EQ(Error::Read, res.error());
  5882. }
  5883. TEST_F(ServerTest, TooLongHeader) {
  5884. Request req;
  5885. req.method = "GET";
  5886. req.path = "/hi";
  5887. std::string host_and_port;
  5888. host_and_port += HOST;
  5889. host_and_port += ":";
  5890. host_and_port += std::to_string(PORT);
  5891. req.headers.emplace("Host", host_and_port.c_str());
  5892. req.headers.emplace("Accept", "*/*");
  5893. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5894. req.headers.emplace(
  5895. "Header-Name",
  5896. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5897. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5898. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5899. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5900. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5901. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5902. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5903. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5904. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5905. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5906. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5907. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5908. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5909. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5910. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5911. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5912. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5913. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5914. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5915. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5916. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5917. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5918. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5919. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5920. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5921. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5922. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5923. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5924. "@@@@@@@@@@@@@@@@@");
  5925. auto res = std::make_shared<Response>();
  5926. auto error = Error::Success;
  5927. auto ret = cli_.send(req, *res, error);
  5928. ASSERT_TRUE(ret);
  5929. EXPECT_EQ(StatusCode::OK_200, res->status);
  5930. }
  5931. TEST_F(ServerTest, HeaderCountAtLimit) {
  5932. // Test with headers just under the 100 limit
  5933. httplib::Headers headers;
  5934. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5935. // This should keep us just under the 100 header limit
  5936. for (int i = 0; i < 95; i++) {
  5937. std::string name = "X-Test-Header-" + std::to_string(i);
  5938. std::string value = "value" + std::to_string(i);
  5939. headers.emplace(name, value);
  5940. }
  5941. // This should work fine as we're under the limit
  5942. auto res = cli_.Get("/hi", headers);
  5943. EXPECT_TRUE(res);
  5944. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5945. }
  5946. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5947. // Test with many headers to exceed the 100 limit
  5948. httplib::Headers headers;
  5949. // Add 150 headers to definitely exceed the 100 limit
  5950. for (int i = 0; i < 150; i++) {
  5951. std::string name = "X-Test-Header-" + std::to_string(i);
  5952. std::string value = "value" + std::to_string(i);
  5953. headers.emplace(name, value);
  5954. }
  5955. // This should fail due to exceeding header count limit
  5956. cli_.set_keep_alive(true);
  5957. auto res = cli_.Get("/hi", headers);
  5958. // The server should respond with 400 Bad Request
  5959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5960. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5961. EXPECT_EQ("close", res->get_header_value("Connection"));
  5962. EXPECT_FALSE(cli_.is_socket_open());
  5963. }
  5964. TEST_F(ServerTest, PercentEncoding) {
  5965. auto res = cli_.Get("/e%6edwith%");
  5966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5967. EXPECT_EQ(StatusCode::OK_200, res->status);
  5968. }
  5969. TEST_F(ServerTest, PercentEncodingUnicode) {
  5970. auto res = cli_.Get("/e%u006edwith%");
  5971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5972. EXPECT_EQ(StatusCode::OK_200, res->status);
  5973. }
  5974. TEST_F(ServerTest, InvalidPercentEncoding) {
  5975. auto res = cli_.Get("/%endwith%");
  5976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5977. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5978. }
  5979. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5980. auto res = cli_.Get("/%uendwith%");
  5981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5982. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5983. }
  5984. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5985. auto res = cli_.Get("/hello?aaa=bbb%");
  5986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5987. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5988. }
  5989. TEST_F(ServerTest, PlusSignEncoding) {
  5990. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5992. EXPECT_EQ(StatusCode::OK_200, res->status);
  5993. EXPECT_EQ("a +b", res->body);
  5994. }
  5995. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5996. // This test simulates a potential DoS attack using many headers
  5997. // to verify our security fix prevents memory exhaustion
  5998. httplib::Headers attack_headers;
  5999. // Attempt to add many headers like an attacker would (200 headers to far
  6000. // exceed limit)
  6001. for (int i = 0; i < 200; i++) {
  6002. std::string name = "X-Attack-Header-" + std::to_string(i);
  6003. std::string value = "attack_payload_" + std::to_string(i);
  6004. attack_headers.emplace(name, value);
  6005. }
  6006. // Try to POST with excessive headers
  6007. cli_.set_keep_alive(true);
  6008. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6009. // Should either fail or return 400 Bad Request due to security limit
  6010. if (res) {
  6011. // If we get a response, it should be 400 Bad Request
  6012. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6013. EXPECT_EQ("close", res->get_header_value("Connection"));
  6014. }
  6015. EXPECT_FALSE(cli_.is_socket_open());
  6016. }
  6017. TEST_F(ServerTest, MultipartFormData) {
  6018. UploadFormDataItems items = {
  6019. {"text1", "text default", "", ""},
  6020. {"text2", "aωb", "", ""},
  6021. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6022. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6023. {"file3", "", "", "application/octet-stream"},
  6024. {"file4", "", "", " application/json tmp-string "}};
  6025. auto res = cli_.Post("/multipart", items);
  6026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6027. EXPECT_EQ(StatusCode::OK_200, res->status);
  6028. }
  6029. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6030. UploadFormDataItems items = {
  6031. {"text", "default text", "", ""},
  6032. {"multi_text1", "aaaaa", "", ""},
  6033. {"multi_text1", "bbbbb", "", ""},
  6034. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6035. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6036. "application/json"},
  6037. };
  6038. auto res = cli_.Post("/multipart/multi_file_values", items);
  6039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6040. EXPECT_EQ(StatusCode::OK_200, res->status);
  6041. }
  6042. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6043. auto res = cli_.Get("/hi");
  6044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6045. EXPECT_EQ(StatusCode::OK_200, res->status);
  6046. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6047. EXPECT_EQ("Hello World!", res->body);
  6048. }
  6049. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6050. Request req;
  6051. req.method = "POST";
  6052. req.path = "/chunked";
  6053. std::string host_and_port;
  6054. host_and_port += HOST;
  6055. host_and_port += ":";
  6056. host_and_port += std::to_string(PORT);
  6057. req.headers.emplace("Host", host_and_port.c_str());
  6058. req.headers.emplace("Accept", "*/*");
  6059. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6060. req.headers.emplace("Content-Type", "text/plain");
  6061. req.headers.emplace("Content-Length", "0");
  6062. req.headers.emplace(
  6063. "Transfer-Encoding",
  6064. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6065. // Client does not chunk, so make a chunked body manually.
  6066. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6067. auto res = std::make_shared<Response>();
  6068. auto error = Error::Success;
  6069. auto ret = cli_.send(req, *res, error);
  6070. ASSERT_TRUE(ret);
  6071. EXPECT_EQ(StatusCode::OK_200, res->status);
  6072. }
  6073. template <typename ClientT>
  6074. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6075. int expected_status) {
  6076. Request req;
  6077. req.method = "POST";
  6078. req.path = "/chunked";
  6079. std::string host_and_port;
  6080. host_and_port += HOST;
  6081. host_and_port += ":";
  6082. host_and_port += std::to_string(PORT);
  6083. req.headers.emplace("Host", host_and_port.c_str());
  6084. req.headers.emplace("Content-Length", "0");
  6085. req.headers.emplace("Transfer-Encoding", "chunked");
  6086. req.body = body;
  6087. auto res = std::make_shared<Response>();
  6088. auto error = Error::Success;
  6089. ASSERT_TRUE(cli.send(req, *res, error));
  6090. EXPECT_EQ(expected_status, res->status);
  6091. }
  6092. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6093. // rather than treat them as valid lengths.
  6094. template <typename ClientT>
  6095. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6096. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6097. }
  6098. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6099. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6100. }
  6101. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6102. expect_chunked_body_rejected(
  6103. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6104. }
  6105. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6106. // chunk-size line carries no CR, LF or other control character ahead of its
  6107. // terminator. Such a line must be refused rather than read as extension text.
  6108. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6109. expect_chunked_body_rejected(
  6110. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6111. }
  6112. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6113. expect_chunked_body_rejected(
  6114. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6115. }
  6116. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6117. expect_chunked_body_rejected(
  6118. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6119. }
  6120. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6121. // The literal stays split: a hex escape consumes every hex digit that
  6122. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6123. expect_chunked_body_rejected(
  6124. cli_, "4;a\x01"
  6125. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6126. }
  6127. TEST_F(ServerTest, AcceptsChunkExtension) {
  6128. expect_chunked_body_status(cli_,
  6129. "4;name=value\r\ndech\r\n"
  6130. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6131. "0;last\r\n\r\n",
  6132. StatusCode::OK_200);
  6133. }
  6134. TEST_F(ServerTest, GetStreamed2) {
  6135. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6137. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6138. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6139. EXPECT_EQ(true, res->has_header("Content-Range"));
  6140. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6141. EXPECT_EQ(std::string("ab"), res->body);
  6142. }
  6143. TEST_F(ServerTest, GetStreamed) {
  6144. auto res = cli_.Get("/streamed");
  6145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6146. EXPECT_EQ(StatusCode::OK_200, res->status);
  6147. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6148. EXPECT_EQ(std::string("aaabbb"), res->body);
  6149. }
  6150. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6151. auto res = cli_.Get("/streamed-without-length",
  6152. Headers{make_range_header({{0, -1}})});
  6153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6154. EXPECT_EQ(StatusCode::OK_200, res->status);
  6155. EXPECT_EQ(false, res->has_header("Content-Length"));
  6156. EXPECT_EQ(false, res->has_header("Content-Range"));
  6157. EXPECT_EQ(std::string("abcdefg"), res->body);
  6158. }
  6159. TEST_F(ServerTest, GetStreamedWithRange1) {
  6160. auto res =
  6161. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6163. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6164. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6165. EXPECT_EQ(true, res->has_header("Content-Range"));
  6166. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6167. EXPECT_EQ(std::string("def"), res->body);
  6168. }
  6169. TEST_F(ServerTest, GetStreamedWithRange2) {
  6170. auto res =
  6171. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6173. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6174. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6175. EXPECT_EQ(true, res->has_header("Content-Range"));
  6176. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6177. EXPECT_EQ(std::string("bcdefg"), res->body);
  6178. }
  6179. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6180. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6182. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6183. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6184. EXPECT_EQ(true, res->has_header("Content-Range"));
  6185. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6186. EXPECT_EQ(std::string("efg"), res->body);
  6187. }
  6188. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6189. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6190. // the entire representation.
  6191. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6192. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6194. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6195. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6196. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6197. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6198. }
  6199. }
  6200. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6201. auto res =
  6202. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6204. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6205. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6206. EXPECT_EQ(false, res->has_header("Content-Range"));
  6207. EXPECT_EQ(0U, res->body.size());
  6208. }
  6209. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6210. // Only a 206 is served as a partial representation. Under any other status
  6211. // `apply_ranges()` reported the full content length, so the body must match
  6212. // that header, and the content provider must never be asked for an offset
  6213. // outside the representation.
  6214. auto check = [&](int status, const char *range) {
  6215. auto path =
  6216. std::string("/streamed-with-range?status=") + std::to_string(status);
  6217. auto ctx = path + " Range: " + range;
  6218. auto res = cli_.Get(path, Headers{{"Range", range}});
  6219. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6220. EXPECT_EQ(status, res->status) << ctx;
  6221. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6222. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6223. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6224. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6225. };
  6226. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6227. check(403, "bytes=3-5");
  6228. // The offset is far past the representation.
  6229. check(403, "bytes=100000-100200");
  6230. // `first_pos` is still -1 here, and the bounds asserts in
  6231. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6232. check(403, "bytes=-3");
  6233. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6234. // multipart branch would have written one that is empty.
  6235. check(403, "bytes=1-2, 4-5");
  6236. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6237. // covers the whole representation.
  6238. check(200, "bytes=3-5");
  6239. check(200, "bytes=1-2, 4-5");
  6240. }
  6241. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6242. auto res =
  6243. cli_.Get("/streamed-with-range",
  6244. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6245. "92233720368547758079223372036854775807"}});
  6246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6247. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6248. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6249. EXPECT_EQ(false, res->has_header("Content-Range"));
  6250. EXPECT_EQ(0U, res->body.size());
  6251. }
  6252. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6253. auto res = cli_.Get(
  6254. "/with-range",
  6255. Headers{{"Range",
  6256. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6257. {"Accept-Encoding", ""}});
  6258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6259. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6260. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6261. EXPECT_EQ(true, res->has_header("Content-Range"));
  6262. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6263. EXPECT_EQ(std::string("abcdefg"), res->body);
  6264. }
  6265. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6266. auto res = cli_.Get("/with-range", Headers{
  6267. {"Range", "bytes=0-"},
  6268. {"Accept-Encoding", ""},
  6269. });
  6270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6271. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6272. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6273. EXPECT_EQ(true, res->has_header("Content-Range"));
  6274. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6275. EXPECT_EQ(std::string("abcdefg"), res->body);
  6276. }
  6277. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6278. auto res = cli_.Get("/streamed-with-range",
  6279. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6281. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6282. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6283. EXPECT_EQ(false, res->has_header("Content-Range"));
  6284. EXPECT_EQ(267U, res->body.size());
  6285. // Check that both range contents are present
  6286. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6287. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6288. // Check that Content-Range headers are present for both ranges
  6289. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6290. std::string::npos);
  6291. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6292. std::string::npos);
  6293. }
  6294. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6295. Ranges ranges;
  6296. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6297. ranges.emplace_back(0, -1);
  6298. }
  6299. auto res = cli_.Get("/streamed-with-range?error",
  6300. Headers{{make_range_header(ranges)}});
  6301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6302. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6303. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6304. EXPECT_EQ(false, res->has_header("Content-Range"));
  6305. EXPECT_EQ(0U, res->body.size());
  6306. }
  6307. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6308. auto res = cli_.Get("/streamed-with-range",
  6309. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6311. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6312. EXPECT_EQ(5U, res->body.size());
  6313. // Check that overlapping ranges are coalesced into a single range
  6314. EXPECT_EQ("bcdef", res->body);
  6315. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6316. // Should be single range, not multipart
  6317. EXPECT_TRUE(res->has_header("Content-Range"));
  6318. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6319. }
  6320. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6321. auto res = cli_.Get("/streamed-with-range",
  6322. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6324. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6325. EXPECT_EQ(268U, res->body.size());
  6326. // Check that both range contents are present
  6327. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6328. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6329. // Check that Content-Range headers are present for both ranges
  6330. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6331. std::string::npos);
  6332. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6333. std::string::npos);
  6334. }
  6335. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6336. auto res = cli_.Get("/streamed-with-range",
  6337. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6339. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6340. EXPECT_EQ(269U, res->body.size());
  6341. // Check that both duplicate range contents are present
  6342. size_t first_abc = res->body.find("abc\r\n");
  6343. EXPECT_TRUE(first_abc != std::string::npos);
  6344. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6345. EXPECT_TRUE(second_abc != std::string::npos);
  6346. // Check that Content-Range headers are present for both ranges
  6347. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6348. EXPECT_TRUE(first_range != std::string::npos);
  6349. size_t second_range =
  6350. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6351. EXPECT_TRUE(second_range != std::string::npos);
  6352. }
  6353. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6354. auto res =
  6355. cli_.Get("/streamed-with-range?error",
  6356. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6358. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6359. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6360. EXPECT_EQ(false, res->has_header("Content-Range"));
  6361. EXPECT_EQ(0U, res->body.size());
  6362. }
  6363. TEST_F(ServerTest, GetStreamedEndless) {
  6364. uint64_t offset = 0;
  6365. auto res = cli_.Get("/streamed-cancel",
  6366. [&](const char * /*data*/, uint64_t data_length) {
  6367. if (offset < 100) {
  6368. offset += data_length;
  6369. return true;
  6370. }
  6371. return false;
  6372. });
  6373. ASSERT_TRUE(!res);
  6374. EXPECT_EQ(Error::Canceled, res.error());
  6375. }
  6376. TEST_F(ServerTest, ClientStop) {
  6377. std::atomic_size_t count{4};
  6378. std::vector<std::thread> threads;
  6379. for (auto i = count.load(); i != 0; --i) {
  6380. threads.emplace_back([&]() {
  6381. auto res = cli_.Get("/streamed-cancel",
  6382. [&](const char *, uint64_t) { return true; });
  6383. --count;
  6384. ASSERT_TRUE(!res);
  6385. EXPECT_TRUE(res.error() == Error::Canceled ||
  6386. res.error() == Error::Read || res.error() == Error::Write);
  6387. });
  6388. }
  6389. std::this_thread::sleep_for(std::chrono::seconds(2));
  6390. while (count != 0) {
  6391. cli_.stop();
  6392. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6393. }
  6394. for (auto &t : threads) {
  6395. t.join();
  6396. }
  6397. }
  6398. TEST_F(ServerTest, GetWithRange1) {
  6399. auto res = cli_.Get("/with-range", Headers{
  6400. make_range_header({{3, 5}}),
  6401. {"Accept-Encoding", ""},
  6402. });
  6403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6404. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6405. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6406. EXPECT_EQ(true, res->has_header("Content-Range"));
  6407. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6408. EXPECT_EQ(std::string("def"), res->body);
  6409. }
  6410. TEST_F(ServerTest, GetWithRange2) {
  6411. auto res = cli_.Get("/with-range", Headers{
  6412. make_range_header({{1, -1}}),
  6413. {"Accept-Encoding", ""},
  6414. });
  6415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6416. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6417. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6418. EXPECT_EQ(true, res->has_header("Content-Range"));
  6419. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6420. EXPECT_EQ(std::string("bcdefg"), res->body);
  6421. }
  6422. TEST_F(ServerTest, GetWithRange3) {
  6423. auto res = cli_.Get("/with-range", Headers{
  6424. make_range_header({{0, 0}}),
  6425. {"Accept-Encoding", ""},
  6426. });
  6427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6428. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6429. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6430. EXPECT_EQ(true, res->has_header("Content-Range"));
  6431. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6432. EXPECT_EQ(std::string("a"), res->body);
  6433. }
  6434. TEST_F(ServerTest, GetWithRange4) {
  6435. auto res = cli_.Get("/with-range", Headers{
  6436. make_range_header({{-1, 2}}),
  6437. {"Accept-Encoding", ""},
  6438. });
  6439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6440. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6441. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6442. EXPECT_EQ(true, res->has_header("Content-Range"));
  6443. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6444. EXPECT_EQ(std::string("fg"), res->body);
  6445. }
  6446. TEST_F(ServerTest, GetWithRange5) {
  6447. auto res = cli_.Get("/with-range", Headers{
  6448. make_range_header({{0, 5}}),
  6449. {"Accept-Encoding", ""},
  6450. });
  6451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6452. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6453. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6454. EXPECT_EQ(true, res->has_header("Content-Range"));
  6455. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6456. EXPECT_EQ(std::string("abcdef"), res->body);
  6457. }
  6458. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6459. auto res =
  6460. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6462. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6463. }
  6464. TEST_F(ServerTest, GetWithRangeMultipart) {
  6465. auto res =
  6466. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6468. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6469. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6470. EXPECT_EQ(false, res->has_header("Content-Range"));
  6471. EXPECT_EQ(267U, res->body.size());
  6472. }
  6473. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6474. auto res = cli_.Get("/with-range",
  6475. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6477. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6478. }
  6479. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6480. auto res = cli_.Get("/with-range-customized-response",
  6481. Headers{{make_range_header({{1, 2}})}});
  6482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6483. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6484. EXPECT_EQ(true, res->has_header("Content-Length"));
  6485. EXPECT_EQ(false, res->has_header("Content-Range"));
  6486. EXPECT_EQ(JSON_DATA, res->body);
  6487. }
  6488. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6489. auto res = cli_.Get("/with-range-customized-response",
  6490. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6492. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6493. EXPECT_EQ(true, res->has_header("Content-Length"));
  6494. EXPECT_EQ(false, res->has_header("Content-Range"));
  6495. EXPECT_EQ(JSON_DATA, res->body);
  6496. }
  6497. TEST_F(ServerTest, Issue1772) {
  6498. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6500. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6501. }
  6502. TEST_F(ServerTest, Issue609) {
  6503. auto res = cli_.Delete("/issue609");
  6504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6505. EXPECT_EQ(StatusCode::OK_200, res->status);
  6506. EXPECT_EQ(std::string("ok"), res->body);
  6507. }
  6508. TEST_F(ServerTest, GetStreamedChunked) {
  6509. auto res = cli_.Get("/streamed-chunked");
  6510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6511. EXPECT_EQ(StatusCode::OK_200, res->status);
  6512. EXPECT_EQ(std::string("123456789"), res->body);
  6513. }
  6514. TEST_F(ServerTest, GetStreamedChunked2) {
  6515. auto res = cli_.Get("/streamed-chunked2");
  6516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6517. EXPECT_EQ(StatusCode::OK_200, res->status);
  6518. EXPECT_EQ(std::string("123456789"), res->body);
  6519. }
  6520. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6521. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6523. EXPECT_EQ(StatusCode::OK_200, res->status);
  6524. EXPECT_EQ(std::string("123456789"), res->body);
  6525. EXPECT_TRUE(res->has_header("Trailer"));
  6526. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6527. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6528. // Trailers are now stored separately from headers (security fix)
  6529. EXPECT_EQ(2U, res->trailers.size());
  6530. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6531. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6532. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6533. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6534. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6535. // Verify trailers are NOT in headers (security verification)
  6536. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6537. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6538. }
  6539. TEST_F(ServerTest, LargeChunkedPost) {
  6540. Request req;
  6541. req.method = "POST";
  6542. req.path = "/large-chunked";
  6543. std::string host_and_port;
  6544. host_and_port += HOST;
  6545. host_and_port += ":";
  6546. host_and_port += std::to_string(PORT);
  6547. req.headers.emplace("Host", host_and_port.c_str());
  6548. req.headers.emplace("Accept", "*/*");
  6549. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6550. req.headers.emplace("Content-Type", "text/plain");
  6551. req.headers.emplace("Content-Length", "0");
  6552. req.headers.emplace("Transfer-Encoding", "chunked");
  6553. std::string long_string(30 * 1024u, 'a');
  6554. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6555. // Attempt to make a large enough post to exceed OS buffers, to test that
  6556. // the server handles short reads if the full chunk data isn't available.
  6557. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6558. auto res = std::make_shared<Response>();
  6559. auto error = Error::Success;
  6560. auto ret = cli_.send(req, *res, error);
  6561. ASSERT_TRUE(ret);
  6562. EXPECT_EQ(StatusCode::OK_200, res->status);
  6563. }
  6564. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6565. auto res = cli_.Get("/remote_addr");
  6566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6567. EXPECT_EQ(StatusCode::OK_200, res->status);
  6568. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6569. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6570. }
  6571. TEST_F(ServerTest, GetMethodLocalAddr) {
  6572. auto res = cli_.Get("/local_addr");
  6573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6574. EXPECT_EQ(StatusCode::OK_200, res->status);
  6575. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6576. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6577. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6578. }
  6579. TEST_F(ServerTest, HTTPResponseSplitting) {
  6580. auto res = cli_.Get("/http_response_splitting");
  6581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6582. EXPECT_EQ(StatusCode::OK_200, res->status);
  6583. }
  6584. TEST_F(ServerTest, SlowRequest) {
  6585. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6586. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6587. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6588. }
  6589. #if 0
  6590. TEST_F(ServerTest, SlowPost) {
  6591. char buffer[64 * 1024];
  6592. memset(buffer, 0x42, sizeof(buffer));
  6593. auto res = cli_.Post(
  6594. "/slowpost", 64 * 1024 * 1024,
  6595. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6596. auto ret = sink.write(buffer, sizeof(buffer));
  6597. EXPECT_TRUE(ret);
  6598. return true;
  6599. },
  6600. "text/plain");
  6601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6602. EXPECT_EQ(StatusCode::OK_200, res->status);
  6603. }
  6604. TEST_F(ServerTest, SlowPostFail) {
  6605. char buffer[64 * 1024];
  6606. memset(buffer, 0x42, sizeof(buffer));
  6607. cli_.set_write_timeout(std::chrono::seconds(0));
  6608. auto res = cli_.Post(
  6609. "/slowpost", 64 * 1024 * 1024,
  6610. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6611. sink.write(buffer, sizeof(buffer));
  6612. return true;
  6613. },
  6614. "text/plain");
  6615. ASSERT_TRUE(!res);
  6616. EXPECT_EQ(Error::Write, res.error());
  6617. }
  6618. #endif
  6619. TEST_F(ServerTest, Put) {
  6620. auto res = cli_.Put("/put", "PUT", "text/plain");
  6621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6622. EXPECT_EQ(StatusCode::OK_200, res->status);
  6623. EXPECT_EQ("PUT", res->body);
  6624. }
  6625. TEST_F(ServerTest, PutWithContentProvider) {
  6626. auto res = cli_.Put(
  6627. "/put", 3,
  6628. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6629. sink.os << "PUT";
  6630. return true;
  6631. },
  6632. "text/plain");
  6633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6634. EXPECT_EQ(StatusCode::OK_200, res->status);
  6635. EXPECT_EQ("PUT", res->body);
  6636. }
  6637. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6638. auto res = cli_.Post(
  6639. "/post", 42,
  6640. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6641. return false;
  6642. },
  6643. "text/plain");
  6644. ASSERT_TRUE(!res);
  6645. EXPECT_EQ(Error::Canceled, res.error());
  6646. }
  6647. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6648. auto res = cli_.Put(
  6649. "/put",
  6650. [](size_t /*offset*/, DataSink &sink) {
  6651. sink.os << "PUT";
  6652. sink.done();
  6653. return true;
  6654. },
  6655. "text/plain");
  6656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6657. EXPECT_EQ(StatusCode::OK_200, res->status);
  6658. EXPECT_EQ("PUT", res->body);
  6659. }
  6660. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6661. auto res = cli_.Post(
  6662. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6663. "text/plain");
  6664. ASSERT_TRUE(!res);
  6665. EXPECT_EQ(Error::Canceled, res.error());
  6666. }
  6667. TEST_F(ServerTest, PostLoopBack) {
  6668. std::string body;
  6669. auto res = cli_.Post(
  6670. "/post-loopback", 9,
  6671. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6672. EXPECT_EQ(9u, length);
  6673. sink.write("123", 3);
  6674. sink.write("456", 3);
  6675. sink.write("789", 3);
  6676. return true;
  6677. },
  6678. "text/plain",
  6679. [&body](const char *data, size_t data_length) {
  6680. body.append(data, data_length);
  6681. return true;
  6682. });
  6683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6684. EXPECT_EQ(StatusCode::OK_200, res->status);
  6685. EXPECT_EQ("123456789", body);
  6686. }
  6687. TEST_F(ServerTest, PutLoopBack) {
  6688. std::string body;
  6689. auto res = cli_.Put(
  6690. "/put-loopback", 9,
  6691. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6692. EXPECT_EQ(9u, length);
  6693. sink.write("123", 3);
  6694. sink.write("456", 3);
  6695. sink.write("789", 3);
  6696. return true;
  6697. },
  6698. "text/plain",
  6699. [&body](const char *data, size_t data_length) {
  6700. body.append(data, data_length);
  6701. return true;
  6702. });
  6703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6704. EXPECT_EQ(StatusCode::OK_200, res->status);
  6705. EXPECT_EQ("123456789", body);
  6706. }
  6707. TEST_F(ServerTest, PatchLoopBack) {
  6708. std::string body;
  6709. auto res = cli_.Patch(
  6710. "/patch-loopback", 9,
  6711. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6712. EXPECT_EQ(9u, length);
  6713. sink.write("123", 3);
  6714. sink.write("456", 3);
  6715. sink.write("789", 3);
  6716. return true;
  6717. },
  6718. "text/plain",
  6719. [&body](const char *data, size_t data_length) {
  6720. body.append(data, data_length);
  6721. return true;
  6722. });
  6723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6724. EXPECT_EQ(StatusCode::OK_200, res->status);
  6725. EXPECT_EQ("123456789", body);
  6726. }
  6727. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6728. std::string body;
  6729. auto res = cli_.Post(
  6730. "/post-loopback",
  6731. [](size_t /*offset*/, DataSink &sink) {
  6732. sink.write("123", 3);
  6733. sink.write("456", 3);
  6734. sink.write("789", 3);
  6735. sink.done();
  6736. return true;
  6737. },
  6738. "text/plain",
  6739. [&body](const char *data, size_t data_length) {
  6740. body.append(data, data_length);
  6741. return true;
  6742. });
  6743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6744. EXPECT_EQ(StatusCode::OK_200, res->status);
  6745. EXPECT_EQ("123456789", body);
  6746. }
  6747. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6748. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6749. cli_.set_compress(true);
  6750. auto res = cli_.Put(
  6751. "/put", 3,
  6752. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6753. sink.os << "PUT";
  6754. return true;
  6755. },
  6756. "text/plain");
  6757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6758. EXPECT_EQ(StatusCode::OK_200, res->status);
  6759. EXPECT_EQ("PUT", res->body);
  6760. }
  6761. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6762. cli_.set_compress(true);
  6763. auto res = cli_.Post(
  6764. "/post", 42,
  6765. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6766. return false;
  6767. },
  6768. "text/plain");
  6769. ASSERT_TRUE(!res);
  6770. EXPECT_EQ(Error::Canceled, res.error());
  6771. }
  6772. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6773. cli_.set_compress(true);
  6774. auto res = cli_.Put(
  6775. "/put",
  6776. [](size_t /*offset*/, DataSink &sink) {
  6777. sink.os << "PUT";
  6778. sink.done();
  6779. return true;
  6780. },
  6781. "text/plain");
  6782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6783. EXPECT_EQ(StatusCode::OK_200, res->status);
  6784. EXPECT_EQ("PUT", res->body);
  6785. }
  6786. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6787. cli_.set_compress(true);
  6788. auto res = cli_.Post(
  6789. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6790. "text/plain");
  6791. ASSERT_TRUE(!res);
  6792. EXPECT_EQ(Error::Canceled, res.error());
  6793. }
  6794. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6795. cli_.set_compress(true);
  6796. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6798. EXPECT_EQ(StatusCode::OK_200, res->status);
  6799. EXPECT_EQ(LARGE_DATA, res->body);
  6800. }
  6801. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6802. #ifdef CPPHTTPLIB_SSL_ENABLED
  6803. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6804. Client cli(s.c_str());
  6805. cli.enable_server_certificate_verification(false);
  6806. #else
  6807. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6808. Client cli(s.c_str());
  6809. #endif
  6810. cli.set_compress(true);
  6811. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6813. EXPECT_EQ(StatusCode::OK_200, res->status);
  6814. EXPECT_EQ(LARGE_DATA, res->body);
  6815. // The compressed size should be less than a 10th of the original. May vary
  6816. // depending on the zlib library.
  6817. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6818. static_cast<uint64_t>(10 * 1024 * 1024));
  6819. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6820. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6821. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6822. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6823. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6824. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6825. #endif
  6826. }
  6827. TEST_F(ServerTest, PutContentWithDeflate) {
  6828. cli_.set_compress(false);
  6829. Headers headers;
  6830. headers.emplace("Content-Encoding", "deflate");
  6831. // PUT in deflate format:
  6832. auto res = cli_.Put("/put", headers,
  6833. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6835. EXPECT_EQ(StatusCode::OK_200, res->status);
  6836. EXPECT_EQ("PUT", res->body);
  6837. }
  6838. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6839. Headers headers;
  6840. headers.emplace("Accept-Encoding", "gzip, deflate");
  6841. auto res = cli_.Get("/streamed-chunked", headers);
  6842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6843. EXPECT_EQ(StatusCode::OK_200, res->status);
  6844. EXPECT_EQ(std::string("123456789"), res->body);
  6845. }
  6846. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6847. Headers headers;
  6848. headers.emplace("Accept-Encoding", "gzip, deflate");
  6849. auto res = cli_.Get("/streamed-chunked2", headers);
  6850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6851. EXPECT_EQ(StatusCode::OK_200, res->status);
  6852. EXPECT_EQ(std::string("123456789"), res->body);
  6853. }
  6854. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6855. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6857. EXPECT_EQ(StatusCode::OK_200, res->status);
  6858. }
  6859. TEST(GzipDecompressor, ChunkedDecompression) {
  6860. std::string data;
  6861. for (size_t i = 0; i < 32 * 1024; ++i) {
  6862. data.push_back(static_cast<char>('a' + i % 26));
  6863. }
  6864. std::string compressed_data;
  6865. {
  6866. httplib::detail::gzip_compressor compressor;
  6867. bool result = compressor.compress(
  6868. data.data(), data.size(),
  6869. /*last=*/true,
  6870. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6871. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6872. compressed_data_size);
  6873. return true;
  6874. });
  6875. ASSERT_TRUE(result);
  6876. }
  6877. std::string decompressed_data;
  6878. {
  6879. httplib::detail::gzip_decompressor decompressor;
  6880. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6881. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6882. size_t chunk_size = 130;
  6883. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6884. chunk_begin += chunk_size) {
  6885. size_t current_chunk_size =
  6886. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6887. bool result = decompressor.decompress(
  6888. compressed_data.data() + chunk_begin, current_chunk_size,
  6889. [&](const char *decompressed_data_chunk,
  6890. size_t decompressed_data_chunk_size) {
  6891. decompressed_data.insert(decompressed_data.size(),
  6892. decompressed_data_chunk,
  6893. decompressed_data_chunk_size);
  6894. return true;
  6895. });
  6896. ASSERT_TRUE(result);
  6897. }
  6898. }
  6899. ASSERT_EQ(data, decompressed_data);
  6900. }
  6901. TEST(GzipDecompressor, DeflateDecompression) {
  6902. std::string original_text = "Raw deflate without gzip";
  6903. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6904. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6905. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6906. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6907. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6908. std::string decompressed_data;
  6909. {
  6910. httplib::detail::gzip_decompressor decompressor;
  6911. bool result = decompressor.decompress(
  6912. compressed_data.data(), compressed_data.size(),
  6913. [&](const char *decompressed_data_chunk,
  6914. size_t decompressed_data_chunk_size) {
  6915. decompressed_data.insert(decompressed_data.size(),
  6916. decompressed_data_chunk,
  6917. decompressed_data_chunk_size);
  6918. return true;
  6919. });
  6920. ASSERT_TRUE(result);
  6921. }
  6922. ASSERT_EQ(original_text, decompressed_data);
  6923. }
  6924. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6925. std::string original_text = "Raw deflate without gzip";
  6926. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6927. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6928. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6929. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6930. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6931. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6932. std::string decompressed_data;
  6933. {
  6934. httplib::detail::gzip_decompressor decompressor;
  6935. bool result = decompressor.decompress(
  6936. compressed_data.data(), compressed_data.size(),
  6937. [&](const char *decompressed_data_chunk,
  6938. size_t decompressed_data_chunk_size) {
  6939. decompressed_data.insert(decompressed_data.size(),
  6940. decompressed_data_chunk,
  6941. decompressed_data_chunk_size);
  6942. return true;
  6943. });
  6944. ASSERT_TRUE(result);
  6945. }
  6946. ASSERT_EQ(original_text, decompressed_data);
  6947. }
  6948. #endif
  6949. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6950. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6951. Headers headers;
  6952. headers.emplace("Accept-Encoding", "br");
  6953. auto res = cli_.Get("/streamed-chunked", headers);
  6954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6955. EXPECT_EQ(StatusCode::OK_200, res->status);
  6956. EXPECT_EQ(std::string("123456789"), res->body);
  6957. }
  6958. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6959. Headers headers;
  6960. headers.emplace("Accept-Encoding", "br");
  6961. auto res = cli_.Get("/streamed-chunked2", headers);
  6962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6963. EXPECT_EQ(StatusCode::OK_200, res->status);
  6964. EXPECT_EQ(std::string("123456789"), res->body);
  6965. }
  6966. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6967. cli_.set_compress(true);
  6968. auto res = cli_.Put(
  6969. "/put", 3,
  6970. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6971. sink.os << "PUT";
  6972. return true;
  6973. },
  6974. "text/plain");
  6975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6976. EXPECT_EQ(StatusCode::OK_200, res->status);
  6977. EXPECT_EQ("PUT", res->body);
  6978. }
  6979. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6980. cli_.set_compress(true);
  6981. auto res = cli_.Put(
  6982. "/put",
  6983. [](size_t /*offset*/, DataSink &sink) {
  6984. sink.os << "PUT";
  6985. sink.done();
  6986. return true;
  6987. },
  6988. "text/plain");
  6989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6990. EXPECT_EQ(StatusCode::OK_200, res->status);
  6991. EXPECT_EQ("PUT", res->body);
  6992. }
  6993. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6994. cli_.set_compress(true);
  6995. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6997. EXPECT_EQ(StatusCode::OK_200, res->status);
  6998. EXPECT_EQ(LARGE_DATA, res->body);
  6999. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7000. }
  7001. #endif
  7002. TEST_F(ServerTest, Patch) {
  7003. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7005. EXPECT_EQ(StatusCode::OK_200, res->status);
  7006. EXPECT_EQ("PATCH", res->body);
  7007. }
  7008. TEST_F(ServerTest, Delete) {
  7009. auto res = cli_.Delete("/delete");
  7010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7011. EXPECT_EQ(StatusCode::OK_200, res->status);
  7012. EXPECT_EQ("DELETE", res->body);
  7013. }
  7014. TEST_F(ServerTest, DeleteContentReceiver) {
  7015. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7017. EXPECT_EQ(StatusCode::OK_200, res->status);
  7018. EXPECT_EQ("content", res->body);
  7019. }
  7020. TEST_F(ServerTest, Options) {
  7021. auto res = cli_.Options("*");
  7022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7023. EXPECT_EQ(StatusCode::OK_200, res->status);
  7024. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7025. EXPECT_TRUE(res->body.empty());
  7026. }
  7027. TEST_F(ServerTest, URL) {
  7028. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7030. EXPECT_EQ(StatusCode::OK_200, res->status);
  7031. }
  7032. TEST_F(ServerTest, ArrayParam) {
  7033. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7035. EXPECT_EQ(StatusCode::OK_200, res->status);
  7036. }
  7037. TEST_F(ServerTest, ArrayParamValues) {
  7038. auto res =
  7039. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7041. EXPECT_EQ(StatusCode::OK_200, res->status);
  7042. }
  7043. TEST_F(ServerTest, NoMultipleHeaders) {
  7044. Headers headers = {{"Content-Length", "5"}};
  7045. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7046. "text/plain");
  7047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7048. EXPECT_EQ(StatusCode::OK_200, res->status);
  7049. }
  7050. TEST_F(ServerTest, PostContentReceiver) {
  7051. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7053. ASSERT_EQ(StatusCode::OK_200, res->status);
  7054. ASSERT_EQ("content", res->body);
  7055. }
  7056. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7057. UploadFormDataItems items = {
  7058. {"text1", "text default", "", ""},
  7059. {"text2", "aωb", "", ""},
  7060. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7061. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7062. {"file3", "", "", "application/octet-stream"},
  7063. };
  7064. auto res = cli_.Post("/content_receiver", items);
  7065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7066. EXPECT_EQ(StatusCode::OK_200, res->status);
  7067. }
  7068. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7069. UploadFormDataItems items = {
  7070. {"text1", "text default", "", ""},
  7071. {"text2", "aωb", "", ""},
  7072. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7073. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7074. {"file3", "", "", "application/octet-stream"},
  7075. };
  7076. auto boundary = std::string("+++++");
  7077. std::string body;
  7078. for (const auto &item : items) {
  7079. body += "--" + boundary + "\r\n";
  7080. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7081. if (!item.filename.empty()) {
  7082. body += "; filename=\"" + item.filename + "\"";
  7083. }
  7084. body += "\r\n";
  7085. if (!item.content_type.empty()) {
  7086. body += "Content-Type: " + item.content_type + "\r\n";
  7087. }
  7088. body += "\r\n";
  7089. body += item.content + "\r\n";
  7090. }
  7091. body += "--" + boundary + "--\r\n";
  7092. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7093. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7095. EXPECT_EQ(StatusCode::OK_200, res->status);
  7096. }
  7097. TEST(MultipartFormDataTest, FieldEscaping) {
  7098. Server svr;
  7099. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7100. const ContentReader &content_reader) {
  7101. ASSERT_TRUE(req.is_multipart_form_data());
  7102. std::vector<FormData> received;
  7103. content_reader(
  7104. [&](const FormData &file) {
  7105. received.push_back(file);
  7106. return true;
  7107. },
  7108. [&](const char *data, size_t data_length) {
  7109. received.back().content.append(data, data_length);
  7110. return true;
  7111. });
  7112. // '"', CR and LF in names and filenames are escaped following the
  7113. // WHATWG HTML standard, so each part still parses as a single part
  7114. // with no injected headers. Content types get CR/LF escaped too,
  7115. // while '"' (legal there, e.g. quoted charset) is preserved.
  7116. ASSERT_EQ(4U, received.size());
  7117. EXPECT_EQ("na%22me", received[0].name);
  7118. EXPECT_EQ("quoted name", received[0].content);
  7119. EXPECT_EQ("file", received[1].name);
  7120. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7121. received[1].filename);
  7122. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7123. EXPECT_EQ("injected", received[1].content);
  7124. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7125. EXPECT_EQ("my%22file.txt", received[2].filename);
  7126. EXPECT_EQ("cr lf name", received[2].content);
  7127. EXPECT_EQ("typed", received[3].name);
  7128. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7129. received[3].content_type);
  7130. EXPECT_EQ("typed content", received[3].content);
  7131. });
  7132. auto port = svr.bind_to_any_port("localhost");
  7133. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7134. auto se = detail::scope_exit([&] {
  7135. svr.stop();
  7136. t.join();
  7137. ASSERT_FALSE(svr.is_running());
  7138. });
  7139. svr.wait_until_ready();
  7140. Client cli("localhost", port);
  7141. UploadFormDataItems items = {
  7142. {"na\"me", "quoted name", "", ""},
  7143. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7144. "application/octet-stream"},
  7145. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7146. {"typed", "typed content", "",
  7147. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7148. };
  7149. auto res = cli.Post("/post", items);
  7150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7151. EXPECT_EQ(StatusCode::OK_200, res->status);
  7152. }
  7153. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7154. const UploadFormDataItems items = {
  7155. {"name1", "Content 1", "", ""},
  7156. {"name2", "Content 2", "file2.txt", "text/plain"},
  7157. };
  7158. Server svr;
  7159. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7160. const ContentReader &content_reader) {
  7161. ASSERT_TRUE(req.is_multipart_form_data());
  7162. std::vector<FormData> received;
  7163. content_reader(
  7164. [&](const FormData &file) {
  7165. received.push_back(file);
  7166. return true;
  7167. },
  7168. [&](const char *data, size_t data_length) {
  7169. received.back().content.append(data, data_length);
  7170. return true;
  7171. });
  7172. ASSERT_EQ(2U, received.size());
  7173. EXPECT_EQ("name1", received[0].name);
  7174. EXPECT_EQ("Content 1", received[0].content);
  7175. EXPECT_EQ("name2", received[1].name);
  7176. EXPECT_EQ("Content 2", received[1].content);
  7177. EXPECT_EQ("file2.txt", received[1].filename);
  7178. EXPECT_EQ("text/plain", received[1].content_type);
  7179. });
  7180. auto port = svr.bind_to_any_port("localhost");
  7181. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7182. auto se = detail::scope_exit([&] {
  7183. svr.stop();
  7184. t.join();
  7185. ASSERT_FALSE(svr.is_running());
  7186. });
  7187. svr.wait_until_ready();
  7188. Client cli("localhost", port);
  7189. // Whole-body serialization with a generated boundary
  7190. {
  7191. MultipartFormDataWriter writer;
  7192. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7193. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7194. writer.content_type());
  7195. auto body = writer.serialize(items);
  7196. EXPECT_EQ(body.size(), writer.content_length(items));
  7197. auto res = cli.Post("/post", body, writer.content_type());
  7198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7199. EXPECT_EQ(StatusCode::OK_200, res->status);
  7200. }
  7201. // Per-part framing with a custom boundary via a content provider
  7202. {
  7203. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7204. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7205. MultipartFormDataWriter writer("custom-boundary_123");
  7206. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7207. std::string body;
  7208. for (const auto &item : items) {
  7209. body += writer.item_begin(item);
  7210. body += item.content;
  7211. body += MultipartFormDataWriter::item_end();
  7212. }
  7213. body += writer.finish();
  7214. EXPECT_EQ(body.size(), writer.content_length(items));
  7215. auto res = cli.Post(
  7216. "/post", body.size(),
  7217. [&](size_t offset, size_t length, DataSink &sink) {
  7218. sink.write(body.data() + offset, length);
  7219. return true;
  7220. },
  7221. writer.content_type());
  7222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7223. EXPECT_EQ(StatusCode::OK_200, res->status);
  7224. }
  7225. }
  7226. TEST_F(ServerTest, PostContentReceiverGzip) {
  7227. cli_.set_compress(true);
  7228. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7230. ASSERT_EQ(StatusCode::OK_200, res->status);
  7231. ASSERT_EQ("content", res->body);
  7232. }
  7233. TEST_F(ServerTest, PutContentReceiver) {
  7234. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7236. ASSERT_EQ(StatusCode::OK_200, res->status);
  7237. ASSERT_EQ("content", res->body);
  7238. }
  7239. TEST_F(ServerTest, PatchContentReceiver) {
  7240. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7242. ASSERT_EQ(StatusCode::OK_200, res->status);
  7243. ASSERT_EQ("content", res->body);
  7244. }
  7245. template <typename ClientType>
  7246. void TestWithHeadersAndContentReceiver(
  7247. ClientType &cli,
  7248. std::function<Result(ClientType &, const std::string &, const Headers &,
  7249. const std::string &, const std::string &,
  7250. ContentReceiver, DownloadProgress)>
  7251. request_func) {
  7252. Headers headers;
  7253. headers.emplace("X-Custom-Header", "test-value");
  7254. std::string received_body;
  7255. auto res = request_func(
  7256. cli, "/content_receiver", headers, "content", "application/json",
  7257. [&](const char *data, size_t data_length) {
  7258. received_body.append(data, data_length);
  7259. return true;
  7260. },
  7261. nullptr);
  7262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7263. EXPECT_EQ(StatusCode::OK_200, res->status);
  7264. EXPECT_EQ("content", received_body);
  7265. }
  7266. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7267. #ifdef CPPHTTPLIB_SSL_ENABLED
  7268. using ClientT = SSLClient;
  7269. #else
  7270. using ClientT = Client;
  7271. #endif
  7272. TestWithHeadersAndContentReceiver<ClientT>(
  7273. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7274. const std::string &body, const std::string &content_type,
  7275. ContentReceiver receiver, DownloadProgress progress) {
  7276. return cli.Post(path, headers, body, content_type, receiver, progress);
  7277. });
  7278. }
  7279. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7280. #ifdef CPPHTTPLIB_SSL_ENABLED
  7281. using ClientT = SSLClient;
  7282. #else
  7283. using ClientT = Client;
  7284. #endif
  7285. TestWithHeadersAndContentReceiver<ClientT>(
  7286. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7287. const std::string &body, const std::string &content_type,
  7288. ContentReceiver receiver, DownloadProgress progress) {
  7289. return cli.Put(path, headers, body, content_type, receiver, progress);
  7290. });
  7291. }
  7292. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7293. #ifdef CPPHTTPLIB_SSL_ENABLED
  7294. using ClientT = SSLClient;
  7295. #else
  7296. using ClientT = Client;
  7297. #endif
  7298. TestWithHeadersAndContentReceiver<ClientT>(
  7299. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7300. const std::string &body, const std::string &content_type,
  7301. ContentReceiver receiver, DownloadProgress progress) {
  7302. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7303. });
  7304. }
  7305. template <typename ClientType>
  7306. void TestWithHeadersAndContentReceiverWithProgress(
  7307. ClientType &cli,
  7308. std::function<Result(ClientType &, const std::string &, const Headers &,
  7309. const std::string &, const std::string &,
  7310. ContentReceiver, DownloadProgress)>
  7311. request_func) {
  7312. Headers headers;
  7313. headers.emplace("X-Test-Header", "progress-test");
  7314. std::string received_body;
  7315. auto progress_called = false;
  7316. auto res = request_func(
  7317. cli, "/content_receiver", headers, "content", "text/plain",
  7318. [&](const char *data, size_t data_length) {
  7319. received_body.append(data, data_length);
  7320. return true;
  7321. },
  7322. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7323. progress_called = true;
  7324. return true;
  7325. });
  7326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7327. EXPECT_EQ(StatusCode::OK_200, res->status);
  7328. EXPECT_EQ("content", received_body);
  7329. EXPECT_TRUE(progress_called);
  7330. }
  7331. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7332. #ifdef CPPHTTPLIB_SSL_ENABLED
  7333. using ClientT = SSLClient;
  7334. #else
  7335. using ClientT = Client;
  7336. #endif
  7337. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7338. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7339. const std::string &body, const std::string &content_type,
  7340. ContentReceiver receiver, DownloadProgress progress) {
  7341. return cli.Post(path, headers, body, content_type, receiver, progress);
  7342. });
  7343. }
  7344. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7345. #ifdef CPPHTTPLIB_SSL_ENABLED
  7346. using ClientT = SSLClient;
  7347. #else
  7348. using ClientT = Client;
  7349. #endif
  7350. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7351. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7352. const std::string &body, const std::string &content_type,
  7353. ContentReceiver receiver, DownloadProgress progress) {
  7354. return cli.Put(path, headers, body, content_type, receiver, progress);
  7355. });
  7356. }
  7357. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7358. #ifdef CPPHTTPLIB_SSL_ENABLED
  7359. using ClientT = SSLClient;
  7360. #else
  7361. using ClientT = Client;
  7362. #endif
  7363. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7364. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7365. const std::string &body, const std::string &content_type,
  7366. ContentReceiver receiver, DownloadProgress progress) {
  7367. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7368. });
  7369. }
  7370. template <typename ClientType>
  7371. void TestWithHeadersAndContentReceiverError(
  7372. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7373. const Headers &, const std::string &,
  7374. const std::string &, ContentReceiver)>
  7375. request_func) {
  7376. Headers headers;
  7377. headers.emplace("X-Error-Test", "true");
  7378. std::string received_body;
  7379. auto receiver_failed = false;
  7380. auto res =
  7381. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7382. [&](const char *data, size_t data_length) {
  7383. received_body.append(data, data_length);
  7384. receiver_failed = true;
  7385. return false;
  7386. });
  7387. ASSERT_FALSE(res);
  7388. EXPECT_TRUE(receiver_failed);
  7389. }
  7390. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7391. #ifdef CPPHTTPLIB_SSL_ENABLED
  7392. using ClientT = SSLClient;
  7393. #else
  7394. using ClientT = Client;
  7395. #endif
  7396. TestWithHeadersAndContentReceiverError<ClientT>(
  7397. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7398. const std::string &body, const std::string &content_type,
  7399. ContentReceiver receiver) {
  7400. return cli.Post(path, headers, body, content_type, receiver);
  7401. });
  7402. }
  7403. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7404. #ifdef CPPHTTPLIB_SSL_ENABLED
  7405. using ClientT = SSLClient;
  7406. #else
  7407. using ClientT = Client;
  7408. #endif
  7409. TestWithHeadersAndContentReceiverError<ClientT>(
  7410. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7411. const std::string &body, const std::string &content_type,
  7412. ContentReceiver receiver) {
  7413. return cli.Put(path, headers, body, content_type, receiver);
  7414. });
  7415. }
  7416. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7417. #ifdef CPPHTTPLIB_SSL_ENABLED
  7418. using ClientT = SSLClient;
  7419. #else
  7420. using ClientT = Client;
  7421. #endif
  7422. TestWithHeadersAndContentReceiverError<ClientT>(
  7423. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7424. const std::string &body, const std::string &content_type,
  7425. ContentReceiver receiver) {
  7426. return cli.Patch(path, headers, body, content_type, receiver);
  7427. });
  7428. }
  7429. TEST_F(ServerTest, PostQueryStringAndBody) {
  7430. auto res =
  7431. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7433. ASSERT_EQ(StatusCode::OK_200, res->status);
  7434. }
  7435. TEST_F(ServerTest, HTTP2Magic) {
  7436. Request req;
  7437. req.method = "PRI";
  7438. req.path = "*";
  7439. req.body = "SM";
  7440. auto res = std::make_shared<Response>();
  7441. auto error = Error::Success;
  7442. auto ret = cli_.send(req, *res, error);
  7443. ASSERT_TRUE(ret);
  7444. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7445. }
  7446. TEST_F(ServerTest, KeepAlive) {
  7447. auto res = cli_.Get("/hi");
  7448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7449. EXPECT_EQ(StatusCode::OK_200, res->status);
  7450. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7451. EXPECT_EQ("Hello World!", res->body);
  7452. res = cli_.Get("/hi");
  7453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7454. EXPECT_EQ(StatusCode::OK_200, res->status);
  7455. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7456. EXPECT_EQ("Hello World!", res->body);
  7457. res = cli_.Get("/hi");
  7458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7459. EXPECT_EQ(StatusCode::OK_200, res->status);
  7460. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7461. EXPECT_EQ("Hello World!", res->body);
  7462. res = cli_.Get("/not-exist");
  7463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7464. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7465. res = cli_.Post("/empty", "", "text/plain");
  7466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7467. EXPECT_EQ(StatusCode::OK_200, res->status);
  7468. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7469. EXPECT_EQ("empty", res->body);
  7470. EXPECT_EQ("close", res->get_header_value("Connection"));
  7471. res = cli_.Post(
  7472. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7473. "text/plain");
  7474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7475. EXPECT_EQ(StatusCode::OK_200, res->status);
  7476. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7477. EXPECT_EQ("empty", res->body);
  7478. cli_.set_keep_alive(false);
  7479. res = cli_.Get("/last-request");
  7480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7481. EXPECT_EQ(StatusCode::OK_200, res->status);
  7482. EXPECT_EQ("close", res->get_header_value("Connection"));
  7483. }
  7484. TEST_F(ServerTest, TooManyRedirect) {
  7485. cli_.set_follow_location(true);
  7486. auto res = cli_.Get("/redirect/0");
  7487. ASSERT_TRUE(!res);
  7488. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7489. }
  7490. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7491. Request req;
  7492. req.method = "FOOBAR";
  7493. req.path = "/hi";
  7494. cli_.set_keep_alive(true);
  7495. auto res = cli_.send(req);
  7496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7497. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7498. EXPECT_EQ("close", res->get_header_value("Connection"));
  7499. EXPECT_FALSE(cli_.is_socket_open());
  7500. }
  7501. TEST_F(ServerTest, CustomRouteReadsBody) {
  7502. const std::string xml =
  7503. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7504. Request req;
  7505. req.method = "PROPFIND";
  7506. req.path = "/dav/dir";
  7507. req.set_header("Depth", "1");
  7508. req.body = xml;
  7509. auto res = cli_.send(req);
  7510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7511. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7512. EXPECT_EQ(xml, res->body);
  7513. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7514. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7515. }
  7516. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7517. Request req;
  7518. req.method = "PROPFIND";
  7519. req.path = "/dav/42";
  7520. auto res = cli_.send(req);
  7521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7522. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7523. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7524. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7525. }
  7526. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7527. Request req;
  7528. req.method = "PROPFIND";
  7529. req.path = "/dav-re/123";
  7530. auto res = cli_.send(req);
  7531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7532. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7533. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7534. }
  7535. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7536. Request req;
  7537. req.method = "MKCOL";
  7538. req.path = "/dav-mkcol";
  7539. auto res = cli_.send(req);
  7540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7541. EXPECT_EQ(StatusCode::Created_201, res->status);
  7542. }
  7543. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7544. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7545. Request req;
  7546. req.method = "REPORT";
  7547. req.path = "/dav-report";
  7548. req.body = xml;
  7549. auto res = cli_.send(req);
  7550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7551. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7552. EXPECT_EQ(xml, res->body);
  7553. }
  7554. // A content reader route must fire even when the request carries no body,
  7555. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7556. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7557. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7558. Request req;
  7559. req.method = "REPORT";
  7560. req.path = "/dav-report";
  7561. auto res = cli_.send(req);
  7562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7563. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7564. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7565. }
  7566. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7567. Request req;
  7568. req.method = "PROPFIND";
  7569. req.path = "/not-dav";
  7570. auto res = cli_.send(req);
  7571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7572. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7573. }
  7574. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7575. Request req;
  7576. req.method = "UNLOCK";
  7577. req.path = "/dav/dir";
  7578. cli_.set_keep_alive(true);
  7579. auto res = cli_.send(req);
  7580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7581. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7582. EXPECT_EQ("close", res->get_header_value("Connection"));
  7583. EXPECT_FALSE(cli_.is_socket_open());
  7584. }
  7585. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7586. // The mount point serves this path, but only for GET and HEAD.
  7587. auto get_res = cli_.Get("/dir/index.html");
  7588. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7589. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7590. Request req;
  7591. req.method = "PROPFIND";
  7592. req.path = "/dir/index.html";
  7593. auto res = cli_.send(req);
  7594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7595. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7596. }
  7597. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7598. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7599. cli_.set_keep_alive(true);
  7600. for (auto i = 0; i < 2; i++) {
  7601. Request req;
  7602. req.method = "PROPFIND";
  7603. req.path = "/dav/dir";
  7604. req.body = xml;
  7605. auto res = cli_.send(req);
  7606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7607. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7608. EXPECT_EQ(xml, res->body);
  7609. EXPECT_TRUE(cli_.is_socket_open());
  7610. }
  7611. // A built-in method must still be served on the same connection.
  7612. cli_.set_keep_alive(false);
  7613. auto res = cli_.Get("/hi");
  7614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7615. EXPECT_EQ(StatusCode::OK_200, res->status);
  7616. EXPECT_EQ("close", res->get_header_value("Connection"));
  7617. }
  7618. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7619. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7620. Request req;
  7621. req.method = "PROPFIND";
  7622. req.path = "/dav/dir";
  7623. req.set_header("Expect", "100-continue");
  7624. req.body = xml;
  7625. auto res = cli_.send(req);
  7626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7627. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7628. EXPECT_EQ(xml, res->body);
  7629. }
  7630. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7631. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7632. TEST_F(ServerTest, Gzip) {
  7633. Headers headers;
  7634. headers.emplace("Accept-Encoding", "gzip, deflate");
  7635. auto res = cli_.Get("/compress", headers);
  7636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7637. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7638. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7639. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7640. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7641. "7890123456789012345678901234567890",
  7642. res->body);
  7643. EXPECT_EQ(StatusCode::OK_200, res->status);
  7644. }
  7645. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7646. Headers headers;
  7647. headers.emplace("Accept-Encoding", "gzip, deflate");
  7648. auto res = cli_.Get("/compress-with-charset", headers);
  7649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7650. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7651. EXPECT_EQ("application/json; charset=utf-8",
  7652. res->get_header_value("Content-Type"));
  7653. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7654. "7890123456789012345678901234567890",
  7655. res->body);
  7656. EXPECT_EQ(StatusCode::OK_200, res->status);
  7657. }
  7658. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7659. Headers headers;
  7660. headers.emplace("Accept-Encoding", "");
  7661. auto res = cli_.Get("/compress", headers);
  7662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7663. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7664. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7665. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7666. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7667. "7890123456789012345678901234567890",
  7668. res->body);
  7669. EXPECT_EQ(StatusCode::OK_200, res->status);
  7670. }
  7671. TEST_F(ServerTest, GzipWithContentReceiver) {
  7672. Headers headers;
  7673. headers.emplace("Accept-Encoding", "gzip, deflate");
  7674. std::string body;
  7675. auto res = cli_.Get("/compress", headers,
  7676. [&](const char *data, uint64_t data_length) {
  7677. EXPECT_EQ(100U, data_length);
  7678. body.append(data, data_length);
  7679. return true;
  7680. });
  7681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7682. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7683. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7684. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7685. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7686. "7890123456789012345678901234567890",
  7687. body);
  7688. EXPECT_EQ(StatusCode::OK_200, res->status);
  7689. }
  7690. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7691. Headers headers;
  7692. headers.emplace("Accept-Encoding", "gzip, deflate");
  7693. cli_.set_decompress(false);
  7694. auto res = cli_.Get("/compress", headers);
  7695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7696. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7697. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7698. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7699. EXPECT_EQ(33U, res->body.size());
  7700. EXPECT_EQ(StatusCode::OK_200, res->status);
  7701. }
  7702. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7703. Headers headers;
  7704. headers.emplace("Accept-Encoding", "");
  7705. std::string body;
  7706. auto res = cli_.Get("/compress", headers,
  7707. [&](const char *data, uint64_t data_length) {
  7708. EXPECT_EQ(100U, data_length);
  7709. body.append(data, data_length);
  7710. return true;
  7711. });
  7712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7713. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7714. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7715. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7716. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7717. "7890123456789012345678901234567890",
  7718. body);
  7719. EXPECT_EQ(StatusCode::OK_200, res->status);
  7720. }
  7721. TEST_F(ServerTest, NoGzip) {
  7722. Headers headers;
  7723. headers.emplace("Accept-Encoding", "gzip, deflate");
  7724. auto res = cli_.Get("/nocompress", headers);
  7725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7726. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7727. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7728. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7729. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7730. "7890123456789012345678901234567890",
  7731. res->body);
  7732. EXPECT_EQ(StatusCode::OK_200, res->status);
  7733. }
  7734. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7735. Headers headers;
  7736. headers.emplace("Accept-Encoding", "gzip, deflate");
  7737. std::string body;
  7738. auto res = cli_.Get("/nocompress", headers,
  7739. [&](const char *data, uint64_t data_length) {
  7740. EXPECT_EQ(100U, data_length);
  7741. body.append(data, data_length);
  7742. return true;
  7743. });
  7744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7745. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7746. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7747. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7748. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7749. "7890123456789012345678901234567890",
  7750. body);
  7751. EXPECT_EQ(StatusCode::OK_200, res->status);
  7752. }
  7753. TEST_F(ServerTest, MultipartFormDataGzip) {
  7754. UploadFormDataItems items = {
  7755. {"key1", "test", "", ""},
  7756. {"key2", "--abcdefg123", "", ""},
  7757. };
  7758. cli_.set_compress(true);
  7759. auto res = cli_.Post("/compress-multipart", items);
  7760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7761. EXPECT_EQ(StatusCode::OK_200, res->status);
  7762. }
  7763. #endif
  7764. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7765. // Static file compression is opt-in, so these run their own server rather than
  7766. // flipping it on for the shared ServerTest fixture, which would silently
  7767. // rewrite what every other static file test is asserting.
  7768. class StaticFileCompressionTest : public ::testing::Test {
  7769. protected:
  7770. void TearDown() override {
  7771. if (t_.joinable()) {
  7772. svr_.stop();
  7773. t_.join();
  7774. }
  7775. }
  7776. int start(const std::function<void(Server &)> &configure = nullptr) {
  7777. // Serves the same tree as a directory of build-time compressed assets
  7778. // would be served: the mount point names the coding the files are already
  7779. // stored in. Registered before "/" so it is the one that matches.
  7780. svr_.set_mount_point("/pre-encoded", "./www",
  7781. {{"Content-Encoding", "gzip"}});
  7782. svr_.set_mount_point("/", "./www");
  7783. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  7784. res.set_file_content("./www/dir/index.html", "text/html");
  7785. });
  7786. svr_.Get("/pre-encoded-file-content",
  7787. [](const Request & /*req*/, Response &res) {
  7788. res.set_header("Content-Encoding", "gzip");
  7789. res.set_file_content("./www/dir/index.html", "text/html");
  7790. });
  7791. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  7792. res.set_content_provider(
  7793. 6, "text/plain",
  7794. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7795. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  7796. return true;
  7797. });
  7798. });
  7799. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  7800. res.set_content_provider(
  7801. 1000, "text/plain",
  7802. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7803. if (offset < 100) {
  7804. std::string data(100, 'A');
  7805. sink.write(data.data(), data.size());
  7806. return true;
  7807. }
  7808. std::this_thread::sleep_for(std::chrono::seconds(2));
  7809. std::string data(900, 'B');
  7810. sink.write(data.data(), data.size());
  7811. return true;
  7812. });
  7813. });
  7814. if (configure) { configure(svr_); }
  7815. auto port = svr_.bind_to_any_port(HOST);
  7816. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  7817. svr_.wait_until_ready();
  7818. return port;
  7819. }
  7820. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  7821. // Every file under ./www except 1MB.txt is smaller than the default
  7822. // 1400-byte floor, so a test that needs a small file compressed has to lower
  7823. // it out of the way.
  7824. static void enable_without_floor(Server &svr) {
  7825. svr.set_static_file_compression(true);
  7826. svr.set_static_file_compression_min_length(0);
  7827. }
  7828. Server svr_;
  7829. std::thread t_;
  7830. };
  7831. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  7832. auto port = start();
  7833. Client cli(HOST, port);
  7834. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7836. EXPECT_EQ(StatusCode::OK_200, res->status);
  7837. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7838. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7839. EXPECT_EQ(1048576U, res->body.size());
  7840. }
  7841. TEST_F(StaticFileCompressionTest, MountPoint) {
  7842. auto port = start(enable);
  7843. Client cli(HOST, port);
  7844. cli.set_decompress(false);
  7845. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7847. EXPECT_EQ(StatusCode::OK_200, res->status);
  7848. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7849. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7850. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  7851. // The response stays self-delimiting: a length, not a chunked body.
  7852. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7853. EXPECT_EQ(std::to_string(res->body.size()),
  7854. res->get_header_value("Content-Length"));
  7855. EXPECT_LT(res->body.size(), 1048576U);
  7856. EXPECT_FALSE(res->body.empty());
  7857. }
  7858. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  7859. auto port = start(enable);
  7860. Client cli(HOST, port);
  7861. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7863. EXPECT_EQ(StatusCode::OK_200, res->status);
  7864. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7865. EXPECT_EQ(1048576U, res->body.size());
  7866. }
  7867. TEST_F(StaticFileCompressionTest, FileContent) {
  7868. auto port = start(enable_without_floor);
  7869. Client cli(HOST, port);
  7870. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  7871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7872. EXPECT_EQ(StatusCode::OK_200, res->status);
  7873. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7874. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7875. EXPECT_EQ(104U, res->body.size());
  7876. }
  7877. // A handler that serves an already-encoded file names the coding itself. The
  7878. // file-backed path decided its coding from Accept-Encoding and the content
  7879. // type alone, so it compressed the stored bytes a second time and appended a
  7880. // second Content-Encoding field line.
  7881. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  7882. auto port = start(enable_without_floor);
  7883. Client cli(HOST, port);
  7884. cli.set_decompress(false);
  7885. auto res = cli.Get("/pre-encoded-file-content",
  7886. Headers{{"Accept-Encoding", "gzip"}});
  7887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7888. EXPECT_EQ(StatusCode::OK_200, res->status);
  7889. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7890. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7891. // Vary belongs to a coding the server chose, and it chose none here.
  7892. EXPECT_FALSE(res->has_header("Vary"));
  7893. // The file travels exactly as it is stored on disk.
  7894. EXPECT_EQ(104U, res->body.size());
  7895. }
  7896. // The 1MB file clears the default floor, so this one runs the configuration a
  7897. // deployment would actually have.
  7898. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  7899. auto port = start(enable);
  7900. Client cli(HOST, port);
  7901. cli.set_decompress(false);
  7902. auto res =
  7903. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7905. EXPECT_EQ(StatusCode::OK_200, res->status);
  7906. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7907. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7908. EXPECT_FALSE(res->has_header("Vary"));
  7909. EXPECT_EQ(1048576U, res->body.size());
  7910. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7911. }
  7912. TEST_F(StaticFileCompressionTest, Head) {
  7913. auto port = start(enable);
  7914. Client cli(HOST, port);
  7915. cli.set_decompress(false);
  7916. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7917. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  7918. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7920. EXPECT_EQ(StatusCode::OK_200, res->status);
  7921. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7922. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7923. // HEAD still reports the size a GET would return.
  7924. EXPECT_EQ(get->get_header_value("Content-Length"),
  7925. res->get_header_value("Content-Length"));
  7926. EXPECT_TRUE(res->body.empty());
  7927. }
  7928. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  7929. auto port = start(enable);
  7930. Client cli(HOST, port);
  7931. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  7932. {"Accept-Encoding", "gzip"}});
  7933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7934. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7935. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7936. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7937. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7938. EXPECT_EQ("cd", res->body);
  7939. }
  7940. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  7941. auto port = start(enable);
  7942. Client cli(HOST, port);
  7943. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  7944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7945. EXPECT_EQ(StatusCode::OK_200, res->status);
  7946. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7947. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7948. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7949. }
  7950. TEST_F(StaticFileCompressionTest, EmptyFile) {
  7951. auto port = start(enable);
  7952. Client cli(HOST, port);
  7953. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  7954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7955. EXPECT_EQ(StatusCode::OK_200, res->status);
  7956. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7957. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7958. EXPECT_TRUE(res->body.empty());
  7959. }
  7960. TEST_F(StaticFileCompressionTest, MinLength) {
  7961. auto port = start(enable);
  7962. Client cli(HOST, port);
  7963. // 104 bytes, well under the default floor. Compressing it would add the
  7964. // gzip header and trailer to a body that already fits in one packet.
  7965. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7967. EXPECT_EQ(StatusCode::OK_200, res->status);
  7968. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7969. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  7970. }
  7971. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  7972. auto port = start([](Server &svr) {
  7973. svr.set_static_file_compression(true);
  7974. svr.set_static_file_compression_min_length(1);
  7975. });
  7976. Client cli(HOST, port);
  7977. cli.set_decompress(false);
  7978. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  7979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7980. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7981. // A 9-byte file comes back larger than it went in, because gzip's header and
  7982. // trailer outweigh anything deflate can save. That is the end of the range
  7983. // the floor exists to keep out.
  7984. EXPECT_GT(res->body.size(), 9U);
  7985. }
  7986. TEST_F(StaticFileCompressionTest, MaxLength) {
  7987. auto port = start([](Server &svr) {
  7988. svr.set_static_file_compression(true);
  7989. svr.set_static_file_compression_min_length(0);
  7990. svr.set_static_file_compression_max_length(1024);
  7991. });
  7992. Client cli(HOST, port);
  7993. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  7994. // defines `small` as a macro on Windows.
  7995. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7996. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  7997. EXPECT_FALSE(over->has_header("Content-Encoding"));
  7998. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  7999. // Under it: compressed.
  8000. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8001. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8002. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8003. }
  8004. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8005. auto port = start(enable_without_floor);
  8006. Client cli(HOST, port);
  8007. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8008. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8009. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8010. auto identity_etag = identity->get_header_value("ETag");
  8011. ASSERT_FALSE(identity_etag.empty());
  8012. auto gzipped =
  8013. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8014. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8015. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8016. auto gzip_etag = gzipped->get_header_value("ETag");
  8017. ASSERT_FALSE(gzip_etag.empty());
  8018. // Two representations, two validators.
  8019. EXPECT_NE(identity_etag, gzip_etag);
  8020. // Each one revalidates against the request that would produce it...
  8021. auto fresh =
  8022. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8023. {"If-None-Match", gzip_etag}});
  8024. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8025. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8026. auto fresh_identity =
  8027. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8028. {"If-None-Match", identity_etag}});
  8029. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8030. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8031. // ...and not against the other representation.
  8032. auto crossed =
  8033. cli.Get("/dir/index.html",
  8034. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8035. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8036. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8037. }
  8038. // The opt-in covers responses the server reads off disk itself. A caller's own
  8039. // known-length provider keeps its Content-Length and, more importantly, keeps
  8040. // delivering incrementally: routing it through a compressor would hold every
  8041. // write back until zlib's window filled.
  8042. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8043. auto port = start(enable);
  8044. Client cli(HOST, port);
  8045. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8047. EXPECT_EQ(StatusCode::OK_200, res->status);
  8048. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8049. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8050. EXPECT_EQ("aaabbb", res->body);
  8051. }
  8052. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8053. auto port = start(enable);
  8054. Client cli(HOST, port);
  8055. cli.set_read_timeout(1, 0);
  8056. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8057. Headers{{"Accept-Encoding", "gzip"}});
  8058. ASSERT_TRUE(handle.is_valid());
  8059. // The provider writes 100 bytes and then stalls for longer than the read
  8060. // timeout. Those first bytes have to arrive anyway: run the response through
  8061. // a compressor and zlib holds them until its window fills, so the read would
  8062. // come back empty instead.
  8063. char buf[256];
  8064. auto n = handle.read(buf, sizeof(buf));
  8065. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8066. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8067. }
  8068. #endif
  8069. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8070. TEST_F(ServerTest, Brotli) {
  8071. Headers headers;
  8072. headers.emplace("Accept-Encoding", "br");
  8073. auto res = cli_.Get("/compress", headers);
  8074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8075. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8076. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8077. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8078. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8079. "7890123456789012345678901234567890",
  8080. res->body);
  8081. EXPECT_EQ(StatusCode::OK_200, res->status);
  8082. }
  8083. #endif
  8084. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8085. TEST_F(ServerTest, Zstd) {
  8086. Headers headers;
  8087. headers.emplace("Accept-Encoding", "zstd");
  8088. auto res = cli_.Get("/compress", headers);
  8089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8090. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8091. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8092. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8093. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8094. "7890123456789012345678901234567890",
  8095. res->body);
  8096. EXPECT_EQ(StatusCode::OK_200, res->status);
  8097. }
  8098. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8099. Headers headers;
  8100. headers.emplace("Accept-Encoding", "");
  8101. auto res = cli_.Get("/compress", headers);
  8102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8103. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8104. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8105. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8106. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8107. "7890123456789012345678901234567890",
  8108. res->body);
  8109. EXPECT_EQ(StatusCode::OK_200, res->status);
  8110. }
  8111. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8112. Headers headers;
  8113. headers.emplace("Accept-Encoding", "zstd");
  8114. std::string body;
  8115. auto res = cli_.Get("/compress", headers,
  8116. [&](const char *data, uint64_t data_length) {
  8117. EXPECT_EQ(100U, data_length);
  8118. body.append(data, data_length);
  8119. return true;
  8120. });
  8121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8122. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8123. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8124. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8125. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8126. "7890123456789012345678901234567890",
  8127. body);
  8128. EXPECT_EQ(StatusCode::OK_200, res->status);
  8129. }
  8130. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8131. Headers headers;
  8132. headers.emplace("Accept-Encoding", "zstd");
  8133. cli_.set_decompress(false);
  8134. auto res = cli_.Get("/compress", headers);
  8135. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8136. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8137. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8138. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8140. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8141. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8142. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8143. EXPECT_EQ(StatusCode::OK_200, res->status);
  8144. ASSERT_EQ(26U, res->body.size());
  8145. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8146. 0);
  8147. }
  8148. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8149. Headers headers;
  8150. headers.emplace("Accept-Encoding", "");
  8151. std::string body;
  8152. auto res = cli_.Get("/compress", headers,
  8153. [&](const char *data, uint64_t data_length) {
  8154. EXPECT_EQ(100U, data_length);
  8155. body.append(data, data_length);
  8156. return true;
  8157. });
  8158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8159. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8160. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8161. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8162. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8163. "7890123456789012345678901234567890",
  8164. body);
  8165. EXPECT_EQ(StatusCode::OK_200, res->status);
  8166. }
  8167. TEST_F(ServerTest, NoZstd) {
  8168. Headers headers;
  8169. headers.emplace("Accept-Encoding", "zstd");
  8170. auto res = cli_.Get("/nocompress", headers);
  8171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8172. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8173. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8174. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8175. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8176. "7890123456789012345678901234567890",
  8177. res->body);
  8178. EXPECT_EQ(StatusCode::OK_200, res->status);
  8179. }
  8180. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8181. Headers headers;
  8182. headers.emplace("Accept-Encoding", "zstd");
  8183. std::string body;
  8184. auto res = cli_.Get("/nocompress", headers,
  8185. [&](const char *data, uint64_t data_length) {
  8186. EXPECT_EQ(100U, data_length);
  8187. body.append(data, data_length);
  8188. return true;
  8189. });
  8190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8191. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8192. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8193. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8194. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8195. "7890123456789012345678901234567890",
  8196. body);
  8197. EXPECT_EQ(StatusCode::OK_200, res->status);
  8198. }
  8199. // TODO: How to enable zstd ??
  8200. TEST_F(ServerTest, MultipartFormDataZstd) {
  8201. UploadFormDataItems items = {
  8202. {"key1", "test", "", ""},
  8203. {"key2", "--abcdefg123", "", ""},
  8204. };
  8205. Headers headers;
  8206. headers.emplace("Accept-Encoding", "zstd");
  8207. cli_.set_compress(true);
  8208. auto res = cli_.Post("/compress-multipart", headers, items);
  8209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8210. EXPECT_EQ(StatusCode::OK_200, res->status);
  8211. }
  8212. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8213. Headers headers;
  8214. headers.emplace("Accept-Encoding", "zstd");
  8215. cli_.set_compress(true);
  8216. auto res = cli_.Put(
  8217. "/put", headers, 3,
  8218. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8219. sink.os << "PUT";
  8220. return true;
  8221. },
  8222. "text/plain");
  8223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8224. EXPECT_EQ(StatusCode::OK_200, res->status);
  8225. EXPECT_EQ("PUT", res->body);
  8226. }
  8227. // Pre-compression logging tests
  8228. TEST_F(ServerTest, PreCompressionLogging) {
  8229. // Test data for compression (matches the actual /compress endpoint content)
  8230. const std::string test_content =
  8231. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8232. "3456789012345678901234567890";
  8233. // Variables to capture logging data
  8234. std::string pre_compression_body;
  8235. std::string pre_compression_content_type;
  8236. std::string pre_compression_content_encoding;
  8237. std::string post_compression_body;
  8238. std::string post_compression_content_type;
  8239. std::string post_compression_content_encoding;
  8240. // Set up pre-compression logger
  8241. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8242. const Response &res) {
  8243. pre_compression_body = res.body;
  8244. pre_compression_content_type = res.get_header_value("Content-Type");
  8245. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8246. });
  8247. // Set up post-compression logger
  8248. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8249. post_compression_body = res.body;
  8250. post_compression_content_type = res.get_header_value("Content-Type");
  8251. post_compression_content_encoding =
  8252. res.get_header_value("Content-Encoding");
  8253. });
  8254. // Test with gzip compression
  8255. Headers headers;
  8256. headers.emplace("Accept-Encoding", "gzip");
  8257. auto res = cli_.Get("/compress", headers);
  8258. // Verify response was compressed
  8259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8260. EXPECT_EQ(StatusCode::OK_200, res->status);
  8261. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8262. // Verify pre-compression logger captured uncompressed content
  8263. EXPECT_EQ(test_content, pre_compression_body);
  8264. EXPECT_EQ("text/plain", pre_compression_content_type);
  8265. EXPECT_TRUE(pre_compression_content_encoding
  8266. .empty()); // No encoding header before compression
  8267. // Verify post-compression logger captured compressed content
  8268. EXPECT_NE(test_content,
  8269. post_compression_body); // Should be different after compression
  8270. EXPECT_EQ("text/plain", post_compression_content_type);
  8271. EXPECT_EQ("gzip", post_compression_content_encoding);
  8272. // Verify compressed content is smaller
  8273. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8274. }
  8275. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8276. const std::string test_content =
  8277. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8278. "3456789012345678901234567890";
  8279. std::string pre_compression_body;
  8280. std::string post_compression_body;
  8281. svr_.set_pre_compression_logger(
  8282. [&](const Request & /*req*/, const Response &res) {
  8283. pre_compression_body = res.body;
  8284. });
  8285. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8286. post_compression_body = res.body;
  8287. });
  8288. Headers headers;
  8289. headers.emplace("Accept-Encoding", "br");
  8290. auto res = cli_.Get("/compress", headers);
  8291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8292. EXPECT_EQ(StatusCode::OK_200, res->status);
  8293. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8294. // Verify pre-compression content is uncompressed
  8295. EXPECT_EQ(test_content, pre_compression_body);
  8296. // Verify post-compression content is compressed
  8297. EXPECT_NE(test_content, post_compression_body);
  8298. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8299. }
  8300. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8301. const std::string test_content =
  8302. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8303. "3456789012345678901234567890";
  8304. std::string pre_compression_body;
  8305. std::string post_compression_body;
  8306. svr_.set_pre_compression_logger(
  8307. [&](const Request & /*req*/, const Response &res) {
  8308. pre_compression_body = res.body;
  8309. });
  8310. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8311. post_compression_body = res.body;
  8312. });
  8313. // Request without compression (use /nocompress endpoint)
  8314. Headers headers;
  8315. auto res = cli_.Get("/nocompress", headers);
  8316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8317. EXPECT_EQ(StatusCode::OK_200, res->status);
  8318. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8319. // Pre-compression logger should not be called when no compression is applied
  8320. EXPECT_TRUE(
  8321. pre_compression_body.empty()); // Pre-compression logger not called
  8322. EXPECT_EQ(
  8323. test_content,
  8324. post_compression_body); // Post-compression logger captures final content
  8325. }
  8326. TEST_F(ServerTest, LoggerSeesContentLength) {
  8327. size_t logged_content_length = 0;
  8328. std::string logged_content_length_header;
  8329. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8330. logged_content_length = res.content_length_;
  8331. logged_content_length_header = res.get_header_value("Content-Length");
  8332. });
  8333. auto res = cli_.Get("/nocompress");
  8334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8335. EXPECT_EQ(StatusCode::OK_200, res->status);
  8336. EXPECT_EQ(res->body.size(), logged_content_length);
  8337. EXPECT_EQ(std::to_string(logged_content_length),
  8338. logged_content_length_header);
  8339. }
  8340. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8341. const std::string test_content =
  8342. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8343. "3456789012345678901234567890";
  8344. std::string pre_compression_body;
  8345. bool pre_logger_called = false;
  8346. // Set only pre-compression logger
  8347. svr_.set_pre_compression_logger(
  8348. [&](const Request & /*req*/, const Response &res) {
  8349. pre_compression_body = res.body;
  8350. pre_logger_called = true;
  8351. });
  8352. Headers headers;
  8353. headers.emplace("Accept-Encoding", "gzip");
  8354. auto res = cli_.Get("/compress", headers);
  8355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8356. EXPECT_EQ(StatusCode::OK_200, res->status);
  8357. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8358. // Verify pre-compression logger was called
  8359. EXPECT_TRUE(pre_logger_called);
  8360. EXPECT_EQ(test_content, pre_compression_body);
  8361. }
  8362. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8363. {
  8364. // Test with Expect: 100-continue header - success case
  8365. // Server returns 100 Continue, client sends body, server returns 200 OK
  8366. Request req;
  8367. req.method = "POST";
  8368. req.path = "/post-large";
  8369. req.set_header("Expect", "100-continue");
  8370. req.body = LARGE_DATA;
  8371. Response res;
  8372. auto error = Error::Success;
  8373. cli_.set_keep_alive(true);
  8374. auto ret = cli_.send(req, res, error);
  8375. EXPECT_TRUE(ret);
  8376. EXPECT_EQ(StatusCode::OK_200, res.status);
  8377. EXPECT_EQ(LARGE_DATA, res.body);
  8378. }
  8379. {
  8380. // Test with Expect: 100-continue header - error case
  8381. // Client should not send the body when server returns an error
  8382. Request req;
  8383. req.method = "POST";
  8384. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8385. req.set_header("Expect", "100-continue");
  8386. req.body = LARGE_DATA;
  8387. Response res;
  8388. auto error = Error::Success;
  8389. auto start = std::chrono::high_resolution_clock::now();
  8390. cli_.set_keep_alive(true);
  8391. auto ret = cli_.send(req, res, error);
  8392. auto end = std::chrono::high_resolution_clock::now();
  8393. auto elapsed =
  8394. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8395. .count();
  8396. // With Expect: 100-continue, request completes successfully but with error
  8397. EXPECT_TRUE(ret);
  8398. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8399. EXPECT_EQ("close", res.get_header_value("Connection"));
  8400. EXPECT_FALSE(cli_.is_socket_open());
  8401. EXPECT_LE(elapsed, 2000);
  8402. }
  8403. {
  8404. // Send an extra GET request to ensure error recovery without hanging
  8405. Request req;
  8406. req.method = "GET";
  8407. req.path = "/hi";
  8408. auto start = std::chrono::high_resolution_clock::now();
  8409. auto res = cli_.send(req);
  8410. auto end = std::chrono::high_resolution_clock::now();
  8411. auto elapsed =
  8412. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8413. .count();
  8414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8415. EXPECT_EQ(StatusCode::OK_200, res->status);
  8416. EXPECT_EQ("Hello World!", res->body);
  8417. EXPECT_LE(elapsed, 500);
  8418. }
  8419. }
  8420. TEST(ZstdDecompressor, ChunkedDecompression) {
  8421. std::string data;
  8422. for (size_t i = 0; i < 32 * 1024; ++i) {
  8423. data.push_back(static_cast<char>('a' + i % 26));
  8424. }
  8425. std::string compressed_data;
  8426. {
  8427. httplib::detail::zstd_compressor compressor;
  8428. bool result = compressor.compress(
  8429. data.data(), data.size(),
  8430. /*last=*/true,
  8431. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8432. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8433. compressed_data_size);
  8434. return true;
  8435. });
  8436. ASSERT_TRUE(result);
  8437. }
  8438. std::string decompressed_data;
  8439. {
  8440. httplib::detail::zstd_decompressor decompressor;
  8441. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8442. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8443. size_t chunk_size = 130;
  8444. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8445. chunk_begin += chunk_size) {
  8446. size_t current_chunk_size =
  8447. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8448. bool result = decompressor.decompress(
  8449. compressed_data.data() + chunk_begin, current_chunk_size,
  8450. [&](const char *decompressed_data_chunk,
  8451. size_t decompressed_data_chunk_size) {
  8452. decompressed_data.insert(decompressed_data.size(),
  8453. decompressed_data_chunk,
  8454. decompressed_data_chunk_size);
  8455. return true;
  8456. });
  8457. ASSERT_TRUE(result);
  8458. }
  8459. }
  8460. ASSERT_EQ(data, decompressed_data);
  8461. }
  8462. TEST(ZstdDecompressor, Decompress) {
  8463. std::string original_text = "Compressed with ZSTD";
  8464. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8465. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8466. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8467. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8468. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8469. std::string decompressed_data;
  8470. {
  8471. httplib::detail::zstd_decompressor decompressor;
  8472. bool result = decompressor.decompress(
  8473. compressed_data.data(), compressed_data.size(),
  8474. [&](const char *decompressed_data_chunk,
  8475. size_t decompressed_data_chunk_size) {
  8476. decompressed_data.insert(decompressed_data.size(),
  8477. decompressed_data_chunk,
  8478. decompressed_data_chunk_size);
  8479. return true;
  8480. });
  8481. ASSERT_TRUE(result);
  8482. }
  8483. ASSERT_EQ(original_text, decompressed_data);
  8484. }
  8485. #endif
  8486. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8487. // separate chunks so that the server sees each part in its own read(). Used to
  8488. // place a read boundary at a specific offset of a request body.
  8489. static bool send_request_in_parts(time_t read_timeout_sec,
  8490. const std::vector<std::string> &parts,
  8491. std::string *resp = nullptr,
  8492. int port = PORT) {
  8493. auto error = Error::Success;
  8494. auto client_sock = detail::create_client_socket(
  8495. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8496. /*connection_timeout_sec=*/5, 0,
  8497. /*read_timeout_sec=*/5, 0,
  8498. /*write_timeout_sec=*/5, 0, std::string(), error);
  8499. if (client_sock == INVALID_SOCKET) { return false; }
  8500. auto ret = detail::process_client_socket(
  8501. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8502. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8503. for (size_t i = 0; i < parts.size(); i++) {
  8504. const auto &part = parts[i];
  8505. if (part.size() !=
  8506. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8507. return false;
  8508. }
  8509. if (i + 1 < parts.size()) {
  8510. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8511. }
  8512. }
  8513. char buf[512];
  8514. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8515. while (line_reader.getline()) {
  8516. if (resp) { *resp += line_reader.ptr(); }
  8517. }
  8518. return true;
  8519. });
  8520. detail::close_socket(client_sock);
  8521. return ret;
  8522. }
  8523. // Sends a raw request to a server listening at HOST:PORT.
  8524. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8525. std::string *resp = nullptr, int port = PORT) {
  8526. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8527. }
  8528. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8529. Server svr;
  8530. std::string header_value;
  8531. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8532. header_value = req.get_header_value("foo");
  8533. res.set_content("ok", "text/plain");
  8534. });
  8535. thread t = thread([&] { svr.listen(HOST, PORT); });
  8536. auto se = detail::scope_exit([&] {
  8537. svr.stop();
  8538. t.join();
  8539. ASSERT_FALSE(svr.is_running());
  8540. });
  8541. svr.wait_until_ready();
  8542. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8543. // like characters are not treated the same - use vertical tab and escape.
  8544. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8545. "foo: \t \v bar \x1B\t \r\n"
  8546. "Connection: close\r\n"
  8547. "\r\n";
  8548. std::string res;
  8549. ASSERT_TRUE(send_request(5, req, &res));
  8550. EXPECT_EQ(header_value, "");
  8551. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8552. }
  8553. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8554. Server svr;
  8555. std::string received;
  8556. svr.Get("/order", [&](const Request &req, Response &res) {
  8557. received = entries_to_string(req.headers);
  8558. res.set_content("ok", "text/plain");
  8559. });
  8560. auto port = svr.bind_to_any_port(HOST);
  8561. thread t = thread([&] { svr.listen_after_bind(); });
  8562. auto se = detail::scope_exit([&] {
  8563. svr.stop();
  8564. t.join();
  8565. ASSERT_FALSE(svr.is_running());
  8566. });
  8567. svr.wait_until_ready();
  8568. const std::string req = "GET /order HTTP/1.1\r\n"
  8569. "X-First: 1\r\n"
  8570. "X-Dup: a\r\n"
  8571. "X-Second: 2\r\n"
  8572. "X-Dup: b\r\n"
  8573. "Connection: close\r\n"
  8574. "\r\n";
  8575. std::string res;
  8576. ASSERT_TRUE(send_request(5, req, &res, port));
  8577. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8578. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  8579. }
  8580. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8581. Server svr;
  8582. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8583. res.set_header("Set-Cookie", "first=1");
  8584. res.set_header("X-Between", "y");
  8585. res.set_header("Set-Cookie", "second=2");
  8586. res.set_content("ok", "text/plain");
  8587. });
  8588. auto port = svr.bind_to_any_port(HOST);
  8589. thread t = thread([&] { svr.listen_after_bind(); });
  8590. auto se = detail::scope_exit([&] {
  8591. svr.stop();
  8592. t.join();
  8593. ASSERT_FALSE(svr.is_running());
  8594. });
  8595. svr.wait_until_ready();
  8596. Client cli(HOST, port);
  8597. auto res = cli.Get("/cookies");
  8598. ASSERT_TRUE(res);
  8599. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8600. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8601. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8602. }
  8603. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8604. Server svr;
  8605. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8606. auto i = new int(0);
  8607. res.set_header("Trailer", "X-Safe, X-Reflected");
  8608. res.set_chunked_content_provider(
  8609. "text/plain",
  8610. [i](size_t /*offset*/, DataSink &sink) {
  8611. if (*i == 0) {
  8612. sink.os << "body";
  8613. } else {
  8614. Headers trailer;
  8615. // A valid trailer that must survive.
  8616. trailer.emplace("X-Safe", "safe");
  8617. // Attacker-controlled value carrying CR/LF (response splitting).
  8618. trailer.emplace("X-Reflected",
  8619. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8620. // Attacker-controlled name carrying CR/LF.
  8621. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8622. sink.done_with_trailer(trailer);
  8623. }
  8624. (*i)++;
  8625. return true;
  8626. },
  8627. [i](bool /*success*/) { delete i; });
  8628. });
  8629. thread t = thread([&] { svr.listen(HOST, PORT); });
  8630. auto se = detail::scope_exit([&] {
  8631. svr.stop();
  8632. t.join();
  8633. ASSERT_FALSE(svr.is_running());
  8634. });
  8635. svr.wait_until_ready();
  8636. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8637. "Host: " + HOST +
  8638. "\r\n"
  8639. "Connection: close\r\n"
  8640. "\r\n";
  8641. std::string res;
  8642. ASSERT_TRUE(send_request(5, req, &res));
  8643. // The injected fields must not appear anywhere in the raw response.
  8644. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8645. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8646. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8647. // Invalid trailers are dropped entirely, matching set_header().
  8648. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8649. // The valid trailer still passes through.
  8650. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8651. }
  8652. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8653. Server svr;
  8654. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8655. // res.headers is a public field an application can populate directly,
  8656. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8657. // A valid header that must survive.
  8658. res.headers.emplace("X-Safe", "safe");
  8659. // Attacker-controlled value carrying CR/LF (response splitting).
  8660. res.headers.emplace("X-Reflected",
  8661. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8662. // Attacker-controlled name carrying CR/LF.
  8663. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8664. res.set_content("body", "text/plain");
  8665. });
  8666. thread t = thread([&] { svr.listen(HOST, PORT); });
  8667. auto se = detail::scope_exit([&] {
  8668. svr.stop();
  8669. t.join();
  8670. ASSERT_FALSE(svr.is_running());
  8671. });
  8672. svr.wait_until_ready();
  8673. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8674. "Host: " + HOST +
  8675. "\r\n"
  8676. "Connection: close\r\n"
  8677. "\r\n";
  8678. std::string res;
  8679. ASSERT_TRUE(send_request(5, req, &res));
  8680. // The injected fields must not appear anywhere in the raw response.
  8681. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8682. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8683. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8684. // Invalid headers are dropped entirely, matching set_header().
  8685. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8686. // The valid header still passes through.
  8687. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8688. }
  8689. // Forward declaration: in split builds split.py strips `inline` and moves the
  8690. // definition into httplib.cc, so detail::write_request_line is not visible from
  8691. // the public httplib.h. Re-declaring it here lets the tests link against the
  8692. // symbol in both header-only and split builds.
  8693. namespace httplib {
  8694. namespace detail {
  8695. ssize_t write_request_line(Stream &strm, const std::string &method,
  8696. const std::string &path);
  8697. } // namespace detail
  8698. } // namespace httplib
  8699. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  8700. // A well-formed target is written verbatim.
  8701. {
  8702. detail::BufferStream strm;
  8703. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8704. EXPECT_GT(n, 0);
  8705. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8706. }
  8707. // A target carrying CR/LF, SP or other control octets must be rejected
  8708. // before anything reaches the wire, otherwise it splits the request line and
  8709. // injects a header or a whole request.
  8710. const std::string evil_targets[] = {
  8711. "/a\r\nInjected: pwned",
  8712. "/a\rInjected",
  8713. "/a\nInjected",
  8714. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8715. "/a b",
  8716. "/a\tb",
  8717. "/a\x7f",
  8718. };
  8719. for (const auto &evil : evil_targets) {
  8720. detail::BufferStream strm;
  8721. auto n = detail::write_request_line(strm, "GET", evil);
  8722. EXPECT_LT(n, 0);
  8723. EXPECT_TRUE(strm.get_buffer().empty());
  8724. }
  8725. }
  8726. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8727. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  8728. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  8729. // target reaches write_request. The client must fail cleanly with
  8730. // Error::Write instead of putting a request-line-less, header-injecting
  8731. // request on the wire.
  8732. Server svr;
  8733. svr.Get("/a", [](const Request &, Response &res) {
  8734. res.set_content("ok", "text/plain");
  8735. });
  8736. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8737. auto se = detail::scope_exit([&] {
  8738. svr.stop();
  8739. thread.join();
  8740. ASSERT_FALSE(svr.is_running());
  8741. });
  8742. svr.wait_until_ready();
  8743. {
  8744. Client cli(HOST, PORT);
  8745. cli.set_path_encode(false);
  8746. // The request is rejected before anything is written, so the connection
  8747. // stays silent and the subsequent response read would otherwise block for
  8748. // the full default read timeout. Shorten it -- the assertion is on the
  8749. // error, not the timeout.
  8750. cli.set_read_timeout(1, 0);
  8751. auto res = cli.Get("/a\r\nInjected: pwned");
  8752. EXPECT_FALSE(res);
  8753. EXPECT_EQ(Error::Write, res.error());
  8754. }
  8755. }
  8756. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  8757. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  8758. // including extension methods.
  8759. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  8760. for (const auto &method : good_methods) {
  8761. detail::BufferStream strm;
  8762. auto n = detail::write_request_line(strm, method, "/");
  8763. EXPECT_GT(n, 0);
  8764. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  8765. }
  8766. // A method carrying CR/LF would split the request line and smuggle a whole
  8767. // request ahead of the real one. A space or an empty method corrupts the
  8768. // request line. All must be rejected before anything reaches the wire.
  8769. const std::string evil_methods[] = {
  8770. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8771. "GET\r\nInjected: pwned",
  8772. "GET\r",
  8773. "GET\n",
  8774. "GE T",
  8775. "",
  8776. };
  8777. for (const auto &evil : evil_methods) {
  8778. detail::BufferStream strm;
  8779. auto n = detail::write_request_line(strm, evil, "/");
  8780. EXPECT_LT(n, 0);
  8781. EXPECT_TRUE(strm.get_buffer().empty());
  8782. }
  8783. }
  8784. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  8785. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  8786. // through Client::send must fail with Error::Write and no request, neither
  8787. // the smuggled one nor the real one, may reach the server.
  8788. Server svr;
  8789. std::atomic<int> request_count(0);
  8790. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  8791. request_count++;
  8792. res.status = StatusCode::OK_200;
  8793. return Server::HandlerResponse::Handled;
  8794. });
  8795. auto port = svr.bind_to_any_port(HOST);
  8796. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  8797. auto se = detail::scope_exit([&] {
  8798. svr.stop();
  8799. thread.join();
  8800. ASSERT_FALSE(svr.is_running());
  8801. });
  8802. svr.wait_until_ready();
  8803. {
  8804. Client cli(HOST, port);
  8805. const std::string evil_methods[] = {
  8806. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8807. "GE T",
  8808. "",
  8809. };
  8810. for (const auto &evil : evil_methods) {
  8811. Request req;
  8812. req.method = evil;
  8813. req.path = "/";
  8814. auto res = cli.send(req);
  8815. EXPECT_FALSE(res);
  8816. EXPECT_EQ(Error::Write, res.error());
  8817. }
  8818. auto handle =
  8819. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  8820. EXPECT_FALSE(handle.is_valid());
  8821. EXPECT_EQ(Error::Write, handle.error);
  8822. // A valid request on the same client still goes through.
  8823. auto res = cli.Get("/");
  8824. ASSERT_TRUE(res);
  8825. EXPECT_EQ(StatusCode::OK_200, res->status);
  8826. }
  8827. EXPECT_EQ(1, request_count.load());
  8828. }
  8829. // Sends a raw request and verifies that there isn't a crash or exception.
  8830. static void test_raw_request(const std::string &req,
  8831. std::string *out = nullptr) {
  8832. Server svr;
  8833. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8834. res.set_content("ok", "text/plain");
  8835. });
  8836. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  8837. res.set_content("ok", "text/plain");
  8838. });
  8839. svr.Get("/header_field_value_check",
  8840. [&](const Request & /*req*/, Response &res) {
  8841. res.set_content("ok", "text/plain");
  8842. });
  8843. svr.CustomRoute("PROPFIND", "/dav",
  8844. [&](const Request & /*req*/, Response &res) {
  8845. res.status = StatusCode::MultiStatus_207;
  8846. });
  8847. // Server read timeout must be longer than the client read timeout for the
  8848. // bug to reproduce, probably to force the server to process a request
  8849. // without a trailing blank line.
  8850. const time_t client_read_timeout_sec = 1;
  8851. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  8852. bool listen_thread_ok = false;
  8853. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  8854. auto se = detail::scope_exit([&] {
  8855. svr.stop();
  8856. t.join();
  8857. ASSERT_FALSE(svr.is_running());
  8858. EXPECT_TRUE(listen_thread_ok);
  8859. });
  8860. svr.wait_until_ready();
  8861. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  8862. }
  8863. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  8864. // A certain header line causes an exception if the header property is parsed
  8865. // naively with a single regex. This occurs with libc++ but not libstdc++.
  8866. test_raw_request(
  8867. "GET /hi HTTP/1.1\r\n"
  8868. " : "
  8869. " "
  8870. " ");
  8871. }
  8872. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  8873. // A certain header line causes an exception if the header property *name* is
  8874. // parsed with a regular expression starting with "(.+?):" - this is a non-
  8875. // greedy matcher and requires backtracking when there are a lot of ":"
  8876. // characters.
  8877. // This occurs with libc++ but not libstdc++.
  8878. test_raw_request(
  8879. "GET /hi HTTP/1.1\r\n"
  8880. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  8881. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8882. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  8883. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  8884. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  8885. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  8886. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  8887. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  8888. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8889. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8890. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  8891. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8892. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  8893. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8894. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  8895. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  8896. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8897. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  8898. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  8899. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  8900. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  8901. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  8902. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  8903. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  8904. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8905. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8906. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  8907. "&&&%%%");
  8908. }
  8909. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  8910. // Make sure this doesn't crash the server.
  8911. // In a previous version of the header line regex, the "\r" rendered the line
  8912. // unparsable and the regex engine repeatedly backtracked, trying to look for
  8913. // a new position where the leading white space ended and the field value
  8914. // began.
  8915. // The crash occurs with libc++ but not libstdc++.
  8916. test_raw_request("GET /hi HTTP/1.1\r\n"
  8917. "a:" +
  8918. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  8919. "\r\n"
  8920. "\r\n");
  8921. }
  8922. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  8923. std::string out;
  8924. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8925. "Content-Type: text/plain\r\n"
  8926. "Transfer-Encoding: chunked\r\n"
  8927. "\r\n"
  8928. "nothex\r\n",
  8929. &out);
  8930. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8931. }
  8932. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  8933. std::string out;
  8934. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8935. "Content-Type: text/plain\r\n"
  8936. "Transfer-Encoding: chunked\r\n"
  8937. "\r\n"
  8938. "3\r\n"
  8939. "xyz\r\n"
  8940. "NaN\r\n",
  8941. &out);
  8942. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8943. }
  8944. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  8945. std::string out;
  8946. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8947. "Content-Type: text/plain\r\n"
  8948. "Transfer-Encoding: chunked\r\n"
  8949. "\r\n"
  8950. // Length is too large for 64 bits.
  8951. "1ffffffffffffffff\r\n"
  8952. "xyz\r\n",
  8953. &out);
  8954. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8955. }
  8956. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  8957. test_raw_request("GET /hi HTTP/1.1\r\n"
  8958. "Content-Type: text/plain\r\n\r");
  8959. }
  8960. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  8961. std::string out;
  8962. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  8963. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8964. }
  8965. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  8966. for (auto target : {"/h\ri", "/h\x7fi"}) {
  8967. std::string out;
  8968. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  8969. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  8970. }
  8971. }
  8972. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  8973. std::string out;
  8974. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  8975. "Connection: close\r\n\r\n",
  8976. &out);
  8977. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8978. }
  8979. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  8980. Server svr;
  8981. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  8982. EXPECT_TRUE(!req.remote_addr.empty());
  8983. });
  8984. thread t = thread([&] { svr.listen(HOST, PORT); });
  8985. auto se = detail::scope_exit([&] {
  8986. svr.stop();
  8987. t.join();
  8988. ASSERT_FALSE(svr.is_running());
  8989. });
  8990. svr.wait_until_ready();
  8991. // Send an invalid request line to trigger Bad Request
  8992. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  8993. std::string out;
  8994. ASSERT_TRUE(send_request(5, bad_req, &out));
  8995. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8996. }
  8997. // A custom method with neither Content-Length nor Transfer-Encoding must be
  8998. // answered right away rather than blocking on a read that waits for EOF.
  8999. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9000. std::string out;
  9001. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9002. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9003. }
  9004. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9005. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9006. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9007. for (const auto *method : methods) {
  9008. Server svr;
  9009. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9010. EXPECT_FALSE(svr.is_valid()) << method;
  9011. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9012. }
  9013. }
  9014. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9015. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9016. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9017. for (const auto *method : methods) {
  9018. Server svr;
  9019. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9020. EXPECT_FALSE(svr.is_valid()) << method;
  9021. }
  9022. }
  9023. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9024. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9025. "COPY", "MOVE", "LOCK",
  9026. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9027. Server svr;
  9028. for (const auto *method : methods) {
  9029. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9030. }
  9031. EXPECT_TRUE(svr.is_valid());
  9032. }
  9033. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9034. Server svr;
  9035. svr.CustomRoute("POST", "/x",
  9036. [](const Request &, Response &, const ContentReader &) {});
  9037. EXPECT_FALSE(svr.is_valid());
  9038. }
  9039. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9040. Server svr;
  9041. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9042. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9043. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9044. EXPECT_FALSE(svr.is_valid());
  9045. }
  9046. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9047. Server svr;
  9048. auto captured = Error::Success;
  9049. svr.set_error_logger(
  9050. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9051. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9052. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9053. }
  9054. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9055. std::string out;
  9056. std::string request(
  9057. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9058. test_raw_request(request, &out);
  9059. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9060. }
  9061. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9062. std::string out;
  9063. std::string request(
  9064. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9065. test_raw_request(request, &out);
  9066. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9067. }
  9068. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9069. std::string out;
  9070. std::string request(
  9071. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9072. test_raw_request(request, &out);
  9073. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9074. }
  9075. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9076. std::string out;
  9077. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9078. "Test: \r\n\r\n",
  9079. &out);
  9080. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9081. }
  9082. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9083. Server svr;
  9084. std::string x_custom;
  9085. std::string cookie;
  9086. std::string xff;
  9087. std::string x_unicode;
  9088. std::string x_iis;
  9089. svr.Get("/check", [&](const Request &req, Response &res) {
  9090. x_custom = req.get_header_value("X-Custom");
  9091. cookie = req.get_header_value("Cookie");
  9092. xff = req.get_header_value("X-Forwarded-For");
  9093. x_unicode = req.get_header_value("X-Unicode");
  9094. x_iis = req.get_header_value("X-IIS");
  9095. res.set_content("ok", "text/plain");
  9096. });
  9097. thread t = thread([&] { svr.listen(HOST, PORT); });
  9098. auto se = detail::scope_exit([&] {
  9099. svr.stop();
  9100. t.join();
  9101. ASSERT_FALSE(svr.is_running());
  9102. });
  9103. svr.wait_until_ready();
  9104. const std::string req = "GET /check HTTP/1.1\r\n"
  9105. "Host: localhost\r\n"
  9106. "X-Custom: a%0D%0AInjected: b\r\n"
  9107. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9108. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9109. "X-Unicode: %E3%81%82\r\n"
  9110. "X-IIS: %u00E9\r\n"
  9111. "Connection: close\r\n"
  9112. "\r\n";
  9113. std::string res;
  9114. ASSERT_TRUE(send_request(5, req, &res));
  9115. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9116. // Every value must be returned verbatim (wire form), with no decoding.
  9117. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9118. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9119. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9120. EXPECT_EQ("%E3%81%82", x_unicode);
  9121. EXPECT_EQ("%u00E9", x_iis);
  9122. }
  9123. // Applications that previously relied on automatic percent-decoding can
  9124. // reproduce the old behavior by explicitly calling decode_path_component()
  9125. // or, for RFC 3986 conformance, decode_uri_component().
  9126. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9127. Server svr;
  9128. std::string decoded;
  9129. svr.Get("/check", [&](const Request &req, Response &res) {
  9130. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9131. res.set_content("ok", "text/plain");
  9132. });
  9133. thread t = thread([&] { svr.listen(HOST, PORT); });
  9134. auto se = detail::scope_exit([&] {
  9135. svr.stop();
  9136. t.join();
  9137. ASSERT_FALSE(svr.is_running());
  9138. });
  9139. svr.wait_until_ready();
  9140. const std::string req = "GET /check HTTP/1.1\r\n"
  9141. "Host: localhost\r\n"
  9142. "X-Custom: hello%20world\r\n"
  9143. "Connection: close\r\n"
  9144. "\r\n";
  9145. std::string res;
  9146. ASSERT_TRUE(send_request(5, req, &res));
  9147. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9148. EXPECT_EQ("hello world", decoded);
  9149. }
  9150. // Regression test for #2033. Browsers send Referer values that include
  9151. // percent-encoded characters such as %0A inside the URL. Decoding the
  9152. // header value would either trip the post-decode CR/LF/NUL guard (the
  9153. // original bug, returning 400) or, after that guard was relaxed, silently
  9154. // store a literal LF — both unacceptable. The wire form must round-trip.
  9155. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9156. Server svr;
  9157. std::string referer;
  9158. svr.Get("/check", [&](const Request &req, Response &res) {
  9159. referer = req.get_header_value("Referer");
  9160. res.set_content("ok", "text/plain");
  9161. });
  9162. thread t = thread([&] { svr.listen(HOST, PORT); });
  9163. auto se = detail::scope_exit([&] {
  9164. svr.stop();
  9165. t.join();
  9166. ASSERT_FALSE(svr.is_running());
  9167. });
  9168. svr.wait_until_ready();
  9169. const std::string req = "GET /check HTTP/1.1\r\n"
  9170. "Host: localhost\r\n"
  9171. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9172. "Connection: close\r\n"
  9173. "\r\n";
  9174. std::string res;
  9175. ASSERT_TRUE(send_request(5, req, &res));
  9176. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9177. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9178. }
  9179. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9180. Server svr;
  9181. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9182. res.set_header("Cache-Control", "no-cache");
  9183. res.set_chunked_content_provider(
  9184. "text/event-stream", [](size_t offset, DataSink &sink) {
  9185. std::string s = "data:";
  9186. s += std::to_string(offset);
  9187. s += "\n\n";
  9188. auto ret = sink.write(s.data(), s.size());
  9189. EXPECT_TRUE(ret);
  9190. std::this_thread::sleep_for(std::chrono::seconds(1));
  9191. return true;
  9192. });
  9193. });
  9194. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9195. svr.wait_until_ready();
  9196. Client client(HOST, PORT);
  9197. const Headers headers = {{"Accept", "text/event-stream"}};
  9198. auto get_thread = std::thread([&client, &headers]() {
  9199. auto res = client.Get(
  9200. "/events", headers,
  9201. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9202. });
  9203. auto se = detail::scope_exit([&] {
  9204. svr.stop();
  9205. get_thread.join();
  9206. listen_thread.join();
  9207. ASSERT_FALSE(svr.is_running());
  9208. });
  9209. // Give GET time to get a few messages.
  9210. std::this_thread::sleep_for(std::chrono::seconds(2));
  9211. }
  9212. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9213. httplib::Server svr;
  9214. svr.Post("/hi",
  9215. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9216. res.status = StatusCode::OK_200;
  9217. });
  9218. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9219. svr.wait_until_ready();
  9220. Client cli(HOST, PORT);
  9221. auto res = cli.Post("/hi", "data", "text/plain");
  9222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9223. EXPECT_EQ(StatusCode::OK_200, res->status);
  9224. svr.stop();
  9225. thread.join();
  9226. ASSERT_FALSE(svr.is_running());
  9227. res = cli.Post("/hi", "data", "text/plain");
  9228. ASSERT_FALSE(res);
  9229. }
  9230. TEST(ServerStopTest, ListenFailure) {
  9231. Server svr;
  9232. auto t = thread([&]() {
  9233. auto ret = svr.listen("????", PORT);
  9234. EXPECT_FALSE(ret);
  9235. });
  9236. svr.wait_until_ready();
  9237. svr.stop();
  9238. t.join();
  9239. }
  9240. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9241. TEST(ServerStopTest, Decommision) {
  9242. Server svr;
  9243. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9244. for (int i = 0; i < 4; i++) {
  9245. auto is_even = !(i % 2);
  9246. std::thread t{[&] {
  9247. try {
  9248. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9249. if (is_even) {
  9250. throw std::runtime_error("Some thing that happens to go wrong.");
  9251. }
  9252. svr.listen(HOST, PORT);
  9253. } catch (...) { svr.decommission(); }
  9254. }};
  9255. svr.wait_until_ready();
  9256. // Server is up
  9257. {
  9258. Client cli(HOST, PORT);
  9259. auto res = cli.Get("/hi");
  9260. if (is_even) {
  9261. EXPECT_FALSE(res);
  9262. } else {
  9263. EXPECT_TRUE(res);
  9264. EXPECT_EQ("hi...", res->body);
  9265. }
  9266. }
  9267. svr.stop();
  9268. t.join();
  9269. // Server is down...
  9270. {
  9271. Client cli(HOST, PORT);
  9272. auto res = cli.Get("/hi");
  9273. EXPECT_FALSE(res);
  9274. }
  9275. }
  9276. }
  9277. #endif
  9278. // Helper function for string body upload progress tests
  9279. template <typename SetupHandler, typename ClientCall>
  9280. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9281. ClientCall &&client_call,
  9282. const string &body) {
  9283. Server svr;
  9284. setup_handler(svr);
  9285. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9286. auto se = detail::scope_exit([&] {
  9287. svr.stop();
  9288. t.join();
  9289. });
  9290. svr.wait_until_ready();
  9291. Client cli(HOST, PORT);
  9292. vector<uint64_t> progress_values;
  9293. bool progress_called = false;
  9294. auto res =
  9295. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9296. progress_values.push_back(current);
  9297. progress_called = true;
  9298. return true;
  9299. });
  9300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9301. EXPECT_EQ(200, res->status);
  9302. EXPECT_TRUE(progress_called);
  9303. }
  9304. TEST(UploadProgressTest, PostStringBodyBasic) {
  9305. TestStringBodyUploadProgress(
  9306. [](Server &svr) {
  9307. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9308. res.set_content("received", "text/plain");
  9309. });
  9310. },
  9311. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9312. return cli.Post("/test", body, "text/plain", progress_callback);
  9313. },
  9314. "test data for upload progress");
  9315. }
  9316. TEST(UploadProgressTest, PutStringBodyBasic) {
  9317. TestStringBodyUploadProgress(
  9318. [](Server &svr) {
  9319. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9320. res.set_content("put received", "text/plain");
  9321. });
  9322. },
  9323. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9324. return cli.Put("/test", body, "text/plain", progress_callback);
  9325. },
  9326. "put test data for upload progress");
  9327. }
  9328. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9329. TestStringBodyUploadProgress(
  9330. [](Server &svr) {
  9331. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9332. res.set_content("patch received", "text/plain");
  9333. });
  9334. },
  9335. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9336. return cli.Patch("/test", body, "text/plain", progress_callback);
  9337. },
  9338. "patch test data for upload progress");
  9339. }
  9340. // Helper function for content provider upload progress tests
  9341. template <typename SetupHandler, typename ClientCall>
  9342. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9343. ClientCall &&client_call) {
  9344. Server svr;
  9345. setup_handler(svr);
  9346. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9347. auto se = detail::scope_exit([&] {
  9348. svr.stop();
  9349. t.join();
  9350. });
  9351. svr.wait_until_ready();
  9352. Client cli(HOST, PORT);
  9353. vector<uint64_t> progress_values;
  9354. auto res =
  9355. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9356. progress_values.push_back(current);
  9357. return true;
  9358. });
  9359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9360. EXPECT_EQ(200, res->status);
  9361. EXPECT_FALSE(progress_values.empty());
  9362. }
  9363. TEST(UploadProgressTest, PostContentProviderProgress) {
  9364. TestContentProviderUploadProgress(
  9365. [](Server &svr) {
  9366. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9367. res.set_content("provider received", "text/plain");
  9368. });
  9369. },
  9370. [](Client &cli, UploadProgress progress_callback) {
  9371. return cli.Post(
  9372. "/test", 10,
  9373. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9374. sink.os << "test data";
  9375. return true;
  9376. },
  9377. "text/plain", progress_callback);
  9378. });
  9379. }
  9380. // Helper function for multipart upload progress tests
  9381. template <typename SetupHandler, typename ClientCall>
  9382. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9383. ClientCall &&client_call,
  9384. const string &endpoint) {
  9385. Server svr;
  9386. setup_handler(svr);
  9387. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9388. auto se = detail::scope_exit([&] {
  9389. svr.stop();
  9390. t.join();
  9391. });
  9392. svr.wait_until_ready();
  9393. Client cli(HOST, PORT);
  9394. vector<uint64_t> progress_values;
  9395. UploadFormDataItems items = {
  9396. {"field1", "value1", "", ""},
  9397. {"field2", "longer value for progress tracking test", "", ""},
  9398. {"file1", "file content data for upload progress", "test.txt",
  9399. "text/plain"}};
  9400. auto res = client_call(cli, endpoint, items,
  9401. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9402. progress_values.push_back(current);
  9403. return true;
  9404. });
  9405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9406. EXPECT_EQ(200, res->status);
  9407. EXPECT_FALSE(progress_values.empty());
  9408. }
  9409. TEST(UploadProgressTest, PostMultipartProgress) {
  9410. TestMultipartUploadProgress(
  9411. [](Server &svr) {
  9412. svr.Post("/multipart", [](const Request &req, Response &res) {
  9413. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9414. res.set_content("multipart received", "text/plain");
  9415. });
  9416. },
  9417. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9418. UploadProgress progress_callback) {
  9419. return cli.Post(endpoint, items, progress_callback);
  9420. },
  9421. "/multipart");
  9422. }
  9423. // Helper function for basic download progress tests
  9424. template <typename SetupHandler, typename ClientCall>
  9425. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9426. ClientCall &&client_call, const string &endpoint,
  9427. size_t expected_content_size) {
  9428. Server svr;
  9429. setup_handler(svr);
  9430. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9431. auto se = detail::scope_exit([&] {
  9432. svr.stop();
  9433. t.join();
  9434. });
  9435. svr.wait_until_ready();
  9436. Client cli(HOST, PORT);
  9437. vector<uint64_t> progress_values;
  9438. auto res = client_call(cli, endpoint,
  9439. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9440. progress_values.push_back(current);
  9441. return true;
  9442. });
  9443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9444. EXPECT_EQ(200, res->status);
  9445. EXPECT_FALSE(progress_values.empty());
  9446. EXPECT_EQ(expected_content_size, res->body.size());
  9447. }
  9448. TEST(DownloadProgressTest, GetBasic) {
  9449. TestBasicDownloadProgress(
  9450. [](Server &svr) {
  9451. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9452. string content(1000, 'D');
  9453. res.set_content(content, "text/plain");
  9454. });
  9455. },
  9456. [](Client &cli, const string &endpoint,
  9457. DownloadProgress progress_callback) {
  9458. return cli.Get(endpoint, progress_callback);
  9459. },
  9460. "/download", 1000u);
  9461. }
  9462. // Helper function for content receiver download progress tests
  9463. template <typename SetupHandler, typename ClientCall>
  9464. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9465. ClientCall &&client_call,
  9466. const string &endpoint,
  9467. size_t expected_content_size) {
  9468. Server svr;
  9469. setup_handler(svr);
  9470. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9471. auto se = detail::scope_exit([&] {
  9472. svr.stop();
  9473. t.join();
  9474. });
  9475. svr.wait_until_ready();
  9476. Client cli(HOST, PORT);
  9477. vector<uint64_t> progress_values;
  9478. string received_body;
  9479. auto res = client_call(
  9480. cli, endpoint,
  9481. [&](const char *data, size_t data_length) -> bool {
  9482. received_body.append(data, data_length);
  9483. return true;
  9484. },
  9485. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9486. progress_values.push_back(current);
  9487. return true;
  9488. });
  9489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9490. EXPECT_EQ(200, res->status);
  9491. EXPECT_FALSE(progress_values.empty());
  9492. EXPECT_EQ(expected_content_size, received_body.size());
  9493. EXPECT_TRUE(res->body.empty());
  9494. }
  9495. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9496. TestContentReceiverDownloadProgress(
  9497. [](Server &svr) {
  9498. svr.Get("/download-receiver",
  9499. [](const Request & /*req*/, Response &res) {
  9500. string content(2000, 'R');
  9501. res.set_content(content, "text/plain");
  9502. });
  9503. },
  9504. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9505. DownloadProgress progress_callback) {
  9506. return cli.Get(endpoint, content_receiver, progress_callback);
  9507. },
  9508. "/download-receiver", 2000u);
  9509. }
  9510. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9511. // A provider reaching a pass with nothing to hand over - an empty buffer
  9512. // popped off a queue, say - must not be taken to mean the body is finished.
  9513. // It used to end the loop with the terminating chunk unwritten while the
  9514. // server still considered the response complete, so the peer waited for an
  9515. // end that never arrived.
  9516. Server svr;
  9517. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9518. auto step = std::make_shared<int>(0);
  9519. res.set_chunked_content_provider("text/plain",
  9520. [step](size_t /*offset*/, DataSink &sink) {
  9521. switch ((*step)++) {
  9522. case 0: sink.write("", 0); break;
  9523. case 1: sink.write("hello", 5); break;
  9524. default: sink.done(); break;
  9525. }
  9526. return true;
  9527. });
  9528. });
  9529. auto port = svr.bind_to_any_port(HOST);
  9530. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9531. auto listen_se = detail::scope_exit([&] {
  9532. svr.stop();
  9533. listen_thread.join();
  9534. ASSERT_FALSE(svr.is_running());
  9535. });
  9536. svr.wait_until_ready();
  9537. Client cli(HOST, port);
  9538. // Without the fix the body is never terminated, so bound the wait rather
  9539. // than letting the test hang on the default read timeout.
  9540. cli.set_read_timeout(5, 0);
  9541. auto res = cli.Get("/stream");
  9542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9543. EXPECT_EQ(StatusCode::OK_200, res->status);
  9544. EXPECT_EQ("hello", res->body);
  9545. }
  9546. TEST(StreamingTest, NoContentLengthStreaming) {
  9547. Server svr;
  9548. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9549. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9550. if (offset < 6) {
  9551. sink.os << (offset < 3 ? "a" : "b");
  9552. } else {
  9553. sink.done();
  9554. }
  9555. return true;
  9556. });
  9557. });
  9558. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9559. auto listen_se = detail::scope_exit([&] {
  9560. svr.stop();
  9561. listen_thread.join();
  9562. ASSERT_FALSE(svr.is_running());
  9563. });
  9564. svr.wait_until_ready();
  9565. Client client(HOST, PORT);
  9566. auto get_thread = std::thread([&client]() {
  9567. std::string s;
  9568. auto res =
  9569. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9570. s += std::string(data, len);
  9571. return true;
  9572. });
  9573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9574. EXPECT_EQ(StatusCode::OK_200, res->status);
  9575. EXPECT_EQ("aaabbb", s);
  9576. });
  9577. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9578. // Give GET time to get a few messages.
  9579. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9580. }
  9581. TEST(MountTest, Unmount) {
  9582. Server svr;
  9583. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9584. auto se = detail::scope_exit([&] {
  9585. svr.stop();
  9586. listen_thread.join();
  9587. ASSERT_FALSE(svr.is_running());
  9588. });
  9589. svr.wait_until_ready();
  9590. Client cli("localhost", PORT);
  9591. svr.set_mount_point("/mount2", "./www2");
  9592. auto res = cli.Get("/");
  9593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9594. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9595. res = cli.Get("/mount2/dir/test.html");
  9596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9597. EXPECT_EQ(StatusCode::OK_200, res->status);
  9598. svr.set_mount_point("/", "./www");
  9599. res = cli.Get("/dir/");
  9600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9601. EXPECT_EQ(StatusCode::OK_200, res->status);
  9602. svr.remove_mount_point("/");
  9603. res = cli.Get("/dir/");
  9604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9605. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9606. svr.remove_mount_point("/mount2");
  9607. res = cli.Get("/mount2/dir/test.html");
  9608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9609. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9610. }
  9611. TEST(MountTest, PathSegmentBoundary) {
  9612. Server svr;
  9613. svr.set_mount_point("/mount2", "./www2");
  9614. svr.set_mount_point("/", "./www");
  9615. auto port = svr.bind_to_any_port(HOST);
  9616. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9617. auto se = detail::scope_exit([&] {
  9618. svr.stop();
  9619. listen_thread.join();
  9620. ASSERT_FALSE(svr.is_running());
  9621. });
  9622. svr.wait_until_ready();
  9623. Client cli(HOST, port);
  9624. auto res = cli.Get("/mount2/dir/test.html");
  9625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9626. EXPECT_EQ(StatusCode::OK_200, res->status);
  9627. // "/mount2" must not match part-way through a path segment.
  9628. res = cli.Get("/mount2dir/test.html");
  9629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9630. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9631. // A mount point ending in '/' keeps matching every path below it.
  9632. res = cli.Get("/dir/test.html");
  9633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9634. EXPECT_EQ(StatusCode::OK_200, res->status);
  9635. }
  9636. TEST(MountTest, Redicect) {
  9637. Server svr;
  9638. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9639. auto se = detail::scope_exit([&] {
  9640. svr.stop();
  9641. listen_thread.join();
  9642. ASSERT_FALSE(svr.is_running());
  9643. });
  9644. svr.set_mount_point("/", "./www");
  9645. svr.wait_until_ready();
  9646. Client cli("localhost", PORT);
  9647. auto res = cli.Get("/dir/");
  9648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9649. EXPECT_EQ(StatusCode::OK_200, res->status);
  9650. res = cli.Get("/dir");
  9651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9652. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9653. res = cli.Get("/file");
  9654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9655. EXPECT_EQ(StatusCode::OK_200, res->status);
  9656. res = cli.Get("/file/");
  9657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9658. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9659. cli.set_follow_location(true);
  9660. res = cli.Get("/dir");
  9661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9662. EXPECT_EQ(StatusCode::OK_200, res->status);
  9663. }
  9664. TEST(MountTest, MultibytesPathName) {
  9665. Server svr;
  9666. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9667. auto se = detail::scope_exit([&] {
  9668. svr.stop();
  9669. listen_thread.join();
  9670. ASSERT_FALSE(svr.is_running());
  9671. });
  9672. svr.set_mount_point("/", "./www");
  9673. svr.wait_until_ready();
  9674. Client cli("localhost", PORT);
  9675. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  9676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9677. EXPECT_EQ(StatusCode::OK_200, res->status);
  9678. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  9679. }
  9680. #ifdef _WIN32
  9681. // Issue #2435: mmap::open() must succeed even when another handle holds
  9682. // the file open for writing (e.g. an active log file).
  9683. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  9684. const char *path = "mmap_concurrent_writer_test.txt";
  9685. const char *content = "hello";
  9686. {
  9687. std::ofstream f(path, std::ios::binary);
  9688. f.write(content, static_cast<std::streamsize>(strlen(content)));
  9689. }
  9690. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  9691. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  9692. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  9693. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  9694. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  9695. detail::mmap m(path);
  9696. ASSERT_TRUE(m.is_open());
  9697. EXPECT_EQ(strlen(content), m.size());
  9698. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  9699. }
  9700. #endif
  9701. #ifndef _WIN32
  9702. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  9703. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  9704. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  9705. TEST(MmapTest, FailedMappingIsNotOpen) {
  9706. const char *path = "./mmap_failed_mapping_test_dir";
  9707. ASSERT_EQ(0, ::mkdir(path, 0755));
  9708. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  9709. detail::mmap m(path);
  9710. EXPECT_FALSE(m.is_open());
  9711. EXPECT_EQ(0U, m.size());
  9712. EXPECT_NE(static_cast<const void *>(m.data()),
  9713. static_cast<const void *>(MAP_FAILED));
  9714. }
  9715. #endif
  9716. TEST(KeepAliveTest, ReadTimeout) {
  9717. Server svr;
  9718. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9719. std::this_thread::sleep_for(std::chrono::seconds(2));
  9720. res.set_content("a", "text/plain");
  9721. });
  9722. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9723. res.set_content("b", "text/plain");
  9724. });
  9725. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9726. auto se = detail::scope_exit([&] {
  9727. svr.stop();
  9728. listen_thread.join();
  9729. ASSERT_FALSE(svr.is_running());
  9730. });
  9731. svr.wait_until_ready();
  9732. Client cli("localhost", PORT);
  9733. cli.set_keep_alive(true);
  9734. cli.set_read_timeout(std::chrono::seconds(1));
  9735. auto resa = cli.Get("/a");
  9736. ASSERT_FALSE(resa);
  9737. EXPECT_EQ(Error::Read, resa.error());
  9738. auto resb = cli.Get("/b");
  9739. ASSERT_TRUE(resb);
  9740. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9741. EXPECT_EQ("b", resb->body);
  9742. }
  9743. TEST(KeepAliveTest, MaxCount) {
  9744. size_t keep_alive_max_count = 3;
  9745. Server svr;
  9746. svr.set_keep_alive_max_count(keep_alive_max_count);
  9747. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9748. res.set_content("Hello World!", "text/plain");
  9749. });
  9750. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9751. auto se = detail::scope_exit([&] {
  9752. svr.stop();
  9753. listen_thread.join();
  9754. ASSERT_FALSE(svr.is_running());
  9755. });
  9756. svr.wait_until_ready();
  9757. Client cli(HOST, PORT);
  9758. cli.set_keep_alive(true);
  9759. for (size_t i = 0; i < 5; i++) {
  9760. auto result = cli.Get("/hi");
  9761. ASSERT_TRUE(result);
  9762. EXPECT_EQ(StatusCode::OK_200, result->status);
  9763. if (i == keep_alive_max_count - 1) {
  9764. EXPECT_EQ("close", result->get_header_value("Connection"));
  9765. } else {
  9766. EXPECT_FALSE(result->has_header("Connection"));
  9767. }
  9768. }
  9769. }
  9770. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  9771. // can pull the next one into the server's buffer. The server must serve it
  9772. // without waiting for the socket to become readable again. The keep-alive
  9773. // timeout outlasts the client's read timeout, so a request left waiting for it
  9774. // shows up as a missing response.
  9775. static void serve_pipelining_routes(Server &svr,
  9776. const std::function<void(int)> &client) {
  9777. svr.set_keep_alive_timeout(5);
  9778. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  9779. res.set_content("hi " + req.matches[1].str(), "text/plain");
  9780. });
  9781. svr.Post("/echo", [](const Request &req, Response &res) {
  9782. res.set_content("echo " + req.body, "text/plain");
  9783. });
  9784. auto port = svr.bind_to_any_port(HOST);
  9785. thread t = thread([&] { svr.listen_after_bind(); });
  9786. auto se = detail::scope_exit([&] {
  9787. svr.stop();
  9788. t.join();
  9789. });
  9790. svr.wait_until_ready();
  9791. client(port);
  9792. }
  9793. static std::string
  9794. send_pipelined_requests(const std::vector<std::string> &parts) {
  9795. Server svr;
  9796. std::string res;
  9797. serve_pipelining_routes(svr, [&](int port) {
  9798. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  9799. });
  9800. return res;
  9801. }
  9802. static void expect_in_order(const std::string &res,
  9803. const std::vector<std::string> &bodies) {
  9804. size_t pos = 0;
  9805. for (const auto &body : bodies) {
  9806. pos = res.find(body, pos);
  9807. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  9808. pos += body.size();
  9809. }
  9810. }
  9811. TEST(KeepAliveTest, PipelinedRequests) {
  9812. auto res = send_pipelined_requests(
  9813. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9814. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  9815. "Content-Length: 4\r\n\r\nbody"
  9816. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  9817. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  9818. }
  9819. // The second request starts in the server's buffer and ends on the socket.
  9820. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  9821. auto res =
  9822. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9823. "GET /hi/2 HTTP/1.1\r\nHo",
  9824. "st: localhost\r\nConnection: close\r\n\r\n"});
  9825. expect_in_order(res, {"hi 1", "hi 2"});
  9826. }
  9827. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  9828. // CRLF after a body does not turn into a 400 for the next request.
  9829. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  9830. auto res = send_pipelined_requests(
  9831. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  9832. "Content-Length: 4\r\n\r\nbody\r\n"
  9833. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  9834. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  9835. expect_in_order(res, {"echo body", "hi 2"});
  9836. }
  9837. // Where an unparsable request ends is unknown, so what follows it in the buffer
  9838. // must not be served as the next request.
  9839. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  9840. auto res = send_pipelined_requests(
  9841. {"INVALID REQUEST LINE\r\n\r\n"
  9842. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  9843. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9844. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  9845. }
  9846. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9847. // Over TLS, the next request is held by the TLS library as already decrypted
  9848. // data rather than on the socket.
  9849. TEST(KeepAliveTest, SSLPipelinedRequests) {
  9850. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9851. std::string res;
  9852. serve_pipelining_routes(svr, [&](int port) {
  9853. auto error = Error::Success;
  9854. auto sock = detail::create_client_socket(
  9855. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9856. /*connection_timeout_sec=*/5, 0,
  9857. /*read_timeout_sec=*/2, 0,
  9858. /*write_timeout_sec=*/5, 0, std::string(), error);
  9859. ASSERT_NE(INVALID_SOCKET, sock);
  9860. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9861. auto ctx = SSL_CTX_new(TLS_client_method());
  9862. auto ssl = SSL_new(ctx);
  9863. auto ssl_se = detail::scope_exit([&] {
  9864. SSL_free(ssl);
  9865. SSL_CTX_free(ctx);
  9866. });
  9867. SSL_set_fd(ssl, static_cast<int>(sock));
  9868. ASSERT_EQ(1, SSL_connect(ssl));
  9869. // One write, so all three requests arrive in one TLS record
  9870. const std::string req =
  9871. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9872. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9873. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
  9874. ASSERT_EQ(static_cast<int>(req.size()),
  9875. SSL_write(ssl, req.data(), static_cast<int>(req.size())));
  9876. char buf[512];
  9877. int n;
  9878. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9879. res.append(buf, static_cast<size_t>(n));
  9880. }
  9881. });
  9882. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  9883. }
  9884. #endif
  9885. TEST(KeepAliveTest, Issue1041) {
  9886. Server svr;
  9887. svr.set_keep_alive_timeout(3);
  9888. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9889. res.set_content("Hello World!", "text/plain");
  9890. });
  9891. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9892. auto se = detail::scope_exit([&] {
  9893. svr.stop();
  9894. listen_thread.join();
  9895. ASSERT_FALSE(svr.is_running());
  9896. });
  9897. svr.wait_until_ready();
  9898. Client cli(HOST, PORT);
  9899. cli.set_keep_alive(true);
  9900. auto result = cli.Get("/hi");
  9901. ASSERT_TRUE(result);
  9902. EXPECT_EQ(StatusCode::OK_200, result->status);
  9903. std::this_thread::sleep_for(std::chrono::seconds(5));
  9904. result = cli.Get("/hi");
  9905. ASSERT_TRUE(result);
  9906. EXPECT_EQ(StatusCode::OK_200, result->status);
  9907. }
  9908. TEST(KeepAliveTest, Issue1959) {
  9909. Server svr;
  9910. svr.set_keep_alive_timeout(5);
  9911. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9912. res.set_content("a", "text/plain");
  9913. });
  9914. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9915. auto se = detail::scope_exit([&] {
  9916. if (!svr.is_running()) return;
  9917. svr.stop();
  9918. listen_thread.join();
  9919. ASSERT_FALSE(svr.is_running());
  9920. });
  9921. svr.wait_until_ready();
  9922. Client cli("localhost", PORT);
  9923. cli.set_keep_alive(true);
  9924. using namespace std::chrono;
  9925. auto start = steady_clock::now();
  9926. cli.Get("/a");
  9927. svr.stop();
  9928. listen_thread.join();
  9929. auto end = steady_clock::now();
  9930. auto elapsed = duration_cast<milliseconds>(end - start).count();
  9931. EXPECT_LT(elapsed, 5000);
  9932. }
  9933. #ifdef CPPHTTPLIB_SSL_ENABLED
  9934. TEST(KeepAliveTest, SSLClientReconnection) {
  9935. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9936. ASSERT_TRUE(svr.is_valid());
  9937. svr.set_keep_alive_timeout(1);
  9938. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9939. res.set_content("Hello World!", "text/plain");
  9940. });
  9941. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9942. auto se = detail::scope_exit([&] {
  9943. svr.stop();
  9944. listen_thread.join();
  9945. ASSERT_FALSE(svr.is_running());
  9946. });
  9947. svr.wait_until_ready();
  9948. SSLClient cli(HOST, PORT);
  9949. cli.enable_server_certificate_verification(false);
  9950. cli.set_keep_alive(true);
  9951. auto result = cli.Get("/hi");
  9952. ASSERT_TRUE(result);
  9953. EXPECT_EQ(StatusCode::OK_200, result->status);
  9954. result = cli.Get("/hi");
  9955. ASSERT_TRUE(result);
  9956. EXPECT_EQ(StatusCode::OK_200, result->status);
  9957. std::this_thread::sleep_for(std::chrono::seconds(2));
  9958. // Recoonect
  9959. result = cli.Get("/hi");
  9960. ASSERT_TRUE(result);
  9961. EXPECT_EQ(StatusCode::OK_200, result->status);
  9962. result = cli.Get("/hi");
  9963. ASSERT_TRUE(result);
  9964. EXPECT_EQ(StatusCode::OK_200, result->status);
  9965. }
  9966. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  9967. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9968. ASSERT_TRUE(svr.is_valid());
  9969. svr.set_keep_alive_timeout(1);
  9970. std::string content = "reconnect";
  9971. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  9972. res.set_content("Hello World!", "text/plain");
  9973. });
  9974. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9975. auto se = detail::scope_exit([&] {
  9976. svr.stop();
  9977. listen_thread.join();
  9978. ASSERT_FALSE(svr.is_running());
  9979. });
  9980. svr.wait_until_ready();
  9981. SSLClient cli(HOST, PORT);
  9982. cli.enable_server_certificate_verification(false);
  9983. cli.set_keep_alive(true);
  9984. auto result = cli.Post(
  9985. "/hi", content.size(),
  9986. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9987. sink.write(content.c_str(), content.size());
  9988. return true;
  9989. },
  9990. "text/plain");
  9991. ASSERT_TRUE(result);
  9992. EXPECT_EQ(200, result->status);
  9993. std::this_thread::sleep_for(std::chrono::seconds(2));
  9994. // Recoonect
  9995. result = cli.Post(
  9996. "/hi", content.size(),
  9997. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9998. sink.write(content.c_str(), content.size());
  9999. return true;
  10000. },
  10001. "text/plain");
  10002. ASSERT_TRUE(result);
  10003. EXPECT_EQ(200, result->status);
  10004. result = cli.Post(
  10005. "/hi", content.size(),
  10006. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10007. sink.write(content.c_str(), content.size());
  10008. return true;
  10009. },
  10010. "text/plain");
  10011. ASSERT_TRUE(result);
  10012. EXPECT_EQ(200, result->status);
  10013. }
  10014. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10015. using namespace httplib::tls;
  10016. {
  10017. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10018. ASSERT_TRUE(svr.is_valid());
  10019. svr.Get("/sni", [&](const Request &req, Response &res) {
  10020. std::string expected = req.sni();
  10021. EXPECT_EQ(expected, req.get_param_value("expected"));
  10022. res.set_content("ok", "text/plain");
  10023. });
  10024. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10025. auto se = detail::scope_exit([&] {
  10026. svr.stop();
  10027. listen_thread.join();
  10028. ASSERT_FALSE(svr.is_running());
  10029. });
  10030. svr.wait_until_ready();
  10031. {
  10032. SSLClient cli("localhost", PORT);
  10033. cli.enable_server_certificate_verification(false);
  10034. auto res = cli.Get("/sni?expected=localhost");
  10035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10036. }
  10037. {
  10038. SSLClient cli("::1", PORT);
  10039. cli.enable_server_certificate_verification(false);
  10040. auto res = cli.Get("/sni?expected=");
  10041. // NOTE: This may fail if the server is listening on IPv4 only
  10042. // (e.g., when localhost resolves to 127.0.0.1 only)
  10043. if (res) {
  10044. EXPECT_EQ(StatusCode::OK_200, res->status);
  10045. } else {
  10046. EXPECT_EQ(Error::Connection, res.error());
  10047. }
  10048. }
  10049. }
  10050. }
  10051. #endif
  10052. TEST(ClientProblemDetectionTest, ContentProvider) {
  10053. Server svr;
  10054. size_t content_length = 1024 * 1024;
  10055. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10056. res.set_content_provider(
  10057. content_length, "text/plain",
  10058. [&](size_t offset, size_t length, DataSink &sink) {
  10059. auto out_len = std::min(length, static_cast<size_t>(1024));
  10060. std::string out(out_len, '@');
  10061. sink.write(out.data(), out_len);
  10062. return offset < 4096;
  10063. },
  10064. [](bool success) { ASSERT_FALSE(success); });
  10065. });
  10066. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10067. res.set_content_provider(
  10068. 0, "text/plain",
  10069. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10070. EXPECT_TRUE(false);
  10071. return true;
  10072. },
  10073. [](bool success) { ASSERT_FALSE(success); });
  10074. });
  10075. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10076. auto se = detail::scope_exit([&] {
  10077. svr.stop();
  10078. listen_thread.join();
  10079. ASSERT_FALSE(svr.is_running());
  10080. });
  10081. svr.wait_until_ready();
  10082. Client cli("localhost", PORT);
  10083. {
  10084. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10085. size_t /*data_length*/) { return false; });
  10086. ASSERT_FALSE(res);
  10087. }
  10088. {
  10089. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10090. size_t /*data_length*/) { return false; });
  10091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10092. }
  10093. }
  10094. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10095. // A provider that reports success without writing anything and without
  10096. // calling done() used to be handed the same offset and length again on every
  10097. // pass, so it spun for as long as the peer stayed connected.
  10098. Server svr;
  10099. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10100. res.set_content("ok", "text/plain");
  10101. });
  10102. auto port = svr.bind_to_any_port(HOST);
  10103. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10104. auto se = detail::scope_exit([&] {
  10105. svr.stop();
  10106. listen_thread.join();
  10107. ASSERT_FALSE(svr.is_running());
  10108. });
  10109. svr.wait_until_ready();
  10110. std::atomic<int> call_count{0};
  10111. Client cli(HOST, port);
  10112. auto res = cli.Post(
  10113. "/", 1024,
  10114. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10115. // Give up after enough passes to show the spin, so that losing the
  10116. // check below fails this test instead of hanging it.
  10117. return ++call_count < 100;
  10118. },
  10119. "text/plain");
  10120. ASSERT_FALSE(res);
  10121. EXPECT_EQ(Error::Write, res.error());
  10122. EXPECT_EQ(1, call_count.load());
  10123. }
  10124. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10125. // A writer only has to assign `write`. The other three used to be left as
  10126. // empty std::functions, so a provider calling one threw
  10127. // std::bad_function_call out of the thread running it and took the whole
  10128. // process down.
  10129. DataSink sink;
  10130. std::string written;
  10131. sink.write = [&](const char *data, size_t data_len) {
  10132. written.append(data, data_len);
  10133. return true;
  10134. };
  10135. EXPECT_TRUE(sink.is_writable());
  10136. sink.done();
  10137. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10138. EXPECT_TRUE(written.empty());
  10139. }
  10140. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10141. // A sink that cannot carry trailers still has to finish.
  10142. DataSink sink;
  10143. auto done_count = 0;
  10144. sink.done = [&]() { done_count++; };
  10145. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10146. EXPECT_EQ(1, done_count);
  10147. }
  10148. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10149. Server svr;
  10150. const std::string body(4096, 'x');
  10151. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10152. res.set_content_provider(body.size(), "text/plain",
  10153. [&](size_t offset, size_t length, DataSink &sink) {
  10154. sink.write(body.data() + offset, length);
  10155. sink.done();
  10156. return true;
  10157. });
  10158. });
  10159. auto port = svr.bind_to_any_port(HOST);
  10160. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10161. auto se = detail::scope_exit([&] {
  10162. svr.stop();
  10163. listen_thread.join();
  10164. ASSERT_FALSE(svr.is_running());
  10165. });
  10166. svr.wait_until_ready();
  10167. Client cli(HOST, port);
  10168. auto res = cli.Get("/");
  10169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10170. EXPECT_EQ(StatusCode::OK_200, res->status);
  10171. EXPECT_EQ(body, res->body);
  10172. }
  10173. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10174. Server svr;
  10175. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10176. res.set_content_provider(
  10177. 1024, "text/plain",
  10178. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10179. sink.write("hello", 5);
  10180. sink.done(); // short of the 1024 bytes the response promised
  10181. return true;
  10182. });
  10183. });
  10184. auto port = svr.bind_to_any_port(HOST);
  10185. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10186. auto se = detail::scope_exit([&] {
  10187. svr.stop();
  10188. listen_thread.join();
  10189. ASSERT_FALSE(svr.is_running());
  10190. });
  10191. svr.wait_until_ready();
  10192. Client cli(HOST, port);
  10193. cli.set_read_timeout(5, 0);
  10194. // The response is short of its Content-Length, so the client cannot read a
  10195. // complete body. What matters is that this returns at all: a no-op done()
  10196. // would leave the writer looping over a provider that never makes progress.
  10197. auto res = cli.Get("/");
  10198. EXPECT_FALSE(res);
  10199. }
  10200. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10201. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10202. // The compressed path builds the whole body before connecting, so this
  10203. // fails client-side and never reaches a server.
  10204. Client cli(HOST, PORT);
  10205. cli.set_compress(true);
  10206. auto res = cli.Post(
  10207. "/", 1024,
  10208. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10209. sink.write("hello", 5);
  10210. sink.done(); // short of the 1024 bytes the request announced
  10211. return true;
  10212. },
  10213. "text/plain");
  10214. ASSERT_FALSE(res);
  10215. EXPECT_EQ(Error::Write, res.error());
  10216. }
  10217. #endif
  10218. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  10219. Server svr;
  10220. svr.set_error_handler([](Request const &, Response &res) -> void {
  10221. res.set_chunked_content_provider(
  10222. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10223. sink.os << "hello";
  10224. sink.os << "world";
  10225. sink.done();
  10226. return true;
  10227. });
  10228. });
  10229. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10230. auto se = detail::scope_exit([&] {
  10231. svr.stop();
  10232. listen_thread.join();
  10233. ASSERT_FALSE(svr.is_running());
  10234. });
  10235. svr.wait_until_ready();
  10236. Client cli("localhost", PORT);
  10237. auto res = cli.Get("/");
  10238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10239. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10240. EXPECT_EQ("helloworld", res->body);
  10241. }
  10242. TEST(LongPollingTest, ClientCloseDetection) {
  10243. Server svr;
  10244. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10245. res.set_chunked_content_provider(
  10246. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10247. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10248. sink.os << "hello";
  10249. auto count = 10;
  10250. while (count > 0 && sink.is_writable()) {
  10251. this_thread::sleep_for(chrono::milliseconds(10));
  10252. count--;
  10253. }
  10254. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  10255. return true;
  10256. });
  10257. });
  10258. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10259. auto se = detail::scope_exit([&] {
  10260. svr.stop();
  10261. listen_thread.join();
  10262. ASSERT_FALSE(svr.is_running());
  10263. });
  10264. svr.wait_until_ready();
  10265. Client cli("localhost", PORT);
  10266. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10267. EXPECT_EQ("hello", string(data, data_length));
  10268. return false; // close the socket immediately.
  10269. });
  10270. ASSERT_FALSE(res);
  10271. }
  10272. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  10273. Server svr;
  10274. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10275. res.set_chunked_content_provider(
  10276. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10277. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10278. sink.os << "hello";
  10279. EXPECT_TRUE(sink.os.good());
  10280. // Wait for the client to close the connection
  10281. auto count = 10;
  10282. while (count > 0 && sink.is_writable()) {
  10283. this_thread::sleep_for(chrono::milliseconds(10));
  10284. count--;
  10285. }
  10286. // After client disconnect, write repeatedly until the socket
  10287. // write actually fails (small writes may be absorbed by the
  10288. // kernel buffer)
  10289. std::string chunk(1024, 'x');
  10290. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  10291. sink.os << chunk;
  10292. }
  10293. EXPECT_TRUE(sink.os.fail());
  10294. return true;
  10295. });
  10296. });
  10297. auto port = svr.bind_to_any_port("localhost");
  10298. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10299. auto se = detail::scope_exit([&] {
  10300. svr.stop();
  10301. listen_thread.join();
  10302. ASSERT_FALSE(svr.is_running());
  10303. });
  10304. svr.wait_until_ready();
  10305. Client cli("localhost", port);
  10306. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10307. EXPECT_EQ("hello", string(data, data_length));
  10308. return false; // close the socket immediately.
  10309. });
  10310. ASSERT_FALSE(res);
  10311. }
  10312. TEST(GetWithParametersTest, GetWithParameters) {
  10313. Server svr;
  10314. svr.Get("/", [&](const Request &req, Response &) {
  10315. EXPECT_EQ("world", req.get_param_value("hello"));
  10316. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10317. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10318. });
  10319. svr.Get("/params", [&](const Request &req, Response &) {
  10320. EXPECT_EQ("world", req.get_param_value("hello"));
  10321. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10322. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10323. });
  10324. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10325. EXPECT_EQ("resource-id", req.matches[1]);
  10326. EXPECT_EQ("foo", req.get_param_value("param1"));
  10327. EXPECT_EQ("bar", req.get_param_value("param2"));
  10328. });
  10329. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10330. EXPECT_EQ("user-id", req.path_params.at("id"));
  10331. EXPECT_EQ("foo", req.get_param_value("param1"));
  10332. EXPECT_EQ("bar", req.get_param_value("param2"));
  10333. });
  10334. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10335. auto se = detail::scope_exit([&] {
  10336. svr.stop();
  10337. listen_thread.join();
  10338. ASSERT_FALSE(svr.is_running());
  10339. });
  10340. svr.wait_until_ready();
  10341. {
  10342. Client cli(HOST, PORT);
  10343. Params params;
  10344. params.emplace("hello", "world");
  10345. params.emplace("hello2", "world2");
  10346. params.emplace("hello3", "world3");
  10347. auto res = cli.Get("/", params, Headers{});
  10348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10349. EXPECT_EQ(StatusCode::OK_200, res->status);
  10350. }
  10351. {
  10352. Client cli(HOST, PORT);
  10353. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10355. EXPECT_EQ(StatusCode::OK_200, res->status);
  10356. }
  10357. {
  10358. Client cli(HOST, PORT);
  10359. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  10360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10361. EXPECT_EQ(StatusCode::OK_200, res->status);
  10362. }
  10363. {
  10364. Client cli(HOST, PORT);
  10365. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  10366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10367. EXPECT_EQ(StatusCode::OK_200, res->status);
  10368. }
  10369. }
  10370. TEST(GetWithParametersTest, GetWithParameters2) {
  10371. Server svr;
  10372. svr.Get("/", [&](const Request &req, Response &res) {
  10373. auto text = req.get_param_value("hello");
  10374. res.set_content(text, "text/plain");
  10375. });
  10376. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10377. auto se = detail::scope_exit([&] {
  10378. svr.stop();
  10379. listen_thread.join();
  10380. ASSERT_FALSE(svr.is_running());
  10381. });
  10382. svr.wait_until_ready();
  10383. Client cli("localhost", PORT);
  10384. Params params;
  10385. params.emplace("hello", "world");
  10386. std::string body;
  10387. auto res = cli.Get("/", params, Headers{},
  10388. [&](const char *data, size_t data_length) {
  10389. body.append(data, data_length);
  10390. return true;
  10391. });
  10392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10393. EXPECT_EQ(StatusCode::OK_200, res->status);
  10394. EXPECT_EQ("world", body);
  10395. }
  10396. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  10397. Server svr;
  10398. svr.Get("/search", [&](const Request &req, Response &res) {
  10399. auto q = req.get_param_value("q");
  10400. res.set_content(q, "text/plain");
  10401. });
  10402. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10403. auto se = detail::scope_exit([&] {
  10404. svr.stop();
  10405. listen_thread.join();
  10406. ASSERT_FALSE(svr.is_running());
  10407. });
  10408. svr.wait_until_ready();
  10409. Client cli("localhost", PORT);
  10410. // Verify that Get(path, params) works without requiring Headers argument
  10411. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  10412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10413. EXPECT_EQ(StatusCode::OK_200, res->status);
  10414. EXPECT_EQ("cpp-httplib", res->body);
  10415. }
  10416. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  10417. auto host = "httpbingo.org";
  10418. auto path = std::string{"/range/32"};
  10419. #ifdef CPPHTTPLIB_SSL_ENABLED
  10420. SSLClient cli(host);
  10421. #else
  10422. Client cli(host);
  10423. #endif
  10424. cli.set_default_headers({make_range_header({{1, 10}})});
  10425. cli.set_connection_timeout(5);
  10426. {
  10427. auto res = cli.Get(path);
  10428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10429. EXPECT_EQ("bcdefghijk", res->body);
  10430. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10431. }
  10432. {
  10433. auto res = cli.Get(path);
  10434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10435. EXPECT_EQ("bcdefghijk", res->body);
  10436. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10437. }
  10438. }
  10439. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  10440. Server svr;
  10441. svr.set_default_headers({{"Hello", "World"}});
  10442. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10443. res.set_content("ok", "text/plain");
  10444. });
  10445. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10446. auto se = detail::scope_exit([&] {
  10447. svr.stop();
  10448. listen_thread.join();
  10449. ASSERT_FALSE(svr.is_running());
  10450. });
  10451. svr.wait_until_ready();
  10452. Client cli("localhost", PORT);
  10453. auto res = cli.Get("/");
  10454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10455. EXPECT_EQ(StatusCode::OK_200, res->status);
  10456. EXPECT_EQ("ok", res->body);
  10457. EXPECT_EQ("World", res->get_header_value("Hello"));
  10458. }
  10459. #ifdef CPPHTTPLIB_SSL_ENABLED
  10460. TEST(KeepAliveTest, ReadTimeoutSSL) {
  10461. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10462. ASSERT_TRUE(svr.is_valid());
  10463. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10464. std::this_thread::sleep_for(std::chrono::seconds(2));
  10465. res.set_content("a", "text/plain");
  10466. });
  10467. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10468. res.set_content("b", "text/plain");
  10469. });
  10470. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10471. auto se = detail::scope_exit([&] {
  10472. svr.stop();
  10473. listen_thread.join();
  10474. ASSERT_FALSE(svr.is_running());
  10475. });
  10476. svr.wait_until_ready();
  10477. SSLClient cli("localhost", PORT);
  10478. cli.enable_server_certificate_verification(false);
  10479. cli.set_keep_alive(true);
  10480. cli.set_read_timeout(std::chrono::seconds(1));
  10481. auto resa = cli.Get("/a");
  10482. ASSERT_TRUE(!resa);
  10483. EXPECT_EQ(Error::Read, resa.error());
  10484. auto resb = cli.Get("/b");
  10485. ASSERT_TRUE(resb);
  10486. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10487. EXPECT_EQ("b", resb->body);
  10488. }
  10489. // Closing an idle keep-alive connection sends close_notify and returns. The
  10490. // server must not wait for the client's close_notify: an idle client never
  10491. // sends one, so the worker would be held until the read timeout expires, and
  10492. // stop() would wait for it.
  10493. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  10494. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10495. ASSERT_TRUE(svr.is_valid());
  10496. svr.set_keep_alive_timeout(1);
  10497. svr.set_read_timeout(10, 0);
  10498. svr.Get("/", [](const Request &, Response &res) {
  10499. res.set_content("ok", "text/plain");
  10500. });
  10501. auto port = svr.bind_to_any_port(HOST);
  10502. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10503. auto se = detail::scope_exit([&] {
  10504. if (listen_thread.joinable()) {
  10505. svr.stop();
  10506. listen_thread.join();
  10507. }
  10508. });
  10509. svr.wait_until_ready();
  10510. SSLClient cli(HOST, port);
  10511. cli.enable_server_certificate_verification(false);
  10512. cli.set_keep_alive(true);
  10513. auto res = cli.Get("/");
  10514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10515. EXPECT_EQ(StatusCode::OK_200, res->status);
  10516. // Stay idle past the keep-alive timeout so the server closes the connection.
  10517. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  10518. auto start = std::chrono::steady_clock::now();
  10519. svr.stop();
  10520. listen_thread.join();
  10521. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10522. std::chrono::steady_clock::now() - start)
  10523. .count();
  10524. EXPECT_LT(elapsed, 3000);
  10525. }
  10526. #endif
  10527. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  10528. protected:
  10529. ServerTestWithAI_PASSIVE()
  10530. : cli_(HOST, PORT)
  10531. #ifdef CPPHTTPLIB_SSL_ENABLED
  10532. ,
  10533. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10534. #endif
  10535. {
  10536. #ifdef CPPHTTPLIB_SSL_ENABLED
  10537. cli_.enable_server_certificate_verification(false);
  10538. #endif
  10539. }
  10540. virtual void SetUp() {
  10541. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10542. res.set_content("Hello World!", "text/plain");
  10543. });
  10544. t_ = thread(
  10545. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  10546. svr_.wait_until_ready();
  10547. }
  10548. virtual void TearDown() {
  10549. svr_.stop();
  10550. t_.join();
  10551. }
  10552. #ifdef CPPHTTPLIB_SSL_ENABLED
  10553. SSLClient cli_;
  10554. SSLServer svr_;
  10555. #else
  10556. Client cli_;
  10557. Server svr_;
  10558. #endif
  10559. thread t_;
  10560. };
  10561. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  10562. auto res = cli_.Get("/hi");
  10563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10564. EXPECT_EQ(StatusCode::OK_200, res->status);
  10565. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  10566. EXPECT_EQ("Hello World!", res->body);
  10567. }
  10568. class ServerUpDownTest : public ::testing::Test {
  10569. protected:
  10570. ServerUpDownTest() : cli_(HOST, PORT) {}
  10571. virtual void SetUp() {
  10572. t_ = thread([&]() {
  10573. svr_.bind_to_any_port(HOST);
  10574. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10575. ASSERT_TRUE(svr_.listen_after_bind());
  10576. });
  10577. svr_.wait_until_ready();
  10578. }
  10579. virtual void TearDown() {
  10580. svr_.stop();
  10581. t_.join();
  10582. }
  10583. Client cli_;
  10584. Server svr_;
  10585. thread t_;
  10586. };
  10587. TEST_F(ServerUpDownTest, QuickStartStop) {
  10588. // Should not crash, especially when run with
  10589. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  10590. }
  10591. class PayloadMaxLengthTest : public ::testing::Test {
  10592. protected:
  10593. PayloadMaxLengthTest()
  10594. : cli_(HOST, PORT)
  10595. #ifdef CPPHTTPLIB_SSL_ENABLED
  10596. ,
  10597. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10598. #endif
  10599. {
  10600. #ifdef CPPHTTPLIB_SSL_ENABLED
  10601. cli_.enable_server_certificate_verification(false);
  10602. #endif
  10603. }
  10604. virtual void SetUp() {
  10605. svr_.set_payload_max_length(8);
  10606. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10607. res.set_content("test", "text/plain");
  10608. });
  10609. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10610. svr_.wait_until_ready();
  10611. }
  10612. virtual void TearDown() {
  10613. svr_.stop();
  10614. t_.join();
  10615. }
  10616. #ifdef CPPHTTPLIB_SSL_ENABLED
  10617. SSLClient cli_;
  10618. SSLServer svr_;
  10619. #else
  10620. Client cli_;
  10621. Server svr_;
  10622. #endif
  10623. thread t_;
  10624. };
  10625. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  10626. auto res = cli_.Post("/test", "123456789", "text/plain");
  10627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10628. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10629. res = cli_.Post("/test", "12345678", "text/plain");
  10630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10631. EXPECT_EQ(StatusCode::OK_200, res->status);
  10632. }
  10633. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  10634. // Test chunked encoding with payload exceeding the 8-byte limit
  10635. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  10636. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  10637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10638. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10639. }
  10640. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  10641. // Test chunked encoding with payload within the 8-byte limit
  10642. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  10643. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  10644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10645. EXPECT_EQ(StatusCode::OK_200, res->status);
  10646. }
  10647. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  10648. // Test using send_request to send chunked data exceeding payload limit
  10649. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  10650. "Host: " +
  10651. std::string(HOST) + ":" + std::to_string(PORT) +
  10652. "\r\n"
  10653. "Transfer-Encoding: chunked\r\n"
  10654. "Connection: close\r\n"
  10655. "\r\n"
  10656. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  10657. "0123456789\r\n"
  10658. "0\r\n" // End chunk
  10659. "\r\n";
  10660. std::string response;
  10661. bool result = send_request(1, chunked_request, &response);
  10662. if (!result) {
  10663. // If send_request fails, it might be because the server closed the
  10664. // connection due to payload limit enforcement, which is acceptable
  10665. SUCCEED()
  10666. << "Server rejected oversized chunked request (connection closed)";
  10667. } else {
  10668. // If we got a response, check if it's an error response or connection was
  10669. // closed early Short response length indicates connection was closed due to
  10670. // payload limit
  10671. if (response.length() <= 10) {
  10672. SUCCEED() << "Server closed connection for oversized chunked request";
  10673. } else {
  10674. // Check for error status codes
  10675. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10676. response.find("Payload Too Large") != std::string::npos ||
  10677. response.find("400") != std::string::npos);
  10678. }
  10679. }
  10680. }
  10681. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  10682. // Test request without Content-Length header exceeding payload limit
  10683. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10684. "Host: " +
  10685. std::string(HOST) + ":" +
  10686. std::to_string(PORT) +
  10687. "\r\n"
  10688. "Connection: close\r\n"
  10689. "\r\n";
  10690. // Add payload exceeding the 8-byte limit
  10691. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  10692. request_without_content_length += large_payload;
  10693. std::string response;
  10694. bool result = send_request(1, request_without_content_length, &response);
  10695. if (!result) {
  10696. // If send_request fails, server likely closed connection due to payload
  10697. // limit
  10698. SUCCEED() << "Server rejected oversized request without Content-Length "
  10699. "(connection closed)";
  10700. } else {
  10701. // Check if server responded with error or closed connection early
  10702. if (response.length() <= 10) {
  10703. SUCCEED() << "Server closed connection for oversized request without "
  10704. "Content-Length";
  10705. } else {
  10706. // Check for error status codes
  10707. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10708. response.find("Payload Too Large") != std::string::npos ||
  10709. response.find("400") != std::string::npos);
  10710. }
  10711. }
  10712. }
  10713. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  10714. // Test request without Content-Length header within payload limit
  10715. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10716. "Host: " +
  10717. std::string(HOST) + ":" +
  10718. std::to_string(PORT) +
  10719. "\r\n"
  10720. "Connection: close\r\n"
  10721. "\r\n";
  10722. // Add payload within the 8-byte limit
  10723. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  10724. request_without_content_length += small_payload;
  10725. std::string response;
  10726. bool result = send_request(1, request_without_content_length, &response);
  10727. // For requests without Content-Length, the server may have different behavior
  10728. // The key is that it should not reject due to payload limit for small
  10729. // payloads
  10730. if (result) {
  10731. // Check for any HTTP response (success or error, but not connection closed)
  10732. if (response.length() > 10) {
  10733. SUCCEED()
  10734. << "Server processed request without Content-Length within limit";
  10735. } else {
  10736. // Short response might indicate connection closed, which is acceptable
  10737. SUCCEED() << "Server closed connection for request without "
  10738. "Content-Length (acceptable behavior)";
  10739. }
  10740. } else {
  10741. // Connection failure might be due to protocol requirements
  10742. SUCCEED() << "Connection issue with request without Content-Length "
  10743. "(environment-specific)";
  10744. }
  10745. }
  10746. class LargePayloadMaxLengthTest : public ::testing::Test {
  10747. protected:
  10748. LargePayloadMaxLengthTest()
  10749. : cli_(HOST, PORT)
  10750. #ifdef CPPHTTPLIB_SSL_ENABLED
  10751. ,
  10752. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10753. #endif
  10754. {
  10755. #ifdef CPPHTTPLIB_SSL_ENABLED
  10756. cli_.enable_server_certificate_verification(false);
  10757. #endif
  10758. }
  10759. virtual void SetUp() {
  10760. // Set 10MB payload limit
  10761. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  10762. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  10763. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10764. res.set_content("Large payload test", "text/plain");
  10765. });
  10766. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10767. svr_.wait_until_ready();
  10768. }
  10769. virtual void TearDown() {
  10770. svr_.stop();
  10771. t_.join();
  10772. }
  10773. #ifdef CPPHTTPLIB_SSL_ENABLED
  10774. SSLClient cli_;
  10775. SSLServer svr_;
  10776. #else
  10777. Client cli_;
  10778. Server svr_;
  10779. #endif
  10780. thread t_;
  10781. };
  10782. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  10783. // Test chunked encoding with payload within 10MB limit
  10784. std::string medium_payload(5 * 1024 * 1024,
  10785. 'A'); // 5MB payload, within 10MB limit
  10786. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  10787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10788. EXPECT_EQ(StatusCode::OK_200, res->status);
  10789. }
  10790. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  10791. // Test chunked encoding with payload exceeding 10MB limit
  10792. std::string large_payload(12 * 1024 * 1024,
  10793. 'B'); // 12MB payload, exceeds 10MB limit
  10794. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  10795. // Server may either return 413 or close the connection
  10796. if (res) {
  10797. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10798. } else {
  10799. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  10800. }
  10801. }
  10802. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  10803. // Test request without Content-Length header within 10MB limit
  10804. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10805. "Host: " +
  10806. std::string(HOST) + ":" +
  10807. std::to_string(PORT) +
  10808. "\r\n"
  10809. "Connection: close\r\n"
  10810. "\r\n";
  10811. // Add 1MB payload (within 10MB limit)
  10812. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  10813. request_without_content_length += medium_payload;
  10814. std::string response;
  10815. bool result = send_request(5, request_without_content_length, &response);
  10816. if (result) {
  10817. // Should get a proper HTTP response for payloads within limit
  10818. if (response.length() > 10) {
  10819. SUCCEED() << "Server processed 1MB request without Content-Length within "
  10820. "10MB limit";
  10821. } else {
  10822. SUCCEED() << "Server closed connection (acceptable behavior for no "
  10823. "Content-Length)";
  10824. }
  10825. } else {
  10826. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  10827. }
  10828. }
  10829. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  10830. // Test request without Content-Length header exceeding 10MB limit
  10831. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10832. "Host: " +
  10833. std::string(HOST) + ":" +
  10834. std::to_string(PORT) +
  10835. "\r\n"
  10836. "Connection: close\r\n"
  10837. "\r\n";
  10838. // Add 12MB payload (exceeds 10MB limit)
  10839. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  10840. request_without_content_length += large_payload;
  10841. std::string response;
  10842. bool result = send_request(10, request_without_content_length, &response);
  10843. if (!result) {
  10844. // Server should close connection due to payload limit
  10845. SUCCEED() << "Server rejected 12MB request without Content-Length "
  10846. "(connection closed)";
  10847. } else {
  10848. // Check for error response
  10849. if (response.length() <= 10) {
  10850. SUCCEED()
  10851. << "Server closed connection for 12MB request exceeding 10MB limit";
  10852. } else {
  10853. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10854. response.find("Payload Too Large") != std::string::npos ||
  10855. response.find("400") != std::string::npos);
  10856. }
  10857. }
  10858. }
  10859. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10860. // `payload_max_length` is not enforced on decompressed body in ContentReader
  10861. // path.
  10862. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  10863. Server svr;
  10864. const size_t LIMIT = 64 * 1024; // 64KB
  10865. svr.set_payload_max_length(LIMIT);
  10866. size_t total = 0;
  10867. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10868. const ContentReader &content_reader) {
  10869. content_reader([&](const char * /*data*/, size_t len) {
  10870. total += len;
  10871. return true;
  10872. });
  10873. res.status = 200;
  10874. res.set_content("stream_ok", "text/plain");
  10875. });
  10876. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10877. auto se = detail::scope_exit([&] {
  10878. svr.stop();
  10879. thread.join();
  10880. ASSERT_FALSE(svr.is_running());
  10881. });
  10882. svr.wait_until_ready();
  10883. // Prepare 256KB raw data and gzip-compress it
  10884. std::string raw(256 * 1024, 'A');
  10885. std::string gz;
  10886. {
  10887. z_stream zs{};
  10888. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  10889. Z_DEFAULT_STRATEGY);
  10890. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  10891. zs.avail_in = static_cast<uInt>(raw.size());
  10892. char outbuf[4096];
  10893. int ret;
  10894. do {
  10895. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  10896. zs.avail_out = sizeof(outbuf);
  10897. ret = deflate(&zs, Z_FINISH);
  10898. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  10899. } while (ret != Z_STREAM_END);
  10900. deflateEnd(&zs);
  10901. }
  10902. Client cli(HOST, PORT);
  10903. cli.set_connection_timeout(std::chrono::seconds(5));
  10904. Headers headers = {{"Content-Encoding", "gzip"}};
  10905. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  10906. "application/octet-stream");
  10907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10908. // Server must reject oversized decompressed payloads with 413.
  10909. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10910. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10911. EXPECT_LE(total, LIMIT);
  10912. }
  10913. #ifndef CPPHTTPLIB_SSL_ENABLED
  10914. // For a request with neither Content-Length nor Transfer-Encoding, the
  10915. // non-SSL raw-socket fallback in read_content_core() used to hand the
  10916. // compressed wire bytes straight to the ContentReader without ever routing
  10917. // them through the decompressor, so payload_max_length_ only bounded the
  10918. // compressed size on the wire, not the decompressed size.
  10919. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  10920. Server svr;
  10921. const size_t LIMIT = 64 * 1024; // 64KB
  10922. svr.set_payload_max_length(LIMIT);
  10923. size_t total = 0;
  10924. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10925. const ContentReader &content_reader) {
  10926. content_reader([&](const char * /*data*/, size_t len) {
  10927. total += len;
  10928. return true;
  10929. });
  10930. res.status = 200;
  10931. res.set_content("stream_ok", "text/plain");
  10932. });
  10933. auto port = svr.bind_to_any_port(HOST);
  10934. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10935. auto se = detail::scope_exit([&] {
  10936. svr.stop();
  10937. thread.join();
  10938. ASSERT_FALSE(svr.is_running());
  10939. });
  10940. svr.wait_until_ready();
  10941. // Prepare 256KB raw data and gzip-compress it, same payload as the
  10942. // StreamingGzipDecompression test above.
  10943. std::string raw(256 * 1024, 'A');
  10944. std::string gz;
  10945. {
  10946. httplib::detail::gzip_compressor compressor;
  10947. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  10948. [&](const char *chunk, size_t len) {
  10949. gz.append(chunk, len);
  10950. return true;
  10951. });
  10952. ASSERT_TRUE(result);
  10953. }
  10954. // Send the gzip body over raw TCP with neither Content-Length nor
  10955. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  10956. // kicks in.
  10957. std::string req = "POST /stream HTTP/1.1\r\n"
  10958. "Host: " +
  10959. std::string(HOST) + ":" + std::to_string(port) +
  10960. "\r\n"
  10961. "Content-Encoding: gzip\r\n"
  10962. "Connection: close\r\n"
  10963. "\r\n" +
  10964. gz;
  10965. std::string response;
  10966. ASSERT_TRUE(send_request(5, req, &response, port));
  10967. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10968. EXPECT_LE(total, LIMIT);
  10969. }
  10970. #endif
  10971. #endif
  10972. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  10973. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  10974. // the payload must be passed through untouched instead of being rejected.
  10975. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  10976. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10977. Server svr;
  10978. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  10979. res.set_content(body, "image/jpeg");
  10980. res.set_header("Content-Encoding", "UTF-8");
  10981. });
  10982. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  10983. res.set_content(body, "image/jpeg");
  10984. res.set_header("Content-Encoding", "identity");
  10985. });
  10986. svr.Post("/echo", [](const Request &req, Response &res) {
  10987. res.set_content(req.body, "image/jpeg");
  10988. });
  10989. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10990. auto se = detail::scope_exit([&] {
  10991. svr.stop();
  10992. t.join();
  10993. ASSERT_FALSE(svr.is_running());
  10994. });
  10995. svr.wait_until_ready();
  10996. Client cli(HOST, PORT);
  10997. {
  10998. auto res = cli.Get("/image");
  10999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11000. EXPECT_EQ(StatusCode::OK_200, res->status);
  11001. EXPECT_EQ(body, res->body);
  11002. }
  11003. {
  11004. auto res = cli.Get("/identity");
  11005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11006. EXPECT_EQ(StatusCode::OK_200, res->status);
  11007. EXPECT_EQ(body, res->body);
  11008. }
  11009. {
  11010. // The same applies to a request body reaching the server.
  11011. Headers headers = {{"Content-Encoding", "UTF-8"}};
  11012. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  11013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11014. EXPECT_EQ(StatusCode::OK_200, res->status);
  11015. EXPECT_EQ(body, res->body);
  11016. }
  11017. }
  11018. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  11019. // gzip-encoded response even when the build has no zlib support.
  11020. static const char GZIPPED_HELLO_WORLD[] = {
  11021. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  11022. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  11023. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  11024. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  11025. // A content coding is a whole token, not something the field value merely
  11026. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  11027. // as "fibre" look like Brotli, and turned a multi-coding value like
  11028. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  11029. // it was never meant to see.
  11030. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  11031. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11032. Server svr;
  11033. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  11034. res.set_content(body, "image/jpeg");
  11035. res.set_header("Content-Encoding", "fibre");
  11036. });
  11037. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  11038. res.set_content(body, "image/jpeg");
  11039. res.set_header("Content-Encoding", "gzip, br");
  11040. });
  11041. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  11042. res.set_content(body, "image/jpeg");
  11043. res.set_header("Content-Encoding", "x-zstd-ish");
  11044. });
  11045. auto port = svr.bind_to_any_port(HOST);
  11046. thread t = thread([&]() { svr.listen_after_bind(); });
  11047. auto se = detail::scope_exit([&] {
  11048. svr.stop();
  11049. t.join();
  11050. ASSERT_FALSE(svr.is_running());
  11051. });
  11052. svr.wait_until_ready();
  11053. Client cli(HOST, port);
  11054. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  11055. auto res = cli.Get(path);
  11056. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11057. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11058. // Not a coding we recognize, so the payload comes back untouched
  11059. EXPECT_EQ(body, res->body) << path;
  11060. }
  11061. }
  11062. // A content coding cpp-httplib recognizes but was not built with must be
  11063. // reported as such. Handing the still-compressed payload back to the caller
  11064. // would silently corrupt it.
  11065. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  11066. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11067. Server svr;
  11068. // "image/jpeg" keeps the server from applying a content coding of its own,
  11069. // so the hand-crafted Content-Encoding below survives.
  11070. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  11071. res.set_content(gzipped, "image/jpeg");
  11072. res.set_header("Content-Encoding", "gzip");
  11073. });
  11074. // Content codings are case-insensitive (RFC 9110 8.4.1).
  11075. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  11076. res.set_content(gzipped, "image/jpeg");
  11077. res.set_header("Content-Encoding", "GZIP");
  11078. });
  11079. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11080. auto se = detail::scope_exit([&] {
  11081. svr.stop();
  11082. t.join();
  11083. ASSERT_FALSE(svr.is_running());
  11084. });
  11085. svr.wait_until_ready();
  11086. Client cli(HOST, PORT);
  11087. {
  11088. auto res = cli.Get("/gzipped");
  11089. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11091. EXPECT_EQ("Hello World!", res->body);
  11092. #else
  11093. ASSERT_FALSE(res);
  11094. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11095. #endif
  11096. }
  11097. {
  11098. // open_stream() must behave the same way.
  11099. auto handle = cli.open_stream("GET", "/gzipped");
  11100. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11101. ASSERT_TRUE(handle.is_valid());
  11102. std::string received;
  11103. char buf[256];
  11104. ssize_t n;
  11105. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11106. received.append(buf, static_cast<size_t>(n));
  11107. }
  11108. EXPECT_EQ("Hello World!", received);
  11109. #else
  11110. EXPECT_FALSE(handle.is_valid());
  11111. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  11112. #endif
  11113. }
  11114. {
  11115. // A differently-cased coding must not be mistaken for an unknown one, or
  11116. // the body would be handed back still compressed.
  11117. auto res = cli.Get("/gzipped-uppercase");
  11118. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11120. EXPECT_EQ("Hello World!", res->body);
  11121. #else
  11122. ASSERT_FALSE(res);
  11123. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11124. #endif
  11125. }
  11126. }
  11127. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11128. // A handler serving pre-compressed content (e.g. build-time gzipped static
  11129. // assets) sets Content-Encoding itself. The server used to pick a coding from
  11130. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  11131. // body a second time and appending a second Content-Encoding field line, so
  11132. // clients that decode one coding per listed value handed back raw gzip bytes.
  11133. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  11134. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11135. Server svr;
  11136. // text/plain is a compressible type, so only the pre-set Content-Encoding
  11137. // keeps the server from applying a coding of its own.
  11138. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11139. res.set_content(gzipped, "text/plain");
  11140. res.set_header("Content-Encoding", "gzip");
  11141. });
  11142. auto port = svr.bind_to_any_port(HOST);
  11143. thread t = thread([&]() { svr.listen_after_bind(); });
  11144. auto se = detail::scope_exit([&] {
  11145. svr.stop();
  11146. t.join();
  11147. ASSERT_FALSE(svr.is_running());
  11148. });
  11149. svr.wait_until_ready();
  11150. Client cli(HOST, port);
  11151. Headers headers = {{"Accept-Encoding", "gzip"}};
  11152. auto res = cli.Get("/pre-gzipped", headers);
  11153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11154. EXPECT_EQ(StatusCode::OK_200, res->status);
  11155. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11156. EXPECT_EQ("Hello World!", res->body);
  11157. }
  11158. // A chunked provider settles its coding where the headers are written and
  11159. // reuses it at write time. Both ends of that have to hold: a handler's own
  11160. // Content-Encoding suppresses the coding, and a response without one is still
  11161. // compressed as it always was.
  11162. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  11163. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11164. const std::string plain = "Hello World! Hello World! Hello World!";
  11165. Server svr;
  11166. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11167. res.set_header("Content-Encoding", "gzip");
  11168. res.set_chunked_content_provider(
  11169. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  11170. sink.write(gzipped.data(), gzipped.size());
  11171. sink.done();
  11172. return true;
  11173. });
  11174. });
  11175. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  11176. res.set_chunked_content_provider(
  11177. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  11178. sink.write(plain.data(), plain.size());
  11179. sink.done();
  11180. return true;
  11181. });
  11182. });
  11183. auto port = svr.bind_to_any_port(HOST);
  11184. thread t = thread([&]() { svr.listen_after_bind(); });
  11185. auto se = detail::scope_exit([&] {
  11186. svr.stop();
  11187. t.join();
  11188. ASSERT_FALSE(svr.is_running());
  11189. });
  11190. svr.wait_until_ready();
  11191. Client cli(HOST, port);
  11192. Headers headers = {{"Accept-Encoding", "gzip"}};
  11193. {
  11194. auto res = cli.Get("/pre-gzipped", headers);
  11195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11196. EXPECT_EQ(StatusCode::OK_200, res->status);
  11197. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11198. EXPECT_EQ("Hello World!", res->body);
  11199. }
  11200. {
  11201. auto res = cli.Get("/negotiated", headers);
  11202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11203. EXPECT_EQ(StatusCode::OK_200, res->status);
  11204. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  11205. EXPECT_EQ(plain, res->body);
  11206. }
  11207. }
  11208. #endif
  11209. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  11210. // the same message as the comma-joined one, so both have to be read the same
  11211. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  11212. // single gzip coding, and a body the sender says was encoded twice was handed
  11213. // back after one pass, still compressed but presented as decoded.
  11214. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  11215. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11216. Server svr;
  11217. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  11218. res.set_content(body, "image/jpeg");
  11219. res.headers.emplace("Content-Encoding", "gzip");
  11220. res.headers.emplace("Content-Encoding", "gzip");
  11221. });
  11222. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  11223. res.set_content(body, "image/jpeg");
  11224. res.set_header("Content-Encoding", "gzip, gzip");
  11225. });
  11226. auto port = svr.bind_to_any_port(HOST);
  11227. thread t = thread([&]() { svr.listen_after_bind(); });
  11228. auto se = detail::scope_exit([&] {
  11229. svr.stop();
  11230. t.join();
  11231. ASSERT_FALSE(svr.is_running());
  11232. });
  11233. svr.wait_until_ready();
  11234. Client cli(HOST, port);
  11235. // Two codings is not something cpp-httplib decodes, so both representations
  11236. // take the pass-through path rather than one of them being gunzipped once.
  11237. for (const char *path : {"/split", "/joined"}) {
  11238. auto res = cli.Get(path);
  11239. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11240. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11241. EXPECT_EQ(body, res->body) << path;
  11242. }
  11243. }
  11244. // Regression test for DoS vulnerability: a malicious server sending a response
  11245. // without Content-Length header must not cause unbounded memory consumption on
  11246. // the client side. The client should stop reading after a reasonable limit,
  11247. // similar to the server-side set_payload_max_length protection.
  11248. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  11249. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11250. #ifndef _WIN32
  11251. signal(SIGPIPE, SIG_IGN);
  11252. #endif
  11253. auto server_thread = std::thread([] {
  11254. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  11255. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11256. default_socket_options(srv);
  11257. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11258. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11259. sockaddr_in addr{};
  11260. addr.sin_family = AF_INET;
  11261. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11262. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11263. int opt = 1;
  11264. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11265. #ifdef _WIN32
  11266. reinterpret_cast<const char *>(&opt),
  11267. #else
  11268. &opt,
  11269. #endif
  11270. sizeof(opt));
  11271. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11272. ::listen(srv, 1);
  11273. sockaddr_in cli_addr{};
  11274. socklen_t cli_len = sizeof(cli_addr);
  11275. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11276. if (cli != INVALID_SOCKET) {
  11277. char buf[4096];
  11278. ::recv(cli, buf, sizeof(buf), 0);
  11279. // Malicious response: no Content-Length, no chunked encoding
  11280. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11281. "Connection: close\r\n"
  11282. "\r\n";
  11283. ::send(cli,
  11284. #ifdef _WIN32
  11285. static_cast<const char *>(response_header.c_str()),
  11286. static_cast<int>(response_header.size()),
  11287. #else
  11288. response_header.c_str(), response_header.size(),
  11289. #endif
  11290. 0);
  11291. // Send 10MB of data
  11292. std::string chunk(64 * 1024, 'A');
  11293. size_t total_sent = 0;
  11294. while (total_sent < MALICIOUS_DATA_SIZE) {
  11295. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  11296. auto sent = ::send(cli,
  11297. #ifdef _WIN32
  11298. static_cast<const char *>(chunk.c_str()),
  11299. static_cast<int>(to_send),
  11300. #else
  11301. chunk.c_str(), to_send,
  11302. #endif
  11303. 0);
  11304. if (sent <= 0) break;
  11305. total_sent += static_cast<size_t>(sent);
  11306. }
  11307. detail::close_socket(cli);
  11308. }
  11309. detail::close_socket(srv);
  11310. });
  11311. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11312. size_t total_read = 0;
  11313. {
  11314. Client cli("127.0.0.1", PORT + 2);
  11315. cli.set_read_timeout(5, 0);
  11316. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11317. auto stream = cli.open_stream("GET", "/malicious");
  11318. ASSERT_TRUE(stream.is_valid());
  11319. char buffer[64 * 1024];
  11320. ssize_t n;
  11321. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11322. total_read += static_cast<size_t>(n);
  11323. }
  11324. } // StreamHandle and Client destroyed here, closing the socket
  11325. server_thread.join();
  11326. // With set_payload_max_length, the client must stop reading before consuming
  11327. // all 10MB. The read loop should be cut off at or near the configured limit.
  11328. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  11329. << "Client read " << total_read << " bytes, exceeding the configured "
  11330. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  11331. }
  11332. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  11333. // the entire response body without truncation.
  11334. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  11335. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  11336. #ifndef _WIN32
  11337. signal(SIGPIPE, SIG_IGN);
  11338. #endif
  11339. auto server_thread = std::thread([] {
  11340. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11341. default_socket_options(srv);
  11342. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11343. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11344. sockaddr_in addr{};
  11345. addr.sin_family = AF_INET;
  11346. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11347. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11348. int opt = 1;
  11349. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11350. #ifdef _WIN32
  11351. reinterpret_cast<const char *>(&opt),
  11352. #else
  11353. &opt,
  11354. #endif
  11355. sizeof(opt));
  11356. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11357. ::listen(srv, 1);
  11358. sockaddr_in cli_addr{};
  11359. socklen_t cli_len = sizeof(cli_addr);
  11360. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11361. if (cli != INVALID_SOCKET) {
  11362. char buf[4096];
  11363. ::recv(cli, buf, sizeof(buf), 0);
  11364. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11365. "Connection: close\r\n"
  11366. "\r\n";
  11367. ::send(cli,
  11368. #ifdef _WIN32
  11369. static_cast<const char *>(response_header.c_str()),
  11370. static_cast<int>(response_header.size()),
  11371. #else
  11372. response_header.c_str(), response_header.size(),
  11373. #endif
  11374. 0);
  11375. std::string chunk(64 * 1024, 'A');
  11376. size_t total_sent = 0;
  11377. while (total_sent < DATA_SIZE) {
  11378. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11379. auto sent = ::send(cli,
  11380. #ifdef _WIN32
  11381. static_cast<const char *>(chunk.c_str()),
  11382. static_cast<int>(to_send),
  11383. #else
  11384. chunk.c_str(), to_send,
  11385. #endif
  11386. 0);
  11387. if (sent <= 0) break;
  11388. total_sent += static_cast<size_t>(sent);
  11389. }
  11390. #ifdef _WIN32
  11391. ::shutdown(cli, SD_SEND);
  11392. #else
  11393. ::shutdown(cli, SHUT_WR);
  11394. #endif
  11395. // Drain until the client closes its end, ensuring all data is delivered
  11396. char drain[1024];
  11397. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11398. detail::close_socket(cli);
  11399. }
  11400. detail::close_socket(srv);
  11401. });
  11402. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11403. size_t total_read = 0;
  11404. {
  11405. Client cli("127.0.0.1", PORT + 2);
  11406. cli.set_read_timeout(5, 0);
  11407. cli.set_payload_max_length(0); // 0 means no limit
  11408. auto stream = cli.open_stream("GET", "/data");
  11409. ASSERT_TRUE(stream.is_valid());
  11410. char buffer[64 * 1024];
  11411. ssize_t n;
  11412. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11413. total_read += static_cast<size_t>(n);
  11414. }
  11415. }
  11416. server_thread.join();
  11417. EXPECT_EQ(total_read, DATA_SIZE)
  11418. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  11419. << " bytes without truncation, but only read " << total_read << " bytes.";
  11420. }
  11421. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  11422. // enormous Content-Length must not cause the client to pre-allocate a huge
  11423. // response body buffer. The reservation is capped at payload_max_length_, and
  11424. // the read itself fails when the body exceeds the limit.
  11425. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  11426. #ifndef _WIN32
  11427. signal(SIGPIPE, SIG_IGN);
  11428. #endif
  11429. auto server_thread = std::thread([] {
  11430. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11431. default_socket_options(srv);
  11432. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11433. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11434. sockaddr_in addr{};
  11435. addr.sin_family = AF_INET;
  11436. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11437. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11438. int opt = 1;
  11439. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11440. #ifdef _WIN32
  11441. reinterpret_cast<const char *>(&opt),
  11442. #else
  11443. &opt,
  11444. #endif
  11445. sizeof(opt));
  11446. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11447. ::listen(srv, 1);
  11448. sockaddr_in cli_addr{};
  11449. socklen_t cli_len = sizeof(cli_addr);
  11450. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11451. if (cli != INVALID_SOCKET) {
  11452. char buf[4096];
  11453. ::recv(cli, buf, sizeof(buf), 0);
  11454. // Malicious response: claim a 20GB body but send only a tiny payload.
  11455. std::string response = "HTTP/1.1 200 OK\r\n"
  11456. "Content-Length: 20000000000\r\n"
  11457. "\r\n"
  11458. "abc";
  11459. ::send(cli,
  11460. #ifdef _WIN32
  11461. static_cast<const char *>(response.c_str()),
  11462. static_cast<int>(response.size()),
  11463. #else
  11464. response.c_str(), response.size(),
  11465. #endif
  11466. 0);
  11467. detail::close_socket(cli);
  11468. }
  11469. detail::close_socket(srv);
  11470. });
  11471. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11472. {
  11473. Client cli("127.0.0.1", PORT + 2);
  11474. cli.set_read_timeout(5, 0);
  11475. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  11476. // result in a 20GB pre-allocation. The Get() call is expected to fail
  11477. // (server claims more bytes than payload_max_length permits), but it must
  11478. // not exhaust memory before getting there.
  11479. auto res = cli.Get("/malicious");
  11480. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  11481. }
  11482. server_thread.join();
  11483. }
  11484. // Verify that content_receiver bypasses the default payload_max_length,
  11485. // allowing streaming downloads larger than 100MB without requiring an explicit
  11486. // set_payload_max_length call.
  11487. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  11488. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11489. #ifndef _WIN32
  11490. signal(SIGPIPE, SIG_IGN);
  11491. #endif
  11492. auto server_thread = std::thread([] {
  11493. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11494. default_socket_options(srv);
  11495. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11496. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11497. sockaddr_in addr{};
  11498. addr.sin_family = AF_INET;
  11499. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11500. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11501. int opt = 1;
  11502. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11503. #ifdef _WIN32
  11504. reinterpret_cast<const char *>(&opt),
  11505. #else
  11506. &opt,
  11507. #endif
  11508. sizeof(opt));
  11509. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11510. ::listen(srv, 1);
  11511. sockaddr_in cli_addr{};
  11512. socklen_t cli_len = sizeof(cli_addr);
  11513. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11514. if (cli != INVALID_SOCKET) {
  11515. char buf[4096];
  11516. ::recv(cli, buf, sizeof(buf), 0);
  11517. // Response with Content-Length larger than default 100MB limit
  11518. auto content_length = std::to_string(DATA_SIZE);
  11519. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11520. "Content-Length: " +
  11521. content_length +
  11522. "\r\n"
  11523. "Connection: close\r\n"
  11524. "\r\n";
  11525. ::send(cli,
  11526. #ifdef _WIN32
  11527. static_cast<const char *>(response_header.c_str()),
  11528. static_cast<int>(response_header.size()),
  11529. #else
  11530. response_header.c_str(), response_header.size(),
  11531. #endif
  11532. 0);
  11533. std::string chunk(64 * 1024, 'A');
  11534. size_t total_sent = 0;
  11535. while (total_sent < DATA_SIZE) {
  11536. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11537. auto sent = ::send(cli,
  11538. #ifdef _WIN32
  11539. static_cast<const char *>(chunk.c_str()),
  11540. static_cast<int>(to_send),
  11541. #else
  11542. chunk.c_str(), to_send,
  11543. #endif
  11544. 0);
  11545. if (sent <= 0) break;
  11546. total_sent += static_cast<size_t>(sent);
  11547. }
  11548. detail::close_socket(cli);
  11549. }
  11550. detail::close_socket(srv);
  11551. });
  11552. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11553. size_t total_received = 0;
  11554. {
  11555. Client cli("127.0.0.1", PORT + 2);
  11556. cli.set_read_timeout(10, 0);
  11557. // Do NOT call set_payload_max_length — use the default 100MB limit
  11558. auto res =
  11559. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11560. total_received += data_length;
  11561. return true;
  11562. });
  11563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11564. EXPECT_EQ(StatusCode::OK_200, res->status);
  11565. }
  11566. server_thread.join();
  11567. EXPECT_EQ(total_received, DATA_SIZE)
  11568. << "With content_receiver, the client should read all " << DATA_SIZE
  11569. << " bytes despite the default 100MB payload_max_length, but only read "
  11570. << total_received << " bytes.";
  11571. }
  11572. // Verify that an explicit set_payload_max_length smaller than the response is
  11573. // enforced even when a content_receiver is used.
  11574. TEST(ClientVulnerabilityTest,
  11575. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  11576. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11577. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  11578. #ifndef _WIN32
  11579. signal(SIGPIPE, SIG_IGN);
  11580. #endif
  11581. auto server_thread = std::thread([] {
  11582. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11583. default_socket_options(srv);
  11584. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11585. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11586. sockaddr_in addr{};
  11587. addr.sin_family = AF_INET;
  11588. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11589. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11590. int opt = 1;
  11591. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11592. #ifdef _WIN32
  11593. reinterpret_cast<const char *>(&opt),
  11594. #else
  11595. &opt,
  11596. #endif
  11597. sizeof(opt));
  11598. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11599. ::listen(srv, 1);
  11600. sockaddr_in cli_addr{};
  11601. socklen_t cli_len = sizeof(cli_addr);
  11602. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11603. if (cli != INVALID_SOCKET) {
  11604. char buf[4096];
  11605. ::recv(cli, buf, sizeof(buf), 0);
  11606. auto content_length = std::to_string(DATA_SIZE);
  11607. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11608. "Content-Length: " +
  11609. content_length +
  11610. "\r\n"
  11611. "Connection: close\r\n"
  11612. "\r\n";
  11613. ::send(cli,
  11614. #ifdef _WIN32
  11615. static_cast<const char *>(response_header.c_str()),
  11616. static_cast<int>(response_header.size()),
  11617. #else
  11618. response_header.c_str(), response_header.size(),
  11619. #endif
  11620. 0);
  11621. std::string chunk(64 * 1024, 'A');
  11622. size_t total_sent = 0;
  11623. while (total_sent < DATA_SIZE) {
  11624. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11625. auto sent = ::send(cli,
  11626. #ifdef _WIN32
  11627. static_cast<const char *>(chunk.c_str()),
  11628. static_cast<int>(to_send),
  11629. #else
  11630. chunk.c_str(), to_send,
  11631. #endif
  11632. 0);
  11633. if (sent <= 0) break;
  11634. total_sent += static_cast<size_t>(sent);
  11635. }
  11636. detail::close_socket(cli);
  11637. }
  11638. detail::close_socket(srv);
  11639. });
  11640. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11641. size_t total_received = 0;
  11642. {
  11643. Client cli("127.0.0.1", PORT + 2);
  11644. cli.set_read_timeout(10, 0);
  11645. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  11646. auto res =
  11647. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11648. total_received += data_length;
  11649. return true;
  11650. });
  11651. // Should fail because 200MB exceeds the explicit 150MB limit
  11652. EXPECT_FALSE(res);
  11653. }
  11654. server_thread.join();
  11655. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  11656. << "Client with content_receiver should respect the explicit "
  11657. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  11658. << total_received << " bytes.";
  11659. }
  11660. // Verify that an explicit set_payload_max_length larger than the response
  11661. // allows the content_receiver to read all data successfully.
  11662. TEST(ClientVulnerabilityTest,
  11663. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  11664. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11665. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  11666. #ifndef _WIN32
  11667. signal(SIGPIPE, SIG_IGN);
  11668. #endif
  11669. auto server_thread = std::thread([] {
  11670. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11671. default_socket_options(srv);
  11672. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11673. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11674. sockaddr_in addr{};
  11675. addr.sin_family = AF_INET;
  11676. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11677. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11678. int opt = 1;
  11679. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11680. #ifdef _WIN32
  11681. reinterpret_cast<const char *>(&opt),
  11682. #else
  11683. &opt,
  11684. #endif
  11685. sizeof(opt));
  11686. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11687. ::listen(srv, 1);
  11688. sockaddr_in cli_addr{};
  11689. socklen_t cli_len = sizeof(cli_addr);
  11690. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11691. if (cli != INVALID_SOCKET) {
  11692. char buf[4096];
  11693. ::recv(cli, buf, sizeof(buf), 0);
  11694. auto content_length = std::to_string(DATA_SIZE);
  11695. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11696. "Content-Length: " +
  11697. content_length +
  11698. "\r\n"
  11699. "Connection: close\r\n"
  11700. "\r\n";
  11701. ::send(cli,
  11702. #ifdef _WIN32
  11703. static_cast<const char *>(response_header.c_str()),
  11704. static_cast<int>(response_header.size()),
  11705. #else
  11706. response_header.c_str(), response_header.size(),
  11707. #endif
  11708. 0);
  11709. std::string chunk(64 * 1024, 'A');
  11710. size_t total_sent = 0;
  11711. while (total_sent < DATA_SIZE) {
  11712. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11713. auto sent = ::send(cli,
  11714. #ifdef _WIN32
  11715. static_cast<const char *>(chunk.c_str()),
  11716. static_cast<int>(to_send),
  11717. #else
  11718. chunk.c_str(), to_send,
  11719. #endif
  11720. 0);
  11721. if (sent <= 0) break;
  11722. total_sent += static_cast<size_t>(sent);
  11723. }
  11724. #ifdef _WIN32
  11725. ::shutdown(cli, SD_SEND);
  11726. #else
  11727. ::shutdown(cli, SHUT_WR);
  11728. #endif
  11729. char drain[1024];
  11730. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11731. detail::close_socket(cli);
  11732. }
  11733. detail::close_socket(srv);
  11734. });
  11735. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11736. size_t total_received = 0;
  11737. {
  11738. Client cli("127.0.0.1", PORT + 2);
  11739. cli.set_read_timeout(10, 0);
  11740. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  11741. auto res =
  11742. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11743. total_received += data_length;
  11744. return true;
  11745. });
  11746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11747. EXPECT_EQ(StatusCode::OK_200, res->status);
  11748. }
  11749. server_thread.join();
  11750. EXPECT_EQ(total_received, DATA_SIZE)
  11751. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  11752. << " bytes (larger than " << DATA_SIZE
  11753. << " bytes response), content_receiver should read all data, but only "
  11754. "read "
  11755. << total_received << " bytes.";
  11756. }
  11757. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  11758. // Regression test for "zip bomb" attack on the client side: a malicious server
  11759. // sends a small gzip-compressed response that decompresses to a huge payload.
  11760. // The client must enforce payload_max_length on the decompressed size.
  11761. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  11762. constexpr size_t DECOMPRESSED_SIZE =
  11763. 10 * 1024 * 1024; // 10MB after decompression
  11764. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11765. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  11766. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  11767. std::string compressed;
  11768. {
  11769. httplib::detail::gzip_compressor compressor;
  11770. bool ok =
  11771. compressor.compress(uncompressed.data(), uncompressed.size(),
  11772. /*last=*/true, [&](const char *buf, size_t len) {
  11773. compressed.append(buf, len);
  11774. return true;
  11775. });
  11776. ASSERT_TRUE(ok);
  11777. }
  11778. // Sanity: compressed data should be much smaller than the decompressed size
  11779. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  11780. #ifndef _WIN32
  11781. signal(SIGPIPE, SIG_IGN);
  11782. #endif
  11783. // Set up the listening socket in the main thread so the server is guaranteed
  11784. // to be ready before the client connects (eliminates race condition).
  11785. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11786. default_socket_options(srv);
  11787. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11788. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11789. sockaddr_in addr{};
  11790. addr.sin_family = AF_INET;
  11791. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  11792. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11793. int opt = 1;
  11794. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11795. #ifdef _WIN32
  11796. reinterpret_cast<const char *>(&opt),
  11797. #else
  11798. &opt,
  11799. #endif
  11800. sizeof(opt));
  11801. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11802. ASSERT_EQ(0, ::listen(srv, 1));
  11803. auto server_thread = std::thread([&compressed, srv] {
  11804. sockaddr_in cli_addr{};
  11805. socklen_t cli_len = sizeof(cli_addr);
  11806. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11807. if (cli != INVALID_SOCKET) {
  11808. // Read the full HTTP request (until \r\n\r\n)
  11809. char buf[4096];
  11810. size_t total = 0;
  11811. while (total < sizeof(buf)) {
  11812. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  11813. if (n <= 0) break;
  11814. total += static_cast<size_t>(n);
  11815. // Check for end of headers
  11816. if (total >= 4) {
  11817. std::string req(buf, total);
  11818. if (req.find("\r\n\r\n") != std::string::npos) break;
  11819. }
  11820. }
  11821. // Malicious response: gzip-compressed body, no Content-Length
  11822. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11823. "Content-Encoding: gzip\r\n"
  11824. "Connection: close\r\n"
  11825. "\r\n";
  11826. ::send(cli,
  11827. #ifdef _WIN32
  11828. static_cast<const char *>(response_header.c_str()),
  11829. static_cast<int>(response_header.size()),
  11830. #else
  11831. response_header.c_str(), response_header.size(),
  11832. #endif
  11833. 0);
  11834. // Send the compressed payload (small on the wire, huge when decompressed)
  11835. size_t total_sent = 0;
  11836. while (total_sent < compressed.size()) {
  11837. auto to_send = std::min(compressed.size() - total_sent,
  11838. static_cast<size_t>(64 * 1024));
  11839. auto sent =
  11840. ::send(cli,
  11841. #ifdef _WIN32
  11842. static_cast<const char *>(compressed.c_str() + total_sent),
  11843. static_cast<int>(to_send),
  11844. #else
  11845. compressed.c_str() + total_sent, to_send,
  11846. #endif
  11847. 0);
  11848. if (sent <= 0) break;
  11849. total_sent += static_cast<size_t>(sent);
  11850. }
  11851. detail::close_socket(cli);
  11852. }
  11853. });
  11854. auto se = detail::scope_exit([&] {
  11855. detail::close_socket(srv);
  11856. server_thread.join();
  11857. });
  11858. size_t total_decompressed = 0;
  11859. {
  11860. Client cli("127.0.0.1", PORT + 3);
  11861. cli.set_read_timeout(5, 0);
  11862. cli.set_decompress(true);
  11863. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11864. auto stream = cli.open_stream("GET", "/zipbomb");
  11865. ASSERT_TRUE(stream.is_valid());
  11866. char buffer[64 * 1024];
  11867. ssize_t n;
  11868. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11869. total_decompressed += static_cast<size_t>(n);
  11870. }
  11871. }
  11872. // The decompressed size must be capped by payload_max_length. Without
  11873. // protection, the client would decompress the full 10MB from a tiny
  11874. // compressed payload, enabling a zip bomb DoS attack.
  11875. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  11876. << "Client decompressed " << total_decompressed
  11877. << " bytes from a gzip response. The decompressed size should be "
  11878. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  11879. }
  11880. #endif
  11881. TEST(HostAndPortPropertiesTest, NoSSL) {
  11882. httplib::Client cli("www.google.com", 1234);
  11883. ASSERT_EQ("www.google.com", cli.host());
  11884. ASSERT_EQ(1234, cli.port());
  11885. }
  11886. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  11887. httplib::Client cli("www.google.com:1234");
  11888. ASSERT_EQ("www.google.com", cli.host());
  11889. ASSERT_EQ(1234, cli.port());
  11890. }
  11891. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  11892. // Port number that overflows int — should not crash, client becomes invalid
  11893. httplib::Client cli("http://www.google.com:99999999999999999999");
  11894. ASSERT_FALSE(cli.is_valid());
  11895. }
  11896. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  11897. // Port 99999 exceeds valid range (1-65535) — should not crash
  11898. httplib::Client cli("http://www.google.com:99999");
  11899. ASSERT_FALSE(cli.is_valid());
  11900. }
  11901. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  11902. httplib::Client cli("http://www.google.com:80abc");
  11903. ASSERT_FALSE(cli.is_valid());
  11904. }
  11905. #ifdef CPPHTTPLIB_SSL_ENABLED
  11906. TEST(HostAndPortPropertiesTest, SSL) {
  11907. httplib::SSLClient cli("www.google.com");
  11908. ASSERT_EQ("www.google.com", cli.host());
  11909. ASSERT_EQ(443, cli.port());
  11910. }
  11911. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  11912. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  11913. std::string cert;
  11914. read_file(CA_CERT_FILE, cert);
  11915. httplib::SSLClient httplib_client("www.google.com");
  11916. // Load CA store first time
  11917. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11918. // Load CA store second time (update)
  11919. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11920. // Verify client is still valid and can make connections
  11921. httplib_client.enable_server_certificate_verification(true);
  11922. auto res = httplib_client.Get("/");
  11923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11924. // Google may return 200 or 301 depending on various factors
  11925. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  11926. res->status == StatusCode::MovedPermanently_301);
  11927. }
  11928. TEST(SSLClientTest, ServerNameIndication_Online) {
  11929. auto host = "httpbingo.org";
  11930. auto path = std::string{"/get"};
  11931. SSLClient cli(host, 443);
  11932. auto res = cli.Get(path);
  11933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11934. ASSERT_EQ(StatusCode::OK_200, res->status);
  11935. }
  11936. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  11937. // Use a site that will cause SSL verification failure due to self-signed cert
  11938. SSLClient cli("self-signed.badssl.com", 443);
  11939. cli.enable_server_certificate_verification(true);
  11940. auto res = cli.Get("/");
  11941. ASSERT_TRUE(!res);
  11942. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11943. // Verify backend error is captured for SSLServerVerification
  11944. // This occurs when certificate verification fails
  11945. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  11946. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  11947. EXPECT_NE(0UL, res.ssl_backend_error());
  11948. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11949. // For OpenSSL, ssl_error is 0 for verification errors
  11950. EXPECT_EQ(0, res.ssl_error());
  11951. #if !defined(_WIN32) || \
  11952. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11953. // On non-Windows or when Windows Schannel is disabled, the error comes
  11954. // from OpenSSL's verification
  11955. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  11956. res.ssl_backend_error());
  11957. #endif
  11958. #endif
  11959. }
  11960. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  11961. // Use a site where hostname doesn't match the certificate
  11962. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  11963. SSLClient cli("wrong.host.badssl.com", 443);
  11964. cli.enable_server_certificate_verification(true);
  11965. cli.enable_server_hostname_verification(true);
  11966. auto res = cli.Get("/");
  11967. ASSERT_TRUE(!res);
  11968. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  11969. // Verify backend error is captured for hostname verification failure
  11970. EXPECT_NE(0UL, res.ssl_backend_error());
  11971. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11972. // For OpenSSL, ssl_error is 0 for verification errors
  11973. EXPECT_EQ(0, res.ssl_error());
  11974. #if !defined(_WIN32) || \
  11975. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11976. // On non-Windows or when Windows Schannel is disabled, the error comes
  11977. // from OpenSSL's hostname verification
  11978. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  11979. res.ssl_backend_error());
  11980. #endif
  11981. #endif
  11982. }
  11983. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  11984. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11985. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  11986. SSLClient cli("www.google.com", 443);
  11987. cli.enable_server_certificate_verification(true);
  11988. auto res = cli.Get("/");
  11989. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11990. }
  11991. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  11992. SSLClient cli("www.google.com", 443);
  11993. cli.enable_server_certificate_verification(true);
  11994. cli.enable_windows_certificate_verification(false);
  11995. auto res = cli.Get("/");
  11996. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11997. }
  11998. // The server sends an intermediate cross-signed by a root Windows trusts,
  11999. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  12000. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  12001. SSLClient cli("accounts.spotify.com", 443);
  12002. auto res = cli.Get("/");
  12003. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  12004. << " ssl_backend_error=" << res.ssl_backend_error();
  12005. }
  12006. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  12007. // policy status, which no backend reports for a self-signed certificate.
  12008. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  12009. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12010. ASSERT_TRUE(svr.is_valid());
  12011. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12012. auto se = detail::scope_exit([&] {
  12013. svr.stop();
  12014. t.join();
  12015. ASSERT_FALSE(svr.is_running());
  12016. });
  12017. svr.wait_until_ready();
  12018. SSLClient cli("127.0.0.1", PORT);
  12019. cli.set_connection_timeout(30);
  12020. auto res = cli.Get("/");
  12021. ASSERT_FALSE(res);
  12022. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12023. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  12024. }
  12025. #endif
  12026. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  12027. Client cli("https://google.com");
  12028. auto res = cli.Get("/");
  12029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12030. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12031. }
  12032. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  12033. SSLClient cli("google.com");
  12034. cli.set_ca_cert_path(CA_CERT_FILE);
  12035. auto res = cli.Get("/");
  12036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12037. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12038. }
  12039. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  12040. SSLClient cli("google.com");
  12041. cli.enable_server_certificate_verification(true);
  12042. cli.set_ca_cert_path("hello");
  12043. auto res = cli.Get("/");
  12044. ASSERT_TRUE(!res);
  12045. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  12046. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  12047. // should be set
  12048. EXPECT_EQ(0, res.ssl_error());
  12049. // Verify backend error is captured for SSLLoadingCerts
  12050. // This error occurs when loading CA certificates fails
  12051. EXPECT_NE(0UL, res.ssl_backend_error());
  12052. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12053. // OpenSSL specific error codes:
  12054. // > openssl errstr 0x80000002
  12055. // error:80000002:system library::No such file or directory
  12056. // > openssl errstr 0xA000126
  12057. // error:0A000126:SSL routines::unexpected eof while reading
  12058. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  12059. res.ssl_backend_error() == 0xA000126);
  12060. #endif
  12061. }
  12062. TEST(SSLClientTest, ServerCertificateVerification4) {
  12063. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12064. ASSERT_TRUE(svr.is_valid());
  12065. svr.Get("/test", [&](const Request &, Response &res) {
  12066. res.set_content("test", "text/plain");
  12067. svr.stop();
  12068. ASSERT_TRUE(true);
  12069. });
  12070. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12071. auto se = detail::scope_exit([&] {
  12072. t.join();
  12073. ASSERT_FALSE(svr.is_running());
  12074. });
  12075. svr.wait_until_ready();
  12076. SSLClient cli("127.0.0.1", PORT);
  12077. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12078. cli.enable_server_certificate_verification(true);
  12079. cli.set_connection_timeout(30);
  12080. auto res = cli.Get("/test");
  12081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12082. ASSERT_EQ(StatusCode::OK_200, res->status);
  12083. }
  12084. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  12085. std::string cert;
  12086. read_file(CA_CERT_FILE, cert);
  12087. SSLClient cli("google.com");
  12088. cli.load_ca_cert_store(cert.data(), cert.size());
  12089. const auto res = cli.Get("/");
  12090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12091. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12092. }
  12093. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  12094. // clang-format off
  12095. static constexpr char cert[] =
  12096. "GlobalSign Root CA\n"
  12097. "==================\n"
  12098. "-----BEGIN CERTIFICATE-----\n"
  12099. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  12100. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  12101. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  12102. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  12103. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  12104. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  12105. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  12106. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  12107. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  12108. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  12109. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  12110. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  12111. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  12112. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  12113. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  12114. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  12115. "-----END CERTIFICATE-----\n";
  12116. // clang-format on
  12117. SSLClient cli("google.com");
  12118. cli.load_ca_cert_store(cert, sizeof(cert));
  12119. const auto res = cli.Get("/");
  12120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12121. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12122. }
  12123. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  12124. SSLClient cli("www.youtube.com");
  12125. cli.set_ca_cert_path(CA_CERT_FILE);
  12126. cli.enable_server_certificate_verification(true);
  12127. cli.set_follow_location(true);
  12128. auto res = cli.Get("/");
  12129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12130. ASSERT_EQ(StatusCode::OK_200, res->status);
  12131. }
  12132. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  12133. SSLClient cli("wWw.YouTube.Com");
  12134. cli.set_ca_cert_path(CA_CERT_FILE);
  12135. cli.enable_server_certificate_verification(true);
  12136. cli.enable_server_hostname_verification(true);
  12137. cli.set_follow_location(true);
  12138. auto res = cli.Get("/");
  12139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12140. ASSERT_EQ(StatusCode::OK_200, res->status);
  12141. }
  12142. TEST(SSLClientTest, HostNameMatchCase_Online) {
  12143. SSLClient cli("gOoGlE.COm");
  12144. cli.enable_server_certificate_verification(true);
  12145. cli.enable_server_hostname_verification(true);
  12146. cli.set_follow_location(true);
  12147. auto res = cli.Get("/");
  12148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12149. ASSERT_EQ(StatusCode::OK_200, res->status);
  12150. }
  12151. TEST(SSLClientTest, Issue2004_Online) {
  12152. Client client("https://google.com");
  12153. client.set_follow_location(true);
  12154. auto res = client.Get("/");
  12155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12156. ASSERT_EQ(StatusCode::OK_200, res->status);
  12157. auto body = res->body;
  12158. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  12159. }
  12160. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  12161. // Create SSLClient with invalid cert/key to make is_valid() return false
  12162. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  12163. "nonexistent_key.pem");
  12164. // is_valid() should be false due to cert loading failure
  12165. ASSERT_FALSE(cli.is_valid());
  12166. auto res = cli.Get("/");
  12167. ASSERT_FALSE(res);
  12168. EXPECT_EQ(Error::SSLConnection, res.error());
  12169. }
  12170. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  12171. // Test for Issue #2251: SSL error not properly reported when client cert
  12172. // and key paths are swapped or mismatched
  12173. // This simulates the scenario where user accidentally swaps the cert and key
  12174. // files
  12175. // Using client cert file as private key and vice versa (completely wrong)
  12176. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  12177. // Should fail validation due to cert/key mismatch
  12178. ASSERT_FALSE(cli.is_valid());
  12179. // Attempt to make a request should fail with proper error
  12180. auto res = cli.Get("/");
  12181. ASSERT_FALSE(res);
  12182. EXPECT_EQ(Error::SSLConnection, res.error());
  12183. // SSL error should be recorded in the Result object (this is the key fix for
  12184. // Issue #2251)
  12185. auto backend_error = res.ssl_backend_error();
  12186. EXPECT_NE(0u, backend_error);
  12187. }
  12188. // Tests cert/key mismatch detection at the TLS context level
  12189. TEST(TlsApiTest, ClientCertKeyMismatch) {
  12190. // Test that using mismatched cert/key causes connection failure.
  12191. // We verify this at the SSLClient level rather than through internal
  12192. // TLS API functions.
  12193. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  12194. cli.enable_server_certificate_verification(false);
  12195. cli.set_connection_timeout(2);
  12196. // The mismatch should cause a connection or handshake error
  12197. auto res = cli.Get("/test");
  12198. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  12199. // Either way, the request should fail
  12200. EXPECT_FALSE(res);
  12201. }
  12202. #endif
  12203. #if 0
  12204. TEST(SSLClientTest, SetInterfaceWithINET6) {
  12205. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  12206. ASSERT_TRUE(cli != nullptr);
  12207. cli->set_address_family(AF_INET6);
  12208. cli->set_interface("en0");
  12209. auto res = cli->Get("/get");
  12210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12211. ASSERT_EQ(StatusCode::OK_200, res->status);
  12212. }
  12213. #endif
  12214. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  12215. #ifdef CPPHTTPLIB_SSL_ENABLED
  12216. void ClientCertPresent(
  12217. const std::string &client_cert_file,
  12218. const std::string &client_private_key_file,
  12219. const std::string &client_encrypted_private_key_pass = std::string()) {
  12220. using namespace httplib::tls;
  12221. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12222. CLIENT_CA_CERT_DIR);
  12223. ASSERT_TRUE(svr.is_valid());
  12224. svr.Get("/test", [&](const Request &req, Response &res) {
  12225. res.set_content("test", "text/plain");
  12226. auto cert = req.peer_cert();
  12227. ASSERT_TRUE(static_cast<bool>(cert));
  12228. std::string common_name = cert.subject_cn();
  12229. EXPECT_EQ("Common Name", common_name);
  12230. });
  12231. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12232. auto se = detail::scope_exit([&] {
  12233. svr.stop();
  12234. t.join();
  12235. ASSERT_FALSE(svr.is_running());
  12236. });
  12237. svr.wait_until_ready();
  12238. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  12239. client_encrypted_private_key_pass);
  12240. cli.enable_server_certificate_verification(false);
  12241. cli.set_connection_timeout(30);
  12242. auto res = cli.Get("/test");
  12243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12244. ASSERT_EQ(StatusCode::OK_200, res->status);
  12245. }
  12246. TEST(SSLClientServerTest, ClientCertPresent) {
  12247. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12248. }
  12249. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  12250. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12251. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12252. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12253. }
  12254. // PEM memory-based constructor tests (works with all TLS backends)
  12255. void PemMemoryClientCertPresent(
  12256. const std::string &client_cert_file,
  12257. const std::string &client_private_key_file,
  12258. const std::string &client_encrypted_private_key_pass = std::string()) {
  12259. // Read PEM files into memory
  12260. std::string server_cert_pem, server_key_pem;
  12261. std::string client_ca_pem;
  12262. std::string client_cert_pem, client_key_pem;
  12263. read_file(SERVER_CERT_FILE, server_cert_pem);
  12264. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12265. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12266. read_file(client_cert_file, client_cert_pem);
  12267. read_file(client_private_key_file, client_key_pem);
  12268. // Create server with PEM memory
  12269. SSLServer::PemMemory server_pem = {
  12270. server_cert_pem.c_str(),
  12271. server_cert_pem.size(),
  12272. server_key_pem.c_str(),
  12273. server_key_pem.size(),
  12274. client_ca_pem.c_str(),
  12275. client_ca_pem.size(),
  12276. nullptr // no password for server key
  12277. };
  12278. SSLServer svr(server_pem);
  12279. ASSERT_TRUE(svr.is_valid());
  12280. svr.Get("/test", [&](const Request &, Response &res) {
  12281. res.set_content("test", "text/plain");
  12282. });
  12283. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12284. auto se = detail::scope_exit([&] {
  12285. svr.stop();
  12286. t.join();
  12287. ASSERT_FALSE(svr.is_running());
  12288. });
  12289. svr.wait_until_ready();
  12290. // Create client with PEM memory
  12291. const char *password = client_encrypted_private_key_pass.empty()
  12292. ? nullptr
  12293. : client_encrypted_private_key_pass.c_str();
  12294. SSLClient::PemMemory client_pem = {
  12295. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  12296. client_key_pem.size(), password};
  12297. SSLClient cli(HOST, PORT, client_pem);
  12298. cli.enable_server_certificate_verification(false);
  12299. cli.set_connection_timeout(30);
  12300. auto res = cli.Get("/test");
  12301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12302. ASSERT_EQ(StatusCode::OK_200, res->status);
  12303. }
  12304. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  12305. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12306. }
  12307. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  12308. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12309. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12310. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12311. }
  12312. TEST(SSLClientServerTest, ClientCertMissing) {
  12313. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12314. CLIENT_CA_CERT_DIR);
  12315. ASSERT_TRUE(svr.is_valid());
  12316. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  12317. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12318. auto se = detail::scope_exit([&] {
  12319. svr.stop();
  12320. t.join();
  12321. ASSERT_FALSE(svr.is_running());
  12322. });
  12323. svr.wait_until_ready();
  12324. SSLClient cli(HOST, PORT);
  12325. cli.set_connection_timeout(30);
  12326. // cert.pem does not match HOST. Skip the hostname check, which runs before
  12327. // the chain check on Windows, so the result does not depend on the order.
  12328. cli.enable_server_hostname_verification(false);
  12329. auto res = cli.Get("/test");
  12330. ASSERT_TRUE(!res);
  12331. // When client cert is missing and server requires it, connection fails
  12332. // Error type depends on backend implementation
  12333. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12334. res.error() == Error::SSLConnection);
  12335. // Verify backend error is captured
  12336. // Note: This test may have different error codes depending on the exact
  12337. // verification failure
  12338. EXPECT_NE(0UL, res.ssl_backend_error());
  12339. }
  12340. TEST(SSLClientServerTest, TrustDirOptional) {
  12341. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12342. ASSERT_TRUE(svr.is_valid());
  12343. svr.Get("/test", [&](const Request &, Response &res) {
  12344. res.set_content("test", "text/plain");
  12345. });
  12346. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12347. auto se = detail::scope_exit([&] {
  12348. svr.stop();
  12349. t.join();
  12350. ASSERT_FALSE(svr.is_running());
  12351. });
  12352. svr.wait_until_ready();
  12353. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12354. cli.enable_server_certificate_verification(false);
  12355. cli.set_connection_timeout(30);
  12356. auto res = cli.Get("/test");
  12357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12358. ASSERT_EQ(StatusCode::OK_200, res->status);
  12359. }
  12360. TEST(SSLClientServerTest, SSLConnectTimeout) {
  12361. class NoListenSSLServer : public SSLServer {
  12362. public:
  12363. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  12364. const char *client_ca_cert_file_path,
  12365. const char *client_ca_cert_dir_path = nullptr)
  12366. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  12367. client_ca_cert_dir_path),
  12368. stop_(false) {}
  12369. std::atomic_bool stop_;
  12370. private:
  12371. bool process_and_close_socket(socket_t /*sock*/) override {
  12372. // Don't create SSL context
  12373. while (!stop_.load()) {
  12374. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  12375. }
  12376. return true;
  12377. }
  12378. };
  12379. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12380. CLIENT_CA_CERT_FILE);
  12381. ASSERT_TRUE(svr.is_valid());
  12382. svr.Get("/test", [&](const Request &, Response &res) {
  12383. res.set_content("test", "text/plain");
  12384. });
  12385. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12386. auto se = detail::scope_exit([&] {
  12387. svr.stop_ = true;
  12388. svr.stop();
  12389. t.join();
  12390. ASSERT_FALSE(svr.is_running());
  12391. });
  12392. svr.wait_until_ready();
  12393. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12394. cli.enable_server_certificate_verification(false);
  12395. cli.set_connection_timeout(1);
  12396. auto res = cli.Get("/test");
  12397. ASSERT_TRUE(!res);
  12398. EXPECT_EQ(Error::SSLConnection, res.error());
  12399. // Timeout results in WantRead error code (maps to backend-specific value)
  12400. EXPECT_NE(0, res.ssl_error());
  12401. }
  12402. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  12403. // Test SSLServer with client certificate verification using the standard
  12404. // constructor (ContextSetupCallback is tested by backend-specific tests)
  12405. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12406. CLIENT_CA_CERT_DIR);
  12407. ASSERT_TRUE(svr.is_valid());
  12408. svr.Get("/test", [&](const Request &req, Response &res) {
  12409. res.set_content("test", "text/plain");
  12410. auto cert = req.peer_cert();
  12411. ASSERT_TRUE(static_cast<bool>(cert));
  12412. auto common_name = cert.subject_cn();
  12413. EXPECT_EQ("Common Name", common_name);
  12414. });
  12415. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12416. auto se = detail::scope_exit([&] {
  12417. svr.stop();
  12418. t.join();
  12419. ASSERT_FALSE(svr.is_running());
  12420. });
  12421. svr.wait_until_ready();
  12422. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12423. cli.enable_server_certificate_verification(false);
  12424. cli.set_connection_timeout(30);
  12425. auto res = cli.Get("/test");
  12426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12427. ASSERT_EQ(StatusCode::OK_200, res->status);
  12428. }
  12429. // Test verify_hostname for both OpenSSL and MbedTLS backends
  12430. // Verifies that wildcard matching and exact matching work consistently
  12431. TEST(SSLClientServerTest, TlsVerifyHostname) {
  12432. using namespace httplib::tls;
  12433. // We need a running server to test against
  12434. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12435. ASSERT_TRUE(svr.is_valid());
  12436. svr.Get("/test", [](const Request &, Response &res) {
  12437. res.set_content("ok", "text/plain");
  12438. });
  12439. thread t([&]() { svr.listen(HOST, PORT); });
  12440. auto se = detail::scope_exit([&] {
  12441. svr.stop();
  12442. t.join();
  12443. });
  12444. svr.wait_until_ready();
  12445. bool verify_callback_called = false;
  12446. bool verify_result_wrong = false;
  12447. SSLClient cli(HOST, PORT);
  12448. cli.enable_server_certificate_verification(true);
  12449. cli.set_ca_cert_path(CA_CERT_FILE);
  12450. cli.set_connection_timeout(5);
  12451. // Note: Test certificate has CN="Common Name", not "localhost"
  12452. bool verify_result_cn = false;
  12453. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12454. verify_callback_called = true;
  12455. if (!ctx.cert) return false;
  12456. // Test 1: "Common Name" should match (our test server cert CN)
  12457. verify_result_cn = ctx.check_hostname("Common Name");
  12458. // Test 2: wrong hostname should not match
  12459. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  12460. return true; // Accept for the purpose of this test
  12461. });
  12462. auto res = cli.Get("/test");
  12463. // The request may succeed or fail depending on cert configuration
  12464. // but the callback should have been called
  12465. ASSERT_TRUE(verify_callback_called)
  12466. << "Verify callback should have been called";
  12467. // CN="Common Name" should match our test certificate
  12468. //
  12469. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  12470. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  12471. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  12472. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  12473. // <openssl/base.h>, which is included transitively when
  12474. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  12475. #if defined(OPENSSL_IS_BORINGSSL)
  12476. EXPECT_FALSE(verify_result_cn)
  12477. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  12478. #else
  12479. EXPECT_TRUE(verify_result_cn)
  12480. << "verify_hostname should match 'Common Name' (certificate CN)";
  12481. #endif
  12482. // Wrong hostname should not match
  12483. EXPECT_FALSE(verify_result_wrong)
  12484. << "verify_hostname should not match 'wronghost.example.com'";
  12485. }
  12486. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  12487. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  12488. // X509_check_ip behavior and must hold for every backend.
  12489. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  12490. using namespace httplib::tls;
  12491. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  12492. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  12493. ASSERT_TRUE(svr.is_valid());
  12494. svr.Get("/test", [](const Request &, Response &res) {
  12495. res.set_content("ok", "text/plain");
  12496. });
  12497. thread t([&]() { svr.listen(HOST, PORT); });
  12498. auto se = detail::scope_exit([&] {
  12499. svr.stop();
  12500. t.join();
  12501. });
  12502. svr.wait_until_ready();
  12503. bool verify_callback_called = false;
  12504. bool ip_matched_via_cn = true;
  12505. SSLClient cli(HOST, PORT);
  12506. cli.enable_server_certificate_verification(true);
  12507. cli.set_ca_cert_path(CA_CERT_FILE);
  12508. cli.set_connection_timeout(5);
  12509. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12510. verify_callback_called = true;
  12511. if (!ctx.cert) return false;
  12512. // The IP appears only in the CN, so it must NOT be accepted.
  12513. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  12514. return true; // Accept for the purpose of this test
  12515. });
  12516. cli.Get("/test");
  12517. ASSERT_TRUE(verify_callback_called)
  12518. << "Verify callback should have been called";
  12519. EXPECT_FALSE(ip_matched_via_cn)
  12520. << "An IP host must not be authenticated via the certificate CN";
  12521. }
  12522. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  12523. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  12524. using namespace httplib::tls;
  12525. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  12526. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  12527. ASSERT_TRUE(svr.is_valid());
  12528. svr.Get("/test", [](const Request &, Response &res) {
  12529. res.set_content("ok", "text/plain");
  12530. });
  12531. thread t([&]() { svr.listen(HOST, PORT); });
  12532. auto se = detail::scope_exit([&] {
  12533. svr.stop();
  12534. t.join();
  12535. });
  12536. svr.wait_until_ready();
  12537. bool verify_callback_called = false;
  12538. bool san_matched = false;
  12539. bool wrong_ipv6_matched = true;
  12540. bool cn_ipv6_matched = true;
  12541. SSLClient cli(HOST, PORT);
  12542. cli.enable_server_certificate_verification(true);
  12543. cli.set_ca_cert_path(CA_CERT_FILE);
  12544. cli.set_connection_timeout(5);
  12545. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12546. verify_callback_called = true;
  12547. if (!ctx.cert) return false;
  12548. // Matches the IPv6 iPAddress SAN.
  12549. san_matched = ctx.check_hostname("2001:db8::1");
  12550. // A different IPv6 address must not match.
  12551. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  12552. // "::1" lives only in the CN, so it must not be accepted.
  12553. cn_ipv6_matched = ctx.check_hostname("::1");
  12554. return true; // Accept for the purpose of this test
  12555. });
  12556. cli.Get("/test");
  12557. ASSERT_TRUE(verify_callback_called)
  12558. << "Verify callback should have been called";
  12559. EXPECT_TRUE(san_matched)
  12560. << "verify_hostname should match an IPv6 iPAddress SAN";
  12561. EXPECT_FALSE(wrong_ipv6_matched)
  12562. << "verify_hostname should not match a non-matching IPv6 address";
  12563. EXPECT_FALSE(cn_ipv6_matched)
  12564. << "An IPv6 host must not be authenticated via the certificate CN";
  12565. }
  12566. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  12567. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  12568. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  12569. using namespace httplib::tls;
  12570. // SANs: DNS:a.zz, IP:42.46.122.122
  12571. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  12572. ASSERT_TRUE(svr.is_valid());
  12573. svr.Get("/test", [](const Request &, Response &res) {
  12574. res.set_content("ok", "text/plain");
  12575. });
  12576. auto port = svr.bind_to_any_port(HOST);
  12577. thread t([&]() { svr.listen_after_bind(); });
  12578. auto se = detail::scope_exit([&] {
  12579. svr.stop();
  12580. t.join();
  12581. });
  12582. svr.wait_until_ready();
  12583. bool verify_callback_called = false;
  12584. bool dns_san_matched = false;
  12585. bool ip_san_matched = false;
  12586. bool ip_matched_via_dns_san = true;
  12587. bool dns_matched_via_ip_san = true;
  12588. SSLClient cli(HOST, port);
  12589. cli.enable_server_certificate_verification(true);
  12590. cli.set_ca_cert_path(CA_CERT_FILE);
  12591. cli.set_connection_timeout(5);
  12592. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12593. verify_callback_called = true;
  12594. if (!ctx.cert) return false;
  12595. dns_san_matched = ctx.check_hostname("a.zz");
  12596. ip_san_matched = ctx.check_hostname("42.46.122.122");
  12597. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  12598. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  12599. return true; // Accept for the purpose of this test
  12600. });
  12601. cli.Get("/test");
  12602. ASSERT_TRUE(verify_callback_called)
  12603. << "Verify callback should have been called";
  12604. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  12605. EXPECT_TRUE(ip_san_matched)
  12606. << "verify_hostname should match an iPAddress SAN";
  12607. EXPECT_FALSE(ip_matched_via_dns_san)
  12608. << "An IP host must not be authenticated via a dNSName SAN";
  12609. EXPECT_FALSE(dns_matched_via_ip_san)
  12610. << "A DNS host must not be authenticated via an iPAddress SAN";
  12611. }
  12612. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  12613. // "www.*.example.test" names one host and not every host under example.test.
  12614. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  12615. using namespace httplib::tls;
  12616. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  12617. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  12618. ASSERT_TRUE(svr.is_valid());
  12619. svr.Get("/test", [](const Request &, Response &res) {
  12620. res.set_content("ok", "text/plain");
  12621. });
  12622. auto port = svr.bind_to_any_port(HOST);
  12623. thread t([&]() { svr.listen_after_bind(); });
  12624. auto se = detail::scope_exit([&] {
  12625. svr.stop();
  12626. t.join();
  12627. });
  12628. svr.wait_until_ready();
  12629. bool verify_callback_called = false;
  12630. bool leftmost_wildcard_matched = false;
  12631. bool wildcard_spanned_labels = true;
  12632. bool inner_wildcard_matched = true;
  12633. SSLClient cli(HOST, port);
  12634. cli.enable_server_certificate_verification(true);
  12635. cli.set_ca_cert_path(CA_CERT_FILE);
  12636. cli.set_connection_timeout(5);
  12637. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12638. verify_callback_called = true;
  12639. if (!ctx.cert) return false;
  12640. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  12641. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  12642. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  12643. return true; // Accept for the purpose of this test
  12644. });
  12645. cli.Get("/test");
  12646. ASSERT_TRUE(verify_callback_called)
  12647. << "Verify callback should have been called";
  12648. EXPECT_TRUE(leftmost_wildcard_matched)
  12649. << "A leftmost wildcard should match a single label";
  12650. EXPECT_FALSE(wildcard_spanned_labels)
  12651. << "A wildcard label must not match more than one label";
  12652. EXPECT_FALSE(inner_wildcard_matched)
  12653. << "A wildcard outside the leftmost label must not be honoured";
  12654. }
  12655. // sans() must report each SAN entry under its own type.
  12656. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  12657. using namespace httplib::tls;
  12658. // SANs: DNS:a.zz, IP:42.46.122.122
  12659. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  12660. ASSERT_TRUE(svr.is_valid());
  12661. svr.Get("/test", [](const Request &, Response &res) {
  12662. res.set_content("ok", "text/plain");
  12663. });
  12664. auto port = svr.bind_to_any_port(HOST);
  12665. thread t([&]() { svr.listen_after_bind(); });
  12666. auto se = detail::scope_exit([&] {
  12667. svr.stop();
  12668. t.join();
  12669. });
  12670. svr.wait_until_ready();
  12671. bool verify_callback_called = false;
  12672. std::vector<SanEntry> sans;
  12673. SSLClient cli(HOST, port);
  12674. cli.enable_server_certificate_verification(true);
  12675. cli.set_ca_cert_path(CA_CERT_FILE);
  12676. cli.set_connection_timeout(5);
  12677. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12678. verify_callback_called = true;
  12679. if (!ctx.cert) return false;
  12680. sans = ctx.sans();
  12681. return true; // Accept for the purpose of this test
  12682. });
  12683. cli.Get("/test");
  12684. ASSERT_TRUE(verify_callback_called)
  12685. << "Verify callback should have been called";
  12686. auto has_san = [&](SanType type, const std::string &value) {
  12687. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  12688. return san.type == type && san.value == value;
  12689. });
  12690. };
  12691. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  12692. << "sans() should report the dNSName SAN";
  12693. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  12694. << "sans() should report the iPAddress SAN";
  12695. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  12696. << "sans() must not report the dNSName SAN as an address";
  12697. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  12698. << "sans() must not report the iPAddress SAN as a DNS name";
  12699. }
  12700. #endif
  12701. // mbedTLS-specific callback constructor test
  12702. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  12703. #ifdef CPPHTTPLIB_SSL_ENABLED
  12704. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  12705. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12706. ASSERT_TRUE(svr.is_valid());
  12707. // Set up a handler to verify client certificate is present
  12708. bool client_cert_verified = false;
  12709. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12710. // Verify that client certificate was provided
  12711. client_cert_verified = true;
  12712. res.set_content("success", "text/plain");
  12713. });
  12714. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12715. auto se = detail::scope_exit([&] {
  12716. svr.stop();
  12717. t.join();
  12718. ASSERT_FALSE(svr.is_running());
  12719. });
  12720. svr.wait_until_ready();
  12721. // Client with certificate
  12722. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12723. cli.enable_server_certificate_verification(false);
  12724. cli.set_connection_timeout(30);
  12725. auto res = cli.Get("/test");
  12726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12727. ASSERT_EQ(StatusCode::OK_200, res->status);
  12728. ASSERT_TRUE(client_cert_verified);
  12729. EXPECT_EQ("success", res->body);
  12730. }
  12731. #endif
  12732. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  12733. // backends
  12734. #ifdef CPPHTTPLIB_SSL_ENABLED
  12735. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  12736. using namespace httplib::tls;
  12737. // Test that when client CA cert file is provided,
  12738. // the server properly requests and validates client certificates
  12739. // Create a server with client authentication
  12740. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12741. ASSERT_TRUE(svr.is_valid());
  12742. bool handler_called = false;
  12743. svr.Get("/test", [&](const Request &req, Response &res) {
  12744. handler_called = true;
  12745. // Verify that a client certificate was provided
  12746. auto cert = req.peer_cert();
  12747. ASSERT_TRUE(static_cast<bool>(cert));
  12748. // Get the issuer name
  12749. std::string issuer_str = cert.issuer_name();
  12750. ASSERT_FALSE(issuer_str.empty());
  12751. // The client certificate should be issued by our test CA
  12752. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  12753. res.set_content("authenticated", "text/plain");
  12754. });
  12755. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12756. auto se = detail::scope_exit([&] {
  12757. svr.stop();
  12758. t.join();
  12759. ASSERT_FALSE(svr.is_running());
  12760. });
  12761. svr.wait_until_ready();
  12762. // Connect with a client certificate issued by the CA
  12763. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12764. cli.enable_server_certificate_verification(false);
  12765. cli.set_connection_timeout(30);
  12766. auto res = cli.Get("/test");
  12767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12768. ASSERT_EQ(StatusCode::OK_200, res->status);
  12769. ASSERT_TRUE(handler_called);
  12770. EXPECT_EQ("authenticated", res->body);
  12771. }
  12772. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  12773. using namespace httplib::tls;
  12774. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12775. ASSERT_TRUE(svr.is_valid());
  12776. svr.Get("/test", [](const Request &, Response &res) {
  12777. res.set_content("ok", "text/plain");
  12778. });
  12779. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12780. auto se = detail::scope_exit([&] {
  12781. svr.stop();
  12782. t.join();
  12783. });
  12784. svr.wait_until_ready();
  12785. SSLClient cli(HOST, PORT);
  12786. cli.enable_server_certificate_verification(false);
  12787. cli.set_connection_timeout(30);
  12788. bool cert_checked = false;
  12789. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12790. if (ctx.cert) {
  12791. auto sans = ctx.sans();
  12792. // Test certificate may or may not have SANs - just verify the API
  12793. // works If SANs exist, verify the types are valid
  12794. for (const auto &san : sans) {
  12795. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  12796. san.type == SanType::EMAIL || san.type == SanType::URI ||
  12797. san.type == SanType::OTHER);
  12798. EXPECT_FALSE(san.value.empty());
  12799. }
  12800. cert_checked = true;
  12801. }
  12802. return true;
  12803. });
  12804. auto res = cli.Get("/test");
  12805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12806. EXPECT_TRUE(cert_checked);
  12807. }
  12808. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  12809. using namespace httplib::tls;
  12810. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12811. ASSERT_TRUE(svr.is_valid());
  12812. svr.Get("/test", [](const Request &, Response &res) {
  12813. res.set_content("ok", "text/plain");
  12814. });
  12815. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12816. auto se = detail::scope_exit([&] {
  12817. svr.stop();
  12818. t.join();
  12819. });
  12820. svr.wait_until_ready();
  12821. SSLClient cli(HOST, PORT);
  12822. cli.enable_server_certificate_verification(false);
  12823. cli.set_connection_timeout(30);
  12824. bool validity_checked = false;
  12825. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12826. if (ctx.cert) {
  12827. time_t not_before = 0, not_after = 0;
  12828. bool result = ctx.validity(not_before, not_after);
  12829. EXPECT_TRUE(result);
  12830. // Verify that not_before < now < not_after for a valid cert
  12831. time_t now = time(nullptr);
  12832. EXPECT_LT(not_before, now);
  12833. EXPECT_GT(not_after, now);
  12834. validity_checked = true;
  12835. }
  12836. return true;
  12837. });
  12838. auto res = cli.Get("/test");
  12839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12840. EXPECT_TRUE(validity_checked);
  12841. }
  12842. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  12843. using namespace httplib::tls;
  12844. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12845. ASSERT_TRUE(svr.is_valid());
  12846. svr.Get("/test", [](const Request &, Response &res) {
  12847. res.set_content("ok", "text/plain");
  12848. });
  12849. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12850. auto se = detail::scope_exit([&] {
  12851. svr.stop();
  12852. t.join();
  12853. });
  12854. svr.wait_until_ready();
  12855. SSLClient cli(HOST, PORT);
  12856. cli.enable_server_certificate_verification(false);
  12857. cli.set_connection_timeout(30);
  12858. bool serial_checked = false;
  12859. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12860. if (ctx.cert) {
  12861. std::string serial = ctx.serial();
  12862. EXPECT_FALSE(serial.empty());
  12863. // Serial should be a hex string
  12864. for (char c : serial) {
  12865. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  12866. (c >= 'a' && c <= 'f'));
  12867. }
  12868. serial_checked = true;
  12869. }
  12870. return true;
  12871. });
  12872. auto res = cli.Get("/test");
  12873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12874. EXPECT_TRUE(serial_checked);
  12875. }
  12876. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  12877. // Test 1: Valid CA file - no error should be recorded
  12878. {
  12879. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12880. CLIENT_CA_CERT_FILE);
  12881. ASSERT_TRUE(svr.is_valid());
  12882. // With valid setup, last_ssl_error should be 0
  12883. EXPECT_EQ(0, svr.ssl_last_error());
  12884. }
  12885. // Test 2: Invalid CA file content
  12886. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  12887. {
  12888. // Create a temporary file with completely invalid content
  12889. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  12890. {
  12891. std::ofstream ofs(temp_invalid_ca);
  12892. ofs << "This is not a certificate file at all\n";
  12893. ofs << "Just plain text content\n";
  12894. }
  12895. // Create server with invalid CA file
  12896. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  12897. // Clean up temporary file
  12898. std::remove(temp_invalid_ca);
  12899. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  12900. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  12901. // Note: SSL_CTX_load_verify_locations typically fails first,
  12902. // but our error handling code path is still exercised
  12903. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  12904. }
  12905. }
  12906. TEST(VerifyCallbackTest, VerifyContextFields) {
  12907. using namespace httplib::tls;
  12908. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12909. ASSERT_TRUE(svr.is_valid());
  12910. svr.Get("/test", [](const Request &, Response &res) {
  12911. res.set_content("ok", "text/plain");
  12912. });
  12913. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12914. auto se = detail::scope_exit([&] {
  12915. svr.stop();
  12916. t.join();
  12917. });
  12918. svr.wait_until_ready();
  12919. SSLClient cli(HOST, PORT);
  12920. cli.enable_server_certificate_verification(false);
  12921. cli.set_connection_timeout(30);
  12922. int callback_count = 0;
  12923. bool saw_leaf_cert = false;
  12924. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12925. if (ctx.cert) {
  12926. callback_count++;
  12927. // We should see at least one certificate (the leaf)
  12928. std::string cn = ctx.subject_cn();
  12929. if (!cn.empty()) { saw_leaf_cert = true; }
  12930. // Verify context fields are populated
  12931. EXPECT_NE(ctx.session, nullptr);
  12932. EXPECT_GE(ctx.depth, 0);
  12933. }
  12934. return true;
  12935. });
  12936. auto res = cli.Get("/test");
  12937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12938. EXPECT_GT(callback_count, 0);
  12939. EXPECT_TRUE(saw_leaf_cert);
  12940. }
  12941. // Each client's verifier is stored with its own TLS context, so configuring a
  12942. // second client on the same thread must not replace the first one's.
  12943. TEST(VerifyCallbackTest, PerClientVerifiersOnSameThread) {
  12944. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12945. ASSERT_TRUE(svr.is_valid());
  12946. svr.Get("/test", [](const Request &, Response &res) {
  12947. res.set_content("ok", "text/plain");
  12948. });
  12949. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12950. auto se = detail::scope_exit([&] {
  12951. svr.stop();
  12952. t.join();
  12953. });
  12954. svr.wait_until_ready();
  12955. std::atomic<int> count1{0};
  12956. std::atomic<int> count2{0};
  12957. SSLClient cli1(HOST, PORT);
  12958. cli1.enable_server_certificate_verification(false);
  12959. cli1.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  12960. count1++;
  12961. return true;
  12962. });
  12963. SSLClient cli2(HOST, PORT);
  12964. cli2.enable_server_certificate_verification(false);
  12965. cli2.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  12966. count2++;
  12967. return true;
  12968. });
  12969. auto res1 = cli1.Get("/test");
  12970. ASSERT_TRUE(res1) << "Error: " << to_string(res1.error());
  12971. EXPECT_GT(count1.load(), 0);
  12972. EXPECT_EQ(0, count2.load());
  12973. count1 = 0;
  12974. auto res2 = cli2.Get("/test");
  12975. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  12976. EXPECT_EQ(0, count1.load());
  12977. EXPECT_GT(count2.load(), 0);
  12978. }
  12979. // A verifier set on one thread must still run when the request is made from
  12980. // another thread.
  12981. TEST(VerifyCallbackTest, VerifierRunsOnAnotherThread) {
  12982. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12983. ASSERT_TRUE(svr.is_valid());
  12984. svr.Get("/test", [](const Request &, Response &res) {
  12985. res.set_content("ok", "text/plain");
  12986. });
  12987. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12988. auto se = detail::scope_exit([&] {
  12989. svr.stop();
  12990. t.join();
  12991. });
  12992. svr.wait_until_ready();
  12993. std::atomic<int> count{0};
  12994. SSLClient cli(HOST, PORT);
  12995. cli.enable_server_certificate_verification(false);
  12996. cli.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  12997. count++;
  12998. return true;
  12999. });
  13000. Result res;
  13001. thread worker([&]() { res = cli.Get("/test"); });
  13002. worker.join();
  13003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13004. EXPECT_GT(count.load(), 0);
  13005. }
  13006. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  13007. using httplib::tls::TlsError;
  13008. // Test that verify_error_to_string returns empty for success
  13009. std::string success_str = TlsError::verify_error_to_string(0);
  13010. EXPECT_TRUE(success_str.empty());
  13011. // Test that verify_error_to_string returns non-empty for error codes
  13012. // Using a common error code (certificate expired)
  13013. std::string error_str =
  13014. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  13015. EXPECT_FALSE(error_str.empty());
  13016. }
  13017. TEST(SessionVerifierTest, CertificateAccepted) {
  13018. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13019. ASSERT_TRUE(svr.is_valid());
  13020. svr.Get("/test", [](const Request &, Response &res) {
  13021. res.set_content("ok", "text/plain");
  13022. });
  13023. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13024. auto se = detail::scope_exit([&] {
  13025. svr.stop();
  13026. t.join();
  13027. });
  13028. svr.wait_until_ready();
  13029. SSLClient cli(HOST, PORT);
  13030. cli.enable_server_certificate_verification(false);
  13031. cli.set_connection_timeout(30);
  13032. bool callback_called = false;
  13033. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13034. EXPECT_NE(session, nullptr);
  13035. callback_called = true;
  13036. return SSLVerifierResponse::CertificateAccepted;
  13037. });
  13038. auto res = cli.Get("/test");
  13039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13040. EXPECT_EQ(200, res->status);
  13041. EXPECT_TRUE(callback_called);
  13042. }
  13043. TEST(SessionVerifierTest, CertificateRejected) {
  13044. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13045. ASSERT_TRUE(svr.is_valid());
  13046. svr.Get("/test", [](const Request &, Response &res) {
  13047. res.set_content("ok", "text/plain");
  13048. });
  13049. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13050. auto se = detail::scope_exit([&] {
  13051. svr.stop();
  13052. t.join();
  13053. });
  13054. svr.wait_until_ready();
  13055. SSLClient cli(HOST, PORT);
  13056. cli.enable_server_certificate_verification(false);
  13057. cli.set_connection_timeout(30);
  13058. bool callback_called = false;
  13059. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13060. EXPECT_NE(session, nullptr);
  13061. callback_called = true;
  13062. return SSLVerifierResponse::CertificateRejected;
  13063. });
  13064. auto res = cli.Get("/test");
  13065. EXPECT_FALSE(res);
  13066. EXPECT_TRUE(callback_called);
  13067. }
  13068. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  13069. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13070. ASSERT_TRUE(svr.is_valid());
  13071. svr.Get("/test", [](const Request &, Response &res) {
  13072. res.set_content("ok", "text/plain");
  13073. });
  13074. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13075. auto se = detail::scope_exit([&] {
  13076. svr.stop();
  13077. t.join();
  13078. });
  13079. svr.wait_until_ready();
  13080. // NoDecisionMade with verification disabled should succeed (no default check)
  13081. SSLClient cli(HOST, PORT);
  13082. cli.enable_server_certificate_verification(false);
  13083. cli.set_connection_timeout(30);
  13084. bool callback_called = false;
  13085. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13086. EXPECT_NE(session, nullptr);
  13087. callback_called = true;
  13088. return SSLVerifierResponse::NoDecisionMade;
  13089. });
  13090. auto res = cli.Get("/test");
  13091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13092. EXPECT_EQ(200, res->status);
  13093. EXPECT_TRUE(callback_called);
  13094. }
  13095. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  13096. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13097. ASSERT_TRUE(svr.is_valid());
  13098. svr.Get("/test", [](const Request &, Response &res) {
  13099. res.set_content("ok", "text/plain");
  13100. });
  13101. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13102. auto se = detail::scope_exit([&] {
  13103. svr.stop();
  13104. t.join();
  13105. });
  13106. svr.wait_until_ready();
  13107. // NoDecisionMade with verification enabled should fail (self-signed cert).
  13108. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  13109. // so we only check that the request fails, not whether the callback was
  13110. // called.
  13111. SSLClient cli(HOST, PORT);
  13112. cli.enable_server_certificate_verification(true);
  13113. cli.set_connection_timeout(30);
  13114. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13115. EXPECT_NE(session, nullptr);
  13116. return SSLVerifierResponse::NoDecisionMade;
  13117. });
  13118. auto res = cli.Get("/test");
  13119. EXPECT_FALSE(res);
  13120. }
  13121. TEST(SSLClientServerTest, ClientCAListFromPem) {
  13122. // Test SSL server using PemMemory constructor with client CA certificates
  13123. // Read PEM files
  13124. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13125. read_file(SERVER_CERT_FILE, server_cert_pem);
  13126. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13127. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13128. // Create SSLServer with PemMemory constructor including client CA
  13129. SSLServer::PemMemory server_pem = {
  13130. server_cert_pem.c_str(),
  13131. server_cert_pem.size(),
  13132. server_key_pem.c_str(),
  13133. server_key_pem.size(),
  13134. client_ca_pem.c_str(),
  13135. client_ca_pem.size(),
  13136. nullptr // no password for server key
  13137. };
  13138. SSLServer svr(server_pem);
  13139. ASSERT_TRUE(svr.is_valid());
  13140. // No SSL error should be recorded for valid setup
  13141. EXPECT_EQ(0, svr.ssl_last_error());
  13142. // Set up server endpoints
  13143. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  13144. res.set_content("ok", "text/plain");
  13145. });
  13146. // Start server in a thread
  13147. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  13148. svr.wait_until_ready();
  13149. // Connect with client certificate (using constructor with paths)
  13150. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13151. cli.enable_server_certificate_verification(false);
  13152. auto res = cli.Get("/test-pem-ca");
  13153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13154. EXPECT_EQ(200, res->status);
  13155. EXPECT_EQ("ok", res->body);
  13156. svr.stop();
  13157. server_thread.join();
  13158. }
  13159. #endif
  13160. #ifdef _WIN32
  13161. TEST(CleanupTest, WSACleanup) {
  13162. int ret = WSACleanup();
  13163. ASSERT_EQ(0, ret);
  13164. }
  13165. #endif
  13166. #ifndef CPPHTTPLIB_SSL_ENABLED
  13167. TEST(NoSSLSupport, SimpleInterface) {
  13168. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  13169. }
  13170. #endif
  13171. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  13172. TEST(InvalidScheme, SimpleInterface) {
  13173. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  13174. }
  13175. #endif
  13176. TEST(NoScheme, SimpleInterface) {
  13177. Client cli("yahoo.com:80");
  13178. ASSERT_TRUE(cli.is_valid());
  13179. }
  13180. TEST(SendAPI, SimpleInterface_Online) {
  13181. Client cli("http://yahoo.com");
  13182. Request req;
  13183. req.method = "GET";
  13184. req.path = "/";
  13185. auto res = cli.send(req);
  13186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13187. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13188. }
  13189. TEST(SendAPI, WithParamsInRequest) {
  13190. Server svr;
  13191. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  13192. EXPECT_TRUE(req.has_param("test"));
  13193. EXPECT_EQ("test_value", req.get_param_value("test"));
  13194. });
  13195. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13196. auto se = detail::scope_exit([&] {
  13197. svr.stop();
  13198. t.join();
  13199. ASSERT_FALSE(svr.is_running());
  13200. });
  13201. svr.wait_until_ready();
  13202. Client cli(HOST, PORT);
  13203. {
  13204. Request req;
  13205. req.method = "GET";
  13206. req.path = "/";
  13207. req.params.emplace("test", "test_value");
  13208. auto res = cli.send(req);
  13209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13210. }
  13211. {
  13212. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  13213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13214. }
  13215. }
  13216. TEST(ClientImplMethods, GetSocketTest) {
  13217. httplib::Server svr;
  13218. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  13219. res.status = StatusCode::OK_200;
  13220. });
  13221. auto port = svr.bind_to_any_port("127.0.0.1");
  13222. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13223. auto se = detail::scope_exit([&] {
  13224. svr.stop();
  13225. thread.join();
  13226. ASSERT_FALSE(svr.is_running());
  13227. });
  13228. svr.wait_until_ready();
  13229. {
  13230. httplib::Client cli("127.0.0.1", port);
  13231. cli.set_keep_alive(true);
  13232. // Use the behavior of cpp-httplib of opening the connection
  13233. // only when the first request happens. If that changes,
  13234. // this test would be obsolete.
  13235. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  13236. // This also implicitly tests the server. But other tests would fail much
  13237. // earlier than this one to be considered.
  13238. auto res = cli.Get("/");
  13239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13240. EXPECT_EQ(StatusCode::OK_200, res->status);
  13241. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  13242. }
  13243. }
  13244. #ifdef CPPHTTPLIB_SSL_ENABLED
  13245. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  13246. Client cli("http://yahoo.com");
  13247. auto res = cli.Get("/");
  13248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13249. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13250. cli.set_follow_location(true);
  13251. res = cli.Get("/");
  13252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13253. EXPECT_EQ(StatusCode::OK_200, res->status);
  13254. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13255. }
  13256. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  13257. Client cli("https://yahoo.com");
  13258. auto res = cli.Get("/");
  13259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13260. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13261. cli.set_follow_location(true);
  13262. res = cli.Get("/");
  13263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13264. EXPECT_EQ(StatusCode::OK_200, res->status);
  13265. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13266. }
  13267. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  13268. Client cli("https://yahoo.com");
  13269. auto res = cli.Get("/");
  13270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13271. ASSERT_FALSE(!res);
  13272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13273. ASSERT_FALSE(res == nullptr);
  13274. ASSERT_TRUE(res != nullptr);
  13275. EXPECT_EQ(Error::Success, res.error());
  13276. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  13277. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  13278. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13279. cli.set_follow_location(true);
  13280. res = cli.Get("/");
  13281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13282. EXPECT_EQ(Error::Success, res.error());
  13283. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  13284. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  13285. EXPECT_EQ(StatusCode::OK_200, res->status);
  13286. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13287. }
  13288. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13289. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  13290. Client cli("https://cdnjs.cloudflare.com");
  13291. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  13292. Headers{{"Accept-Encoding", "br"}});
  13293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13294. EXPECT_EQ(StatusCode::OK_200, res->status);
  13295. EXPECT_EQ(287630U, res->body.size());
  13296. EXPECT_EQ("application/javascript; charset=utf-8",
  13297. res->get_header_value("Content-Type"));
  13298. }
  13299. #endif
  13300. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  13301. #undef REDIR_HOST // Silence compiler warning
  13302. #define REDIR_HOST "https://httpbingo.org"
  13303. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  13304. Client cli(REDIR_HOST);
  13305. cli.set_follow_location(true);
  13306. auto res =
  13307. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  13308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13309. EXPECT_EQ(StatusCode::OK_200, res->status);
  13310. }
  13311. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  13312. Client cli(REDIR_HOST);
  13313. cli.set_follow_location(true);
  13314. Params params;
  13315. params.emplace("url", "http://example.com");
  13316. params.emplace("status_code", "302");
  13317. auto res = cli.Get(REDIR_PATH, params, Headers{});
  13318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13319. EXPECT_EQ(StatusCode::OK_200, res->status);
  13320. }
  13321. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  13322. Client cli(REDIR_HOST);
  13323. cli.set_follow_location(true);
  13324. Params params;
  13325. params.emplace("url", "http://example.com");
  13326. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  13327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13328. EXPECT_EQ(StatusCode::OK_200, res->status);
  13329. }
  13330. TEST(HttpToHttpsRedirectTest, CertFile) {
  13331. auto ssl_port = PORT + 1;
  13332. Server svr;
  13333. ASSERT_TRUE(svr.is_valid());
  13334. svr.Get("/index", [&](const Request &, Response &res) {
  13335. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13336. "/index");
  13337. svr.stop();
  13338. });
  13339. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13340. ASSERT_TRUE(ssl_svr.is_valid());
  13341. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  13342. res.set_content("test", "text/plain");
  13343. ssl_svr.stop();
  13344. });
  13345. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13346. thread t2 =
  13347. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  13348. auto se = detail::scope_exit([&] {
  13349. t2.join();
  13350. t.join();
  13351. ASSERT_FALSE(svr.is_running());
  13352. });
  13353. svr.wait_until_ready();
  13354. ssl_svr.wait_until_ready();
  13355. Client cli("127.0.0.1", PORT);
  13356. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13357. cli.enable_server_certificate_verification(true);
  13358. cli.set_follow_location(true);
  13359. cli.set_connection_timeout(30);
  13360. auto res = cli.Get("/index");
  13361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13362. ASSERT_EQ(StatusCode::OK_200, res->status);
  13363. }
  13364. TEST(SSLClientRedirectTest, CertFile) {
  13365. auto ssl_port = PORT + 1;
  13366. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13367. ASSERT_TRUE(ssl_svr1.is_valid());
  13368. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13369. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13370. "/index");
  13371. ssl_svr1.stop();
  13372. });
  13373. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13374. ASSERT_TRUE(ssl_svr2.is_valid());
  13375. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13376. res.set_content("test", "text/plain");
  13377. ssl_svr2.stop();
  13378. });
  13379. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13380. thread t2 =
  13381. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13382. auto se = detail::scope_exit([&] {
  13383. t2.join();
  13384. t.join();
  13385. ASSERT_FALSE(ssl_svr1.is_running());
  13386. });
  13387. ssl_svr1.wait_until_ready();
  13388. ssl_svr2.wait_until_ready();
  13389. SSLClient cli("127.0.0.1", PORT);
  13390. std::string cert;
  13391. read_file(SERVER_CERT2_FILE, cert);
  13392. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13393. cli.enable_server_certificate_verification(true);
  13394. cli.set_follow_location(true);
  13395. cli.set_connection_timeout(30);
  13396. auto res = cli.Get("/index");
  13397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13398. ASSERT_EQ(StatusCode::OK_200, res->status);
  13399. }
  13400. // A store set via set_ca_cert_store() must be carried over to the client that
  13401. // follows a cross-host redirect, rather than replaced by the system CAs.
  13402. TEST(SSLClientRedirectTest, SetCaCertStore) {
  13403. auto ssl_port = PORT + 1;
  13404. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13405. ASSERT_TRUE(ssl_svr1.is_valid());
  13406. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13407. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13408. "/index");
  13409. });
  13410. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13411. ASSERT_TRUE(ssl_svr2.is_valid());
  13412. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13413. res.set_content("test", "text/plain");
  13414. });
  13415. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13416. thread t2 =
  13417. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13418. auto se = detail::scope_exit([&] {
  13419. ssl_svr2.stop();
  13420. ssl_svr1.stop();
  13421. t2.join();
  13422. t.join();
  13423. ASSERT_FALSE(ssl_svr1.is_running());
  13424. });
  13425. ssl_svr1.wait_until_ready();
  13426. ssl_svr2.wait_until_ready();
  13427. SSLClient cli("127.0.0.1", PORT);
  13428. std::string cert;
  13429. read_file(SERVER_CERT2_FILE, cert);
  13430. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13431. cli.enable_server_certificate_verification(true);
  13432. cli.set_follow_location(true);
  13433. cli.set_connection_timeout(30);
  13434. auto res = cli.Get("/index");
  13435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13436. ASSERT_EQ(StatusCode::OK_200, res->status);
  13437. }
  13438. // The session verifier must also run for the host a redirect leads to.
  13439. TEST(SSLClientRedirectTest, SessionVerifier) {
  13440. auto ssl_port = PORT + 1;
  13441. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13442. ASSERT_TRUE(ssl_svr1.is_valid());
  13443. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13444. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13445. "/index");
  13446. });
  13447. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13448. ASSERT_TRUE(ssl_svr2.is_valid());
  13449. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13450. res.set_content("test", "text/plain");
  13451. });
  13452. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13453. thread t2 =
  13454. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13455. auto se = detail::scope_exit([&] {
  13456. ssl_svr2.stop();
  13457. ssl_svr1.stop();
  13458. t2.join();
  13459. t.join();
  13460. ASSERT_FALSE(ssl_svr1.is_running());
  13461. });
  13462. ssl_svr1.wait_until_ready();
  13463. ssl_svr2.wait_until_ready();
  13464. SSLClient cli("127.0.0.1", PORT);
  13465. std::string cert;
  13466. read_file(SERVER_CERT2_FILE, cert);
  13467. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13468. cli.enable_server_certificate_verification(true);
  13469. cli.set_follow_location(true);
  13470. cli.set_connection_timeout(30);
  13471. // Accept the first host only.
  13472. std::atomic<int> sessions{0};
  13473. cli.set_session_verifier([&](tls::session_t) -> SSLVerifierResponse {
  13474. return sessions++ == 0 ? SSLVerifierResponse::CertificateAccepted
  13475. : SSLVerifierResponse::CertificateRejected;
  13476. });
  13477. auto res = cli.Get("/index");
  13478. ASSERT_FALSE(res);
  13479. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13480. EXPECT_EQ(2, sessions.load());
  13481. }
  13482. // So must the verifier given to set_server_certificate_verifier().
  13483. TEST(SSLClientRedirectTest, ServerCertificateVerifier) {
  13484. auto ssl_port = PORT + 1;
  13485. std::atomic<bool> redirected{false};
  13486. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13487. ASSERT_TRUE(ssl_svr1.is_valid());
  13488. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13489. redirected = true;
  13490. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13491. "/index");
  13492. });
  13493. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13494. ASSERT_TRUE(ssl_svr2.is_valid());
  13495. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13496. res.set_content("test", "text/plain");
  13497. });
  13498. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13499. thread t2 =
  13500. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13501. auto se = detail::scope_exit([&] {
  13502. ssl_svr2.stop();
  13503. ssl_svr1.stop();
  13504. t2.join();
  13505. t.join();
  13506. ASSERT_FALSE(ssl_svr1.is_running());
  13507. });
  13508. ssl_svr1.wait_until_ready();
  13509. ssl_svr2.wait_until_ready();
  13510. SSLClient cli("127.0.0.1", PORT);
  13511. std::string cert;
  13512. read_file(SERVER_CERT2_FILE, cert);
  13513. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13514. cli.enable_server_certificate_verification(true);
  13515. cli.set_follow_location(true);
  13516. cli.set_connection_timeout(30);
  13517. // Accept the host that redirects only; the verifier runs once per
  13518. // certificate in the chain, so count the calls made after the redirect.
  13519. std::atomic<int> calls_after_redirect{0};
  13520. cli.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  13521. if (!redirected) { return true; }
  13522. calls_after_redirect++;
  13523. return false;
  13524. });
  13525. auto res = cli.Get("/index");
  13526. ASSERT_FALSE(res);
  13527. EXPECT_LT(0, calls_after_redirect.load());
  13528. }
  13529. #endif
  13530. #ifdef CPPHTTPLIB_SSL_ENABLED
  13531. // Test that set_ca_cert_store() skips system certs (consistent with
  13532. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  13533. // should be trusted - system certs should NOT be loaded.
  13534. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  13535. // Load a specific cert that is NOT a system CA cert
  13536. std::string cert;
  13537. read_file(SERVER_CERT2_FILE, cert);
  13538. SSLClient cli("google.com");
  13539. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13540. cli.enable_server_certificate_verification(true);
  13541. // This should FAIL because:
  13542. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  13543. // 2. System certs should NOT be loaded when custom store is set
  13544. // If system certs WERE loaded, this would succeed
  13545. auto res = cli.Get("/");
  13546. ASSERT_FALSE(res);
  13547. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13548. }
  13549. // Same as above, but through the native store handle path. Regression test:
  13550. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  13551. // merged system certs into the user-provided store.
  13552. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  13553. std::string cert;
  13554. read_file(SERVER_CERT2_FILE, cert);
  13555. SSLClient cli("google.com");
  13556. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13557. cli.enable_server_certificate_verification(true);
  13558. auto res = cli.Get("/");
  13559. ASSERT_FALSE(res);
  13560. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13561. }
  13562. // A custom store set via the native handle must still verify a server whose
  13563. // cert it does contain.
  13564. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  13565. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13566. ASSERT_TRUE(svr.is_valid());
  13567. svr.Get("/test", [&](const Request &, Response &res) {
  13568. res.set_content("test", "text/plain");
  13569. });
  13570. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13571. auto se = detail::scope_exit([&] {
  13572. svr.stop();
  13573. t.join();
  13574. ASSERT_FALSE(svr.is_running());
  13575. });
  13576. svr.wait_until_ready();
  13577. SSLClient cli("127.0.0.1", PORT);
  13578. std::string cert;
  13579. read_file(SERVER_CERT2_FILE, cert);
  13580. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13581. cli.enable_server_certificate_verification(true);
  13582. cli.set_connection_timeout(30);
  13583. auto res = cli.Get("/test");
  13584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13585. ASSERT_EQ(StatusCode::OK_200, res->status);
  13586. }
  13587. // CA certs loaded through the universal Client must be transferred to the
  13588. // client created internally for following an HTTPS redirect. Regression test:
  13589. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  13590. // the CA data for redirect transfer.
  13591. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  13592. auto ssl_port = PORT + 1;
  13593. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13594. ASSERT_TRUE(ssl_svr1.is_valid());
  13595. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13596. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13597. "/index");
  13598. });
  13599. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13600. ASSERT_TRUE(ssl_svr2.is_valid());
  13601. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13602. res.set_content("test", "text/plain");
  13603. });
  13604. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13605. thread t2 =
  13606. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13607. auto se = detail::scope_exit([&] {
  13608. ssl_svr2.stop();
  13609. ssl_svr1.stop();
  13610. t2.join();
  13611. t.join();
  13612. ASSERT_FALSE(ssl_svr1.is_running());
  13613. });
  13614. ssl_svr1.wait_until_ready();
  13615. ssl_svr2.wait_until_ready();
  13616. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13617. std::string cert;
  13618. read_file(SERVER_CERT2_FILE, cert);
  13619. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13620. cli.enable_server_certificate_verification(true);
  13621. cli.set_follow_location(true);
  13622. cli.set_connection_timeout(30);
  13623. auto res = cli.Get("/index");
  13624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13625. ASSERT_EQ(StatusCode::OK_200, res->status);
  13626. }
  13627. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  13628. // so a host signed by a system CA verifies even though a custom CA is set
  13629. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  13630. std::string cert;
  13631. read_file(SERVER_CERT2_FILE, cert);
  13632. SSLClient cli("google.com");
  13633. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13634. cli.enable_system_ca(true);
  13635. cli.enable_server_certificate_verification(true);
  13636. auto res = cli.Get("/");
  13637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13638. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13639. }
  13640. // The custom CA remains effective when combined with the system CA
  13641. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  13642. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13643. ASSERT_TRUE(svr.is_valid());
  13644. svr.Get("/test", [&](const Request &, Response &res) {
  13645. res.set_content("test", "text/plain");
  13646. });
  13647. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13648. auto se = detail::scope_exit([&] {
  13649. svr.stop();
  13650. t.join();
  13651. ASSERT_FALSE(svr.is_running());
  13652. });
  13653. svr.wait_until_ready();
  13654. SSLClient cli("127.0.0.1", PORT);
  13655. std::string cert;
  13656. read_file(SERVER_CERT2_FILE, cert);
  13657. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13658. cli.enable_system_ca(true);
  13659. cli.enable_server_certificate_verification(true);
  13660. cli.set_connection_timeout(30);
  13661. auto res = cli.Get("/test");
  13662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13663. ASSERT_EQ(StatusCode::OK_200, res->status);
  13664. }
  13665. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  13666. // skip chain verification entirely (only the certificate identity was
  13667. // checked), so a server presenting an untrusted certificate with a matching
  13668. // IP SAN was accepted. The chain must be validated for IP hosts too.
  13669. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  13670. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13671. ASSERT_TRUE(svr.is_valid());
  13672. svr.Get("/test", [&](const Request &, Response &res) {
  13673. res.set_content("test", "text/plain");
  13674. });
  13675. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13676. auto se = detail::scope_exit([&] {
  13677. svr.stop();
  13678. t.join();
  13679. ASSERT_FALSE(svr.is_running());
  13680. });
  13681. svr.wait_until_ready();
  13682. SSLClient cli("127.0.0.1", PORT);
  13683. std::string cert;
  13684. // A trusted CA that did not sign the server certificate. The server cert
  13685. // (cert2) carries the matching IP SAN, so only chain validation can reject
  13686. // this connection.
  13687. read_file(CLIENT_CA_CERT_FILE, cert);
  13688. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13689. cli.enable_server_certificate_verification(true);
  13690. cli.set_connection_timeout(30);
  13691. auto res = cli.Get("/test");
  13692. ASSERT_FALSE(res);
  13693. }
  13694. // enable_system_ca(false) prevents system CA loading entirely
  13695. TEST(SSLClientTest, DisableSystemCa_Online) {
  13696. SSLClient cli("google.com");
  13697. cli.enable_system_ca(false);
  13698. cli.enable_server_certificate_verification(true);
  13699. auto res = cli.Get("/");
  13700. ASSERT_FALSE(res);
  13701. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  13702. // itself when the CA chain is empty
  13703. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13704. res.error() == Error::SSLConnection);
  13705. }
  13706. // The universal Client forwards enable_system_ca()
  13707. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  13708. std::string cert;
  13709. read_file(SERVER_CERT2_FILE, cert);
  13710. Client cli("https://google.com");
  13711. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13712. cli.enable_system_ca(true);
  13713. cli.enable_server_certificate_verification(true);
  13714. auto res = cli.Get("/");
  13715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13716. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13717. }
  13718. // The system CA policy must carry over to the client created internally for
  13719. // following a cross-host HTTPS redirect
  13720. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  13721. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13722. ASSERT_TRUE(svr.is_valid());
  13723. svr.Get("/index", [&](const Request &, Response &res) {
  13724. res.set_redirect("https://www.google.com/");
  13725. });
  13726. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13727. auto se = detail::scope_exit([&] {
  13728. svr.stop();
  13729. t.join();
  13730. ASSERT_FALSE(svr.is_running());
  13731. });
  13732. svr.wait_until_ready();
  13733. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13734. std::string cert;
  13735. read_file(SERVER_CERT2_FILE, cert);
  13736. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13737. cli.enable_system_ca(true);
  13738. cli.enable_server_certificate_verification(true);
  13739. cli.set_follow_location(true);
  13740. cli.set_connection_timeout(30);
  13741. // Receiving any response proves the redirect client completed the TLS
  13742. // handshake with a system-CA-signed host
  13743. auto res = cli.Get("/index");
  13744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13745. }
  13746. TEST(MultipartFormDataTest, LargeData) {
  13747. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13748. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  13749. const ContentReader &content_reader) {
  13750. if (req.is_multipart_form_data()) {
  13751. std::vector<FormData> items;
  13752. content_reader(
  13753. [&](const FormData &file) {
  13754. items.push_back(file);
  13755. return true;
  13756. },
  13757. [&](const char *data, size_t data_length) {
  13758. items.back().content.append(data, data_length);
  13759. return true;
  13760. });
  13761. EXPECT_TRUE(std::string(items[0].name) == "document");
  13762. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13763. EXPECT_TRUE(items[0].filename == "2MB_data");
  13764. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13765. EXPECT_TRUE(items[1].name == "hello");
  13766. EXPECT_TRUE(items[1].content == "world");
  13767. EXPECT_TRUE(items[1].filename == "");
  13768. EXPECT_TRUE(items[1].content_type == "");
  13769. } else {
  13770. std::string body;
  13771. content_reader([&](const char *data, size_t data_length) {
  13772. body.append(data, data_length);
  13773. return true;
  13774. });
  13775. }
  13776. });
  13777. auto port = svr.bind_to_any_port(HOST);
  13778. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13779. auto se = detail::scope_exit([&] {
  13780. svr.stop();
  13781. t.join();
  13782. ASSERT_FALSE(svr.is_running());
  13783. });
  13784. svr.wait_until_ready();
  13785. {
  13786. std::string data(1024 * 1024 * 2, '.');
  13787. std::stringstream buffer;
  13788. buffer << data;
  13789. SSLClient cli(HOST, port);
  13790. cli.enable_server_certificate_verification(false);
  13791. UploadFormDataItems items{
  13792. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13793. {"hello", "world", "", ""},
  13794. };
  13795. auto res = cli.Post("/post", items);
  13796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13797. ASSERT_EQ(StatusCode::OK_200, res->status);
  13798. }
  13799. }
  13800. TEST(MultipartFormDataTest, DataProviderItems) {
  13801. std::random_device seed_gen;
  13802. std::mt19937 random(seed_gen());
  13803. std::string rand1;
  13804. rand1.resize(1000);
  13805. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  13806. std::string rand2;
  13807. rand2.resize(3000);
  13808. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  13809. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13810. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  13811. const ContentReader &content_reader) {
  13812. ASSERT_FALSE(req.is_multipart_form_data());
  13813. std::string body;
  13814. content_reader([&](const char *data, size_t data_length) {
  13815. body.append(data, data_length);
  13816. return true;
  13817. });
  13818. EXPECT_EQ(body, "");
  13819. });
  13820. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  13821. const ContentReader &content_reader) {
  13822. ASSERT_TRUE(req.is_multipart_form_data());
  13823. std::vector<FormData> items;
  13824. content_reader(
  13825. [&](const FormData &file) {
  13826. items.push_back(file);
  13827. return true;
  13828. },
  13829. [&](const char *data, size_t data_length) {
  13830. items.back().content.append(data, data_length);
  13831. return true;
  13832. });
  13833. ASSERT_TRUE(items.size() == 2);
  13834. EXPECT_EQ(std::string(items[0].name), "name1");
  13835. EXPECT_EQ(items[0].content, "Testing123");
  13836. EXPECT_EQ(items[0].filename, "filename1");
  13837. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13838. EXPECT_EQ(items[1].name, "name2");
  13839. EXPECT_EQ(items[1].content, "Testing456");
  13840. EXPECT_EQ(items[1].filename, "");
  13841. EXPECT_EQ(items[1].content_type, "");
  13842. });
  13843. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  13844. const ContentReader &content_reader) {
  13845. ASSERT_TRUE(req.is_multipart_form_data());
  13846. std::vector<FormData> items;
  13847. content_reader(
  13848. [&](const FormData &file) {
  13849. items.push_back(file);
  13850. return true;
  13851. },
  13852. [&](const char *data, size_t data_length) {
  13853. items.back().content.append(data, data_length);
  13854. return true;
  13855. });
  13856. ASSERT_TRUE(items.size() == 2);
  13857. EXPECT_EQ(items[0].name, "name3");
  13858. EXPECT_EQ(items[0].content, rand1);
  13859. EXPECT_EQ(items[0].filename, "filename3");
  13860. EXPECT_EQ(items[0].content_type, "");
  13861. EXPECT_EQ(items[1].name, "name4");
  13862. EXPECT_EQ(items[1].content, rand2);
  13863. EXPECT_EQ(items[1].filename, "filename4");
  13864. EXPECT_EQ(items[1].content_type, "");
  13865. });
  13866. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  13867. const ContentReader &content_reader) {
  13868. ASSERT_TRUE(req.is_multipart_form_data());
  13869. std::vector<FormData> items;
  13870. content_reader(
  13871. [&](const FormData &file) {
  13872. items.push_back(file);
  13873. return true;
  13874. },
  13875. [&](const char *data, size_t data_length) {
  13876. items.back().content.append(data, data_length);
  13877. return true;
  13878. });
  13879. ASSERT_TRUE(items.size() == 4);
  13880. EXPECT_EQ(std::string(items[0].name), "name1");
  13881. EXPECT_EQ(items[0].content, "Testing123");
  13882. EXPECT_EQ(items[0].filename, "filename1");
  13883. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13884. EXPECT_EQ(items[1].name, "name2");
  13885. EXPECT_EQ(items[1].content, "Testing456");
  13886. EXPECT_EQ(items[1].filename, "");
  13887. EXPECT_EQ(items[1].content_type, "");
  13888. EXPECT_EQ(items[2].name, "name3");
  13889. EXPECT_EQ(items[2].content, rand1);
  13890. EXPECT_EQ(items[2].filename, "filename3");
  13891. EXPECT_EQ(items[2].content_type, "");
  13892. EXPECT_EQ(items[3].name, "name4");
  13893. EXPECT_EQ(items[3].content, rand2);
  13894. EXPECT_EQ(items[3].filename, "filename4");
  13895. EXPECT_EQ(items[3].content_type, "");
  13896. });
  13897. auto port = svr.bind_to_any_port("localhost");
  13898. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13899. auto se = detail::scope_exit([&] {
  13900. svr.stop();
  13901. t.join();
  13902. ASSERT_FALSE(svr.is_running());
  13903. });
  13904. svr.wait_until_ready();
  13905. {
  13906. SSLClient cli("localhost", port);
  13907. cli.enable_server_certificate_verification(false);
  13908. UploadFormDataItems items{
  13909. {"name1", "Testing123", "filename1", "application/octet-stream"},
  13910. {"name2", "Testing456", "", ""}, // not a file
  13911. };
  13912. {
  13913. auto res = cli.Post("/post-none", {}, {}, {});
  13914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13915. ASSERT_EQ(StatusCode::OK_200, res->status);
  13916. }
  13917. FormDataProviderItems providers;
  13918. {
  13919. auto res =
  13920. cli.Post("/post-items", {}, items, providers); // empty providers
  13921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13922. ASSERT_EQ(StatusCode::OK_200, res->status);
  13923. }
  13924. providers.push_back({"name3",
  13925. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13926. // test the offset is given correctly at each step
  13927. if (!offset)
  13928. sink.os.write(rand1.data(), 30);
  13929. else if (offset == 30)
  13930. sink.os.write(rand1.data() + 30, 300);
  13931. else if (offset == 330)
  13932. sink.os.write(rand1.data() + 330, 670);
  13933. else if (offset == rand1.size())
  13934. sink.done();
  13935. return true;
  13936. },
  13937. "filename3",
  13938. {}});
  13939. providers.push_back({"name4",
  13940. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13941. // test the offset is given correctly at each step
  13942. if (!offset)
  13943. sink.os.write(rand2.data(), 2000);
  13944. else if (offset == 2000)
  13945. sink.os.write(rand2.data() + 2000, 1);
  13946. else if (offset == 2001)
  13947. sink.os.write(rand2.data() + 2001, 999);
  13948. else if (offset == rand2.size())
  13949. sink.done();
  13950. return true;
  13951. },
  13952. "filename4",
  13953. {}});
  13954. {
  13955. auto res = cli.Post("/post-providers", {}, {}, providers);
  13956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13957. ASSERT_EQ(StatusCode::OK_200, res->status);
  13958. }
  13959. {
  13960. auto res = cli.Post("/post-both", {}, items, providers);
  13961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13962. ASSERT_EQ(StatusCode::OK_200, res->status);
  13963. }
  13964. }
  13965. }
  13966. TEST(MultipartFormDataTest, BadHeader) {
  13967. Server svr;
  13968. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13969. res.set_content("ok", "text/plain");
  13970. });
  13971. thread t = thread([&] { svr.listen(HOST, PORT); });
  13972. auto se = detail::scope_exit([&] {
  13973. svr.stop();
  13974. t.join();
  13975. ASSERT_FALSE(svr.is_running());
  13976. });
  13977. svr.wait_until_ready();
  13978. const std::string body =
  13979. "This is the preamble. It is to be ignored, though it\r\n"
  13980. "is a handy place for composition agents to include an\r\n"
  13981. "explanatory note to non-MIME conformant readers.\r\n"
  13982. "\r\n"
  13983. "\r\n"
  13984. "--simple boundary\r\n"
  13985. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13986. ": BAD...\r\n"
  13987. "\r\n"
  13988. "value1\r\n"
  13989. "--simple boundary\r\n"
  13990. "Content-Disposition: form-data; name=\"field2\"; "
  13991. "filename=\"example.txt\"\r\n"
  13992. "\r\n"
  13993. "value2\r\n"
  13994. "--simple boundary--\r\n"
  13995. "This is the epilogue. It is also to be ignored.\r\n";
  13996. std::string content_type =
  13997. R"(multipart/form-data; boundary="simple boundary")";
  13998. Client cli(HOST, PORT);
  13999. auto res = cli.Post("/post", body, content_type.c_str());
  14000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14001. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14002. }
  14003. TEST(MultipartFormDataTest, WithPreamble) {
  14004. Server svr;
  14005. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14006. res.set_content("ok", "text/plain");
  14007. });
  14008. thread t = thread([&] { svr.listen(HOST, PORT); });
  14009. auto se = detail::scope_exit([&] {
  14010. svr.stop();
  14011. t.join();
  14012. ASSERT_FALSE(svr.is_running());
  14013. });
  14014. svr.wait_until_ready();
  14015. const std::string body =
  14016. "This is the preamble. It is to be ignored, though it\r\n"
  14017. "is a handy place for composition agents to include an\r\n"
  14018. "explanatory note to non-MIME conformant readers.\r\n"
  14019. "\r\n"
  14020. "\r\n"
  14021. "--simple boundary\r\n"
  14022. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14023. "\r\n"
  14024. "value1\r\n"
  14025. "--simple boundary\r\n"
  14026. "Content-Disposition: form-data; name=\"field2\"; "
  14027. "filename=\"example.txt\"\r\n"
  14028. "\r\n"
  14029. "value2\r\n"
  14030. "--simple boundary--\r\n"
  14031. "This is the epilogue. It is also to be ignored.\r\n";
  14032. std::string content_type =
  14033. R"(multipart/form-data; boundary="simple boundary")";
  14034. Client cli(HOST, PORT);
  14035. auto res = cli.Post("/post", body, content_type.c_str());
  14036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14037. EXPECT_EQ(StatusCode::OK_200, res->status);
  14038. }
  14039. TEST(MultipartFormDataTest, PostCustomBoundary) {
  14040. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14041. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  14042. const ContentReader &content_reader) {
  14043. if (req.is_multipart_form_data()) {
  14044. std::vector<FormData> items;
  14045. content_reader(
  14046. [&](const FormData &file) {
  14047. items.push_back(file);
  14048. return true;
  14049. },
  14050. [&](const char *data, size_t data_length) {
  14051. items.back().content.append(data, data_length);
  14052. return true;
  14053. });
  14054. EXPECT_TRUE(std::string(items[0].name) == "document");
  14055. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14056. EXPECT_TRUE(items[0].filename == "2MB_data");
  14057. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14058. EXPECT_TRUE(items[1].name == "hello");
  14059. EXPECT_TRUE(items[1].content == "world");
  14060. EXPECT_TRUE(items[1].filename == "");
  14061. EXPECT_TRUE(items[1].content_type == "");
  14062. } else {
  14063. std::string body;
  14064. content_reader([&](const char *data, size_t data_length) {
  14065. body.append(data, data_length);
  14066. return true;
  14067. });
  14068. }
  14069. });
  14070. auto port = svr.bind_to_any_port("localhost");
  14071. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14072. auto se = detail::scope_exit([&] {
  14073. svr.stop();
  14074. t.join();
  14075. ASSERT_FALSE(svr.is_running());
  14076. });
  14077. svr.wait_until_ready();
  14078. {
  14079. std::string data(1024 * 1024 * 2, '.');
  14080. std::stringstream buffer;
  14081. buffer << data;
  14082. SSLClient cli("localhost", port);
  14083. cli.enable_server_certificate_verification(false);
  14084. UploadFormDataItems items{
  14085. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14086. {"hello", "world", "", ""},
  14087. };
  14088. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  14089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14090. ASSERT_EQ(StatusCode::OK_200, res->status);
  14091. }
  14092. }
  14093. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  14094. std::string data(1024 * 1024 * 2, '&');
  14095. std::stringstream buffer;
  14096. buffer << data;
  14097. Client cli("https://localhost:8080");
  14098. UploadFormDataItems items{
  14099. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14100. {"hello", "world", "", ""},
  14101. };
  14102. for (const char &c : " \t\r\n") {
  14103. auto res =
  14104. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  14105. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14106. ASSERT_FALSE(res);
  14107. }
  14108. }
  14109. TEST(MultipartFormDataTest, PutFormData) {
  14110. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14111. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  14112. const ContentReader &content_reader) {
  14113. if (req.is_multipart_form_data()) {
  14114. std::vector<FormData> items;
  14115. content_reader(
  14116. [&](const FormData &file) {
  14117. items.push_back(file);
  14118. return true;
  14119. },
  14120. [&](const char *data, size_t data_length) {
  14121. items.back().content.append(data, data_length);
  14122. return true;
  14123. });
  14124. EXPECT_TRUE(std::string(items[0].name) == "document");
  14125. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14126. EXPECT_TRUE(items[0].filename == "2MB_data");
  14127. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14128. EXPECT_TRUE(items[1].name == "hello");
  14129. EXPECT_TRUE(items[1].content == "world");
  14130. EXPECT_TRUE(items[1].filename == "");
  14131. EXPECT_TRUE(items[1].content_type == "");
  14132. } else {
  14133. std::string body;
  14134. content_reader([&](const char *data, size_t data_length) {
  14135. body.append(data, data_length);
  14136. return true;
  14137. });
  14138. }
  14139. });
  14140. auto port = svr.bind_to_any_port("localhost");
  14141. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14142. auto se = detail::scope_exit([&] {
  14143. svr.stop();
  14144. t.join();
  14145. ASSERT_FALSE(svr.is_running());
  14146. });
  14147. svr.wait_until_ready();
  14148. {
  14149. std::string data(1024 * 1024 * 2, '&');
  14150. std::stringstream buffer;
  14151. buffer << data;
  14152. SSLClient cli("localhost", port);
  14153. cli.enable_server_certificate_verification(false);
  14154. UploadFormDataItems items{
  14155. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14156. {"hello", "world", "", ""},
  14157. };
  14158. auto res = cli.Put("/put", items);
  14159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14160. ASSERT_EQ(StatusCode::OK_200, res->status);
  14161. }
  14162. }
  14163. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  14164. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14165. svr.Put("/put_customboundary",
  14166. [&](const Request &req, const Response & /*res*/,
  14167. const ContentReader &content_reader) {
  14168. if (req.is_multipart_form_data()) {
  14169. std::vector<FormData> items;
  14170. content_reader(
  14171. [&](const FormData &file) {
  14172. items.push_back(file);
  14173. return true;
  14174. },
  14175. [&](const char *data, size_t data_length) {
  14176. items.back().content.append(data, data_length);
  14177. return true;
  14178. });
  14179. EXPECT_TRUE(std::string(items[0].name) == "document");
  14180. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14181. EXPECT_TRUE(items[0].filename == "2MB_data");
  14182. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14183. EXPECT_TRUE(items[1].name == "hello");
  14184. EXPECT_TRUE(items[1].content == "world");
  14185. EXPECT_TRUE(items[1].filename == "");
  14186. EXPECT_TRUE(items[1].content_type == "");
  14187. } else {
  14188. std::string body;
  14189. content_reader([&](const char *data, size_t data_length) {
  14190. body.append(data, data_length);
  14191. return true;
  14192. });
  14193. }
  14194. });
  14195. auto port = svr.bind_to_any_port("localhost");
  14196. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14197. auto se = detail::scope_exit([&] {
  14198. svr.stop();
  14199. t.join();
  14200. ASSERT_FALSE(svr.is_running());
  14201. });
  14202. svr.wait_until_ready();
  14203. {
  14204. std::string data(1024 * 1024 * 2, '&');
  14205. std::stringstream buffer;
  14206. buffer << data;
  14207. SSLClient cli("localhost", port);
  14208. cli.enable_server_certificate_verification(false);
  14209. UploadFormDataItems items{
  14210. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14211. {"hello", "world", "", ""},
  14212. };
  14213. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  14214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14215. ASSERT_EQ(StatusCode::OK_200, res->status);
  14216. }
  14217. }
  14218. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  14219. std::string data(1024 * 1024 * 2, '&');
  14220. std::stringstream buffer;
  14221. buffer << data;
  14222. Client cli("https://localhost:8080");
  14223. cli.enable_server_certificate_verification(false);
  14224. UploadFormDataItems items{
  14225. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14226. {"hello", "world", "", ""},
  14227. };
  14228. for (const char &c : " \t\r\n") {
  14229. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  14230. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14231. ASSERT_FALSE(res);
  14232. }
  14233. }
  14234. TEST(MultipartFormDataTest, AlternateFilename) {
  14235. auto handled = false;
  14236. Server svr;
  14237. svr.Post("/test", [&](const Request &req, Response &res) {
  14238. ASSERT_EQ(2u, req.form.files.size());
  14239. ASSERT_EQ(1u, req.form.fields.size());
  14240. // Test files
  14241. const auto &file1 = req.form.get_file("file1");
  14242. ASSERT_EQ("file1", file1.name);
  14243. ASSERT_EQ("A.txt", file1.filename);
  14244. ASSERT_EQ("text/plain", file1.content_type);
  14245. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  14246. const auto &file2 = req.form.get_file("file2");
  14247. ASSERT_EQ("file2", file2.name);
  14248. ASSERT_EQ("a.html", file2.filename);
  14249. ASSERT_EQ("text/html", file2.content_type);
  14250. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  14251. file2.content);
  14252. // Test text field
  14253. const auto &text = req.form.get_field("text");
  14254. ASSERT_EQ("text default", text);
  14255. res.set_content("ok", "text/plain");
  14256. handled = true;
  14257. });
  14258. thread t = thread([&] { svr.listen(HOST, PORT); });
  14259. auto se = detail::scope_exit([&] {
  14260. svr.stop();
  14261. t.join();
  14262. ASSERT_FALSE(svr.is_running());
  14263. ASSERT_TRUE(handled);
  14264. });
  14265. svr.wait_until_ready();
  14266. auto req = "POST /test HTTP/1.1\r\n"
  14267. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14268. "Content-Length: 399\r\n"
  14269. "\r\n"
  14270. "----------\r\n"
  14271. "Content-Disposition: form-data; name=\"text\"\r\n"
  14272. "\r\n"
  14273. "text default\r\n"
  14274. "----------\r\n"
  14275. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  14276. "filename=\"a.txt\"; name=\"file1\"\r\n"
  14277. "Content-Type: text/plain\r\n"
  14278. "\r\n"
  14279. "Content of a.txt.\r\n"
  14280. "\r\n"
  14281. "----------\r\n"
  14282. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  14283. "\"a.html\"\r\n"
  14284. "Content-Type: text/html\r\n"
  14285. "\r\n"
  14286. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  14287. "\r\n"
  14288. "------------\r\n";
  14289. ASSERT_TRUE(send_request(1, req));
  14290. }
  14291. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  14292. auto handled = false;
  14293. Server svr;
  14294. svr.Post("/test", [&](const Request &req, Response &res) {
  14295. // Case-insensitive "utf-8''" prefix with a long value
  14296. const auto &file = req.form.get_file("file1");
  14297. ASSERT_EQ("file1", file.name);
  14298. // 8000 chars exercises both the Content-Disposition parser and the
  14299. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  14300. // Prior to the fix, std::regex_match on this header would cause O(N)
  14301. // stack recursion in libstdc++, leading to SIGSEGV.
  14302. std::string expected_filename(8000, 'A');
  14303. ASSERT_EQ(expected_filename, file.filename);
  14304. res.set_content("ok", "text/plain");
  14305. handled = true;
  14306. });
  14307. thread t = thread([&] { svr.listen(HOST, PORT); });
  14308. auto se = detail::scope_exit([&] {
  14309. svr.stop();
  14310. t.join();
  14311. ASSERT_FALSE(svr.is_running());
  14312. ASSERT_TRUE(handled);
  14313. });
  14314. svr.wait_until_ready();
  14315. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  14316. // Regression test for GHSA-qq6v-r583-3h69
  14317. std::string long_filename(8000, 'A');
  14318. std::string body = "----------\r\n"
  14319. "Content-Disposition: form-data; name=\"file1\"; "
  14320. "filename*=\"Utf-8''" +
  14321. long_filename +
  14322. "\"\r\n"
  14323. "\r\n"
  14324. "hello\r\n"
  14325. "------------\r\n";
  14326. auto req = "POST /test HTTP/1.1\r\n"
  14327. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14328. "Content-Length: " +
  14329. std::to_string(body.size()) + "\r\n\r\n" + body;
  14330. ASSERT_TRUE(send_request(1, req));
  14331. }
  14332. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  14333. auto handled = false;
  14334. Server svr;
  14335. svr.Post("/test", [&](const Request &req, Response &) {
  14336. ASSERT_EQ(2u, req.form.fields.size());
  14337. const auto &text1 = req.form.get_field("text1");
  14338. ASSERT_EQ("text1", text1);
  14339. const auto &text2 = req.form.get_field("text2");
  14340. ASSERT_EQ("text2", text2);
  14341. handled = true;
  14342. });
  14343. thread t = thread([&] { svr.listen(HOST, PORT); });
  14344. auto se = detail::scope_exit([&] {
  14345. svr.stop();
  14346. t.join();
  14347. ASSERT_FALSE(svr.is_running());
  14348. ASSERT_TRUE(handled);
  14349. });
  14350. svr.wait_until_ready();
  14351. auto req = "POST /test HTTP/1.1\r\n"
  14352. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14353. "Content-Length: 146\r\n"
  14354. "\r\n----------\r\n"
  14355. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14356. "\r\n"
  14357. "text1"
  14358. "\r\n----------\r\n"
  14359. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14360. "\r\n"
  14361. "text2"
  14362. "\r\n------------";
  14363. std::string response;
  14364. ASSERT_TRUE(send_request(1, req, &response));
  14365. ASSERT_EQ("200", response.substr(9, 3));
  14366. }
  14367. TEST(MultipartFormDataTest, ContentLength) {
  14368. auto handled = false;
  14369. Server svr;
  14370. svr.Post("/test", [&](const Request &req, Response &) {
  14371. ASSERT_EQ(2u, req.form.fields.size());
  14372. const auto &text1 = req.form.get_field("text1");
  14373. ASSERT_EQ("text1", text1);
  14374. const auto &text2 = req.form.get_field("text2");
  14375. ASSERT_EQ("text2", text2);
  14376. handled = true;
  14377. });
  14378. thread t = thread([&] { svr.listen(HOST, PORT); });
  14379. auto se = detail::scope_exit([&] {
  14380. svr.stop();
  14381. t.join();
  14382. ASSERT_FALSE(svr.is_running());
  14383. ASSERT_TRUE(handled);
  14384. });
  14385. svr.wait_until_ready();
  14386. auto req = "POST /test HTTP/1.1\r\n"
  14387. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14388. "Content-Length: 167\r\n"
  14389. "\r\n----------\r\n"
  14390. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14391. "Content-Length: 5\r\n"
  14392. "\r\n"
  14393. "text1"
  14394. "\r\n----------\r\n"
  14395. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14396. "\r\n"
  14397. "text2"
  14398. "\r\n------------\r\n";
  14399. std::string response;
  14400. ASSERT_TRUE(send_request(1, req, &response));
  14401. ASSERT_EQ("200", response.substr(9, 3));
  14402. }
  14403. TEST(MultipartFormDataTest, AccessPartHeaders) {
  14404. auto handled = false;
  14405. Server svr;
  14406. svr.Post("/test", [&](const Request &req, Response &) {
  14407. ASSERT_EQ(2u, req.form.fields.size());
  14408. const auto &text1 = req.form.get_field("text1");
  14409. ASSERT_EQ("text1", text1);
  14410. // TODO: Add header access for text fields if needed
  14411. const auto &text2 = req.form.get_field("text2");
  14412. ASSERT_EQ("text2", text2);
  14413. // TODO: Header access for text fields needs to be implemented
  14414. // auto &headers = it->second.headers;
  14415. // ASSERT_EQ(3U, headers.size());
  14416. // auto custom_header = headers.find("x-whatever");
  14417. // ASSERT_TRUE(custom_header != headers.end());
  14418. // ASSERT_NE("customvalue", custom_header->second);
  14419. // ASSERT_EQ("CustomValue", custom_header->second);
  14420. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  14421. handled = true;
  14422. });
  14423. thread t = thread([&] { svr.listen(HOST, PORT); });
  14424. auto se = detail::scope_exit([&] {
  14425. svr.stop();
  14426. t.join();
  14427. ASSERT_FALSE(svr.is_running());
  14428. ASSERT_TRUE(handled);
  14429. });
  14430. svr.wait_until_ready();
  14431. auto req = "POST /test HTTP/1.1\r\n"
  14432. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14433. "Content-Length: 232\r\n"
  14434. "\r\n----------\r\n"
  14435. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14436. "Content-Length: 5\r\n"
  14437. "X-Test: 1\r\n"
  14438. "\r\n"
  14439. "text1"
  14440. "\r\n----------\r\n"
  14441. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14442. "Content-Type: text/plain\r\n"
  14443. "X-Whatever: CustomValue\r\n"
  14444. "\r\n"
  14445. "text2"
  14446. "\r\n------------\r\n"
  14447. "That should be disregarded. Not even read";
  14448. std::string response;
  14449. ASSERT_TRUE(send_request(1, req, &response));
  14450. ASSERT_EQ("200", response.substr(9, 3));
  14451. }
  14452. TEST(MultipartFormDataTest, LargeHeader) {
  14453. auto handled = false;
  14454. Server svr;
  14455. svr.Post("/test", [&](const Request &req, Response &) {
  14456. ASSERT_EQ(1u, req.form.fields.size());
  14457. const auto &text = req.form.get_field("name1");
  14458. ASSERT_EQ("text1", text);
  14459. handled = true;
  14460. });
  14461. thread t = thread([&] { svr.listen(HOST, PORT); });
  14462. auto se = detail::scope_exit([&] {
  14463. svr.stop();
  14464. t.join();
  14465. ASSERT_FALSE(svr.is_running());
  14466. ASSERT_TRUE(handled);
  14467. });
  14468. svr.wait_until_ready();
  14469. auto boundary = std::string("cpp-httplib-multipart-data");
  14470. std::string content = "--" + boundary +
  14471. "\r\n"
  14472. "Content-Disposition: form-data; name=\"name1\"\r\n"
  14473. "\r\n"
  14474. "text1\r\n"
  14475. "--" +
  14476. boundary + "--\r\n";
  14477. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  14478. "Content-Type: multipart/form-data;boundary=" +
  14479. boundary +
  14480. "\r\n"
  14481. "Content-Length: " +
  14482. std::to_string(content.size()) +
  14483. "\r\n"
  14484. "Dummy-Header: ";
  14485. std::string header_suffix = "\r\n"
  14486. "\r\n";
  14487. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  14488. size_t header_dummy_size =
  14489. read_buff_size -
  14490. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  14491. auto header_dummy = std::string(header_dummy_size, '@');
  14492. auto req = header_prefix + header_dummy + header_suffix + content;
  14493. std::string response;
  14494. ASSERT_TRUE(send_request(1, req, &response));
  14495. ASSERT_EQ("200", response.substr(9, 3));
  14496. }
  14497. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  14498. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  14499. // (not chunked Transfer-Encoding) after the streaming refactor.
  14500. auto handled = false;
  14501. Server svr;
  14502. svr.Post("/upload", [&](const Request &req, Response &res) {
  14503. auto cl_it = req.headers.find("Content-Length");
  14504. EXPECT_TRUE(cl_it != req.headers.end());
  14505. auto te_it = req.headers.find("Transfer-Encoding");
  14506. EXPECT_TRUE(te_it == req.headers.end());
  14507. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  14508. res.set_content("ok", "text/plain");
  14509. handled = true;
  14510. });
  14511. auto port = svr.bind_to_any_port(HOST);
  14512. auto t = thread([&] { svr.listen_after_bind(); });
  14513. auto se = detail::scope_exit([&] {
  14514. svr.stop();
  14515. t.join();
  14516. ASSERT_FALSE(svr.is_running());
  14517. ASSERT_TRUE(handled);
  14518. });
  14519. svr.wait_until_ready();
  14520. UploadFormDataItems items = {
  14521. {"field1", "hello", "", "text/plain"},
  14522. {"file1", "world", "test.txt", "application/octet-stream"},
  14523. };
  14524. Client cli(HOST, port);
  14525. auto res = cli.Post("/upload", {}, items);
  14526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14527. EXPECT_EQ(StatusCode::OK_200, res->status);
  14528. }
  14529. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  14530. // Verify that make_multipart_content_provider coalesces many small segments
  14531. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  14532. constexpr size_t kItemCount = 1000;
  14533. UploadFormDataItems items;
  14534. items.reserve(kItemCount);
  14535. for (size_t i = 0; i < kItemCount; i++) {
  14536. items.push_back(
  14537. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14538. }
  14539. const std::string boundary = "----test-boundary";
  14540. auto content_length = detail::get_multipart_content_length(items, boundary);
  14541. auto provider = detail::make_multipart_content_provider(items, boundary);
  14542. // Drive the provider the same way write_content_with_progress does
  14543. size_t write_count = 0;
  14544. size_t total_bytes = 0;
  14545. DataSink sink;
  14546. size_t offset = 0;
  14547. sink.write = [&](const char *d, size_t l) -> bool {
  14548. (void)d;
  14549. write_count++;
  14550. total_bytes += l;
  14551. offset += l;
  14552. return true;
  14553. };
  14554. sink.is_writable = []() -> bool { return true; };
  14555. while (offset < content_length) {
  14556. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  14557. }
  14558. EXPECT_EQ(content_length, total_bytes);
  14559. // The total number of segments is 3 * kItemCount + 1 = 3001.
  14560. // With buffering into 64KB blocks, write_count should be much smaller.
  14561. auto segment_count = 3 * kItemCount + 1;
  14562. EXPECT_LT(write_count, segment_count / 10);
  14563. }
  14564. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  14565. // Integration test: send many UploadFormDataItems and verify the server
  14566. // receives all of them correctly (#2410).
  14567. constexpr size_t kItemCount = 500;
  14568. auto handled = false;
  14569. Server svr;
  14570. svr.Post("/upload", [&](const Request &req, Response &res) {
  14571. EXPECT_EQ(kItemCount, req.form.fields.size());
  14572. for (size_t i = 0; i < kItemCount; i++) {
  14573. auto key = "field" + std::to_string(i);
  14574. auto val = "value" + std::to_string(i);
  14575. auto it = req.form.fields.find(key);
  14576. if (it != req.form.fields.end()) {
  14577. EXPECT_EQ(val, it->second.content);
  14578. } else {
  14579. ADD_FAILURE() << "Missing field: " << key;
  14580. }
  14581. }
  14582. res.set_content("ok", "text/plain");
  14583. handled = true;
  14584. });
  14585. auto port = svr.bind_to_any_port(HOST);
  14586. auto t = thread([&] { svr.listen_after_bind(); });
  14587. auto se = detail::scope_exit([&] {
  14588. svr.stop();
  14589. t.join();
  14590. ASSERT_FALSE(svr.is_running());
  14591. ASSERT_TRUE(handled);
  14592. });
  14593. svr.wait_until_ready();
  14594. UploadFormDataItems items;
  14595. items.reserve(kItemCount);
  14596. for (size_t i = 0; i < kItemCount; i++) {
  14597. items.push_back(
  14598. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14599. }
  14600. Client cli(HOST, port);
  14601. auto res = cli.Post("/upload", items);
  14602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14603. EXPECT_EQ(StatusCode::OK_200, res->status);
  14604. }
  14605. TEST(MultipartFormDataTest, MakeFileProvider) {
  14606. // Verify make_file_provider sends a file's contents correctly.
  14607. const std::string file_content(4096, 'Z');
  14608. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  14609. {
  14610. std::ofstream ofs(tmp_path, std::ios::binary);
  14611. ofs.write(file_content.data(),
  14612. static_cast<std::streamsize>(file_content.size()));
  14613. }
  14614. auto handled = false;
  14615. Server svr;
  14616. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  14617. const ContentReader &content_reader) {
  14618. ASSERT_TRUE(req.is_multipart_form_data());
  14619. std::vector<FormData> items;
  14620. content_reader(
  14621. [&](const FormData &file) {
  14622. items.push_back(file);
  14623. return true;
  14624. },
  14625. [&](const char *data, size_t data_length) {
  14626. items.back().content.append(data, data_length);
  14627. return true;
  14628. });
  14629. ASSERT_EQ(1u, items.size());
  14630. EXPECT_EQ("myfile", items[0].name);
  14631. EXPECT_EQ("data.bin", items[0].filename);
  14632. EXPECT_EQ("application/octet-stream", items[0].content_type);
  14633. EXPECT_EQ(file_content, items[0].content);
  14634. handled = true;
  14635. });
  14636. auto port = svr.bind_to_any_port(HOST);
  14637. auto t = thread([&] { svr.listen_after_bind(); });
  14638. auto se = detail::scope_exit([&] {
  14639. svr.stop();
  14640. t.join();
  14641. ASSERT_FALSE(svr.is_running());
  14642. ASSERT_TRUE(handled);
  14643. std::remove(tmp_path.c_str());
  14644. });
  14645. svr.wait_until_ready();
  14646. FormDataProviderItems providers;
  14647. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  14648. "application/octet-stream"));
  14649. Client cli(HOST, port);
  14650. auto res = cli.Post("/upload", {}, {}, providers);
  14651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14652. EXPECT_EQ(StatusCode::OK_200, res->status);
  14653. }
  14654. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  14655. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  14656. // (100) headers is rejected with a 400 Bad Request response.
  14657. Server svr;
  14658. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14659. res.set_content("ok", "text/plain");
  14660. });
  14661. thread t = thread([&] { svr.listen(HOST, PORT); });
  14662. auto se = detail::scope_exit([&] {
  14663. svr.stop();
  14664. t.join();
  14665. ASSERT_FALSE(svr.is_running());
  14666. });
  14667. svr.wait_until_ready();
  14668. // Build a multipart part with 101 custom headers (exceeding
  14669. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  14670. std::stringstream body;
  14671. body << "--simpleboundary\r\n"
  14672. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  14673. for (int i = 0; i < 101; i++) {
  14674. body << "X-Custom-Header-" << i << ": value\r\n";
  14675. }
  14676. body << "\r\n"
  14677. << "value1\r\n"
  14678. << "--simpleboundary--\r\n";
  14679. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  14680. Client cli(HOST, PORT);
  14681. auto res = cli.Post("/post", body.str(), content_type.c_str());
  14682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14683. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14684. }
  14685. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  14686. // A body that never contains the declared boundary must not be accumulated
  14687. // while the parser waits for it. Buffering it would also make every read
  14688. // rescan everything seen so far, which is quadratic in the body size.
  14689. Server svr;
  14690. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14691. res.set_content("ok", "text/plain");
  14692. });
  14693. auto port = svr.bind_to_any_port(HOST);
  14694. thread t = thread([&] { svr.listen_after_bind(); });
  14695. auto se = detail::scope_exit([&] {
  14696. svr.stop();
  14697. t.join();
  14698. ASSERT_FALSE(svr.is_running());
  14699. });
  14700. svr.wait_until_ready();
  14701. Client cli(HOST, port);
  14702. cli.set_read_timeout(60, 0);
  14703. cli.set_write_timeout(60, 0);
  14704. // '-' is the worst case: it matches the first character of the boundary, so
  14705. // every position has to be checked against it.
  14706. auto post_dashes = [&](size_t size) {
  14707. const std::string body(size, '-');
  14708. auto start = std::chrono::steady_clock::now();
  14709. auto res =
  14710. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  14711. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  14712. std::chrono::steady_clock::now() - start)
  14713. .count();
  14714. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14715. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  14716. return ms;
  14717. };
  14718. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  14719. // Windows.
  14720. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  14721. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  14722. // Comparing the two sizes rather than checking an absolute duration keeps
  14723. // this meaningful across build types and CI load, both of which move the
  14724. // absolute numbers by more than an order of magnitude. Four times the bytes
  14725. // costs about four times the time when parsing is linear, and about sixteen
  14726. // times when the body is buffered and rescanned.
  14727. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  14728. EXPECT_LT(ms_16mb, ms_4mb * 10)
  14729. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  14730. << "ms, which suggests the body is being buffered and rescanned";
  14731. }
  14732. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  14733. // A boundary can only be followed by CRLF or by "--", so anything else is
  14734. // malformed no matter what comes next. The parser must say so right away
  14735. // instead of buffering the rest of the declared body.
  14736. Server svr;
  14737. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14738. res.set_content("ok", "text/plain");
  14739. });
  14740. auto port = svr.bind_to_any_port(HOST);
  14741. thread t = thread([&] { svr.listen_after_bind(); });
  14742. auto se = detail::scope_exit([&] {
  14743. svr.stop();
  14744. t.join();
  14745. ASSERT_FALSE(svr.is_running());
  14746. });
  14747. svr.wait_until_ready();
  14748. // Announce a 1 MB body but send only the malformed prefix. A parser that
  14749. // buffers instead of failing would still be waiting for the remaining bytes.
  14750. const std::string body = "--zzzz\r\n"
  14751. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14752. "\r\n"
  14753. "text1"
  14754. "\r\n--zzzzXX";
  14755. const std::string req = "POST /post HTTP/1.1\r\n"
  14756. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14757. "Content-Length: 1048576\r\n"
  14758. "\r\n" +
  14759. body;
  14760. std::string response;
  14761. ASSERT_TRUE(send_request(3, req, &response, port));
  14762. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  14763. EXPECT_EQ("400", response.substr(9, 3));
  14764. }
  14765. // Posts a multipart body split into two writes, so that the server sees the
  14766. // split at whatever offset the caller chose, and expects the single "text1"
  14767. // field to come through.
  14768. static void expect_split_multipart_ok(const std::string &body1,
  14769. const std::string &body2) {
  14770. auto handled = false;
  14771. Server svr;
  14772. svr.Post("/post", [&](const Request &req, Response &) {
  14773. EXPECT_EQ(1u, req.form.fields.size());
  14774. EXPECT_EQ("text1", req.form.get_field("text1"));
  14775. handled = true;
  14776. });
  14777. auto port = svr.bind_to_any_port(HOST);
  14778. thread t = thread([&] { svr.listen_after_bind(); });
  14779. auto se = detail::scope_exit([&] {
  14780. svr.stop();
  14781. t.join();
  14782. ASSERT_FALSE(svr.is_running());
  14783. ASSERT_TRUE(handled);
  14784. });
  14785. svr.wait_until_ready();
  14786. // "Connection: close" makes the server close once it has answered, so the
  14787. // response drain ends immediately instead of idling until the read timeout.
  14788. const std::string head =
  14789. "POST /post HTTP/1.1\r\n"
  14790. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14791. "Connection: close\r\n"
  14792. "Content-Length: " +
  14793. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  14794. std::string response;
  14795. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  14796. ASSERT_GE(response.size(), 12u) << "no response";
  14797. EXPECT_EQ("200", response.substr(9, 3));
  14798. }
  14799. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  14800. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  14801. // ignored, including when it does not arrive in the same read as the
  14802. // close-delimiter itself.
  14803. expect_split_multipart_ok("--zzzz\r\n"
  14804. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14805. "\r\n"
  14806. "text1"
  14807. "\r\n--zzzz--",
  14808. "\r\nthis epilogue must be ignored\r\n");
  14809. }
  14810. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  14811. // The initial boundary may be preceded by a preamble of any length and may
  14812. // straddle a read boundary. Discarding data while waiting for it must not
  14813. // throw away a partial boundary sitting at the end of the buffer.
  14814. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  14815. "zz\r\n"
  14816. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14817. "\r\n"
  14818. "text1"
  14819. "\r\n--zzzz--\r\n");
  14820. }
  14821. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  14822. // The received boundary was only checked for being non-empty, so it could be
  14823. // as long as a header is allowed to be. The parser scans the body for
  14824. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  14825. // costs a nearly full comparison at nearly every position, making the
  14826. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  14827. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  14828. Server svr;
  14829. svr.Post("/post", [](const Request &req, Response &res) {
  14830. EXPECT_EQ(1u, req.form.fields.size());
  14831. EXPECT_EQ("text1", req.form.get_field("text1"));
  14832. res.set_content("ok", "text/plain");
  14833. });
  14834. auto port = svr.bind_to_any_port(HOST);
  14835. thread t = thread([&] { svr.listen_after_bind(); });
  14836. auto se = detail::scope_exit([&] {
  14837. svr.stop();
  14838. t.join();
  14839. ASSERT_FALSE(svr.is_running());
  14840. });
  14841. svr.wait_until_ready();
  14842. Client cli(HOST, port);
  14843. auto post_with_boundary_of_length = [&](size_t len) {
  14844. const std::string boundary(len, 'a');
  14845. const std::string body =
  14846. "--" + boundary +
  14847. "\r\n"
  14848. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14849. "\r\n"
  14850. "text1"
  14851. "\r\n--" +
  14852. boundary + "--\r\n";
  14853. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  14854. };
  14855. auto res = post_with_boundary_of_length(70);
  14856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14857. EXPECT_EQ(StatusCode::OK_200, res->status);
  14858. res = post_with_boundary_of_length(71);
  14859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14860. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14861. }
  14862. TEST(MakeFileBodyTest, Basic) {
  14863. const std::string file_content(4096, 'Z');
  14864. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  14865. {
  14866. std::ofstream ofs(tmp_path, std::ios::binary);
  14867. ofs.write(file_content.data(),
  14868. static_cast<std::streamsize>(file_content.size()));
  14869. }
  14870. auto handled = false;
  14871. Server svr;
  14872. svr.Post("/upload", [&](const Request &req, Response &res) {
  14873. EXPECT_EQ(file_content, req.body);
  14874. handled = true;
  14875. res.status = StatusCode::OK_200;
  14876. });
  14877. auto port = svr.bind_to_any_port(HOST);
  14878. auto t = thread([&] { svr.listen_after_bind(); });
  14879. auto se = detail::scope_exit([&] {
  14880. svr.stop();
  14881. t.join();
  14882. ASSERT_FALSE(svr.is_running());
  14883. ASSERT_TRUE(handled);
  14884. std::remove(tmp_path.c_str());
  14885. });
  14886. svr.wait_until_ready();
  14887. auto fb = make_file_body(tmp_path);
  14888. ASSERT_GT(fb.first, 0u);
  14889. Client cli(HOST, port);
  14890. auto res =
  14891. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  14892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14893. EXPECT_EQ(StatusCode::OK_200, res->status);
  14894. }
  14895. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  14896. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  14897. {
  14898. std::ofstream ofs(path, std::ios::binary);
  14899. const std::string content(100, 'A');
  14900. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14901. }
  14902. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14903. auto body = make_file_body(path);
  14904. ASSERT_EQ(100u, body.first);
  14905. ASSERT_TRUE(static_cast<bool>(body.second));
  14906. // Rewritten shorter after its length was measured - and, on a server, after
  14907. // that length has already gone out as Content-Length.
  14908. {
  14909. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  14910. const std::string content(10, 'A');
  14911. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14912. }
  14913. std::string written;
  14914. DataSink sink;
  14915. sink.write = [&](const char *d, size_t l) {
  14916. written.append(d, l);
  14917. return true;
  14918. };
  14919. // The provider has to report failure. write_content_with_progress() advances
  14920. // its offset only by what was written, so a provider that returns true
  14921. // without completing the length it promised is called again straight away,
  14922. // and again.
  14923. EXPECT_FALSE(body.second(0, body.first, sink));
  14924. EXPECT_EQ(std::string(10, 'A'), written);
  14925. }
  14926. TEST(MakeFileBodyTest, WholeFileIsSent) {
  14927. const std::string path = "./httplib_test_make_file_body_whole.bin";
  14928. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  14929. {
  14930. std::ofstream ofs(path, std::ios::binary);
  14931. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14932. }
  14933. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14934. auto body = make_file_body(path);
  14935. ASSERT_EQ(content.size(), body.first);
  14936. ASSERT_TRUE(static_cast<bool>(body.second));
  14937. std::string written;
  14938. DataSink sink;
  14939. sink.write = [&](const char *d, size_t l) {
  14940. written.append(d, l);
  14941. return true;
  14942. };
  14943. EXPECT_TRUE(body.second(0, body.first, sink));
  14944. EXPECT_EQ(content, written);
  14945. }
  14946. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  14947. static constexpr unsigned int number_of_tasks{1000000};
  14948. std::atomic_uint count{0};
  14949. std::unique_ptr<TaskQueue> task_queue{
  14950. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  14951. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14952. auto queued = task_queue->enqueue(
  14953. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  14954. EXPECT_TRUE(queued);
  14955. }
  14956. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14957. task_queue->shutdown();
  14958. #else
  14959. EXPECT_NO_THROW(task_queue->shutdown());
  14960. #endif
  14961. EXPECT_EQ(number_of_tasks, count.load());
  14962. }
  14963. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  14964. static constexpr unsigned int number_of_tasks{1000000};
  14965. static constexpr unsigned int qlimit{2};
  14966. unsigned int queued_count{0};
  14967. std::atomic_uint count{0};
  14968. std::unique_ptr<TaskQueue> task_queue{
  14969. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  14970. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14971. if (task_queue->enqueue(
  14972. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  14973. queued_count++;
  14974. }
  14975. }
  14976. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14977. task_queue->shutdown();
  14978. #else
  14979. EXPECT_NO_THROW(task_queue->shutdown());
  14980. #endif
  14981. EXPECT_EQ(queued_count, count.load());
  14982. EXPECT_TRUE(queued_count <= number_of_tasks);
  14983. EXPECT_TRUE(queued_count >= qlimit);
  14984. }
  14985. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  14986. // Use a short idle timeout so a dynamic thread spawns, times out and
  14987. // exits during the test, and the pool keeps working afterwards.
  14988. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  14989. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  14990. /*idle_timeout_sec=*/1}};
  14991. std::atomic_uint count{0};
  14992. std::condition_variable cv;
  14993. std::mutex mtx;
  14994. bool release = false;
  14995. // Block the base thread so the second task spawns a dynamic thread.
  14996. EXPECT_TRUE(task_queue->enqueue([&] {
  14997. std::unique_lock<std::mutex> lock(mtx);
  14998. while (!release) {
  14999. cv.wait(lock);
  15000. }
  15001. count++;
  15002. }));
  15003. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15004. // Let the dynamic thread finish its task and exceed the idle timeout.
  15005. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  15006. {
  15007. std::unique_lock<std::mutex> lock(mtx);
  15008. release = true;
  15009. }
  15010. cv.notify_all();
  15011. // The pool must still accept and run tasks after the dynamic thread exited.
  15012. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15013. task_queue->shutdown();
  15014. EXPECT_EQ(3u, count.load());
  15015. }
  15016. TEST(TaskQueueTest, MaxQueuedRequests) {
  15017. static constexpr unsigned int qlimit{3};
  15018. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  15019. std::condition_variable sem_cv;
  15020. std::mutex sem_mtx;
  15021. int credits = 0;
  15022. bool queued;
  15023. /* Fill up the queue with tasks that will block until we give them credits to
  15024. * complete. */
  15025. for (unsigned int n = 0; n <= qlimit;) {
  15026. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  15027. std::unique_lock<std::mutex> lock(sem_mtx);
  15028. while (credits <= 0) {
  15029. sem_cv.wait(lock);
  15030. }
  15031. /* Consume the credit and signal the test code if they are all gone. */
  15032. if (--credits == 0) { sem_cv.notify_one(); }
  15033. });
  15034. if (n < qlimit) {
  15035. /* The first qlimit enqueues must succeed. */
  15036. EXPECT_TRUE(queued);
  15037. } else {
  15038. /* The last one will succeed only when the worker thread
  15039. * starts and dequeues the first blocking task. Although
  15040. * not necessary for the correctness of this test, we sleep for
  15041. * a short while to avoid busy waiting. */
  15042. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15043. }
  15044. if (queued) { n++; }
  15045. }
  15046. /* Further enqueues must fail since the queue is full. */
  15047. for (auto i = 0; i < 4; i++) {
  15048. queued = task_queue->enqueue([] {});
  15049. EXPECT_FALSE(queued);
  15050. }
  15051. /* Give the credits to allow the previous tasks to complete. */
  15052. {
  15053. std::unique_lock<std::mutex> lock(sem_mtx);
  15054. credits += qlimit + 1;
  15055. }
  15056. sem_cv.notify_all();
  15057. /* Wait for all the credits to be consumed. */
  15058. {
  15059. std::unique_lock<std::mutex> lock(sem_mtx);
  15060. while (credits > 0) {
  15061. sem_cv.wait(lock);
  15062. }
  15063. }
  15064. /* Check that we are able again to enqueue at least qlimit tasks. */
  15065. for (unsigned int i = 0; i < qlimit; i++) {
  15066. queued = task_queue->enqueue([] {});
  15067. EXPECT_TRUE(queued);
  15068. }
  15069. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15070. task_queue->shutdown();
  15071. #else
  15072. EXPECT_NO_THROW(task_queue->shutdown());
  15073. #endif
  15074. }
  15075. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  15076. Server svr;
  15077. std::string method;
  15078. std::string body;
  15079. auto has_content_length = false;
  15080. auto has_transfer_encoding = false;
  15081. std::atomic<int> bad_requests{0};
  15082. // Leftover body bytes get parsed as a malformed request and answered with
  15083. // 400
  15084. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  15085. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  15086. });
  15087. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  15088. res.set_redirect("/down", StatusCode::SeeOther_303);
  15089. });
  15090. svr.Get("/down", [&](const Request &req, Response &res) {
  15091. method = req.method;
  15092. body = req.body;
  15093. has_content_length = req.has_header("Content-Length");
  15094. has_transfer_encoding = req.has_header("Transfer-Encoding");
  15095. res.set_content("ok", "text/plain");
  15096. });
  15097. auto port = svr.bind_to_any_port(HOST);
  15098. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15099. auto se = detail::scope_exit([&] {
  15100. svr.stop();
  15101. thread.join();
  15102. ASSERT_FALSE(svr.is_running());
  15103. });
  15104. svr.wait_until_ready();
  15105. const std::string payload = "SECRET-BODY";
  15106. auto check = [&](Client &cli, const Result &res) {
  15107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15108. EXPECT_EQ(StatusCode::OK_200, res->status);
  15109. EXPECT_EQ("ok", res->body);
  15110. EXPECT_EQ("GET", method);
  15111. EXPECT_TRUE(body.empty());
  15112. EXPECT_FALSE(has_content_length);
  15113. EXPECT_FALSE(has_transfer_encoding);
  15114. // Nothing of the original body may be left on the connection
  15115. auto res2 = cli.Get("/down");
  15116. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  15117. EXPECT_EQ(StatusCode::OK_200, res2->status);
  15118. EXPECT_EQ("ok", res2->body);
  15119. EXPECT_EQ(0, bad_requests);
  15120. };
  15121. // With content length
  15122. {
  15123. Client cli(HOST, port);
  15124. cli.set_keep_alive(true);
  15125. cli.set_follow_location(true);
  15126. auto res = cli.Post(
  15127. "/up", payload.size(),
  15128. [&](size_t offset, size_t length, DataSink &sink) {
  15129. return sink.write(payload.data() + offset, length);
  15130. },
  15131. "text/plain");
  15132. check(cli, res);
  15133. }
  15134. // Without content length (chunked)
  15135. {
  15136. Client cli(HOST, port);
  15137. cli.set_keep_alive(true);
  15138. cli.set_follow_location(true);
  15139. auto res = cli.Post(
  15140. "/up",
  15141. [&](size_t /*offset*/, DataSink &sink) {
  15142. sink.write(payload.data(), payload.size());
  15143. sink.done();
  15144. return true;
  15145. },
  15146. "text/plain");
  15147. check(cli, res);
  15148. }
  15149. }
  15150. TEST(RedirectTest, LocationPathIsNotDecoded) {
  15151. Server svr;
  15152. std::string target;
  15153. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  15154. // Echo the still-encoded name back in the Location
  15155. const std::string prefix = "/start/";
  15156. res.status = StatusCode::Found_302;
  15157. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  15158. });
  15159. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  15160. target = req.target;
  15161. res.set_content("ok", "text/plain");
  15162. });
  15163. auto port = svr.bind_to_any_port(HOST);
  15164. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15165. auto se = detail::scope_exit([&] {
  15166. svr.stop();
  15167. thread.join();
  15168. ASSERT_FALSE(svr.is_running());
  15169. });
  15170. svr.wait_until_ready();
  15171. // Decoding the Location path would turn the first four into a path
  15172. // separator, a query delimiter, a fragment delimiter and a different
  15173. // percent-encoded octet. The rest must keep reaching the server as they are.
  15174. const std::vector<std::string> names = {
  15175. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  15176. };
  15177. for (auto path_encode : {true, false}) {
  15178. Client cli(HOST, port);
  15179. cli.set_follow_location(true);
  15180. cli.set_path_encode(path_encode);
  15181. for (const auto &name : names) {
  15182. target.clear();
  15183. auto res = cli.Get("/start/" + name);
  15184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15185. EXPECT_EQ(StatusCode::OK_200, res->status);
  15186. EXPECT_EQ("/dest/" + name, target);
  15187. }
  15188. }
  15189. }
  15190. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  15191. Server svr;
  15192. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15193. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  15194. });
  15195. svr.Get("/hello", [](const Request &req, Response &res) {
  15196. res.set_content(req.get_param_value("key"), "text/plain");
  15197. });
  15198. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15199. auto se = detail::scope_exit([&] {
  15200. svr.stop();
  15201. thread.join();
  15202. ASSERT_FALSE(svr.is_running());
  15203. });
  15204. svr.wait_until_ready();
  15205. {
  15206. Client cli(HOST, PORT);
  15207. cli.set_follow_location(true);
  15208. auto res = cli.Get("/");
  15209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15210. EXPECT_EQ(StatusCode::OK_200, res->status);
  15211. EXPECT_EQ("val&key2=val2", res->body);
  15212. }
  15213. }
  15214. #endif
  15215. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  15216. Server svr;
  15217. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15218. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  15219. });
  15220. svr.Get("/hello", [](const Request &req, Response &res) {
  15221. res.set_content(req.get_param_value("key"), "text/plain");
  15222. });
  15223. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15224. auto se = detail::scope_exit([&] {
  15225. svr.stop();
  15226. thread.join();
  15227. ASSERT_FALSE(svr.is_running());
  15228. });
  15229. svr.wait_until_ready();
  15230. {
  15231. Client cli(HOST, PORT);
  15232. cli.set_follow_location(true);
  15233. auto res = cli.Get("/");
  15234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15235. EXPECT_EQ(StatusCode::OK_200, res->status);
  15236. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  15237. }
  15238. }
  15239. TEST(RedirectTest, RedirectWithPlusInPath) {
  15240. Server svr;
  15241. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15242. res.set_redirect("/a+b");
  15243. });
  15244. // Route pattern uses regex; escape + as \\+
  15245. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  15246. res.set_content(req.path, "text/plain");
  15247. });
  15248. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15249. auto se = detail::scope_exit([&] {
  15250. svr.stop();
  15251. thread.join();
  15252. ASSERT_FALSE(svr.is_running());
  15253. });
  15254. svr.wait_until_ready();
  15255. {
  15256. Client cli(HOST, PORT);
  15257. cli.set_follow_location(true);
  15258. auto res = cli.Get("/");
  15259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15260. EXPECT_EQ(StatusCode::OK_200, res->status);
  15261. EXPECT_EQ("/a+b", res->body);
  15262. }
  15263. }
  15264. TEST(RedirectTest, ResolveRelativeLocation) {
  15265. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  15266. const std::vector<std::pair<std::string, std::string>> cases = {
  15267. {"g", "/b/c/g"},
  15268. {"./g", "/b/c/g"},
  15269. {"g/", "/b/c/g/"},
  15270. {"?y", "/b/c/d;p?y"},
  15271. {"g?y", "/b/c/g?y"},
  15272. {"#s", "/b/c/d;p?q#s"},
  15273. {"g#s", "/b/c/g#s"},
  15274. {"g?y#s", "/b/c/g?y#s"},
  15275. {";x", "/b/c/;x"},
  15276. {"g;x", "/b/c/g;x"},
  15277. {".", "/b/c/"},
  15278. {"./", "/b/c/"},
  15279. {"..", "/b/"},
  15280. {"../", "/b/"},
  15281. {"../g", "/b/g"},
  15282. {"../..", "/"},
  15283. {"../../", "/"},
  15284. {"../../g", "/g"},
  15285. {"../../../g", "/g"},
  15286. {"g.", "/b/c/g."},
  15287. {".g", "/b/c/.g"},
  15288. {"g..", "/b/c/g.."},
  15289. {"..g", "/b/c/..g"},
  15290. {"./../g", "/b/g"},
  15291. {"./g/.", "/b/c/g/"},
  15292. {"g/./h", "/b/c/g/h"},
  15293. {"g/../h", "/b/c/h"},
  15294. {"g;x=1/./y", "/b/c/g;x=1/y"},
  15295. {"g;x=1/../y", "/b/c/y"},
  15296. {"g?y/./x", "/b/c/g?y/./x"},
  15297. {"g#s/../x", "/b/c/g#s/../x"},
  15298. // Not relative-path references, so left for parse_url.
  15299. {"/g", "/g"},
  15300. {"//g", "//g"},
  15301. {"http://g/x", "http://g/x"},
  15302. {"g:h", "g:h"},
  15303. };
  15304. for (const auto &c : cases) {
  15305. EXPECT_EQ(c.second,
  15306. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  15307. << c.first;
  15308. }
  15309. }
  15310. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  15311. Server svr;
  15312. svr.Get("/dir/page", [](const Request &req, Response &res) {
  15313. res.set_redirect(req.get_param_value("to"));
  15314. });
  15315. svr.Get("/dir/next", [](const Request &req, Response &res) {
  15316. res.set_content(req.target, "text/plain");
  15317. });
  15318. svr.Get("/other", [](const Request &req, Response &res) {
  15319. res.set_content(req.target, "text/plain");
  15320. });
  15321. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15322. auto se = detail::scope_exit([&] {
  15323. svr.stop();
  15324. thread.join();
  15325. ASSERT_FALSE(svr.is_running());
  15326. });
  15327. svr.wait_until_ready();
  15328. const std::vector<std::pair<std::string, std::string>> cases = {
  15329. {"next", "/dir/next"},
  15330. {"./next?x=1", "/dir/next?x=1"},
  15331. {"../other", "/other"},
  15332. };
  15333. for (const auto &c : cases) {
  15334. Client cli(HOST, PORT);
  15335. cli.set_follow_location(true);
  15336. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  15337. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  15338. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  15339. EXPECT_EQ(c.second, res->body) << c.first;
  15340. }
  15341. }
  15342. #ifdef CPPHTTPLIB_SSL_ENABLED
  15343. TEST(RedirectTest, Issue2185_Online) {
  15344. SSLClient client("github.com");
  15345. client.set_follow_location(true);
  15346. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  15347. "Coollab-Windows.zip");
  15348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15349. EXPECT_EQ(StatusCode::OK_200, res->status);
  15350. EXPECT_EQ(9920427U, res->body.size());
  15351. }
  15352. #endif
  15353. TEST(VulnerabilityTest, CRLFInjection) {
  15354. Server svr;
  15355. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  15356. res.set_content("Hello 1", "text/plain");
  15357. });
  15358. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  15359. res.set_content("Hello 2", "text/plain");
  15360. });
  15361. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  15362. res.set_content("Hello 3", "text/plain");
  15363. });
  15364. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  15365. res.set_content("Hello 4", "text/plain");
  15366. });
  15367. svr.set_logger([](const Request &req, const Response & /*res*/) {
  15368. for (const auto &x : req.headers) {
  15369. auto key = x.first;
  15370. EXPECT_STRNE("evil", key.c_str());
  15371. }
  15372. });
  15373. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15374. auto se = detail::scope_exit([&] {
  15375. svr.stop();
  15376. thread.join();
  15377. ASSERT_FALSE(svr.is_running());
  15378. });
  15379. svr.wait_until_ready();
  15380. {
  15381. Client cli(HOST, PORT);
  15382. cli.Post("/test1", "A=B",
  15383. "application/x-www-form-urlencoded\r\nevil: hello1");
  15384. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  15385. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  15386. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  15387. }
  15388. }
  15389. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  15390. auto server_thread = std::thread([] {
  15391. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15392. default_socket_options(srv);
  15393. sockaddr_in addr{};
  15394. addr.sin_family = AF_INET;
  15395. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15396. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15397. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  15398. ::listen(srv, 1);
  15399. sockaddr_in cli_addr{};
  15400. socklen_t cli_len = sizeof(cli_addr);
  15401. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15402. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  15403. std::string buf_all;
  15404. char buf[2048];
  15405. ssize_t n;
  15406. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  15407. buf_all.append(buf, static_cast<size_t>(n));
  15408. size_t pos;
  15409. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  15410. auto request_block = buf_all.substr(0, pos + 4); // include separator
  15411. auto e = request_block.find("\r\n");
  15412. if (e != std::string::npos) {
  15413. auto request_line = request_block.substr(0, e);
  15414. std::string msg =
  15415. "CRLF injection detected in request line: '" + request_line + "'";
  15416. EXPECT_FALSE(true) << msg;
  15417. }
  15418. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  15419. ::send(cli,
  15420. #ifdef _WIN32
  15421. static_cast<const char *>(resp.c_str()),
  15422. static_cast<int>(resp.size()),
  15423. #else
  15424. resp.c_str(), resp.size(),
  15425. #endif
  15426. 0);
  15427. buf_all.erase(0, pos + 4);
  15428. }
  15429. }
  15430. detail::close_socket(cli);
  15431. detail::close_socket(srv);
  15432. });
  15433. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15434. auto cli = Client("127.0.0.1", PORT + 1);
  15435. auto headers = Headers{
  15436. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  15437. {"Connection", "keep-alive"}};
  15438. auto res = cli.Get("/hi", headers);
  15439. EXPECT_FALSE(res);
  15440. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15441. server_thread.join();
  15442. }
  15443. // A request rejected before any byte reaches the socket must fail right away
  15444. // instead of waiting for a response the server will never send.
  15445. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  15446. // The kernel completes the TCP handshake from the listen backlog, so the
  15447. // client connects, but nothing ever reads, responds or closes.
  15448. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15449. default_socket_options(srv);
  15450. sockaddr_in addr{};
  15451. addr.sin_family = AF_INET;
  15452. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15453. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15454. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15455. ASSERT_EQ(0, ::listen(srv, 8));
  15456. auto cli = Client("127.0.0.1", PORT + 1);
  15457. cli.set_read_timeout(10, 0);
  15458. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  15459. return std::chrono::duration_cast<std::chrono::milliseconds>(
  15460. std::chrono::steady_clock::now() - start)
  15461. .count();
  15462. };
  15463. {
  15464. Request req;
  15465. req.method = "GE T";
  15466. req.path = "/";
  15467. auto start = std::chrono::steady_clock::now();
  15468. auto res = cli.send(req);
  15469. EXPECT_FALSE(res);
  15470. EXPECT_EQ(Error::Write, res.error());
  15471. EXPECT_LT(elapsed_ms(start), 1000);
  15472. }
  15473. {
  15474. auto start = std::chrono::steady_clock::now();
  15475. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  15476. EXPECT_FALSE(res);
  15477. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15478. EXPECT_LT(elapsed_ms(start), 1000);
  15479. }
  15480. EXPECT_FALSE(cli.is_socket_open());
  15481. detail::close_socket(srv);
  15482. }
  15483. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  15484. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15485. default_socket_options(srv);
  15486. sockaddr_in addr{};
  15487. addr.sin_family = AF_INET;
  15488. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15489. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15490. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15491. ASSERT_EQ(0, ::listen(srv, 1));
  15492. std::string received;
  15493. auto server_thread = std::thread([&] {
  15494. auto sock = ::accept(srv, nullptr, nullptr);
  15495. if (sock == INVALID_SOCKET) { return; }
  15496. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  15497. char buf[2048];
  15498. ssize_t n;
  15499. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  15500. received.append(buf, static_cast<size_t>(n));
  15501. }
  15502. detail::close_socket(sock);
  15503. });
  15504. {
  15505. auto cli = Client("127.0.0.1", PORT + 1);
  15506. // "Z" sorts after the default headers, so writing straight to the socket
  15507. // would have sent the request line and those headers before the rejection.
  15508. auto handle =
  15509. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  15510. EXPECT_FALSE(handle.is_valid());
  15511. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  15512. }
  15513. server_thread.join();
  15514. detail::close_socket(srv);
  15515. EXPECT_TRUE(received.empty()) << received;
  15516. }
  15517. TEST(PathParamsTest, StaticMatch) {
  15518. const auto pattern = "/users/all";
  15519. detail::PathParamsMatcher matcher(pattern);
  15520. Request request;
  15521. request.path = "/users/all";
  15522. ASSERT_TRUE(matcher.match(request));
  15523. std::unordered_map<std::string, std::string> expected_params = {};
  15524. EXPECT_EQ(request.path_params, expected_params);
  15525. }
  15526. TEST(PathParamsTest, StaticMismatch) {
  15527. const auto pattern = "/users/all";
  15528. detail::PathParamsMatcher matcher(pattern);
  15529. Request request;
  15530. request.path = "/users/1";
  15531. ASSERT_FALSE(matcher.match(request));
  15532. }
  15533. TEST(PathParamsTest, SingleParamInTheMiddle) {
  15534. const auto pattern = "/users/:id/subscriptions";
  15535. detail::PathParamsMatcher matcher(pattern);
  15536. Request request;
  15537. request.path = "/users/42/subscriptions";
  15538. ASSERT_TRUE(matcher.match(request));
  15539. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15540. EXPECT_EQ(request.path_params, expected_params);
  15541. }
  15542. TEST(PathParamsTest, SingleParamInTheEnd) {
  15543. const auto pattern = "/users/:id";
  15544. detail::PathParamsMatcher matcher(pattern);
  15545. Request request;
  15546. request.path = "/users/24";
  15547. ASSERT_TRUE(matcher.match(request));
  15548. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  15549. EXPECT_EQ(request.path_params, expected_params);
  15550. }
  15551. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  15552. const auto pattern = "/users/:id/";
  15553. detail::PathParamsMatcher matcher(pattern);
  15554. Request request;
  15555. request.path = "/users/42/";
  15556. ASSERT_TRUE(matcher.match(request));
  15557. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15558. EXPECT_EQ(request.path_params, expected_params);
  15559. }
  15560. TEST(PathParamsTest, EmptyParam) {
  15561. const auto pattern = "/users/:id/";
  15562. detail::PathParamsMatcher matcher(pattern);
  15563. Request request;
  15564. request.path = "/users//";
  15565. ASSERT_TRUE(matcher.match(request));
  15566. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  15567. EXPECT_EQ(request.path_params, expected_params);
  15568. }
  15569. TEST(PathParamsTest, FragmentMismatch) {
  15570. const auto pattern = "/users/:id/";
  15571. detail::PathParamsMatcher matcher(pattern);
  15572. Request request;
  15573. request.path = "/admins/24/";
  15574. ASSERT_FALSE(matcher.match(request));
  15575. }
  15576. TEST(PathParamsTest, ExtraFragments) {
  15577. const auto pattern = "/users/:id";
  15578. detail::PathParamsMatcher matcher(pattern);
  15579. Request request;
  15580. request.path = "/users/42/subscriptions";
  15581. ASSERT_FALSE(matcher.match(request));
  15582. }
  15583. TEST(PathParamsTest, MissingTrailingParam) {
  15584. const auto pattern = "/users/:id";
  15585. detail::PathParamsMatcher matcher(pattern);
  15586. Request request;
  15587. request.path = "/users";
  15588. ASSERT_FALSE(matcher.match(request));
  15589. }
  15590. TEST(PathParamsTest, MissingParamInTheMiddle) {
  15591. const auto pattern = "/users/:id/subscriptions";
  15592. detail::PathParamsMatcher matcher(pattern);
  15593. Request request;
  15594. request.path = "/users/subscriptions";
  15595. ASSERT_FALSE(matcher.match(request));
  15596. }
  15597. TEST(PathParamsTest, MultipleParams) {
  15598. const auto pattern = "/users/:userid/subscriptions/:subid";
  15599. detail::PathParamsMatcher matcher(pattern);
  15600. Request request;
  15601. request.path = "/users/42/subscriptions/2";
  15602. ASSERT_TRUE(matcher.match(request));
  15603. std::unordered_map<std::string, std::string> expected_params = {
  15604. {"userid", "42"}, {"subid", "2"}};
  15605. EXPECT_EQ(request.path_params, expected_params);
  15606. }
  15607. TEST(PathParamsTest, SequenceOfParams) {
  15608. const auto pattern = "/values/:x/:y/:z";
  15609. detail::PathParamsMatcher matcher(pattern);
  15610. Request request;
  15611. request.path = "/values/1/2/3";
  15612. ASSERT_TRUE(matcher.match(request));
  15613. std::unordered_map<std::string, std::string> expected_params = {
  15614. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  15615. EXPECT_EQ(request.path_params, expected_params);
  15616. }
  15617. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  15618. const auto pattern = "/prefix:suffix";
  15619. detail::PathParamsMatcher matcher(pattern);
  15620. Request request;
  15621. request.path = "/prefix:suffix";
  15622. ASSERT_TRUE(matcher.match(request));
  15623. const std::unordered_map<std::string, std::string> expected_params = {};
  15624. EXPECT_EQ(request.path_params, expected_params);
  15625. }
  15626. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  15627. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  15628. // calling thread's stack on a long enough path for a quantified pattern;
  15629. // RegexMatcher must refuse to run regex matching on paths beyond
  15630. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  15631. detail::RegexMatcher matcher("/files/(.*)");
  15632. Request within_limit;
  15633. within_limit.path = "/files/" + std::string(10, 'A');
  15634. EXPECT_TRUE(matcher.match(within_limit));
  15635. Request over_limit;
  15636. over_limit.path =
  15637. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  15638. EXPECT_FALSE(matcher.match(over_limit));
  15639. }
  15640. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  15641. Server svr;
  15642. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  15643. res.set_content("ok", "text/plain");
  15644. });
  15645. auto port = svr.bind_to_any_port(HOST);
  15646. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15647. auto se = detail::scope_exit([&] {
  15648. svr.stop();
  15649. thread.join();
  15650. ASSERT_FALSE(svr.is_running());
  15651. });
  15652. svr.wait_until_ready();
  15653. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  15654. // request URI limit; this used to be able to crash the process.
  15655. std::string path =
  15656. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  15657. std::string req = "GET " + path +
  15658. " HTTP/1.1\r\n"
  15659. "Host: " +
  15660. std::string(HOST) + ":" + std::to_string(port) +
  15661. "\r\n"
  15662. "Connection: close\r\n"
  15663. "\r\n";
  15664. std::string response;
  15665. ASSERT_TRUE(send_request(5, req, &response, port));
  15666. EXPECT_NE(std::string::npos, response.find("404"));
  15667. }
  15668. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  15669. Server svr;
  15670. auto handler = [](const Request & /*req*/, Response &res) {
  15671. res.set_content("hit", "text/plain");
  15672. };
  15673. // No regex metacharacter, so this one is compared literally
  15674. svr.Get("/literal/route", handler);
  15675. // '.' is a regex metacharacter, so this one must keep regex semantics
  15676. svr.Get("/a.c", handler);
  15677. auto port = svr.bind_to_any_port(HOST);
  15678. std::thread t([&]() { svr.listen_after_bind(); });
  15679. auto se = detail::scope_exit([&] {
  15680. svr.stop();
  15681. t.join();
  15682. ASSERT_FALSE(svr.is_running());
  15683. });
  15684. svr.wait_until_ready();
  15685. Client cli(HOST, port);
  15686. struct {
  15687. const char *path;
  15688. int status;
  15689. } cases[] = {
  15690. {"/literal/route", StatusCode::OK_200},
  15691. {"/literal/routes", StatusCode::NotFound_404},
  15692. {"/literal/rout", StatusCode::NotFound_404},
  15693. {"/abc", StatusCode::OK_200},
  15694. {"/a.c", StatusCode::OK_200},
  15695. };
  15696. for (const auto &x : cases) {
  15697. auto res = cli.Get(x.path);
  15698. ASSERT_TRUE(res) << x.path;
  15699. EXPECT_EQ(x.status, res->status) << x.path;
  15700. }
  15701. }
  15702. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  15703. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  15704. // from exhausting the stack, so it must only constrain routes that actually
  15705. // run a regular expression. A literal route is matched by comparison and
  15706. // stays usable at any length.
  15707. Server svr;
  15708. const std::string pattern =
  15709. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  15710. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  15711. res.set_content("hit", "text/plain");
  15712. });
  15713. auto port = svr.bind_to_any_port(HOST);
  15714. std::thread t([&]() { svr.listen_after_bind(); });
  15715. auto se = detail::scope_exit([&] {
  15716. svr.stop();
  15717. t.join();
  15718. ASSERT_FALSE(svr.is_running());
  15719. });
  15720. svr.wait_until_ready();
  15721. Client cli(HOST, port);
  15722. auto res = cli.Get(pattern);
  15723. ASSERT_TRUE(res);
  15724. EXPECT_EQ(StatusCode::OK_200, res->status);
  15725. }
  15726. TEST(ParseUrlTest, VariousPatterns) {
  15727. {
  15728. detail::UrlComponents uc;
  15729. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  15730. EXPECT_EQ("http", uc.scheme);
  15731. EXPECT_EQ("example.com", uc.host);
  15732. EXPECT_EQ("8080", uc.port);
  15733. EXPECT_EQ("/path", uc.path);
  15734. EXPECT_EQ("?q=1", uc.query);
  15735. }
  15736. {
  15737. detail::UrlComponents uc;
  15738. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  15739. EXPECT_EQ("https", uc.scheme);
  15740. EXPECT_EQ("example.com", uc.host);
  15741. EXPECT_TRUE(uc.port.empty());
  15742. EXPECT_EQ("/path", uc.path);
  15743. }
  15744. {
  15745. detail::UrlComponents uc;
  15746. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  15747. EXPECT_EQ("::1", uc.host);
  15748. EXPECT_EQ("8080", uc.port);
  15749. EXPECT_EQ("/path", uc.path);
  15750. }
  15751. {
  15752. detail::UrlComponents uc;
  15753. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  15754. }
  15755. {
  15756. // Bytes after the IPv6 literal must be a delimiter, not folded into
  15757. // the path while the connection still targets the bracketed host.
  15758. detail::UrlComponents uc;
  15759. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  15760. }
  15761. {
  15762. detail::UrlComponents uc;
  15763. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  15764. }
  15765. {
  15766. detail::UrlComponents uc;
  15767. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  15768. EXPECT_EQ("::1", uc.host);
  15769. EXPECT_TRUE(uc.port.empty());
  15770. EXPECT_EQ("/path", uc.path);
  15771. }
  15772. {
  15773. detail::UrlComponents uc;
  15774. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  15775. EXPECT_TRUE(uc.scheme.empty());
  15776. EXPECT_EQ("example.com", uc.host);
  15777. EXPECT_EQ("/path", uc.path);
  15778. EXPECT_EQ("?q=1", uc.query);
  15779. }
  15780. {
  15781. detail::UrlComponents uc;
  15782. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  15783. EXPECT_TRUE(uc.host.empty());
  15784. EXPECT_EQ("/path", uc.path);
  15785. EXPECT_EQ("?q=1", uc.query);
  15786. }
  15787. {
  15788. detail::UrlComponents uc;
  15789. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  15790. EXPECT_EQ("example.com", uc.host);
  15791. EXPECT_EQ("8080", uc.port);
  15792. }
  15793. {
  15794. // Unix socket path — must not be parsed as host
  15795. detail::UrlComponents uc;
  15796. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  15797. EXPECT_TRUE(uc.host.empty());
  15798. }
  15799. {
  15800. detail::UrlComponents uc;
  15801. ASSERT_TRUE(detail::parse_url("", uc));
  15802. EXPECT_TRUE(uc.host.empty());
  15803. EXPECT_TRUE(uc.path.empty());
  15804. }
  15805. {
  15806. detail::UrlComponents uc;
  15807. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  15808. }
  15809. {
  15810. detail::UrlComponents uc;
  15811. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  15812. }
  15813. {
  15814. // Accepted by parse_url; callers restrict to http/https
  15815. detail::UrlComponents uc;
  15816. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  15817. EXPECT_EQ("ftp", uc.scheme);
  15818. }
  15819. {
  15820. detail::UrlComponents uc;
  15821. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  15822. }
  15823. {
  15824. detail::UrlComponents uc;
  15825. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  15826. }
  15827. }
  15828. TEST(ParseUrlTest, FragmentHandling) {
  15829. {
  15830. detail::UrlComponents uc;
  15831. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  15832. EXPECT_EQ("/path", uc.path);
  15833. EXPECT_TRUE(uc.query.empty());
  15834. }
  15835. {
  15836. detail::UrlComponents uc;
  15837. ASSERT_TRUE(detail::parse_url("#frag", uc));
  15838. EXPECT_TRUE(uc.path.empty());
  15839. EXPECT_TRUE(uc.query.empty());
  15840. }
  15841. }
  15842. TEST(ParseUrlTest, UserinfoHandling) {
  15843. // Userinfo with @ but no colon — host includes @
  15844. detail::UrlComponents uc;
  15845. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  15846. EXPECT_EQ("user@host.com", uc.host);
  15847. EXPECT_EQ("/path", uc.path);
  15848. }
  15849. TEST(ParseUrlTest, IPv6EdgeCases) {
  15850. {
  15851. detail::UrlComponents uc;
  15852. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  15853. EXPECT_TRUE(uc.scheme.empty());
  15854. EXPECT_EQ("::1", uc.host);
  15855. EXPECT_EQ("8080", uc.port);
  15856. }
  15857. {
  15858. // Zone ID '%25' is not in [a-fA-F0-9:]
  15859. detail::UrlComponents uc;
  15860. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  15861. }
  15862. }
  15863. TEST(ParseUrlTest, SchemeEdgeCases) {
  15864. {
  15865. detail::UrlComponents uc;
  15866. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  15867. }
  15868. {
  15869. detail::UrlComponents uc;
  15870. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  15871. }
  15872. {
  15873. detail::UrlComponents uc;
  15874. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  15875. }
  15876. }
  15877. TEST(ParseUrlTest, PortEdgeCases) {
  15878. {
  15879. detail::UrlComponents uc;
  15880. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  15881. EXPECT_TRUE(uc.port.empty());
  15882. EXPECT_EQ("/path", uc.path);
  15883. }
  15884. {
  15885. // parse_url accepts any port string; validation is done by parse_port
  15886. detail::UrlComponents uc;
  15887. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  15888. EXPECT_EQ("abc", uc.port);
  15889. }
  15890. }
  15891. TEST(ParseUrlTest, WebSocketPatterns) {
  15892. {
  15893. detail::UrlComponents uc;
  15894. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  15895. EXPECT_EQ("ws", uc.scheme);
  15896. EXPECT_EQ("echo.example.com", uc.host);
  15897. EXPECT_EQ("8080", uc.port);
  15898. EXPECT_EQ("/ws", uc.path);
  15899. }
  15900. {
  15901. detail::UrlComponents uc;
  15902. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  15903. EXPECT_EQ("wss", uc.scheme);
  15904. EXPECT_EQ("echo.example.com", uc.host);
  15905. EXPECT_TRUE(uc.port.empty());
  15906. EXPECT_EQ("/ws", uc.path);
  15907. }
  15908. }
  15909. TEST(ParseUrlTest, QueryOnly) {
  15910. detail::UrlComponents uc;
  15911. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  15912. EXPECT_TRUE(uc.host.empty());
  15913. EXPECT_TRUE(uc.path.empty());
  15914. EXPECT_EQ("?q=1&r=2", uc.query);
  15915. }
  15916. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  15917. detail::UrlComponents uc;
  15918. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  15919. EXPECT_TRUE(uc.scheme.empty());
  15920. EXPECT_EQ("example.com", uc.host);
  15921. EXPECT_EQ("443", uc.port);
  15922. EXPECT_EQ("/path", uc.path);
  15923. }
  15924. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  15925. // If ipv6 regex working, regex match codepath is taken.
  15926. // else port will default to 80 in Client impl
  15927. int clientImplMagicPort = 80;
  15928. int port = 4321;
  15929. // above ports must be different to avoid false negative
  15930. EXPECT_NE(clientImplMagicPort, port);
  15931. std::string ipV6TestURL = "http://[ff06::c3]";
  15932. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  15933. CLIENT_PRIVATE_KEY_FILE);
  15934. EXPECT_EQ(cli.port(), port);
  15935. }
  15936. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  15937. auto file_path = "./www/dir/index.html";
  15938. auto dir_path = "./www/dir";
  15939. detail::FileStat stat_file(file_path);
  15940. EXPECT_TRUE(stat_file.is_file());
  15941. EXPECT_FALSE(stat_file.is_dir());
  15942. detail::FileStat stat_dir(dir_path);
  15943. EXPECT_FALSE(stat_dir.is_file());
  15944. EXPECT_TRUE(stat_dir.is_dir());
  15945. }
  15946. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  15947. // IPv4 with default HTTP port (80)
  15948. EXPECT_EQ("example.com",
  15949. detail::make_host_and_port_string("example.com", 80, false));
  15950. // IPv4 with default HTTPS port (443)
  15951. EXPECT_EQ("example.com",
  15952. detail::make_host_and_port_string("example.com", 443, true));
  15953. // IPv4 with non-default HTTP port
  15954. EXPECT_EQ("example.com:8080",
  15955. detail::make_host_and_port_string("example.com", 8080, false));
  15956. // IPv4 with non-default HTTPS port
  15957. EXPECT_EQ("example.com:8443",
  15958. detail::make_host_and_port_string("example.com", 8443, true));
  15959. // IPv6 with default HTTP port (80)
  15960. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  15961. // IPv6 with default HTTPS port (443)
  15962. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  15963. // IPv6 with non-default HTTP port
  15964. EXPECT_EQ("[::1]:8080",
  15965. detail::make_host_and_port_string("::1", 8080, false));
  15966. // IPv6 with non-default HTTPS port
  15967. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  15968. // IPv6 full address with default port
  15969. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  15970. detail::make_host_and_port_string(
  15971. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  15972. // IPv6 full address with non-default port
  15973. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  15974. detail::make_host_and_port_string(
  15975. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  15976. // IPv6 localhost with non-default port
  15977. EXPECT_EQ("[::1]:3000",
  15978. detail::make_host_and_port_string("::1", 3000, false));
  15979. // IPv6 with zone ID (link-local address) with default port
  15980. EXPECT_EQ("[fe80::1%eth0]",
  15981. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  15982. // IPv6 with zone ID (link-local address) with non-default port
  15983. EXPECT_EQ("[fe80::1%eth0]:8080",
  15984. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  15985. // Edge case: Port 443 with is_ssl=false (should add port)
  15986. EXPECT_EQ("example.com:443",
  15987. detail::make_host_and_port_string("example.com", 443, false));
  15988. // Edge case: Port 80 with is_ssl=true (should add port)
  15989. EXPECT_EQ("example.com:80",
  15990. detail::make_host_and_port_string("example.com", 80, true));
  15991. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  15992. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  15993. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  15994. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  15995. // Security fix: Already bracketed IPv6 should not get double brackets
  15996. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  15997. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  15998. EXPECT_EQ("[::1]:8080",
  15999. detail::make_host_and_port_string("[::1]", 8080, false));
  16000. EXPECT_EQ("[2001:db8::1]:8080",
  16001. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  16002. EXPECT_EQ("[fe80::1%eth0]",
  16003. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  16004. EXPECT_EQ("[fe80::1%eth0]:8080",
  16005. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  16006. // Edge case: Empty host (should return as-is)
  16007. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  16008. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  16009. // This is a known limitation but shouldn't crash
  16010. EXPECT_EQ("[host:name]",
  16011. detail::make_host_and_port_string("host:name", 80, false));
  16012. // Port number edge cases (no validation, but should not crash)
  16013. EXPECT_EQ("example.com:0",
  16014. detail::make_host_and_port_string("example.com", 0, false));
  16015. EXPECT_EQ("example.com:-1",
  16016. detail::make_host_and_port_string("example.com", -1, false));
  16017. EXPECT_EQ("example.com:65535",
  16018. detail::make_host_and_port_string("example.com", 65535, false));
  16019. EXPECT_EQ("example.com:65536",
  16020. detail::make_host_and_port_string("example.com", 65536, false));
  16021. }
  16022. #ifdef CPPHTTPLIB_SSL_ENABLED
  16023. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  16024. httplib::SSLClient cli("roblox.com", 443);
  16025. cli.set_follow_location(true);
  16026. auto res = cli.Get("/");
  16027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16028. EXPECT_EQ(StatusCode::OK_200, res->status);
  16029. }
  16030. #endif
  16031. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  16032. Server svr;
  16033. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16034. EXPECT_EQ(res.status, 400);
  16035. });
  16036. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16037. auto se = detail::scope_exit([&] {
  16038. svr.stop();
  16039. thread.join();
  16040. ASSERT_FALSE(svr.is_running());
  16041. });
  16042. svr.wait_until_ready();
  16043. Client cli(HOST, PORT);
  16044. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  16045. }
  16046. TEST(InvalidHeaderCharsTest, is_field_name) {
  16047. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  16048. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  16049. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  16050. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  16051. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  16052. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  16053. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  16054. EXPECT_FALSE(detail::fields::is_field_name(""));
  16055. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  16056. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  16057. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  16058. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  16059. }
  16060. TEST(InvalidHeaderCharsTest, is_field_value) {
  16061. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  16062. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  16063. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  16064. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  16065. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  16066. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  16067. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  16068. EXPECT_TRUE(detail::fields::is_field_value(""));
  16069. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  16070. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  16071. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  16072. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  16073. EXPECT_TRUE(detail::fields::is_field_value("0"));
  16074. }
  16075. TEST(InvalidHeaderCharsTest, OnServer) {
  16076. Server svr;
  16077. svr.Get("/test_name", [&](const Request &req, Response &res) {
  16078. std::string header = "Not Set";
  16079. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16080. res.set_header(header, "value");
  16081. res.set_content("Page Content Page Content", "text/plain");
  16082. });
  16083. svr.Get("/test_value", [&](const Request &req, Response &res) {
  16084. std::string header = "Not Set";
  16085. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16086. res.set_header("X-Test", header);
  16087. res.set_content("Page Content Page Content", "text/plain");
  16088. });
  16089. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16090. auto se = detail::scope_exit([&] {
  16091. svr.stop();
  16092. thread.join();
  16093. ASSERT_FALSE(svr.is_running());
  16094. });
  16095. svr.wait_until_ready();
  16096. Client cli(HOST, PORT);
  16097. {
  16098. auto res = cli.Get(
  16099. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16101. EXPECT_EQ("Page Content Page Content", res->body);
  16102. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16103. }
  16104. {
  16105. auto res = cli.Get(
  16106. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16108. EXPECT_EQ("Page Content Page Content", res->body);
  16109. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16110. }
  16111. }
  16112. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  16113. auto handled = false;
  16114. Server svr;
  16115. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16116. thread t = thread([&] { svr.listen(HOST, PORT); });
  16117. auto se = detail::scope_exit([&] {
  16118. svr.stop();
  16119. t.join();
  16120. ASSERT_FALSE(svr.is_running());
  16121. ASSERT_FALSE(handled);
  16122. });
  16123. svr.wait_until_ready();
  16124. auto req = "POST /test HTTP/1.1\r\n"
  16125. "Content-Length: x\r\n"
  16126. "\r\n";
  16127. std::string response;
  16128. ASSERT_TRUE(send_request(1, req, &response));
  16129. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16130. response.substr(0, response.find("\r\n")));
  16131. }
  16132. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  16133. // case-insensitive, and a server that receives a 100-continue expectation in
  16134. // an HTTP/1.0 request MUST ignore it.
  16135. static void probe_expect(int port, const std::string &req, bool *got_100) {
  16136. std::string response;
  16137. ASSERT_TRUE(send_request(1, req, &response, port));
  16138. *got_100 = response.find("100 Continue") != std::string::npos;
  16139. }
  16140. class ExpectTokenTest : public ::testing::Test {
  16141. protected:
  16142. void SetUp() override {
  16143. svr_.Post("/p", [](const Request &, Response &res) {
  16144. res.set_content("ok", "text/plain");
  16145. });
  16146. port_ = svr_.bind_to_any_port(HOST);
  16147. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16148. svr_.wait_until_ready();
  16149. }
  16150. void TearDown() override {
  16151. svr_.stop();
  16152. if (thread_.joinable()) { thread_.join(); }
  16153. }
  16154. std::string request(const char *version, const char *expect_value) const {
  16155. return std::string("POST /p ") + version +
  16156. "\r\n"
  16157. "Host: localhost\r\n"
  16158. "Content-Length: 2\r\n"
  16159. "Connection: close\r\n"
  16160. "Expect: " +
  16161. expect_value +
  16162. "\r\n"
  16163. "\r\n"
  16164. "hi";
  16165. }
  16166. Server svr_;
  16167. int port_ = 0;
  16168. thread thread_;
  16169. };
  16170. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  16171. bool got_100 = false;
  16172. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  16173. EXPECT_TRUE(got_100);
  16174. }
  16175. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  16176. bool got_100 = true;
  16177. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  16178. EXPECT_FALSE(got_100);
  16179. }
  16180. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  16181. bool got_100 = false;
  16182. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  16183. EXPECT_TRUE(got_100);
  16184. }
  16185. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  16186. bool got_100 = false;
  16187. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  16188. EXPECT_TRUE(got_100);
  16189. }
  16190. // `100 Continue` is sent only when the server starts reading the body, so a
  16191. // request rejected before that never invites the client to send it. The
  16192. // requests below carry the expectation but withhold the body, as a client
  16193. // waiting for `100 Continue` would.
  16194. // A POST that expects `100 Continue` and withholds its two-byte body.
  16195. static std::string expect_headers_only(const std::string &path) {
  16196. return "POST " + path +
  16197. " HTTP/1.1\r\n"
  16198. "Host: localhost\r\n"
  16199. "Content-Length: 2\r\n"
  16200. "Expect: 100-continue\r\n"
  16201. "\r\n";
  16202. }
  16203. class ExpectLazyContinueTest : public ::testing::Test {
  16204. protected:
  16205. void SetUp() override {
  16206. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  16207. if (req.path == "/pre-routing") {
  16208. res.status = StatusCode::Unauthorized_401;
  16209. return Server::HandlerResponse::Handled;
  16210. }
  16211. return Server::HandlerResponse::Unhandled;
  16212. });
  16213. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  16214. if (req.matched_route == "/pre-request") {
  16215. res.status = StatusCode::Forbidden_403;
  16216. return Server::HandlerResponse::Handled;
  16217. }
  16218. return Server::HandlerResponse::Unhandled;
  16219. });
  16220. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  16221. res.set_content("ok", "text/plain");
  16222. });
  16223. svr_.Post("/pre-request", [](const Request &, Response &res) {
  16224. res.set_content("ok", "text/plain");
  16225. });
  16226. svr_.Post("/reader-used", [](const Request &, Response &res,
  16227. const ContentReader &content_reader) {
  16228. std::string body;
  16229. content_reader([&](const char *data, size_t len) {
  16230. body.append(data, len);
  16231. return true;
  16232. });
  16233. res.set_content(body, "text/plain");
  16234. });
  16235. svr_.Post("/reader-unused",
  16236. [](const Request &, Response &res, const ContentReader &) {
  16237. res.set_content("ignored", "text/plain");
  16238. });
  16239. port_ = svr_.bind_to_any_port(HOST);
  16240. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16241. svr_.wait_until_ready();
  16242. }
  16243. void TearDown() override {
  16244. svr_.stop();
  16245. if (thread_.joinable()) { thread_.join(); }
  16246. }
  16247. // Sends `req` and reads until the server closes the connection. Returns
  16248. // false if the read had to wait for the client-side timeout instead.
  16249. bool send_until_closed(const std::string &req, std::string *resp) const {
  16250. auto start = std::chrono::steady_clock::now();
  16251. if (!send_request(3, req, resp, port_)) { return false; }
  16252. auto elapsed = std::chrono::steady_clock::now() - start;
  16253. return elapsed < std::chrono::seconds(2);
  16254. }
  16255. // The final response comes without `100 Continue`, and the server closes
  16256. // the connection since the body may or may not follow.
  16257. void expect_final_without_interim(const std::string &path,
  16258. const char *status_line) const {
  16259. std::string resp;
  16260. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  16261. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  16262. EXPECT_EQ(0u, resp.find(status_line));
  16263. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16264. }
  16265. Server svr_;
  16266. int port_ = 0;
  16267. thread thread_;
  16268. };
  16269. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  16270. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  16271. }
  16272. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  16273. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  16274. }
  16275. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  16276. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  16277. }
  16278. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  16279. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  16280. }
  16281. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  16282. // The body follows once `100 Continue` has had time to arrive.
  16283. auto req = expect_headers_only("/reader-used");
  16284. req.insert(req.size() - 2, "Connection: close\r\n");
  16285. std::string resp;
  16286. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  16287. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  16288. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  16289. EXPECT_NE(std::string::npos, resp.find("hi"));
  16290. }
  16291. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  16292. // Large enough for the client to add `Expect: 100-continue` itself.
  16293. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  16294. std::atomic<bool> body_sent{false};
  16295. Client cli(HOST, port_);
  16296. auto res = cli.Post(
  16297. "/pre-request", length,
  16298. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  16299. body_sent = true;
  16300. std::string chunk(len, 'x');
  16301. sink.write(chunk.data(), chunk.size());
  16302. return true;
  16303. },
  16304. "application/octet-stream");
  16305. ASSERT_TRUE(res);
  16306. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16307. EXPECT_FALSE(body_sent);
  16308. }
  16309. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  16310. Server svr;
  16311. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  16312. return StatusCode::ExpectationFailed_417;
  16313. });
  16314. svr.Post("/p", [](const Request &, Response &res) {
  16315. res.set_content("ok", "text/plain");
  16316. });
  16317. auto port = svr.bind_to_any_port(HOST);
  16318. thread t = thread([&] { svr.listen_after_bind(); });
  16319. auto se = detail::scope_exit([&] {
  16320. svr.stop();
  16321. t.join();
  16322. });
  16323. svr.wait_until_ready();
  16324. std::string resp;
  16325. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  16326. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  16327. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16328. // Exactly one response: the route handler must not run after the 417.
  16329. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  16330. }
  16331. #ifndef _WIN32
  16332. TEST(Expect100ContinueTest, ServerClosesConnection) {
  16333. static constexpr char reject[] = "Unauthorized";
  16334. static constexpr char accept[] = "Upload accepted";
  16335. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  16336. Server svr;
  16337. svr.set_expect_100_continue_handler(
  16338. [](const Request & /*req*/, Response &res) {
  16339. res.status = StatusCode::Unauthorized_401;
  16340. res.set_content(reject, "text/plain");
  16341. return res.status;
  16342. });
  16343. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  16344. res.set_content(accept, "text/plain");
  16345. });
  16346. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16347. auto se = detail::scope_exit([&] {
  16348. svr.stop();
  16349. thread.join();
  16350. ASSERT_FALSE(svr.is_running());
  16351. });
  16352. svr.wait_until_ready();
  16353. {
  16354. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  16355. curl_easy_init(), &curl_easy_cleanup};
  16356. ASSERT_NE(curl, nullptr);
  16357. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  16358. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  16359. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  16360. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  16361. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  16362. &curl_slist_free_all};
  16363. ASSERT_NE(list, nullptr);
  16364. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  16365. struct read_data {
  16366. size_t read_size;
  16367. size_t total_size;
  16368. } data = {0, total_size};
  16369. using read_callback_t =
  16370. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16371. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  16372. void *userdata) -> size_t {
  16373. read_data *d = (read_data *)userdata;
  16374. if (!userdata || d->read_size >= d->total_size) { return 0; }
  16375. std::fill_n(ptr, size * nmemb, 'A');
  16376. d->read_size += size * nmemb;
  16377. return size * nmemb;
  16378. };
  16379. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  16380. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  16381. std::vector<char> buffer;
  16382. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  16383. using write_callback_t =
  16384. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16385. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  16386. void *userdata) -> size_t {
  16387. std::vector<char> *buf = (std::vector<char> *)userdata;
  16388. buf->reserve(buf->size() + size * nmemb + 1);
  16389. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  16390. return size * nmemb;
  16391. };
  16392. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  16393. {
  16394. const auto res = curl_easy_perform(curl.get());
  16395. ASSERT_EQ(res, CURLE_OK);
  16396. }
  16397. {
  16398. auto response_code = long{};
  16399. const auto res =
  16400. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  16401. ASSERT_EQ(res, CURLE_OK);
  16402. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  16403. }
  16404. {
  16405. auto dl = curl_off_t{};
  16406. const auto res =
  16407. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  16408. ASSERT_EQ(res, CURLE_OK);
  16409. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  16410. }
  16411. {
  16412. buffer.push_back('\0');
  16413. ASSERT_STRCASEEQ(buffer.data(), reject);
  16414. }
  16415. }
  16416. }
  16417. #endif
  16418. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  16419. // Regression test for #2458.
  16420. //
  16421. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  16422. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  16423. // ticket can make the client socket spuriously readable during the
  16424. // 100-continue wait. If the readiness is mistaken for an incoming response,
  16425. // the client withholds the body and then blocks reading a response that never
  16426. // comes, failing with `Failed to read connection`.
  16427. //
  16428. // A correct client (like curl) sends the body once no `100 Continue` arrives
  16429. // within the timeout. This raw OpenSSL server deliberately never sends
  16430. // `100 Continue`; the client must still deliver the body and receive 200.
  16431. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  16432. signal(SIGPIPE, SIG_IGN);
  16433. const auto port = PORT + 4;
  16434. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16435. ASSERT_NE(srv, INVALID_SOCKET);
  16436. int opt = 1;
  16437. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  16438. sockaddr_in addr{};
  16439. addr.sin_family = AF_INET;
  16440. addr.sin_port = htons(static_cast<uint16_t>(port));
  16441. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16442. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16443. ASSERT_EQ(0, ::listen(srv, 1));
  16444. std::atomic<size_t> server_body_bytes{0};
  16445. auto server_thread = std::thread([&] {
  16446. sockaddr_in cli_addr{};
  16447. socklen_t cli_len = sizeof(cli_addr);
  16448. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16449. if (cli == INVALID_SOCKET) { return; }
  16450. // Bound the lifetime of the server side so a buggy client (which never
  16451. // sends the body) cannot make this thread block forever on join.
  16452. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  16453. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  16454. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  16455. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  16456. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  16457. SSL *ssl = SSL_new(ctx);
  16458. SSL_set_fd(ssl, static_cast<int>(cli));
  16459. if (SSL_accept(ssl) > 0) {
  16460. // Read the request headers. Reading here also flushes the TLS 1.3
  16461. // session tickets to the client. Deliberately do NOT send
  16462. // `100 Continue`.
  16463. std::string buf;
  16464. char tmp[1024];
  16465. while (buf.find("\r\n\r\n") == std::string::npos) {
  16466. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16467. if (n <= 0) { break; }
  16468. buf.append(tmp, static_cast<size_t>(n));
  16469. }
  16470. // A correct client sends the body now; count what arrives.
  16471. auto pos = buf.find("\r\n\r\n");
  16472. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  16473. while (body < 4096) {
  16474. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16475. if (n <= 0) { break; }
  16476. body += static_cast<size_t>(n);
  16477. }
  16478. server_body_bytes = body;
  16479. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  16480. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  16481. SSL_shutdown(ssl);
  16482. }
  16483. SSL_free(ssl);
  16484. detail::close_socket(cli);
  16485. SSL_CTX_free(ctx);
  16486. });
  16487. auto se = detail::scope_exit([&] {
  16488. server_thread.join();
  16489. detail::close_socket(srv);
  16490. });
  16491. SSLClient cli("127.0.0.1", port);
  16492. cli.enable_server_certificate_verification(false);
  16493. cli.set_connection_timeout(5, 0);
  16494. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  16495. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  16496. std::string body(4096, 'A');
  16497. auto res = cli.Put("/api/test", body, "application/json");
  16498. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  16499. EXPECT_EQ(StatusCode::OK_200, res->status);
  16500. EXPECT_EQ(body.size(), server_body_bytes.load());
  16501. }
  16502. #endif
  16503. template <typename S, typename C>
  16504. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  16505. svr.Get("/stream", [&](const Request &, Response &res) {
  16506. auto data = new std::string("01234567890123456789");
  16507. res.set_content_provider(
  16508. data->size(), "text/plain",
  16509. [&, data](size_t offset, size_t length, DataSink &sink) {
  16510. const size_t DATA_CHUNK_SIZE = 4;
  16511. const auto &d = *data;
  16512. std::this_thread::sleep_for(std::chrono::seconds(1));
  16513. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  16514. return true;
  16515. },
  16516. [data](bool success) {
  16517. EXPECT_FALSE(success);
  16518. delete data;
  16519. });
  16520. });
  16521. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  16522. auto i = new size_t(0);
  16523. res.set_content_provider(
  16524. "text/plain",
  16525. [i](size_t, DataSink &sink) {
  16526. if (*i < 5) {
  16527. std::this_thread::sleep_for(std::chrono::seconds(1));
  16528. sink.write("abcd", 4);
  16529. (*i)++;
  16530. } else {
  16531. sink.done();
  16532. }
  16533. return true;
  16534. },
  16535. [i](bool success) {
  16536. EXPECT_FALSE(success);
  16537. delete i;
  16538. });
  16539. });
  16540. svr.Get("/chunked", [&](const Request &, Response &res) {
  16541. auto i = new size_t(0);
  16542. res.set_chunked_content_provider(
  16543. "text/plain",
  16544. [i](size_t, DataSink &sink) {
  16545. if (*i < 5) {
  16546. std::this_thread::sleep_for(std::chrono::seconds(1));
  16547. sink.os << "abcd";
  16548. (*i)++;
  16549. } else {
  16550. sink.done();
  16551. }
  16552. return true;
  16553. },
  16554. [i](bool success) {
  16555. EXPECT_FALSE(success);
  16556. delete i;
  16557. });
  16558. });
  16559. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16560. auto se = detail::scope_exit([&] {
  16561. svr.stop();
  16562. listen_thread.join();
  16563. ASSERT_FALSE(svr.is_running());
  16564. });
  16565. svr.wait_until_ready();
  16566. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  16567. {
  16568. auto start = std::chrono::steady_clock::now();
  16569. auto res = cli.Get("/stream");
  16570. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16571. std::chrono::steady_clock::now() - start)
  16572. .count();
  16573. ASSERT_FALSE(res);
  16574. EXPECT_EQ(Error::Read, res.error());
  16575. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16576. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16577. }
  16578. {
  16579. auto start = std::chrono::steady_clock::now();
  16580. auto res = cli.Get("/stream_without_length");
  16581. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16582. std::chrono::steady_clock::now() - start)
  16583. .count();
  16584. ASSERT_FALSE(res);
  16585. EXPECT_EQ(Error::Read, res.error());
  16586. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16587. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16588. }
  16589. {
  16590. auto start = std::chrono::steady_clock::now();
  16591. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  16592. EXPECT_EQ("abcd", string(data, data_length));
  16593. return true;
  16594. });
  16595. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16596. std::chrono::steady_clock::now() - start)
  16597. .count();
  16598. ASSERT_FALSE(res);
  16599. EXPECT_EQ(Error::Read, res.error());
  16600. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16601. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16602. }
  16603. }
  16604. TEST(MaxTimeoutTest, ContentStream) {
  16605. time_t timeout = 2000;
  16606. time_t threshold = 200;
  16607. Server svr;
  16608. Client cli("localhost", PORT);
  16609. max_timeout_test(svr, cli, timeout, threshold);
  16610. }
  16611. #ifdef CPPHTTPLIB_SSL_ENABLED
  16612. TEST(MaxTimeoutTest, ContentStreamSSL) {
  16613. time_t timeout = 2000;
  16614. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  16615. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16616. SSLClient cli("localhost", PORT);
  16617. cli.enable_server_certificate_verification(false);
  16618. max_timeout_test(svr, cli, timeout, threshold);
  16619. }
  16620. #endif
  16621. class EventDispatcher {
  16622. public:
  16623. EventDispatcher() {}
  16624. bool wait_event(DataSink *sink) {
  16625. unique_lock<mutex> lk(m_);
  16626. int id = id_;
  16627. // Wait with timeout to prevent hanging if client disconnects
  16628. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  16629. [&] { return cid_ == id; })) {
  16630. return false; // Timeout occurred
  16631. }
  16632. sink->write(message_.data(), message_.size());
  16633. return true;
  16634. }
  16635. void send_event(const string &message) {
  16636. lock_guard<mutex> lk(m_);
  16637. cid_ = id_++;
  16638. message_ = message;
  16639. cv_.notify_all();
  16640. }
  16641. private:
  16642. mutex m_;
  16643. condition_variable cv_;
  16644. atomic_int id_{0};
  16645. atomic_int cid_{-1};
  16646. string message_;
  16647. };
  16648. TEST(ClientInThreadTest, Issue2068) {
  16649. EventDispatcher ed;
  16650. Server svr;
  16651. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  16652. res.set_chunked_content_provider("text/event-stream",
  16653. [&](size_t /*offset*/, DataSink &sink) {
  16654. return ed.wait_event(&sink);
  16655. });
  16656. });
  16657. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  16658. svr.wait_until_ready();
  16659. thread event_thread([&] {
  16660. int id = 0;
  16661. while (svr.is_running()) {
  16662. this_thread::sleep_for(chrono::milliseconds(500));
  16663. std::stringstream ss;
  16664. ss << "data: " << id << "\n\n";
  16665. ed.send_event(ss.str());
  16666. id++;
  16667. }
  16668. });
  16669. auto se = detail::scope_exit([&] {
  16670. svr.stop();
  16671. listen_thread.join();
  16672. event_thread.join();
  16673. ASSERT_FALSE(svr.is_running());
  16674. });
  16675. {
  16676. auto client = detail::make_unique<Client>(HOST, PORT);
  16677. client->set_read_timeout(std::chrono::minutes(10));
  16678. std::atomic<bool> stop{false};
  16679. std::thread t([&] {
  16680. client->Get("/event1",
  16681. [&](const char *, size_t) -> bool { return !stop; });
  16682. });
  16683. std::this_thread::sleep_for(std::chrono::seconds(2));
  16684. stop = true;
  16685. client->stop();
  16686. t.join();
  16687. // Reset client after thread has finished
  16688. client.reset();
  16689. }
  16690. }
  16691. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  16692. auto handled = false;
  16693. Server svr;
  16694. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16695. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16696. auto se = detail::scope_exit([&] {
  16697. svr.stop();
  16698. t.join();
  16699. ASSERT_FALSE(svr.is_running());
  16700. ASSERT_FALSE(handled);
  16701. });
  16702. svr.wait_until_ready();
  16703. // Two Content-Length headers with different values — must be rejected
  16704. auto req = "POST /test HTTP/1.1\r\n"
  16705. "Content-Length: 5\r\n"
  16706. "Content-Length: 10\r\n"
  16707. "\r\n"
  16708. "hello";
  16709. std::string response;
  16710. ASSERT_TRUE(send_request(1, req, &response));
  16711. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16712. response.substr(0, response.find("\r\n")));
  16713. }
  16714. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  16715. auto handled = false;
  16716. Server svr;
  16717. svr.Post("/test", [&](const Request &, Response &res) {
  16718. handled = true;
  16719. res.set_content("ok", "text/plain");
  16720. });
  16721. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16722. auto se = detail::scope_exit([&] {
  16723. svr.stop();
  16724. t.join();
  16725. ASSERT_FALSE(svr.is_running());
  16726. ASSERT_TRUE(handled);
  16727. });
  16728. svr.wait_until_ready();
  16729. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  16730. auto req = "POST /test HTTP/1.1\r\n"
  16731. "Content-Length: 5\r\n"
  16732. "Content-Length: 5\r\n"
  16733. "\r\n"
  16734. "hello";
  16735. std::string response;
  16736. ASSERT_TRUE(send_request(1, req, &response));
  16737. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  16738. }
  16739. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  16740. Server svr;
  16741. svr.Get("/test", [](const Request &, Response &res) {
  16742. res.set_content("ok", "text/plain");
  16743. });
  16744. auto port = svr.bind_to_any_port(HOST);
  16745. thread t = thread([&] { svr.listen_after_bind(); });
  16746. auto se = detail::scope_exit([&] {
  16747. svr.stop();
  16748. t.join();
  16749. ASSERT_FALSE(svr.is_running());
  16750. });
  16751. svr.wait_until_ready();
  16752. auto status_line = [&](const std::string &host_lines) {
  16753. std::string res;
  16754. send_request(
  16755. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  16756. &res, port);
  16757. return res.substr(0, res.find("\r\n"));
  16758. };
  16759. const char *accepted[] = {
  16760. "Host: localhost\r\n",
  16761. "Host: a.example:8080\r\n",
  16762. "Host: my_service\r\n",
  16763. "Host: [::1]:8080\r\n",
  16764. "Host: [fe80::1%25eth0]\r\n",
  16765. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  16766. };
  16767. for (auto host_lines : accepted) {
  16768. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  16769. }
  16770. const char *rejected[] = {
  16771. "Host: a.example\r\nHost: b.example\r\n",
  16772. "Host: a.example\r\nHost: a.example\r\n",
  16773. "Host: a@b.example\r\n",
  16774. "Host: a.example/b\r\n",
  16775. "Host: a.example\\b\r\n",
  16776. "Host: a.example?b\r\n",
  16777. "Host: a.example#b\r\n",
  16778. "Host: a.example b.example\r\n",
  16779. };
  16780. for (auto host_lines : rejected) {
  16781. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  16782. << host_lines;
  16783. }
  16784. }
  16785. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  16786. Server svr;
  16787. svr.Get("/", [](const Request &req, Response &res) {
  16788. EXPECT_EQ(2U, req.trailers.size());
  16789. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  16790. // Denied
  16791. EXPECT_FALSE(req.has_trailer("Content-Length"));
  16792. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  16793. // Accepted
  16794. EXPECT_TRUE(req.has_trailer("X-Hello"));
  16795. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  16796. EXPECT_TRUE(req.has_trailer("X-World"));
  16797. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  16798. res.set_content("ok", "text/plain");
  16799. });
  16800. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16801. auto se = detail::scope_exit([&] {
  16802. svr.stop();
  16803. t.join();
  16804. ASSERT_FALSE(svr.is_running());
  16805. });
  16806. svr.wait_until_ready();
  16807. const std::string req = "GET / HTTP/1.1\r\n"
  16808. "Transfer-Encoding: chunked\r\n"
  16809. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  16810. "\r\n"
  16811. "0\r\n"
  16812. "Content-Length: 10\r\n"
  16813. "Host: internal.local\r\n"
  16814. "Content-Type: malicious/content\r\n"
  16815. "Cookie: any\r\n"
  16816. "Set-Cookie: any\r\n"
  16817. "X-Forwarded-For: attacker.com\r\n"
  16818. "X-Real-Ip: 1.1.1.1\r\n"
  16819. "X-Hello: hello\r\n"
  16820. "X-World: world\r\n"
  16821. "\r\n";
  16822. std::string res;
  16823. ASSERT_TRUE(send_request(1, req, &res));
  16824. }
  16825. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  16826. // several field lines, and the combined value is what has to be parsed. A
  16827. // Trailer field split across lines therefore declares every name it lists;
  16828. // reading only the first line silently drops the trailers the later lines
  16829. // declare. The prohibited-trailer filter still applies to every line.
  16830. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  16831. Server svr;
  16832. size_t observed_trailer_count = 0;
  16833. std::string observed_hello;
  16834. std::string observed_world;
  16835. bool observed_content_length = true;
  16836. svr.Get("/", [&](const Request &req, Response &res) {
  16837. observed_trailer_count = req.trailers.size();
  16838. observed_hello = req.get_trailer_value("X-Hello");
  16839. observed_world = req.get_trailer_value("X-World");
  16840. observed_content_length = req.has_trailer("Content-Length");
  16841. res.set_content("ok", "text/plain");
  16842. });
  16843. auto port = svr.bind_to_any_port(HOST);
  16844. thread t = thread([&]() { svr.listen_after_bind(); });
  16845. auto se = detail::scope_exit([&] {
  16846. svr.stop();
  16847. t.join();
  16848. ASSERT_FALSE(svr.is_running());
  16849. });
  16850. svr.wait_until_ready();
  16851. const std::string req = "GET / HTTP/1.1\r\n"
  16852. "Transfer-Encoding: chunked\r\n"
  16853. "Trailer: X-Hello\r\n"
  16854. "Trailer: X-World, Content-Length\r\n"
  16855. "\r\n"
  16856. "0\r\n"
  16857. "X-Hello: hello\r\n"
  16858. "X-World: world\r\n"
  16859. "Content-Length: 10\r\n"
  16860. "\r\n";
  16861. std::string res;
  16862. ASSERT_TRUE(send_request(1, req, &res, port));
  16863. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  16864. // Accepted: both field lines contribute to the declared set
  16865. EXPECT_EQ(2U, observed_trailer_count);
  16866. EXPECT_EQ(observed_hello, "hello");
  16867. EXPECT_EQ(observed_world, "world");
  16868. // Denied: a prohibited name stays prohibited on a later field line
  16869. EXPECT_FALSE(observed_content_length);
  16870. }
  16871. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  16872. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  16873. // unbounded run of fields that are never declared, because the counter would
  16874. // only advance for declared fields.
  16875. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  16876. Server svr;
  16877. bool handler_called = false;
  16878. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  16879. handler_called = true;
  16880. res.set_content("ok", "text/plain");
  16881. });
  16882. auto port = svr.bind_to_any_port(HOST);
  16883. thread t = thread([&]() { svr.listen_after_bind(); });
  16884. auto se = detail::scope_exit([&] {
  16885. svr.stop();
  16886. t.join();
  16887. ASSERT_FALSE(svr.is_running());
  16888. });
  16889. svr.wait_until_ready();
  16890. // Declare nothing, then send far more undeclared trailer fields than the
  16891. // header-count limit. Parsing must stop and reject the request rather than
  16892. // read every line.
  16893. std::string req = "GET / HTTP/1.1\r\n"
  16894. "Transfer-Encoding: chunked\r\n"
  16895. "\r\n"
  16896. "0\r\n";
  16897. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  16898. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  16899. }
  16900. req += "\r\n";
  16901. std::string res;
  16902. ASSERT_TRUE(send_request(1, req, &res, port));
  16903. // The request is rejected before the handler runs.
  16904. EXPECT_FALSE(handler_called);
  16905. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  16906. }
  16907. // The set of declared trailer names is capped so a peer cannot grow it without
  16908. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  16909. // declared past the cap is not honored, even if the field is actually sent.
  16910. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  16911. Server svr;
  16912. // One name inside the cap and one past it, so the test tracks the cap rather
  16913. // than a fixed count.
  16914. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  16915. const std::string within_cap_name = "X-T-0";
  16916. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  16917. bool observed_within_cap = false;
  16918. bool observed_past_cap = false;
  16919. svr.Get("/", [&](const Request &req, Response &res) {
  16920. observed_within_cap = req.has_trailer(within_cap_name);
  16921. observed_past_cap = req.has_trailer(past_cap_name);
  16922. res.set_content("ok", "text/plain");
  16923. });
  16924. auto port = svr.bind_to_any_port(HOST);
  16925. thread t = thread([&]() { svr.listen_after_bind(); });
  16926. auto se = detail::scope_exit([&] {
  16927. svr.stop();
  16928. t.join();
  16929. ASSERT_FALSE(svr.is_running());
  16930. });
  16931. svr.wait_until_ready();
  16932. // Declare more trailer names than the cap in a single Trailer field, then
  16933. // actually send the first (within the cap) and the last (past it).
  16934. std::string trailer_decl = "Trailer: ";
  16935. for (int i = 0; i < declared_count; i++) {
  16936. if (i != 0) { trailer_decl += ", "; }
  16937. trailer_decl += "X-T-" + std::to_string(i);
  16938. }
  16939. trailer_decl += "\r\n";
  16940. const std::string req = "GET / HTTP/1.1\r\n"
  16941. "Transfer-Encoding: chunked\r\n" +
  16942. trailer_decl +
  16943. "\r\n"
  16944. "0\r\n" +
  16945. within_cap_name + ": a\r\n" + past_cap_name +
  16946. ": b\r\n"
  16947. "\r\n";
  16948. std::string res;
  16949. ASSERT_TRUE(send_request(1, req, &res, port));
  16950. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  16951. // A name within the cap is honored; one declared past the cap is dropped.
  16952. EXPECT_TRUE(observed_within_cap);
  16953. EXPECT_FALSE(observed_past_cap);
  16954. }
  16955. // A direct client that is not listed in trusted_proxies must not be able to
  16956. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  16957. // the peer address on the actual TCP connection determines whether the
  16958. // header is honored.
  16959. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  16960. Server svr;
  16961. // Deliberately does NOT include the loopback address the test client
  16962. // actually connects from, so the direct connection is not a trusted proxy.
  16963. svr.set_trusted_proxies({"203.0.113.66"});
  16964. std::string observed_remote_addr;
  16965. svr.Get("/ip", [&](const Request &req, Response &res) {
  16966. observed_remote_addr = req.remote_addr;
  16967. res.set_content("ok", "text/plain");
  16968. });
  16969. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16970. auto se = detail::scope_exit([&] {
  16971. svr.stop();
  16972. t.join();
  16973. ASSERT_FALSE(svr.is_running());
  16974. });
  16975. svr.wait_until_ready();
  16976. Client cli(HOST, PORT);
  16977. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  16978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16979. EXPECT_EQ(StatusCode::OK_200, res->status);
  16980. // The connecting peer is not a trusted proxy, so the spoofed header must be
  16981. // ignored entirely and the real connection-level address retained.
  16982. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16983. observed_remote_addr == "127.0.0.1");
  16984. }
  16985. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  16986. Server svr;
  16987. std::string observed_remote_addr;
  16988. std::string observed_xff;
  16989. svr.Get("/ip", [&](const Request &req, Response &res) {
  16990. observed_remote_addr = req.remote_addr;
  16991. observed_xff = req.get_header_value("X-Forwarded-For");
  16992. res.set_content("ok", "text/plain");
  16993. });
  16994. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16995. auto se = detail::scope_exit([&] {
  16996. svr.stop();
  16997. t.join();
  16998. ASSERT_FALSE(svr.is_running());
  16999. });
  17000. svr.wait_until_ready();
  17001. Client cli(HOST, PORT);
  17002. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  17003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17004. EXPECT_EQ(StatusCode::OK_200, res->status);
  17005. EXPECT_EQ(observed_xff, "203.0.113.66");
  17006. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17007. observed_remote_addr == "127.0.0.1");
  17008. }
  17009. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  17010. Server svr;
  17011. svr.set_trusted_proxies({"203.0.113.66"});
  17012. std::string observed_remote_addr;
  17013. std::string observed_xff;
  17014. svr.Get("/ip", [&](const Request &req, Response &res) {
  17015. observed_remote_addr = req.remote_addr;
  17016. observed_xff = req.get_header_value("X-Forwarded-For");
  17017. res.set_content("ok", "text/plain");
  17018. });
  17019. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17020. auto se = detail::scope_exit([&] {
  17021. svr.stop();
  17022. t.join();
  17023. ASSERT_FALSE(svr.is_running());
  17024. });
  17025. svr.wait_until_ready();
  17026. Client cli(HOST, PORT);
  17027. auto res = cli.Get("/ip");
  17028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17029. EXPECT_EQ(StatusCode::OK_200, res->status);
  17030. EXPECT_EQ(observed_xff, "");
  17031. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17032. observed_remote_addr == "127.0.0.1");
  17033. }
  17034. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  17035. Server svr;
  17036. // Include the loopback address the test client actually connects from, so
  17037. // the direct connection itself is recognized as the trusted proxy hop.
  17038. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  17039. std::string observed_remote_addr;
  17040. std::string observed_xff;
  17041. svr.Get("/ip", [&](const Request &req, Response &res) {
  17042. observed_remote_addr = req.remote_addr;
  17043. observed_xff = req.get_header_value("X-Forwarded-For");
  17044. res.set_content("ok", "text/plain");
  17045. });
  17046. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17047. auto se = detail::scope_exit([&] {
  17048. svr.stop();
  17049. t.join();
  17050. ASSERT_FALSE(svr.is_running());
  17051. });
  17052. svr.wait_until_ready();
  17053. Client cli(HOST, PORT);
  17054. auto res = cli.Get(
  17055. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  17056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17057. EXPECT_EQ(StatusCode::OK_200, res->status);
  17058. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  17059. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17060. }
  17061. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  17062. Server svr;
  17063. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  17064. std::string observed_remote_addr;
  17065. std::string observed_xff;
  17066. svr.Get("/ip", [&](const Request &req, Response &res) {
  17067. observed_remote_addr = req.remote_addr;
  17068. observed_xff = req.get_header_value("X-Forwarded-For");
  17069. res.set_content("ok", "text/plain");
  17070. });
  17071. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17072. auto se = detail::scope_exit([&] {
  17073. svr.stop();
  17074. t.join();
  17075. ASSERT_FALSE(svr.is_running());
  17076. });
  17077. svr.wait_until_ready();
  17078. Client cli(HOST, PORT);
  17079. auto res = cli.Get(
  17080. "/ip",
  17081. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17083. EXPECT_EQ(StatusCode::OK_200, res->status);
  17084. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17085. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17086. }
  17087. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  17088. Server svr;
  17089. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17090. std::string observed_remote_addr;
  17091. std::string observed_xff;
  17092. svr.Get("/ip", [&](const Request &req, Response &res) {
  17093. observed_remote_addr = req.remote_addr;
  17094. observed_xff = req.get_header_value("X-Forwarded-For");
  17095. res.set_content("ok", "text/plain");
  17096. });
  17097. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17098. auto se = detail::scope_exit([&] {
  17099. svr.stop();
  17100. t.join();
  17101. ASSERT_FALSE(svr.is_running());
  17102. });
  17103. svr.wait_until_ready();
  17104. Client cli(HOST, PORT);
  17105. auto res = cli.Get(
  17106. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  17107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17108. EXPECT_EQ(StatusCode::OK_200, res->status);
  17109. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  17110. // by the closest hop) is used. The leftmost entry is fully client-controlled
  17111. // and must not be selected.
  17112. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  17113. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  17114. }
  17115. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  17116. Server svr;
  17117. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  17118. std::string observed_remote_addr;
  17119. svr.Get("/ip", [&](const Request &req, Response &res) {
  17120. observed_remote_addr = req.remote_addr;
  17121. res.set_content("ok", "text/plain");
  17122. });
  17123. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17124. auto se = detail::scope_exit([&] {
  17125. svr.stop();
  17126. t.join();
  17127. ASSERT_FALSE(svr.is_running());
  17128. });
  17129. svr.wait_until_ready();
  17130. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  17131. // a forged address and the trusted proxy's own address; the forged value must
  17132. // not win over the address the trusted proxy actually recorded.
  17133. Client cli(HOST, PORT);
  17134. auto res = cli.Get(
  17135. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  17136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17137. EXPECT_EQ(StatusCode::OK_200, res->status);
  17138. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  17139. }
  17140. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  17141. Server svr;
  17142. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17143. std::string observed_remote_addr;
  17144. std::string observed_xff;
  17145. svr.Get("/ip", [&](const Request &req, Response &res) {
  17146. observed_remote_addr = req.remote_addr;
  17147. observed_xff = req.get_header_value("X-Forwarded-For");
  17148. res.set_content("ok", "text/plain");
  17149. });
  17150. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17151. auto se = detail::scope_exit([&] {
  17152. svr.stop();
  17153. t.join();
  17154. ASSERT_FALSE(svr.is_running());
  17155. });
  17156. svr.wait_until_ready();
  17157. Client cli(HOST, PORT);
  17158. auto res = cli.Get(
  17159. "/ip",
  17160. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17162. EXPECT_EQ(StatusCode::OK_200, res->status);
  17163. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17164. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17165. }
  17166. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  17167. Server svr;
  17168. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17169. std::string observed_remote_addr;
  17170. std::string observed_xff;
  17171. svr.Get("/ip", [&](const Request &req, Response &res) {
  17172. observed_remote_addr = req.remote_addr;
  17173. observed_xff = req.get_header_value("X-Forwarded-For");
  17174. res.set_content("ok", "text/plain");
  17175. });
  17176. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17177. auto se = detail::scope_exit([&] {
  17178. svr.stop();
  17179. t.join();
  17180. ASSERT_FALSE(svr.is_running());
  17181. });
  17182. svr.wait_until_ready();
  17183. std::string raw_req =
  17184. "GET /ip HTTP/1.1\r\n"
  17185. "Host: localhost\r\n"
  17186. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  17187. "Connection: close\r\n"
  17188. "\r\n";
  17189. std::string out;
  17190. ASSERT_TRUE(send_request(5, raw_req, &out));
  17191. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17192. // Header parser trims surrounding whitespace of the header value
  17193. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  17194. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17195. }
  17196. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  17197. // one comma-joined value, in the order received. Proxies such as HAProxy append
  17198. // their own X-Forwarded-For as a separate field line rather than extending the
  17199. // one the client sent, so every occurrence has to be taken into account.
  17200. // Reading only the first one hands back the address the client chose.
  17201. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  17202. Server svr;
  17203. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17204. std::string observed_remote_addr;
  17205. size_t observed_xff_count = 0;
  17206. svr.Get("/ip", [&](const Request &req, Response &res) {
  17207. observed_remote_addr = req.remote_addr;
  17208. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  17209. res.set_content("ok", "text/plain");
  17210. });
  17211. auto port = svr.bind_to_any_port(HOST);
  17212. thread t = thread([&]() { svr.listen_after_bind(); });
  17213. auto se = detail::scope_exit([&] {
  17214. svr.stop();
  17215. t.join();
  17216. ASSERT_FALSE(svr.is_running());
  17217. });
  17218. svr.wait_until_ready();
  17219. // The client supplies the first field line; the trusted proxy appends the
  17220. // address it observed as a second one.
  17221. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  17222. "Host: localhost\r\n"
  17223. "X-Forwarded-For: 1.2.3.4\r\n"
  17224. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  17225. "Connection: close\r\n"
  17226. "\r\n";
  17227. std::string out;
  17228. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17229. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17230. EXPECT_EQ(observed_xff_count, 2U);
  17231. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17232. // The same chain spread over one field line per hop derives the same client
  17233. // address, i.e. the split and the comma-joined representations agree.
  17234. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  17235. "Host: localhost\r\n"
  17236. "X-Forwarded-For: 1.2.3.4\r\n"
  17237. "X-Forwarded-For: 198.51.100.23\r\n"
  17238. "X-Forwarded-For: 192.0.2.45\r\n"
  17239. "Connection: close\r\n"
  17240. "\r\n";
  17241. out.clear();
  17242. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  17243. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17244. EXPECT_EQ(observed_xff_count, 3U);
  17245. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17246. }
  17247. // An X-Forwarded-For header whose value parses to zero IP segments must not
  17248. // crash the server (it used to call front() on an empty vector inside
  17249. // get_client_ip). The connection-level remote address must be retained instead.
  17250. static void run_malformed_xff_test(const std::string &xff_value) {
  17251. Server svr;
  17252. svr.set_trusted_proxies({"192.0.2.45"});
  17253. std::string observed_remote_addr;
  17254. svr.Get("/ip", [&](const Request &req, Response &res) {
  17255. observed_remote_addr = req.remote_addr;
  17256. res.set_content("ok", "text/plain");
  17257. });
  17258. int port = 0;
  17259. thread t = thread([&]() {
  17260. port = svr.bind_to_any_port(HOST);
  17261. svr.listen_after_bind();
  17262. });
  17263. auto se = detail::scope_exit([&] {
  17264. svr.stop();
  17265. t.join();
  17266. ASSERT_FALSE(svr.is_running());
  17267. });
  17268. svr.wait_until_ready();
  17269. Client cli(HOST, port);
  17270. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  17271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17272. EXPECT_EQ(StatusCode::OK_200, res->status);
  17273. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17274. observed_remote_addr == "127.0.0.1");
  17275. }
  17276. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  17277. run_malformed_xff_test("");
  17278. }
  17279. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  17280. run_malformed_xff_test(",");
  17281. }
  17282. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  17283. run_malformed_xff_test(", , ,");
  17284. }
  17285. // The same rule applies to Accept: a request whose acceptable types are spread
  17286. // over several field lines must be negotiated against all of them.
  17287. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  17288. // case-insensitive connection options. Comparing the whole field value against
  17289. // one option misses a client that sends several of them, and misses every
  17290. // casing but the one written in the comparison.
  17291. //
  17292. // Sends req, reads the response, then reuses the same socket for a second
  17293. // request to find out whether the server kept the connection.
  17294. static void probe_connection_reuse(int port, const std::string &req,
  17295. bool *announced_close, bool *reusable) {
  17296. auto error = Error::Success;
  17297. auto sock = detail::create_client_socket(
  17298. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17299. /*connection_timeout_sec=*/5, 0,
  17300. /*read_timeout_sec=*/1, 0,
  17301. /*write_timeout_sec=*/5, 0, std::string(), error);
  17302. ASSERT_NE(sock, INVALID_SOCKET);
  17303. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  17304. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  17305. "Host: localhost\r\n"
  17306. "Connection: close\r\n"
  17307. "\r\n";
  17308. std::string first_response;
  17309. std::string second_response;
  17310. detail::process_client_socket(
  17311. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  17312. [&](Stream &strm) {
  17313. if (strm.write(req.data(), req.size()) !=
  17314. static_cast<ssize_t>(req.size())) {
  17315. return false;
  17316. }
  17317. char buf[512];
  17318. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  17319. // Headers plus the two-byte body of the handler below
  17320. while (reader.getline()) {
  17321. first_response += reader.ptr();
  17322. if (first_response.find("ok") != std::string::npos) { break; }
  17323. }
  17324. if (strm.write(second.data(), second.size()) !=
  17325. static_cast<ssize_t>(second.size())) {
  17326. return true;
  17327. }
  17328. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  17329. while (reader2.getline()) {
  17330. second_response += reader2.ptr();
  17331. if (second_response.find("ok") != std::string::npos) { break; }
  17332. }
  17333. return true;
  17334. });
  17335. *announced_close =
  17336. first_response.find("Connection: close") != std::string::npos;
  17337. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  17338. }
  17339. class ConnectionTokenTest : public ::testing::Test {
  17340. protected:
  17341. void SetUp() override {
  17342. svr_.Get("/keepalive", [](const Request &, Response &res) {
  17343. res.set_content("ok", "text/plain");
  17344. });
  17345. port_ = svr_.bind_to_any_port(HOST);
  17346. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17347. svr_.wait_until_ready();
  17348. }
  17349. void TearDown() override {
  17350. svr_.stop();
  17351. if (thread_.joinable()) { thread_.join(); }
  17352. }
  17353. Server svr_;
  17354. int port_ = 0;
  17355. thread thread_;
  17356. };
  17357. // "close" alongside another option still closes the connection, and the
  17358. // response says so rather than leaving the peer to discover it.
  17359. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  17360. bool announced_close = false;
  17361. bool reusable = true;
  17362. probe_connection_reuse(port_,
  17363. "GET /keepalive HTTP/1.1\r\n"
  17364. "Host: localhost\r\n"
  17365. "Connection: keep-alive, close\r\n"
  17366. "\r\n",
  17367. &announced_close, &reusable);
  17368. EXPECT_TRUE(announced_close);
  17369. EXPECT_FALSE(reusable);
  17370. }
  17371. // "close" split over two field lines is the same list, so it is honored too.
  17372. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  17373. bool announced_close = false;
  17374. bool reusable = true;
  17375. probe_connection_reuse(port_,
  17376. "GET /keepalive HTTP/1.1\r\n"
  17377. "Host: localhost\r\n"
  17378. "Connection: keep-alive\r\n"
  17379. "Connection: close\r\n"
  17380. "\r\n",
  17381. &announced_close, &reusable);
  17382. EXPECT_TRUE(announced_close);
  17383. EXPECT_FALSE(reusable);
  17384. }
  17385. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  17386. // keep-alive in the spelling everyone actually sends keeps its connection.
  17387. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  17388. bool announced_close = false;
  17389. bool reusable = false;
  17390. probe_connection_reuse(port_,
  17391. "GET /keepalive HTTP/1.0\r\n"
  17392. "Host: localhost\r\n"
  17393. "Connection: keep-alive\r\n"
  17394. "\r\n",
  17395. &announced_close, &reusable);
  17396. EXPECT_FALSE(announced_close);
  17397. EXPECT_TRUE(reusable);
  17398. }
  17399. // A token the value merely contains is not the token itself.
  17400. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  17401. bool announced_close = false;
  17402. bool reusable = false;
  17403. probe_connection_reuse(port_,
  17404. "GET /keepalive HTTP/1.1\r\n"
  17405. "Host: localhost\r\n"
  17406. "Connection: notclose\r\n"
  17407. "\r\n",
  17408. &announced_close, &reusable);
  17409. EXPECT_FALSE(announced_close);
  17410. EXPECT_TRUE(reusable);
  17411. }
  17412. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  17413. Server svr;
  17414. std::vector<std::string> observed_types;
  17415. svr.Get("/", [&](const Request &req, Response &res) {
  17416. observed_types = req.accept_content_types;
  17417. res.set_content("ok", "text/plain");
  17418. });
  17419. auto port = svr.bind_to_any_port(HOST);
  17420. thread t = thread([&]() { svr.listen_after_bind(); });
  17421. auto se = detail::scope_exit([&] {
  17422. svr.stop();
  17423. t.join();
  17424. ASSERT_FALSE(svr.is_running());
  17425. });
  17426. svr.wait_until_ready();
  17427. Client cli(HOST, port);
  17428. Headers headers;
  17429. headers.emplace("Accept", "text/plain;q=0.5");
  17430. headers.emplace("Accept", "application/json");
  17431. auto res = cli.Get("/", headers);
  17432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17433. EXPECT_EQ(StatusCode::OK_200, res->status);
  17434. // Sorted by q-value, so the second field line's type comes first
  17435. ASSERT_EQ(2U, observed_types.size());
  17436. EXPECT_EQ("application/json", observed_types[0]);
  17437. EXPECT_EQ("text/plain", observed_types[1]);
  17438. }
  17439. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  17440. // empty field line must not contribute a bare comma to the combined value.
  17441. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  17442. Server svr;
  17443. std::vector<std::string> observed_types;
  17444. svr.Get("/", [&](const Request &req, Response &res) {
  17445. observed_types = req.accept_content_types;
  17446. res.set_content("ok", "text/plain");
  17447. });
  17448. auto port = svr.bind_to_any_port(HOST);
  17449. thread t = thread([&]() { svr.listen_after_bind(); });
  17450. auto se = detail::scope_exit([&] {
  17451. svr.stop();
  17452. t.join();
  17453. ASSERT_FALSE(svr.is_running());
  17454. });
  17455. svr.wait_until_ready();
  17456. // Empty first field line, then a real one
  17457. std::string raw_req = "GET / HTTP/1.1\r\n"
  17458. "Host: localhost\r\n"
  17459. "Accept:\r\n"
  17460. "Accept: application/json\r\n"
  17461. "Connection: close\r\n"
  17462. "\r\n";
  17463. std::string out;
  17464. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17465. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17466. ASSERT_EQ(1U, observed_types.size());
  17467. EXPECT_EQ("application/json", observed_types[0]);
  17468. }
  17469. // The skip in get_combined_header_value() is what keeps an empty field line
  17470. // from contributing a bare comma. Only a trailing empty field line exercises
  17471. // it: a leading one is already covered by the "combined is still empty" check,
  17472. // and parse_accept_header() now ignores the empty element either way, so the
  17473. // request-level test above can no longer tell the two apart.
  17474. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  17475. Headers headers;
  17476. headers.emplace("Accept", "text/html");
  17477. headers.emplace("Accept", "");
  17478. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  17479. headers.clear();
  17480. headers.emplace("Accept", "");
  17481. headers.emplace("Accept", "application/json");
  17482. EXPECT_EQ("application/json",
  17483. detail::get_combined_header_value(headers, "Accept"));
  17484. }
  17485. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17486. // An encoding offered on a later Accept-Encoding field line is still offered.
  17487. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  17488. Server svr;
  17489. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17490. res.set_content(std::string(1024, 'x'), "text/plain");
  17491. });
  17492. auto port = svr.bind_to_any_port(HOST);
  17493. thread t = thread([&]() { svr.listen_after_bind(); });
  17494. auto se = detail::scope_exit([&] {
  17495. svr.stop();
  17496. t.join();
  17497. ASSERT_FALSE(svr.is_running());
  17498. });
  17499. svr.wait_until_ready();
  17500. Client cli(HOST, port);
  17501. cli.set_decompress(false);
  17502. Headers headers;
  17503. headers.emplace("Accept-Encoding", "identity");
  17504. headers.emplace("Accept-Encoding", "gzip");
  17505. auto res = cli.Get("/", headers);
  17506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17507. EXPECT_EQ(StatusCode::OK_200, res->status);
  17508. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  17509. }
  17510. #endif
  17511. #ifndef _WIN32
  17512. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  17513. Server svr;
  17514. svr.Post("/post", [&](const Request &req, Response &res) {
  17515. res.set_content(req.body, "text/plain");
  17516. });
  17517. svr.Put("/put", [&](const Request &req, Response &res) {
  17518. res.set_content(req.body, "text/plain");
  17519. });
  17520. svr.Patch("/patch", [&](const Request &req, Response &res) {
  17521. res.set_content(req.body, "text/plain");
  17522. });
  17523. svr.Delete("/delete", [&](const Request &req, Response &res) {
  17524. res.set_content(req.body, "text/plain");
  17525. });
  17526. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17527. auto se = detail::scope_exit([&] {
  17528. svr.stop();
  17529. t.join();
  17530. ASSERT_FALSE(svr.is_running());
  17531. });
  17532. svr.wait_until_ready();
  17533. std::string resp;
  17534. // POST without Content-Length
  17535. ASSERT_TRUE(send_request(5,
  17536. "POST /post HTTP/1.1\r\n"
  17537. "Host: localhost\r\n"
  17538. "Connection: close\r\n"
  17539. "\r\n",
  17540. &resp));
  17541. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17542. // PUT without Content-Length
  17543. resp.clear();
  17544. ASSERT_TRUE(send_request(5,
  17545. "PUT /put HTTP/1.1\r\n"
  17546. "Host: localhost\r\n"
  17547. "Connection: close\r\n"
  17548. "\r\n",
  17549. &resp));
  17550. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17551. // PATCH without Content-Length
  17552. resp.clear();
  17553. ASSERT_TRUE(send_request(5,
  17554. "PATCH /patch HTTP/1.1\r\n"
  17555. "Host: localhost\r\n"
  17556. "Connection: close\r\n"
  17557. "\r\n",
  17558. &resp));
  17559. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17560. // DELETE without Content-Length
  17561. resp.clear();
  17562. ASSERT_TRUE(send_request(5,
  17563. "DELETE /delete HTTP/1.1\r\n"
  17564. "Host: localhost\r\n"
  17565. "Connection: close\r\n"
  17566. "\r\n",
  17567. &resp));
  17568. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17569. }
  17570. #endif
  17571. //==============================================================================
  17572. // open_stream() Tests
  17573. //==============================================================================
  17574. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  17575. std::string result;
  17576. char buf[8192];
  17577. ssize_t n;
  17578. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17579. result.append(buf, static_cast<size_t>(n));
  17580. }
  17581. return result;
  17582. }
  17583. // Mock stream for unit tests
  17584. class MockStream : public Stream {
  17585. public:
  17586. std::string data;
  17587. size_t pos = 0;
  17588. ssize_t error_after = -1; // -1 = no error
  17589. explicit MockStream(const std::string &d, ssize_t err = -1)
  17590. : data(d), error_after(err) {}
  17591. bool is_readable() const override { return true; }
  17592. bool wait_readable() const override { return true; }
  17593. bool wait_writable() const override { return true; }
  17594. ssize_t read(char *ptr, size_t size) override {
  17595. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  17596. if (pos >= data.size()) return 0;
  17597. size_t limit =
  17598. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  17599. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  17600. std::memcpy(ptr, data.data() + pos, to_read);
  17601. pos += to_read;
  17602. return static_cast<ssize_t>(to_read);
  17603. }
  17604. ssize_t write(const char *, size_t) override { return -1; }
  17605. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  17606. ip = "127.0.0.1";
  17607. port = 0;
  17608. }
  17609. void get_local_ip_and_port(std::string &ip, int &port) const override {
  17610. ip = "127.0.0.1";
  17611. port = 0;
  17612. }
  17613. socket_t socket() const override { return INVALID_SOCKET; }
  17614. time_t duration() const override { return 0; }
  17615. };
  17616. TEST(StreamHandleTest, Basic) {
  17617. ClientImpl::StreamHandle handle;
  17618. EXPECT_FALSE(handle.is_valid());
  17619. handle.response = detail::make_unique<Response>();
  17620. handle.error = Error::Connection;
  17621. EXPECT_FALSE(handle.is_valid());
  17622. handle.error = Error::Success;
  17623. EXPECT_TRUE(handle.is_valid());
  17624. }
  17625. TEST(BodyReaderTest, Basic) {
  17626. MockStream stream("Hello, World!");
  17627. detail::BodyReader reader;
  17628. reader.stream = &stream;
  17629. reader.content_length = 13;
  17630. char buf[32];
  17631. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  17632. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  17633. EXPECT_TRUE(reader.eof);
  17634. }
  17635. TEST(BodyReaderTest, NoStream) {
  17636. detail::BodyReader reader;
  17637. char buf[32];
  17638. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  17639. EXPECT_EQ(Error::Connection, reader.last_error);
  17640. }
  17641. TEST(BodyReaderTest, Error) {
  17642. MockStream stream("Hello, World!", 5);
  17643. detail::BodyReader reader;
  17644. reader.stream = &stream;
  17645. reader.content_length = 13;
  17646. char buf[32];
  17647. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  17648. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  17649. EXPECT_EQ(Error::Read, reader.last_error);
  17650. }
  17651. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  17652. // Mock-based StreamHandle tests relying on private internals are removed.
  17653. class OpenStreamTest : public ::testing::Test {
  17654. protected:
  17655. void SetUp() override {
  17656. svr_.Get("/hello", [](const Request &, Response &res) {
  17657. res.set_content("Hello World!", "text/plain");
  17658. });
  17659. svr_.Get("/large", [](const Request &, Response &res) {
  17660. res.set_content(std::string(10000, 'X'), "text/plain");
  17661. });
  17662. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  17663. res.set_content("Hello World!", "image/jpeg");
  17664. res.set_header("Content-Encoding", "UTF-8");
  17665. });
  17666. svr_.Get("/chunked", [](const Request &, Response &res) {
  17667. res.set_chunked_content_provider("text/plain",
  17668. [](size_t offset, DataSink &sink) {
  17669. if (offset < 15) {
  17670. sink.write("chunk", 5);
  17671. return true;
  17672. }
  17673. sink.done();
  17674. return true;
  17675. });
  17676. });
  17677. svr_.Get("/compressible", [](const Request &, Response &res) {
  17678. res.set_chunked_content_provider("text/plain", [](size_t offset,
  17679. DataSink &sink) {
  17680. if (offset < 100 * 1024) {
  17681. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  17682. sink.write(chunk.data(), chunk.size());
  17683. return true;
  17684. }
  17685. sink.done();
  17686. return true;
  17687. });
  17688. });
  17689. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  17690. [](const Request & /*req*/, Response &res) {
  17691. auto i = new int(0);
  17692. res.set_header("Trailer", "Content-Length, X-Allowed");
  17693. res.set_chunked_content_provider(
  17694. "text/plain",
  17695. [i](size_t /*offset*/, DataSink &sink) {
  17696. switch (*i) {
  17697. case 0: sink.os << "123"; break;
  17698. case 1: sink.os << "456"; break;
  17699. case 2: sink.os << "789"; break;
  17700. case 3: {
  17701. sink.done_with_trailer(
  17702. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  17703. } break;
  17704. }
  17705. (*i)++;
  17706. return true;
  17707. },
  17708. [i](bool success) {
  17709. EXPECT_TRUE(success);
  17710. delete i;
  17711. });
  17712. });
  17713. // Echo headers endpoint for header-related tests
  17714. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  17715. std::string body;
  17716. for (const auto &h : req.headers) {
  17717. body.append(h.first);
  17718. body.push_back(':');
  17719. body.append(h.second);
  17720. body.push_back('\n');
  17721. }
  17722. res.set_content(body, "text/plain");
  17723. });
  17724. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  17725. std::string body;
  17726. for (const auto &h : req.headers) {
  17727. body.append(h.first);
  17728. body.push_back(':');
  17729. body.append(h.second);
  17730. body.push_back('\n');
  17731. }
  17732. res.set_content(body, "text/plain");
  17733. });
  17734. port_ = svr_.bind_to_any_port("127.0.0.1");
  17735. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17736. svr_.wait_until_ready();
  17737. }
  17738. void TearDown() override {
  17739. svr_.stop();
  17740. if (thread_.joinable()) thread_.join();
  17741. }
  17742. Server svr_;
  17743. std::thread thread_;
  17744. int port_ = 0;
  17745. };
  17746. TEST_F(OpenStreamTest, Basic) {
  17747. Client cli("127.0.0.1", port_);
  17748. auto handle = cli.open_stream("GET", "/hello");
  17749. EXPECT_TRUE(handle.is_valid());
  17750. EXPECT_EQ("Hello World!", read_all(handle));
  17751. }
  17752. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  17753. Client cli("127.0.0.1", port_);
  17754. auto handle = cli.open_stream("GET", "/unknown-encoding");
  17755. ASSERT_TRUE(handle.is_valid());
  17756. EXPECT_EQ("Hello World!", read_all(handle));
  17757. }
  17758. TEST_F(OpenStreamTest, SmallBuffer) {
  17759. Client cli("127.0.0.1", port_);
  17760. auto handle = cli.open_stream("GET", "/hello");
  17761. std::string result;
  17762. char buf[4];
  17763. ssize_t n;
  17764. while ((n = handle.read(buf, sizeof(buf))) > 0)
  17765. result.append(buf, static_cast<size_t>(n));
  17766. EXPECT_EQ("Hello World!", result);
  17767. }
  17768. TEST_F(OpenStreamTest, DefaultHeaders) {
  17769. Client cli("127.0.0.1", port_);
  17770. // open_stream GET should include Host, User-Agent and Accept-Encoding
  17771. {
  17772. auto handle = cli.open_stream("GET", "/echo-headers");
  17773. ASSERT_TRUE(handle.is_valid());
  17774. auto body = read_all(handle);
  17775. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  17776. std::string::npos);
  17777. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  17778. std::string::npos);
  17779. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  17780. }
  17781. // open_stream POST with body and no explicit content_type should NOT add
  17782. // text/plain Content-Type (behavior differs from non-streaming path), but
  17783. // should include Content-Length
  17784. {
  17785. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  17786. ASSERT_TRUE(handle.is_valid());
  17787. auto body = read_all(handle);
  17788. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  17789. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  17790. }
  17791. // open_stream POST with explicit Content-Type should preserve it
  17792. {
  17793. auto handle = cli.open_stream("POST", "/echo-headers", {},
  17794. {{"Content-Type", "application/custom"}},
  17795. "{}", "application/custom");
  17796. ASSERT_TRUE(handle.is_valid());
  17797. auto body = read_all(handle);
  17798. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  17799. }
  17800. // User-specified User-Agent must not be overwritten for stream API
  17801. {
  17802. auto handle = cli.open_stream("GET", "/echo-headers", {},
  17803. {{"User-Agent", "MyAgent/1.2"}});
  17804. ASSERT_TRUE(handle.is_valid());
  17805. auto body = read_all(handle);
  17806. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  17807. }
  17808. }
  17809. TEST_F(OpenStreamTest, Large) {
  17810. Client cli("127.0.0.1", port_);
  17811. auto handle = cli.open_stream("GET", "/large");
  17812. EXPECT_EQ(10000u, read_all(handle).size());
  17813. }
  17814. TEST_F(OpenStreamTest, ConnectionError) {
  17815. Client cli("127.0.0.1", 9999);
  17816. auto handle = cli.open_stream("GET", "/hello");
  17817. EXPECT_FALSE(handle.is_valid());
  17818. }
  17819. TEST_F(OpenStreamTest, Chunked) {
  17820. Client cli("127.0.0.1", port_);
  17821. auto handle = cli.open_stream("GET", "/chunked");
  17822. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17823. "Transfer-Encoding") == "chunked");
  17824. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  17825. }
  17826. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  17827. Client cli("127.0.0.1", port_);
  17828. auto handle =
  17829. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  17830. ASSERT_TRUE(handle.is_valid());
  17831. // Consume body to allow trailers to be received/parsed
  17832. auto body = read_all(handle);
  17833. // Explicitly parse trailers (ensure trailers are available for assertion)
  17834. handle.parse_trailers_if_needed();
  17835. EXPECT_EQ(std::string("123456789"), body);
  17836. // The response should include a Trailer header declaring both names
  17837. ASSERT_TRUE(handle.response);
  17838. EXPECT_TRUE(handle.response->has_header("Trailer"));
  17839. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  17840. handle.response->get_header_value("Trailer"));
  17841. // Prohibited trailer must not be present
  17842. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  17843. // Allowed trailer should be present
  17844. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  17845. EXPECT_EQ(std::string("yes"),
  17846. handle.response->get_trailer_value("X-Allowed"));
  17847. // Verify trailers are NOT present as regular headers
  17848. EXPECT_EQ(std::string(""),
  17849. handle.response->get_header_value("Content-Length"));
  17850. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  17851. }
  17852. static std::thread serve_single_response(std::promise<int> &port_promise,
  17853. const std::string &response) {
  17854. return std::thread([&port_promise, response] {
  17855. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17856. default_socket_options(srv);
  17857. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  17858. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  17859. sockaddr_in addr{};
  17860. addr.sin_family = AF_INET;
  17861. addr.sin_port = htons(0); // Let OS assign a free port
  17862. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17863. int opt = 1;
  17864. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  17865. #ifdef _WIN32
  17866. reinterpret_cast<const char *>(&opt),
  17867. #else
  17868. &opt,
  17869. #endif
  17870. sizeof(opt));
  17871. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  17872. ::listen(srv, 1) != 0) {
  17873. port_promise.set_value(-1);
  17874. detail::close_socket(srv);
  17875. return;
  17876. }
  17877. socklen_t addr_len = sizeof(addr);
  17878. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  17879. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  17880. sockaddr_in cli_addr{};
  17881. socklen_t cli_len = sizeof(cli_addr);
  17882. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17883. if (cli != INVALID_SOCKET) {
  17884. // Read the complete HTTP request (until the blank line that terminates
  17885. // headers) before sending the response. If the server closes the socket
  17886. // while the client's request data is still unread in the kernel receive
  17887. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  17888. // connection on both sides: it discards the client's receive buffer
  17889. // (which already holds our response) and causes any in-progress write on
  17890. // the client to fail with ECONNRESET. Reading all request data first
  17891. // ensures close() emits a graceful FIN.
  17892. {
  17893. char rbuf[256];
  17894. std::string req;
  17895. while (req.find("\r\n\r\n") == std::string::npos) {
  17896. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  17897. if (n <= 0) { break; }
  17898. req.append(rbuf, static_cast<size_t>(n));
  17899. }
  17900. }
  17901. ::send(cli,
  17902. #ifdef _WIN32
  17903. static_cast<const char *>(response.c_str()),
  17904. static_cast<int>(response.size()),
  17905. #else
  17906. response.c_str(), response.size(),
  17907. #endif
  17908. 0);
  17909. detail::close_socket(cli);
  17910. }
  17911. detail::close_socket(srv);
  17912. });
  17913. }
  17914. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  17915. #ifndef _WIN32
  17916. signal(SIGPIPE, SIG_IGN);
  17917. #endif
  17918. std::promise<int> port_promise;
  17919. auto port_future = port_promise.get_future();
  17920. auto server_thread =
  17921. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  17922. "Content-Type: text/plain\r\n"
  17923. "Content-Length: not-a-number\r\n"
  17924. "Connection: close\r\n"
  17925. "\r\n"
  17926. "hello");
  17927. auto port = port_future.get();
  17928. ASSERT_GT(port, 0);
  17929. Client cli("127.0.0.1", port);
  17930. auto handle = cli.open_stream("GET", "/");
  17931. EXPECT_FALSE(handle.is_valid());
  17932. server_thread.join();
  17933. }
  17934. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  17935. #ifndef _WIN32
  17936. signal(SIGPIPE, SIG_IGN);
  17937. #endif
  17938. std::promise<int> port_promise;
  17939. auto port_future = port_promise.get_future();
  17940. auto server_thread = serve_single_response(
  17941. port_promise, "HTTP/1.1 200 OK\r\n"
  17942. "Content-Type: text/plain\r\n"
  17943. "Content-Length: 99999999999999999999999999\r\n"
  17944. "Connection: close\r\n"
  17945. "\r\n"
  17946. "hello");
  17947. auto port = port_future.get();
  17948. ASSERT_GT(port, 0);
  17949. // Historically std::stoull would throw std::out_of_range here and crash
  17950. // the process, then parsing silently clamped to a bogus framing length and
  17951. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  17952. // so the stream fails to open, matching the not-a-number case above. The
  17953. // process still must NOT terminate.
  17954. Client cli("127.0.0.1", port);
  17955. auto handle = cli.open_stream("GET", "/");
  17956. EXPECT_FALSE(handle.is_valid());
  17957. server_thread.join();
  17958. }
  17959. // Serves `response` to the single request `fn` makes with a fresh client.
  17960. template <typename Fn>
  17961. static void with_single_response(const std::string &response, Fn fn) {
  17962. #ifndef _WIN32
  17963. signal(SIGPIPE, SIG_IGN);
  17964. #endif
  17965. std::promise<int> port_promise;
  17966. auto port_future = port_promise.get_future();
  17967. auto server_thread = serve_single_response(port_promise, response);
  17968. auto se = detail::scope_exit([&] { server_thread.join(); });
  17969. auto port = port_future.get();
  17970. ASSERT_GT(port, 0);
  17971. Client cli("127.0.0.1", port);
  17972. fn(cli);
  17973. }
  17974. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  17975. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  17976. // the chunked coding and drop Content-Length, so a front-end that trusts
  17977. // Content-Length would disagree about where the body ends (response
  17978. // smuggling). The client must reject such a response.
  17979. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  17980. for (const char *te : {"chunked", "gzip, chunked"}) {
  17981. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  17982. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  17983. "\r\n" + "Connection: close\r\n" + "\r\n" +
  17984. "5\r\nhello\r\n0\r\n\r\n";
  17985. with_single_response(response, [&](Client &cli) {
  17986. auto res = cli.Get("/");
  17987. EXPECT_FALSE(static_cast<bool>(res)) << te;
  17988. EXPECT_EQ(Error::Read, res.error()) << te;
  17989. });
  17990. with_single_response(response, [&](Client &cli) {
  17991. auto handle = cli.open_stream("GET", "/");
  17992. EXPECT_FALSE(handle.is_valid()) << te;
  17993. EXPECT_EQ(Error::Read, handle.error) << te;
  17994. });
  17995. }
  17996. }
  17997. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  17998. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  17999. // closing the connection (unlike a request, which must be rejected).
  18000. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  18001. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18002. "Transfer-Encoding: chunked\r\n"
  18003. "Connection: close\r\n"
  18004. "\r\n"
  18005. "5\r\nhello\r\n0\r\n\r\n",
  18006. "HTTP/1.1 200 OK\r\n"
  18007. "Transfer-Encoding: gzip\r\n"
  18008. "Connection: close\r\n"
  18009. "\r\n"
  18010. "hello"}) {
  18011. with_single_response(response, [&](Client &cli) {
  18012. auto res = cli.Get("/");
  18013. ASSERT_TRUE(static_cast<bool>(res)) << response;
  18014. EXPECT_EQ("hello", res->body);
  18015. });
  18016. with_single_response(response, [&](Client &cli) {
  18017. auto handle = cli.open_stream("GET", "/");
  18018. ASSERT_TRUE(handle.is_valid()) << response;
  18019. EXPECT_EQ("hello", read_all(handle));
  18020. });
  18021. }
  18022. }
  18023. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  18024. // framing headers describe nothing to read and must not be rejected.
  18025. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  18026. const std::string framing = "Content-Length: 5\r\n"
  18027. "Transfer-Encoding: chunked\r\n"
  18028. "Connection: close\r\n"
  18029. "\r\n";
  18030. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18031. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  18032. });
  18033. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18034. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  18035. });
  18036. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  18037. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  18038. with_single_response(response, [&](Client &cli) {
  18039. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  18040. });
  18041. with_single_response(response, [&](Client &cli) {
  18042. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  18043. });
  18044. }
  18045. }
  18046. // A payload max length of 0 means no limit, however the body is framed.
  18047. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  18048. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18049. "Transfer-Encoding: chunked\r\n"
  18050. "\r\n"
  18051. "5\r\nhello\r\n0\r\n\r\n",
  18052. "HTTP/1.1 200 OK\r\n"
  18053. "Connection: close\r\n"
  18054. "\r\n"
  18055. "hello"}) {
  18056. with_single_response(response, [&](Client &cli) {
  18057. cli.set_payload_max_length(0);
  18058. auto res = cli.Get("/");
  18059. ASSERT_TRUE(res) << response;
  18060. EXPECT_EQ("hello", res->body) << response;
  18061. });
  18062. }
  18063. }
  18064. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  18065. Server svr;
  18066. svr.set_payload_max_length(0);
  18067. svr.Post("/echo", [](const Request &req, Response &res) {
  18068. res.set_content(req.body, "text/plain");
  18069. });
  18070. auto port = svr.bind_to_any_port(HOST);
  18071. thread t = thread([&] { svr.listen_after_bind(); });
  18072. auto se = detail::scope_exit([&] {
  18073. svr.stop();
  18074. t.join();
  18075. ASSERT_FALSE(svr.is_running());
  18076. });
  18077. svr.wait_until_ready();
  18078. Client cli(HOST, port);
  18079. auto res = cli.Post(
  18080. "/echo",
  18081. [](size_t /*offset*/, DataSink &sink) {
  18082. sink.write("hello", 5);
  18083. sink.done();
  18084. return true;
  18085. },
  18086. "text/plain");
  18087. ASSERT_TRUE(res);
  18088. EXPECT_EQ(StatusCode::OK_200, res->status);
  18089. EXPECT_EQ("hello", res->body);
  18090. }
  18091. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18092. TEST_F(OpenStreamTest, Gzip) {
  18093. Client cli("127.0.0.1", port_);
  18094. auto handle = cli.open_stream("GET", "/compressible", {},
  18095. {{"Accept-Encoding", "gzip"}});
  18096. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  18097. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18098. }
  18099. #endif
  18100. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18101. TEST_F(OpenStreamTest, Brotli) {
  18102. Client cli("127.0.0.1", port_);
  18103. auto handle =
  18104. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  18105. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  18106. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18107. }
  18108. #endif
  18109. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18110. TEST_F(OpenStreamTest, Zstd) {
  18111. Client cli("127.0.0.1", port_);
  18112. auto handle = cli.open_stream("GET", "/compressible", {},
  18113. {{"Accept-Encoding", "zstd"}});
  18114. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  18115. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18116. }
  18117. #endif
  18118. #ifdef CPPHTTPLIB_SSL_ENABLED
  18119. class SSLOpenStreamTest : public ::testing::Test {
  18120. protected:
  18121. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  18122. void SetUp() override {
  18123. svr_.Get("/hello", [](const Request &, Response &res) {
  18124. res.set_content("Hello SSL World!", "text/plain");
  18125. });
  18126. svr_.Get("/chunked", [](const Request &, Response &res) {
  18127. res.set_chunked_content_provider("text/plain",
  18128. [](size_t offset, DataSink &sink) {
  18129. if (offset < 15) {
  18130. sink.write("chunk", 5);
  18131. return true;
  18132. }
  18133. sink.done();
  18134. return true;
  18135. });
  18136. });
  18137. svr_.Post("/echo", [](const Request &req, Response &res) {
  18138. res.set_content(req.body, req.get_header_value("Content-Type"));
  18139. });
  18140. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  18141. std::string body = req.body;
  18142. res.set_chunked_content_provider(
  18143. "text/plain", [body](size_t offset, DataSink &sink) {
  18144. if (offset < body.size()) {
  18145. sink.write(body.data() + offset, body.size() - offset);
  18146. }
  18147. sink.done();
  18148. return true;
  18149. });
  18150. });
  18151. port_ = svr_.bind_to_any_port("127.0.0.1");
  18152. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18153. svr_.wait_until_ready();
  18154. }
  18155. void TearDown() override {
  18156. svr_.stop();
  18157. if (thread_.joinable()) thread_.join();
  18158. }
  18159. SSLServer svr_;
  18160. std::thread thread_;
  18161. int port_ = 0;
  18162. };
  18163. TEST_F(SSLOpenStreamTest, Basic) {
  18164. SSLClient cli("127.0.0.1", port_);
  18165. cli.enable_server_certificate_verification(false);
  18166. auto handle = cli.open_stream("GET", "/hello");
  18167. ASSERT_TRUE(handle.is_valid());
  18168. EXPECT_EQ("Hello SSL World!", read_all(handle));
  18169. }
  18170. TEST_F(SSLOpenStreamTest, Chunked) {
  18171. SSLClient cli("127.0.0.1", port_);
  18172. cli.enable_server_certificate_verification(false);
  18173. auto handle = cli.open_stream("GET", "/chunked");
  18174. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18175. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18176. "Transfer-Encoding") == "chunked");
  18177. auto body = read_all(handle);
  18178. EXPECT_EQ("chunkchunkchunk", body);
  18179. }
  18180. TEST_F(SSLOpenStreamTest, Post) {
  18181. SSLClient cli("127.0.0.1", port_);
  18182. cli.enable_server_certificate_verification(false);
  18183. auto handle =
  18184. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  18185. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18186. EXPECT_EQ(200, handle.response->status);
  18187. auto body = read_all(handle);
  18188. EXPECT_EQ("Hello SSL POST", body);
  18189. }
  18190. TEST_F(SSLOpenStreamTest, PostChunked) {
  18191. SSLClient cli("127.0.0.1", port_);
  18192. cli.enable_server_certificate_verification(false);
  18193. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  18194. "Chunked SSL Data", "text/plain");
  18195. ASSERT_TRUE(handle.is_valid());
  18196. EXPECT_EQ(200, handle.response->status);
  18197. auto body = read_all(handle);
  18198. EXPECT_EQ("Chunked SSL Data", body);
  18199. }
  18200. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  18201. // Content-Length is terminated by the server closing the connection. When the
  18202. // SSL peer sends a close_notify after the body, the client must treat it as a
  18203. // clean EOF and return a successful response rather than an error.
  18204. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  18205. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18206. ASSERT_TRUE(svr.is_valid());
  18207. svr.set_keep_alive_max_count(1);
  18208. const std::string expected_body = "Hello from connection-close response!";
  18209. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  18210. res.set_content_provider("text/plain",
  18211. [&](size_t offset, DataSink &sink) -> bool {
  18212. if (offset < expected_body.size()) {
  18213. sink.write(expected_body.data() + offset,
  18214. expected_body.size() - offset);
  18215. }
  18216. sink.done();
  18217. return true;
  18218. });
  18219. });
  18220. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  18221. auto se = detail::scope_exit([&] {
  18222. svr.stop();
  18223. listen_thread.join();
  18224. ASSERT_FALSE(svr.is_running());
  18225. });
  18226. svr.wait_until_ready();
  18227. SSLClient cli(HOST, PORT);
  18228. cli.enable_server_certificate_verification(false);
  18229. auto res = cli.Get("/no-content-length");
  18230. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  18231. EXPECT_EQ(StatusCode::OK_200, res->status);
  18232. EXPECT_EQ(expected_body, res->body);
  18233. }
  18234. #endif // CPPHTTPLIB_SSL_ENABLED
  18235. //==============================================================================
  18236. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  18237. // results for various scenarios.
  18238. //==============================================================================
  18239. TEST(ParityTest, GetVsOpenStream) {
  18240. Server svr;
  18241. const std::string path = "/parity";
  18242. const std::string content = "Parity test content: hello world";
  18243. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18244. res.set_content(content, "text/plain");
  18245. });
  18246. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18247. auto se = detail::scope_exit([&] {
  18248. svr.stop();
  18249. t.join();
  18250. ASSERT_FALSE(svr.is_running());
  18251. });
  18252. svr.wait_until_ready();
  18253. Client cli(HOST, PORT);
  18254. // Non-stream path
  18255. auto r1 = cli.Get(path);
  18256. ASSERT_TRUE(r1);
  18257. EXPECT_EQ(StatusCode::OK_200, r1->status);
  18258. // Stream path
  18259. auto h = cli.open_stream("GET", path);
  18260. ASSERT_TRUE(h.is_valid());
  18261. EXPECT_EQ(r1->body, read_all(h));
  18262. }
  18263. // Helper to compress data with provided compressor type T
  18264. template <typename Compressor>
  18265. static std::string compress_payload_for_parity(const std::string &in) {
  18266. std::string out;
  18267. Compressor compressor;
  18268. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  18269. [&](const char *data, size_t n) {
  18270. out.append(data, n);
  18271. return true;
  18272. });
  18273. EXPECT_TRUE(ok);
  18274. return out;
  18275. }
  18276. // Helper function for compression parity tests
  18277. template <typename Compressor>
  18278. static void test_compression_parity(const std::string &original,
  18279. const std::string &path,
  18280. const std::string &encoding) {
  18281. const std::string compressed =
  18282. compress_payload_for_parity<Compressor>(original);
  18283. Server svr;
  18284. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18285. res.set_content(compressed, "application/octet-stream");
  18286. res.set_header("Content-Encoding", encoding);
  18287. });
  18288. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  18289. auto se = detail::scope_exit([&] {
  18290. svr.stop();
  18291. t.join();
  18292. ASSERT_FALSE(svr.is_running());
  18293. });
  18294. svr.wait_until_ready();
  18295. Client cli(HOST, PORT);
  18296. // Non-streaming
  18297. {
  18298. auto res = cli.Get(path);
  18299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18300. EXPECT_EQ(StatusCode::OK_200, res->status);
  18301. EXPECT_EQ(original, res->body);
  18302. }
  18303. // Streaming
  18304. {
  18305. auto h = cli.open_stream("GET", path);
  18306. ASSERT_TRUE(h.is_valid());
  18307. EXPECT_EQ(original, read_all(h));
  18308. }
  18309. }
  18310. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18311. TEST(ParityTest, Gzip) {
  18312. test_compression_parity<detail::gzip_compressor>(
  18313. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  18314. }
  18315. #endif
  18316. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18317. TEST(ParityTest, Brotli) {
  18318. test_compression_parity<detail::brotli_compressor>(
  18319. "Hello, brotli parity test payload", "/parity-br", "br");
  18320. }
  18321. #endif
  18322. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18323. TEST(ParityTest, Zstd) {
  18324. test_compression_parity<detail::zstd_compressor>(
  18325. "Zstandard parity test payload", "/parity-zstd", "zstd");
  18326. }
  18327. #endif
  18328. //==============================================================================
  18329. // New Stream API Tests
  18330. //==============================================================================
  18331. inline std::string read_body(httplib::stream::Result &result) {
  18332. std::string body;
  18333. while (result.next()) {
  18334. body.append(result.data(), result.size());
  18335. }
  18336. return body;
  18337. }
  18338. TEST(ClientConnectionTest, Basic) {
  18339. httplib::ClientConnection conn;
  18340. EXPECT_FALSE(conn.is_open());
  18341. conn.sock = 1;
  18342. EXPECT_TRUE(conn.is_open());
  18343. httplib::ClientConnection conn2(std::move(conn));
  18344. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  18345. conn2.sock = INVALID_SOCKET;
  18346. }
  18347. // Unified test server for all stream::* tests
  18348. class StreamApiTest : public ::testing::Test {
  18349. protected:
  18350. void SetUp() override {
  18351. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18352. res.set_content("Hello World!", "text/plain");
  18353. });
  18354. svr_.Get("/echo-params",
  18355. [](const httplib::Request &req, httplib::Response &res) {
  18356. std::string r;
  18357. for (const auto &p : req.params) {
  18358. if (!r.empty()) r += "&";
  18359. r += p.first + "=" + p.second;
  18360. }
  18361. res.set_content(r, "text/plain");
  18362. });
  18363. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18364. res.set_content(req.body, req.get_header_value("Content-Type"));
  18365. });
  18366. svr_.Post("/echo-headers",
  18367. [](const httplib::Request &req, httplib::Response &res) {
  18368. std::string r;
  18369. for (const auto &h : req.headers)
  18370. r += h.first + ": " + h.second + "\n";
  18371. res.set_content(r, "text/plain");
  18372. });
  18373. svr_.Post("/echo-params",
  18374. [](const httplib::Request &req, httplib::Response &res) {
  18375. std::string r = "params:";
  18376. for (const auto &p : req.params)
  18377. r += p.first + "=" + p.second + ";";
  18378. res.set_content(r + " body:" + req.body, "text/plain");
  18379. });
  18380. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  18381. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  18382. });
  18383. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18384. res.set_content("PUT:" + req.body, "text/plain");
  18385. });
  18386. svr_.Patch("/echo",
  18387. [](const httplib::Request &req, httplib::Response &res) {
  18388. res.set_content("PATCH:" + req.body, "text/plain");
  18389. });
  18390. svr_.Delete(
  18391. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  18392. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  18393. "text/plain");
  18394. });
  18395. svr_.Get("/head-test",
  18396. [](const httplib::Request &, httplib::Response &res) {
  18397. res.set_content("body for HEAD", "text/plain");
  18398. });
  18399. svr_.Options("/options",
  18400. [](const httplib::Request &, httplib::Response &res) {
  18401. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  18402. });
  18403. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  18404. svr_.wait_until_ready();
  18405. }
  18406. void TearDown() override {
  18407. svr_.stop();
  18408. if (thread_.joinable()) thread_.join();
  18409. }
  18410. httplib::Server svr_;
  18411. std::thread thread_;
  18412. };
  18413. // stream::Get tests
  18414. TEST_F(StreamApiTest, GetBasic) {
  18415. httplib::Client cli(HOST, PORT);
  18416. auto result = httplib::stream::Get(cli, "/hello");
  18417. ASSERT_TRUE(result.is_valid());
  18418. EXPECT_EQ(200, result.status());
  18419. EXPECT_EQ("Hello World!", read_body(result));
  18420. }
  18421. TEST_F(StreamApiTest, GetWithParams) {
  18422. httplib::Client cli(HOST, PORT);
  18423. httplib::Params params{{"foo", "bar"}};
  18424. auto result = httplib::stream::Get(cli, "/echo-params", params);
  18425. ASSERT_TRUE(result.is_valid());
  18426. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  18427. }
  18428. TEST_F(StreamApiTest, GetConnectionError) {
  18429. httplib::Client cli(HOST, 9999);
  18430. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  18431. }
  18432. TEST_F(StreamApiTest, Get404) {
  18433. httplib::Client cli(HOST, PORT);
  18434. auto result = httplib::stream::Get(cli, "/nonexistent");
  18435. EXPECT_TRUE(result.is_valid());
  18436. EXPECT_EQ(404, result.status());
  18437. }
  18438. // stream::Post tests
  18439. TEST_F(StreamApiTest, PostBasic) {
  18440. httplib::Client cli(HOST, PORT);
  18441. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  18442. "application/json");
  18443. ASSERT_TRUE(result.is_valid());
  18444. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  18445. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  18446. }
  18447. TEST_F(StreamApiTest, PostWithHeaders) {
  18448. httplib::Client cli(HOST, PORT);
  18449. httplib::Headers headers{{"X-Custom", "value"}};
  18450. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  18451. "text/plain");
  18452. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  18453. }
  18454. TEST_F(StreamApiTest, PostWithParams) {
  18455. httplib::Client cli(HOST, PORT);
  18456. httplib::Params params{{"k", "v"}};
  18457. auto result =
  18458. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  18459. auto body = read_body(result);
  18460. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  18461. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  18462. }
  18463. TEST_F(StreamApiTest, PostLarge) {
  18464. httplib::Client cli(HOST, PORT);
  18465. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  18466. size_t total = 0;
  18467. while (result.next()) {
  18468. total += result.size();
  18469. }
  18470. EXPECT_EQ(100u * 1024u, total);
  18471. }
  18472. // stream::Put/Patch tests
  18473. TEST_F(StreamApiTest, PutAndPatch) {
  18474. httplib::Client cli(HOST, PORT);
  18475. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  18476. EXPECT_EQ("PUT:test", read_body(put));
  18477. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  18478. EXPECT_EQ("PATCH:test", read_body(patch));
  18479. }
  18480. // stream::Delete tests
  18481. TEST_F(StreamApiTest, Delete) {
  18482. httplib::Client cli(HOST, PORT);
  18483. auto del1 = httplib::stream::Delete(cli, "/resource");
  18484. EXPECT_EQ("Deleted", read_body(del1));
  18485. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  18486. EXPECT_EQ("Deleted:data", read_body(del2));
  18487. }
  18488. // stream::Head/Options tests
  18489. TEST_F(StreamApiTest, HeadAndOptions) {
  18490. httplib::Client cli(HOST, PORT);
  18491. auto head = httplib::stream::Head(cli, "/head-test");
  18492. EXPECT_TRUE(head.is_valid());
  18493. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  18494. auto opts = httplib::stream::Options(cli, "/options");
  18495. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  18496. }
  18497. // SSL stream::* tests
  18498. #ifdef CPPHTTPLIB_SSL_ENABLED
  18499. class SSLStreamApiTest : public ::testing::Test {
  18500. protected:
  18501. void SetUp() override {
  18502. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18503. res.set_content("Hello SSL!", "text/plain");
  18504. });
  18505. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18506. res.set_content(req.body, "text/plain");
  18507. });
  18508. port_ = svr_.bind_to_any_port("127.0.0.1");
  18509. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18510. svr_.wait_until_ready();
  18511. }
  18512. void TearDown() override {
  18513. svr_.stop();
  18514. if (thread_.joinable()) thread_.join();
  18515. }
  18516. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  18517. std::thread thread_;
  18518. int port_ = 0;
  18519. };
  18520. TEST_F(SSLStreamApiTest, GetAndPost) {
  18521. httplib::SSLClient cli("127.0.0.1", port_);
  18522. cli.enable_server_certificate_verification(false);
  18523. auto get = httplib::stream::Get(cli, "/hello");
  18524. EXPECT_EQ("Hello SSL!", read_body(get));
  18525. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  18526. EXPECT_EQ("test", read_body(post));
  18527. }
  18528. #endif
  18529. // Tests for Error::Timeout and Error::ConnectionClosed error types
  18530. // These errors are set in SocketStream/SSLSocketStream and propagated through
  18531. // BodyReader
  18532. TEST(ErrorHandlingTest, StreamReadTimeout) {
  18533. // Test that read timeout during streaming is detected
  18534. // Use a large content-length response where server delays mid-stream
  18535. Server svr;
  18536. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18537. // Send a large response with delay in the middle
  18538. res.set_content_provider(
  18539. 1000, // content_length
  18540. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  18541. if (offset < 100) {
  18542. // Send first 100 bytes immediately
  18543. std::string data(100, 'A');
  18544. sink.write(data.c_str(), data.size());
  18545. return true;
  18546. }
  18547. // Then delay longer than client timeout
  18548. std::this_thread::sleep_for(std::chrono::seconds(3));
  18549. std::string data(900, 'B');
  18550. sink.write(data.c_str(), data.size());
  18551. return true;
  18552. });
  18553. });
  18554. auto port = 8091;
  18555. std::thread t([&]() { svr.listen("localhost", port); });
  18556. svr.wait_until_ready();
  18557. Client cli("localhost", port);
  18558. cli.set_read_timeout(1, 0); // 1 second timeout
  18559. auto handle = cli.open_stream("GET", "/slow-stream");
  18560. ASSERT_TRUE(handle.is_valid());
  18561. char buf[256];
  18562. ssize_t total = 0;
  18563. ssize_t n;
  18564. bool got_error = false;
  18565. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18566. total += n;
  18567. }
  18568. if (n < 0) {
  18569. got_error = true;
  18570. // Should be timeout or read error
  18571. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18572. handle.get_read_error() == Error::Read)
  18573. << "Actual error: " << to_string(handle.get_read_error());
  18574. }
  18575. // Either we got an error, or we got less data than expected
  18576. EXPECT_TRUE(got_error || total < 1000)
  18577. << "Expected timeout but got all " << total << " bytes";
  18578. svr.stop();
  18579. t.join();
  18580. }
  18581. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  18582. // Test connection closed detection via BodyReader
  18583. Server svr;
  18584. std::atomic<bool> close_now{false};
  18585. svr.Get("/will-close", [&](const Request &, Response &res) {
  18586. res.set_content_provider(
  18587. 10000, // Large content_length that we won't fully send
  18588. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18589. if (offset < 100) {
  18590. std::string data(100, 'X');
  18591. sink.write(data.c_str(), data.size());
  18592. return true;
  18593. }
  18594. // Wait for signal then abort
  18595. while (!close_now) {
  18596. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18597. }
  18598. return false; // Abort - server will close connection
  18599. });
  18600. });
  18601. auto port = 8092;
  18602. std::thread t([&]() { svr.listen("localhost", port); });
  18603. svr.wait_until_ready();
  18604. Client cli("localhost", port);
  18605. auto handle = cli.open_stream("GET", "/will-close");
  18606. ASSERT_TRUE(handle.is_valid());
  18607. char buf[256];
  18608. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18609. EXPECT_GT(n, 0) << "First read should succeed";
  18610. // Signal server to close
  18611. close_now = true;
  18612. // Keep reading until error or EOF
  18613. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18614. // Keep reading
  18615. }
  18616. // Should get an error since content_length wasn't satisfied
  18617. if (n < 0) {
  18618. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  18619. handle.get_read_error() == Error::Read)
  18620. << "Actual error: " << to_string(handle.get_read_error());
  18621. }
  18622. svr.stop();
  18623. t.join();
  18624. }
  18625. #ifdef CPPHTTPLIB_SSL_ENABLED
  18626. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  18627. // Test that read timeout during SSL streaming is detected
  18628. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18629. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18630. res.set_content_provider(
  18631. 1000, "text/plain",
  18632. [](size_t offset, size_t /*length*/, DataSink &sink) {
  18633. if (offset < 100) {
  18634. std::string data(100, 'A');
  18635. sink.write(data.c_str(), data.size());
  18636. return true;
  18637. }
  18638. std::this_thread::sleep_for(std::chrono::seconds(3));
  18639. std::string data(900, 'B');
  18640. sink.write(data.c_str(), data.size());
  18641. return true;
  18642. });
  18643. });
  18644. auto port = 8093;
  18645. std::thread t([&]() { svr.listen("localhost", port); });
  18646. svr.wait_until_ready();
  18647. SSLClient cli("localhost", port);
  18648. cli.enable_server_certificate_verification(false);
  18649. cli.set_read_timeout(1, 0); // 1 second timeout
  18650. auto handle = cli.open_stream("GET", "/slow-stream");
  18651. ASSERT_TRUE(handle.is_valid());
  18652. char buf[256];
  18653. ssize_t total = 0;
  18654. ssize_t n;
  18655. bool got_error = false;
  18656. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18657. total += n;
  18658. }
  18659. if (n < 0) {
  18660. got_error = true;
  18661. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18662. handle.get_read_error() == Error::Read)
  18663. << "Actual error: " << to_string(handle.get_read_error());
  18664. }
  18665. EXPECT_TRUE(got_error || total < 1000)
  18666. << "Expected timeout but got all " << total << " bytes";
  18667. svr.stop();
  18668. t.join();
  18669. }
  18670. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  18671. // Test SSL connection closed detection
  18672. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18673. std::atomic<bool> close_now{false};
  18674. svr.Get("/will-close", [&](const Request &, Response &res) {
  18675. res.set_content_provider(
  18676. 10000, "text/plain",
  18677. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18678. if (offset < 100) {
  18679. std::string data(100, 'X');
  18680. sink.write(data.c_str(), data.size());
  18681. return true;
  18682. }
  18683. while (!close_now) {
  18684. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18685. }
  18686. return false;
  18687. });
  18688. });
  18689. auto port = 8094;
  18690. std::thread t([&]() { svr.listen("localhost", port); });
  18691. svr.wait_until_ready();
  18692. SSLClient cli("localhost", port);
  18693. cli.enable_server_certificate_verification(false);
  18694. auto handle = cli.open_stream("GET", "/will-close");
  18695. ASSERT_TRUE(handle.is_valid());
  18696. char buf[256];
  18697. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18698. EXPECT_GT(n, 0);
  18699. // Signal server to close
  18700. close_now = true;
  18701. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18702. // Keep reading
  18703. }
  18704. if (n < 0) {
  18705. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  18706. handle.get_read_error() == Error::Read)
  18707. << "Actual error: " << to_string(handle.get_read_error());
  18708. }
  18709. svr.stop();
  18710. t.join();
  18711. }
  18712. #endif
  18713. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  18714. using namespace httplib;
  18715. // Create a test file
  18716. const char *fname = "etag_testfile.txt";
  18717. const char *content = "etag-content";
  18718. {
  18719. std::ofstream ofs(fname);
  18720. ofs << content;
  18721. ASSERT_TRUE(ofs.good());
  18722. }
  18723. Server svr;
  18724. svr.set_mount_point("/static", ".");
  18725. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  18726. svr.wait_until_ready();
  18727. Client cli(HOST, PORT);
  18728. // First request: should get 200 with ETag header
  18729. auto res1 = cli.Get("/static/etag_testfile.txt");
  18730. ASSERT_TRUE(res1);
  18731. ASSERT_EQ(200, res1->status);
  18732. ASSERT_TRUE(res1->has_header("ETag"));
  18733. std::string etag = res1->get_header_value("ETag");
  18734. EXPECT_FALSE(etag.empty());
  18735. // Verify ETag format: W/"hex-hex"
  18736. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  18737. EXPECT_EQ('W', etag[0]);
  18738. EXPECT_EQ('/', etag[1]);
  18739. EXPECT_EQ('"', etag[2]);
  18740. EXPECT_EQ('"', etag.back());
  18741. // Exact match: expect 304 Not Modified
  18742. Headers h2 = {{"If-None-Match", etag}};
  18743. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  18744. ASSERT_TRUE(res2);
  18745. EXPECT_EQ(304, res2->status);
  18746. // Wildcard match: expect 304 Not Modified
  18747. Headers h3 = {{"If-None-Match", "*"}};
  18748. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  18749. ASSERT_TRUE(res3);
  18750. EXPECT_EQ(304, res3->status);
  18751. // Non-matching ETag: expect 200
  18752. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  18753. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  18754. ASSERT_TRUE(res4);
  18755. EXPECT_EQ(200, res4->status);
  18756. // Multiple ETags with one matching: expect 304
  18757. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  18758. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  18759. ASSERT_TRUE(res5);
  18760. EXPECT_EQ(304, res5->status);
  18761. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  18762. // that equivalent to the single comma-separated list above, so the match on
  18763. // the second line must still be found.
  18764. Headers h6;
  18765. h6.emplace("If-None-Match", "W/\"other\"");
  18766. h6.emplace("If-None-Match", etag);
  18767. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  18768. ASSERT_TRUE(res6);
  18769. EXPECT_EQ(304, res6->status);
  18770. svr.stop();
  18771. t.join();
  18772. std::remove(fname);
  18773. }
  18774. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  18775. using namespace httplib;
  18776. Server svr;
  18777. svr.set_mount_point("/static", ".");
  18778. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18779. svr.wait_until_ready();
  18780. Client cli(HOST, PORT);
  18781. // Send If-None-Match: * to a non-existent file
  18782. Headers h = {{"If-None-Match", "*"}};
  18783. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  18784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18785. EXPECT_EQ(404, res->status);
  18786. svr.stop();
  18787. t.join();
  18788. }
  18789. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  18790. using namespace httplib;
  18791. // Create a test file
  18792. const char *fname = "etag_boundary_testfile.txt";
  18793. const char *content = "boundary-test";
  18794. {
  18795. std::ofstream ofs(fname);
  18796. ofs << content;
  18797. ASSERT_TRUE(ofs.good());
  18798. }
  18799. Server svr;
  18800. svr.set_mount_point("/static", ".");
  18801. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  18802. svr.wait_until_ready();
  18803. Client cli(HOST, PORT);
  18804. // Get the actual ETag
  18805. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  18806. ASSERT_TRUE(res1);
  18807. ASSERT_EQ(200, res1->status);
  18808. ASSERT_TRUE(res1->has_header("ETag"));
  18809. std::string etag = res1->get_header_value("ETag");
  18810. // Test 1: Very long ETag value (longer than actual ETag)
  18811. // Should NOT match and return 200 (not trigger out-of-bounds read)
  18812. Headers h1 = {{"If-None-Match", "W/"
  18813. "\"very-long-etag-value-that-is-much-longer-"
  18814. "than-the-actual-etag-value\""}};
  18815. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  18816. ASSERT_TRUE(res2);
  18817. EXPECT_EQ(200, res2->status); // Should not match
  18818. // Test 2: Long string followed by wildcard
  18819. // Should match on "*" and return 304 (without out-of-bounds read on the long
  18820. // string)
  18821. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  18822. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  18823. ASSERT_TRUE(res3);
  18824. EXPECT_EQ(304, res3->status); // Should match on "*"
  18825. // Test 3: Wildcard followed by long string
  18826. // Should match on "*" immediately and return 304
  18827. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  18828. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  18829. ASSERT_TRUE(res4);
  18830. EXPECT_EQ(304, res4->status); // Should match on "*"
  18831. // Test 4: Multiple long non-matching values
  18832. // Should NOT match and return 200 (test that all comparisons are safe)
  18833. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  18834. "W/\"second-long-non-matching-value\", "
  18835. "W/\"third-long-non-matching-value\""}};
  18836. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  18837. ASSERT_TRUE(res5);
  18838. EXPECT_EQ(200, res5->status); // Should not match
  18839. // Test 5: Single character that is not "*" (edge case)
  18840. Headers h5 = {{"If-None-Match", "X"}};
  18841. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  18842. ASSERT_TRUE(res6);
  18843. EXPECT_EQ(200, res6->status); // Should not match
  18844. svr.stop();
  18845. t.join();
  18846. std::remove(fname);
  18847. }
  18848. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  18849. using namespace httplib;
  18850. // Create a test file
  18851. const char *fname = "ims_testfile.txt";
  18852. const char *content = "if-modified-since-test";
  18853. {
  18854. std::ofstream ofs(fname);
  18855. ofs << content;
  18856. ASSERT_TRUE(ofs.good());
  18857. }
  18858. Server svr;
  18859. svr.set_mount_point("/static", ".");
  18860. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18861. svr.wait_until_ready();
  18862. Client cli(HOST, PORT);
  18863. // First request: should get 200 with Last-Modified header
  18864. auto res1 = cli.Get("/static/ims_testfile.txt");
  18865. ASSERT_TRUE(res1);
  18866. ASSERT_EQ(200, res1->status);
  18867. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18868. std::string last_modified = res1->get_header_value("Last-Modified");
  18869. EXPECT_FALSE(last_modified.empty());
  18870. // If-Modified-Since with same time: expect 304
  18871. Headers h2 = {{"If-Modified-Since", last_modified}};
  18872. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  18873. ASSERT_TRUE(res2);
  18874. EXPECT_EQ(304, res2->status);
  18875. // If-Modified-Since with future time: expect 304
  18876. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18877. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  18878. ASSERT_TRUE(res3);
  18879. EXPECT_EQ(304, res3->status);
  18880. // If-Modified-Since with past time: expect 200
  18881. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18882. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  18883. ASSERT_TRUE(res4);
  18884. EXPECT_EQ(200, res4->status);
  18885. // If-None-Match takes precedence over If-Modified-Since
  18886. // (send matching ETag with old If-Modified-Since -> should still be 304)
  18887. ASSERT_TRUE(res1->has_header("ETag"));
  18888. std::string etag = res1->get_header_value("ETag");
  18889. Headers h5 = {{"If-None-Match", etag},
  18890. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18891. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  18892. ASSERT_TRUE(res5);
  18893. EXPECT_EQ(304, res5->status);
  18894. svr.stop();
  18895. t.join();
  18896. std::remove(fname);
  18897. }
  18898. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  18899. using namespace httplib;
  18900. Server svr;
  18901. // Endpoint that returns compressible content
  18902. svr.Get("/compressible", [](const Request &, Response &res) {
  18903. // Return a large enough body to trigger compression
  18904. std::string body(1000, 'a');
  18905. res.set_content(body, "text/plain");
  18906. });
  18907. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18908. svr.wait_until_ready();
  18909. Client cli(HOST, PORT);
  18910. // Request with gzip support: should get Vary header when compressed
  18911. cli.set_compress(true);
  18912. auto res1 = cli.Get("/compressible");
  18913. ASSERT_TRUE(res1);
  18914. EXPECT_EQ(200, res1->status);
  18915. // If Content-Encoding is set, Vary should also be set
  18916. if (res1->has_header("Content-Encoding")) {
  18917. EXPECT_TRUE(res1->has_header("Vary"));
  18918. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  18919. }
  18920. // Request without Accept-Encoding header: should not have compression
  18921. Headers h_no_compress;
  18922. auto res2 = cli.Get("/compressible", h_no_compress);
  18923. ASSERT_TRUE(res2);
  18924. EXPECT_EQ(200, res2->status);
  18925. // Verify Vary header is present when compression is applied
  18926. // (the exact behavior depends on server configuration)
  18927. svr.stop();
  18928. t.join();
  18929. }
  18930. TEST(ETagTest, IfRangeWithETag) {
  18931. using namespace httplib;
  18932. // Create a test file with known content
  18933. const char *fname = "if_range_testfile.txt";
  18934. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  18935. {
  18936. std::ofstream ofs(fname);
  18937. ofs << content;
  18938. ASSERT_TRUE(ofs.good());
  18939. }
  18940. Server svr;
  18941. svr.set_mount_point("/static", ".");
  18942. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18943. svr.wait_until_ready();
  18944. Client cli(HOST, PORT);
  18945. // First request: get ETag
  18946. auto res1 = cli.Get("/static/if_range_testfile.txt");
  18947. ASSERT_TRUE(res1);
  18948. ASSERT_EQ(200, res1->status);
  18949. ASSERT_TRUE(res1->has_header("ETag"));
  18950. std::string etag = res1->get_header_value("ETag");
  18951. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  18952. // Since our server generates weak ETags (W/"..."), If-Range with our
  18953. // ETag should NOT result in partial content - it should return full content.
  18954. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  18955. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  18956. ASSERT_TRUE(res2);
  18957. // Weak ETag in If-Range -> full content (200), not partial (206)
  18958. EXPECT_EQ(200, res2->status);
  18959. EXPECT_EQ(content, res2->body);
  18960. EXPECT_FALSE(res2->has_header("Content-Range"));
  18961. // Range request with non-matching If-Range (ETag): should get 200 (full
  18962. // content)
  18963. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  18964. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  18965. ASSERT_TRUE(res3);
  18966. EXPECT_EQ(200, res3->status);
  18967. EXPECT_EQ(content, res3->body);
  18968. EXPECT_FALSE(res3->has_header("Content-Range"));
  18969. // Range request with strong ETag (hypothetical - our server doesn't generate
  18970. // strong ETags, but if client sends a strong ETag that doesn't match, it
  18971. // should return full content)
  18972. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  18973. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  18974. ASSERT_TRUE(res4);
  18975. EXPECT_EQ(200, res4->status);
  18976. EXPECT_EQ(content, res4->body);
  18977. EXPECT_FALSE(res4->has_header("Content-Range"));
  18978. svr.stop();
  18979. t.join();
  18980. std::remove(fname);
  18981. }
  18982. TEST(ETagTest, IfRangeWithDate) {
  18983. using namespace httplib;
  18984. // Create a test file
  18985. const char *fname = "if_range_date_testfile.txt";
  18986. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  18987. {
  18988. std::ofstream ofs(fname);
  18989. ofs << content;
  18990. ASSERT_TRUE(ofs.good());
  18991. }
  18992. Server svr;
  18993. svr.set_mount_point("/static", ".");
  18994. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18995. svr.wait_until_ready();
  18996. Client cli(HOST, PORT);
  18997. // First request: get Last-Modified
  18998. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  18999. ASSERT_TRUE(res1);
  19000. ASSERT_EQ(200, res1->status);
  19001. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19002. std::string last_modified = res1->get_header_value("Last-Modified");
  19003. // Range request with matching If-Range (date): should get 206
  19004. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  19005. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  19006. ASSERT_TRUE(res2);
  19007. EXPECT_EQ(206, res2->status);
  19008. EXPECT_EQ("FGHIJ", res2->body);
  19009. // Range request with old If-Range date: should get 200 (full content)
  19010. Headers h3 = {{"Range", "bytes=5-9"},
  19011. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19012. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  19013. ASSERT_TRUE(res3);
  19014. EXPECT_EQ(200, res3->status);
  19015. EXPECT_EQ(content, res3->body);
  19016. // Range request with future If-Range date: should get 206
  19017. Headers h4 = {{"Range", "bytes=0-4"},
  19018. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19019. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  19020. ASSERT_TRUE(res4);
  19021. EXPECT_EQ(206, res4->status);
  19022. EXPECT_EQ("ABCDE", res4->body);
  19023. svr.stop();
  19024. t.join();
  19025. std::remove(fname);
  19026. }
  19027. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  19028. using namespace httplib;
  19029. const char *fname = "etag_malformed.txt";
  19030. const char *content = "malformed-etag";
  19031. {
  19032. std::ofstream ofs(fname);
  19033. ofs << content;
  19034. ASSERT_TRUE(ofs.good());
  19035. }
  19036. Server svr;
  19037. svr.set_mount_point("/static", ".");
  19038. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19039. svr.wait_until_ready();
  19040. Client cli(HOST, PORT);
  19041. // baseline: should get 200 and an ETag
  19042. auto res1 = cli.Get("/static/etag_malformed.txt");
  19043. ASSERT_TRUE(res1);
  19044. ASSERT_EQ(200, res1->status);
  19045. ASSERT_TRUE(res1->has_header("ETag"));
  19046. // Malformed ETag value (missing quotes) should be treated as non-matching
  19047. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  19048. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  19049. ASSERT_TRUE(res_bad);
  19050. EXPECT_EQ(200, res_bad->status);
  19051. // Whitespace-only header value should be considered invalid / non-matching
  19052. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  19053. "Host: localhost\r\n"
  19054. "If-None-Match: \r\n"
  19055. "Connection: close\r\n"
  19056. "\r\n";
  19057. std::string out;
  19058. ASSERT_TRUE(send_request(5, raw_req, &out));
  19059. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19060. svr.stop();
  19061. t.join();
  19062. std::remove(fname);
  19063. }
  19064. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  19065. using namespace httplib;
  19066. const char *fname = "ims_invalid_format.txt";
  19067. const char *content = "ims-bad-format";
  19068. {
  19069. std::ofstream ofs(fname);
  19070. ofs << content;
  19071. ASSERT_TRUE(ofs.good());
  19072. }
  19073. Server svr;
  19074. svr.set_mount_point("/static", ".");
  19075. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19076. svr.wait_until_ready();
  19077. Client cli(HOST, PORT);
  19078. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  19079. ASSERT_TRUE(res1);
  19080. ASSERT_EQ(200, res1->status);
  19081. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19082. // If-Modified-Since with invalid format should not result in 304
  19083. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  19084. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  19085. ASSERT_TRUE(res_bad);
  19086. EXPECT_EQ(200, res_bad->status);
  19087. // If-Range with invalid date format should be treated as mismatch -> full
  19088. // content (200)
  19089. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  19090. {"If-Range", "invalid-date"}};
  19091. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  19092. ASSERT_TRUE(res_ifrange);
  19093. EXPECT_EQ(200, res_ifrange->status);
  19094. svr.stop();
  19095. t.join();
  19096. std::remove(fname);
  19097. }
  19098. TEST(ETagTest, IfRangeWithMalformedETag) {
  19099. using namespace httplib;
  19100. const char *fname = "ifrange_malformed.txt";
  19101. const std::string content = "0123456789";
  19102. {
  19103. std::ofstream ofs(fname);
  19104. ofs << content;
  19105. ASSERT_TRUE(ofs.good());
  19106. }
  19107. Server svr;
  19108. svr.set_mount_point("/static", ".");
  19109. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19110. svr.wait_until_ready();
  19111. Client cli(HOST, PORT);
  19112. // First request: get ETag
  19113. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  19114. ASSERT_TRUE(res1);
  19115. ASSERT_EQ(200, res1->status);
  19116. ASSERT_TRUE(res1->has_header("ETag"));
  19117. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  19118. // full content (200)
  19119. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  19120. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  19121. ASSERT_TRUE(res2);
  19122. EXPECT_EQ(200, res2->status);
  19123. EXPECT_EQ(content, res2->body);
  19124. svr.stop();
  19125. t.join();
  19126. std::remove(fname);
  19127. }
  19128. TEST(ETagTest, ExtremeLargeDateValues) {
  19129. using namespace httplib;
  19130. const char *fname = "ims_extreme_date.txt";
  19131. const char *content = "ims-extreme-date";
  19132. {
  19133. std::ofstream ofs(fname);
  19134. ofs << content;
  19135. ASSERT_TRUE(ofs.good());
  19136. }
  19137. Server svr;
  19138. svr.set_mount_point("/static", ".");
  19139. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19140. svr.wait_until_ready();
  19141. Client cli(HOST, PORT);
  19142. auto res1 = cli.Get(std::string("/static/") + fname);
  19143. ASSERT_TRUE(res1);
  19144. ASSERT_EQ(200, res1->status);
  19145. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19146. // Extremely large year that may overflow date parsing routines.
  19147. Headers h_large_date = {
  19148. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19149. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  19150. ASSERT_TRUE(res_bad);
  19151. // Expect server to treat this as invalid/mismatch and return full content
  19152. EXPECT_EQ(200, res_bad->status);
  19153. // If-Range with extremely large date should be treated as mismatch -> full
  19154. // content (200)
  19155. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  19156. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19157. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  19158. ASSERT_TRUE(res_ifrange);
  19159. EXPECT_EQ(200, res_ifrange->status);
  19160. svr.stop();
  19161. t.join();
  19162. std::remove(fname);
  19163. }
  19164. TEST(ETagTest, NegativeFileModificationTime) {
  19165. using namespace httplib;
  19166. const char *fname = "ims_negative_mtime.txt";
  19167. const std::string content = "negative-mtime";
  19168. {
  19169. std::ofstream ofs(fname);
  19170. ofs << content;
  19171. ASSERT_TRUE(ofs.good());
  19172. }
  19173. // Try to set file mtime to a negative value. This may fail on some
  19174. // platforms/filesystems; if it fails, the test will still verify server
  19175. // behaves safely by performing a regular conditional request.
  19176. #if defined(__APPLE__) || defined(__linux__)
  19177. bool set_negative = false;
  19178. do {
  19179. struct timeval times[2];
  19180. // access time: now
  19181. times[0].tv_sec = time(nullptr);
  19182. times[0].tv_usec = 0;
  19183. // modification time: negative (e.g., -1)
  19184. times[1].tv_sec = -1;
  19185. times[1].tv_usec = 0;
  19186. if (utimes(fname, times) == 0) { set_negative = true; }
  19187. } while (0);
  19188. #else
  19189. bool set_negative = false;
  19190. #endif
  19191. Server svr;
  19192. svr.set_mount_point("/static", ".");
  19193. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19194. svr.wait_until_ready();
  19195. Client cli(HOST, PORT);
  19196. auto res1 = cli.Get(std::string("/static/") + fname);
  19197. ASSERT_TRUE(res1);
  19198. ASSERT_EQ(200, res1->status);
  19199. bool has_last_modified = res1->has_header("Last-Modified");
  19200. std::string last_modified;
  19201. if (has_last_modified) {
  19202. last_modified = res1->get_header_value("Last-Modified");
  19203. }
  19204. if (set_negative) {
  19205. // If we successfully set a negative mtime, ensure server returns a
  19206. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  19207. // with an old date and ensure server handles it without crash.
  19208. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  19209. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  19210. ASSERT_TRUE(res2);
  19211. // Behavior may vary; at minimum ensure server responds (200 or 304).
  19212. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  19213. } else {
  19214. // Could not set negative mtime on this platform; fall back to verifying
  19215. // that normal invalid/malformed dates are treated safely (non-304).
  19216. Headers h_bad_date = {
  19217. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19218. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  19219. ASSERT_TRUE(res_bad);
  19220. EXPECT_EQ(200, res_bad->status);
  19221. }
  19222. svr.stop();
  19223. t.join();
  19224. std::remove(fname);
  19225. }
  19226. //==============================================================================
  19227. // Integration Tests with Server
  19228. //==============================================================================
  19229. class SSEIntegrationTest : public ::testing::Test {
  19230. protected:
  19231. void SetUp() override {
  19232. stop_server_.store(false);
  19233. events_.clear();
  19234. server_ = httplib::detail::make_unique<Server>();
  19235. setup_server();
  19236. start_server();
  19237. }
  19238. void TearDown() override {
  19239. stop_server_.store(true);
  19240. event_cv_.notify_all();
  19241. server_->stop();
  19242. if (server_thread_.joinable()) { server_thread_.join(); }
  19243. }
  19244. void setup_server() {
  19245. // Simple SSE endpoint
  19246. server_->Get("/events", [this](const Request &req, Response &res) {
  19247. auto last_id = req.get_header_value("Last-Event-ID");
  19248. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  19249. res.set_chunked_content_provider(
  19250. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  19251. std::unique_lock<std::mutex> lock(event_mutex_);
  19252. if (event_cv_.wait_for(
  19253. lock, std::chrono::milliseconds(200), [this] {
  19254. return !events_.empty() || stop_server_.load();
  19255. })) {
  19256. if (stop_server_.load()) { return false; }
  19257. if (!events_.empty()) {
  19258. std::string event = events_.front();
  19259. events_.erase(events_.begin());
  19260. sink.write(event.data(), event.size());
  19261. return true;
  19262. }
  19263. }
  19264. return !stop_server_.load();
  19265. });
  19266. });
  19267. // Endpoint that returns error
  19268. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  19269. res.status = 500;
  19270. res.set_content("Internal Server Error", "text/plain");
  19271. });
  19272. // Endpoint for custom event types
  19273. server_->Get("/custom-events", [](const Request &, Response &res) {
  19274. res.set_chunked_content_provider(
  19275. "text/event-stream", [](size_t offset, DataSink &sink) {
  19276. if (offset == 0) {
  19277. std::string event = "event: update\ndata: updated\n\n"
  19278. "event: delete\ndata: deleted\n\n";
  19279. sink.write(event.data(), event.size());
  19280. }
  19281. return false; // End stream after sending
  19282. });
  19283. });
  19284. }
  19285. void start_server() {
  19286. port_ = server_->bind_to_any_port(HOST);
  19287. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19288. // Wait for server to start
  19289. while (!server_->is_running()) {
  19290. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19291. }
  19292. }
  19293. int get_port() const { return port_; }
  19294. void send_event(const std::string &event) {
  19295. std::lock_guard<std::mutex> lock(event_mutex_);
  19296. events_.push_back(event);
  19297. event_cv_.notify_all();
  19298. }
  19299. std::unique_ptr<Server> server_;
  19300. std::thread server_thread_;
  19301. std::mutex event_mutex_;
  19302. std::condition_variable event_cv_;
  19303. std::vector<std::string> events_;
  19304. std::atomic<bool> stop_server_{false};
  19305. std::string last_received_event_id_;
  19306. int port_ = 0;
  19307. };
  19308. //==============================================================================
  19309. // SSE Parsing Tests
  19310. //==============================================================================
  19311. class SSEParsingTest : public SSEIntegrationTest {
  19312. protected:
  19313. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  19314. // A trailing sentinel event tells when the whole stream has been parsed.
  19315. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  19316. auto body = stream + "event: end\ndata: end\n\n";
  19317. server_->Get("/parse", [body](const Request &, Response &res) {
  19318. res.set_content(body, "text/event-stream");
  19319. });
  19320. return collect("/parse");
  19321. }
  19322. // Runs SSEClient against path until an "end" event arrives and returns the
  19323. // messages dispatched before it
  19324. std::vector<sse::SSEMessage> collect(const std::string &path) {
  19325. Client client(HOST, get_port());
  19326. sse::SSEClient sse(client, path);
  19327. std::mutex mutex;
  19328. std::condition_variable cv;
  19329. std::vector<sse::SSEMessage> messages;
  19330. auto done = false;
  19331. sse.on_message([&](const sse::SSEMessage &msg) {
  19332. std::lock_guard<std::mutex> lock(mutex);
  19333. // Ignore a replay from a reconnect that races with stop()
  19334. if (!done) { messages.push_back(msg); }
  19335. });
  19336. sse.on_event("end", [&](const sse::SSEMessage &) {
  19337. std::lock_guard<std::mutex> lock(mutex);
  19338. done = true;
  19339. cv.notify_all();
  19340. });
  19341. sse.set_reconnect_interval(100);
  19342. sse.start_async();
  19343. {
  19344. std::unique_lock<std::mutex> lock(mutex);
  19345. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  19346. }
  19347. sse.stop();
  19348. EXPECT_TRUE(done);
  19349. return messages;
  19350. }
  19351. };
  19352. TEST_F(SSEParsingTest, SingleLineData) {
  19353. auto msgs = parse("data: hello\n\n");
  19354. ASSERT_EQ(msgs.size(), 1u);
  19355. EXPECT_EQ(msgs[0].data, "hello");
  19356. EXPECT_EQ(msgs[0].event, "message");
  19357. }
  19358. TEST_F(SSEParsingTest, MultiLineData) {
  19359. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  19360. ASSERT_EQ(msgs.size(), 1u);
  19361. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  19362. }
  19363. TEST_F(SSEParsingTest, CustomEventType) {
  19364. auto msgs = parse("event: update\ndata: payload\n\n");
  19365. ASSERT_EQ(msgs.size(), 1u);
  19366. EXPECT_EQ(msgs[0].event, "update");
  19367. EXPECT_EQ(msgs[0].data, "payload");
  19368. }
  19369. TEST_F(SSEParsingTest, EventIdHandling) {
  19370. auto msgs = parse("id: 12345\ndata: test\n\n");
  19371. ASSERT_EQ(msgs.size(), 1u);
  19372. EXPECT_EQ(msgs[0].id, "12345");
  19373. }
  19374. TEST_F(SSEParsingTest, EmptyEventId) {
  19375. auto msgs = parse("id:\ndata: test\n\n");
  19376. ASSERT_EQ(msgs.size(), 1u);
  19377. EXPECT_EQ(msgs[0].id, "");
  19378. }
  19379. TEST_F(SSEParsingTest, CommentsIgnored) {
  19380. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  19381. ASSERT_EQ(msgs.size(), 1u);
  19382. EXPECT_EQ(msgs[0].data, "hello");
  19383. EXPECT_EQ(msgs[0].event, "message");
  19384. }
  19385. TEST_F(SSEParsingTest, ColonInValue) {
  19386. auto msgs = parse("data: hello:world:test\n\n");
  19387. ASSERT_EQ(msgs.size(), 1u);
  19388. EXPECT_EQ(msgs[0].data, "hello:world:test");
  19389. }
  19390. TEST_F(SSEParsingTest, FieldNameOnly) {
  19391. // A line without a colon is a field name with an empty value
  19392. auto msgs = parse("data\n\n");
  19393. ASSERT_EQ(msgs.size(), 1u);
  19394. EXPECT_EQ(msgs[0].data, "");
  19395. }
  19396. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  19397. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  19398. ASSERT_EQ(msgs.size(), 1u);
  19399. EXPECT_EQ(msgs[0].event, "update");
  19400. EXPECT_EQ(msgs[0].data, "hello");
  19401. }
  19402. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  19403. auto msgs = parse("data\r\n\r\n");
  19404. ASSERT_EQ(msgs.size(), 1u);
  19405. EXPECT_EQ(msgs[0].data, "");
  19406. }
  19407. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  19408. auto msgs = parse("event: update\rdata: hello\r\r");
  19409. ASSERT_EQ(msgs.size(), 1u);
  19410. EXPECT_EQ(msgs[0].event, "update");
  19411. EXPECT_EQ(msgs[0].data, "hello");
  19412. }
  19413. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  19414. // Chunk boundaries fall inside every \r\n and right before the first one
  19415. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  19416. "\n\r", "\nevent: end\ndata: end\n\n"};
  19417. server_->Get("/split", [chunks](const Request &, Response &res) {
  19418. auto i = std::make_shared<size_t>(0);
  19419. res.set_chunked_content_provider(
  19420. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  19421. if (*i == chunks.size()) {
  19422. sink.done();
  19423. } else {
  19424. sink.write(chunks[*i].data(), chunks[*i].size());
  19425. (*i)++;
  19426. }
  19427. return true;
  19428. });
  19429. });
  19430. auto msgs = collect("/split");
  19431. ASSERT_EQ(msgs.size(), 1u);
  19432. EXPECT_EQ(msgs[0].event, "update");
  19433. EXPECT_EQ(msgs[0].data, "hello");
  19434. }
  19435. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  19436. // Only a BOM at the start of the stream is ignored
  19437. auto msgs = parse("\xEF\xBB\xBF"
  19438. "data: first\n\n"
  19439. "\xEF\xBB\xBF"
  19440. "data: second\n\n");
  19441. ASSERT_EQ(msgs.size(), 1u);
  19442. EXPECT_EQ(msgs[0].data, "first");
  19443. }
  19444. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  19445. auto msgs = parse("unknown: value\ndata: hello\n\n");
  19446. ASSERT_EQ(msgs.size(), 1u);
  19447. EXPECT_EQ(msgs[0].data, "hello");
  19448. EXPECT_EQ(msgs[0].event, "message");
  19449. }
  19450. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  19451. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  19452. ASSERT_EQ(msgs.size(), 2u);
  19453. EXPECT_EQ(msgs[0].data, "hello");
  19454. EXPECT_EQ(msgs[1].data, "hello");
  19455. }
  19456. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  19457. // An event without data is not dispatched, and its type must not leak
  19458. // into the next event
  19459. auto msgs = parse("event: update\n\ndata: hello\n\n");
  19460. ASSERT_EQ(msgs.size(), 1u);
  19461. EXPECT_EQ(msgs[0].event, "message");
  19462. EXPECT_EQ(msgs[0].data, "hello");
  19463. }
  19464. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  19465. // The first connection sends only an id; the second echoes back the
  19466. // Last-Event-ID it was reconnected with
  19467. std::atomic<int> connection_count{0};
  19468. server_->Get("/id-only", [&](const Request &req, Response &res) {
  19469. if (connection_count++ == 0) {
  19470. res.set_content("id: 42\n\n", "text/event-stream");
  19471. } else {
  19472. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19473. "\n\nevent: end\ndata: end\n\n",
  19474. "text/event-stream");
  19475. }
  19476. });
  19477. auto msgs = collect("/id-only");
  19478. ASSERT_EQ(msgs.size(), 1u);
  19479. EXPECT_EQ(msgs[0].data, "42");
  19480. }
  19481. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  19482. // The first connection sets an id and then clears it with an empty one; the
  19483. // second reports whether it was reconnected with a Last-Event-ID
  19484. std::atomic<int> connection_count{0};
  19485. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  19486. if (connection_count++ == 0) {
  19487. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  19488. "text/event-stream");
  19489. } else {
  19490. res.set_content(
  19491. std::string("data: ") +
  19492. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  19493. "\n\nevent: end\ndata: end\n\n",
  19494. "text/event-stream");
  19495. }
  19496. });
  19497. auto msgs = collect("/id-clear");
  19498. ASSERT_EQ(msgs.size(), 3u);
  19499. EXPECT_EQ(msgs[0].id, "1");
  19500. EXPECT_EQ(msgs[1].id, "");
  19501. EXPECT_EQ(msgs[2].data, "not sent");
  19502. }
  19503. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  19504. // The first connection sets an id and then sends ids that cannot be carried
  19505. // in a header; the second echoes back the Last-Event-ID it was reconnected
  19506. // with
  19507. std::atomic<int> connection_count{0};
  19508. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  19509. if (connection_count++ == 0) {
  19510. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  19511. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  19512. "text/event-stream");
  19513. } else {
  19514. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19515. "\n\nevent: end\ndata: end\n\n",
  19516. "text/event-stream");
  19517. }
  19518. });
  19519. auto msgs = collect("/id-unsendable");
  19520. ASSERT_EQ(msgs.size(), 1u);
  19521. EXPECT_EQ(msgs[0].data, "42");
  19522. }
  19523. TEST_F(SSEParsingTest, CompleteEventParsing) {
  19524. auto msgs = parse("event: notification\nid: evt-42\n"
  19525. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  19526. ASSERT_EQ(msgs.size(), 1u);
  19527. EXPECT_EQ(msgs[0].event, "notification");
  19528. EXPECT_EQ(msgs[0].id, "evt-42");
  19529. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  19530. }
  19531. TEST(SSEMessageTest, Clear) {
  19532. sse::SSEMessage msg;
  19533. msg.event = "custom";
  19534. msg.data = "some data";
  19535. msg.id = "123";
  19536. msg.clear();
  19537. EXPECT_EQ(msg.event, "message");
  19538. EXPECT_EQ(msg.data, "");
  19539. EXPECT_EQ(msg.id, "");
  19540. }
  19541. //==============================================================================
  19542. // SSE Integration Tests
  19543. //==============================================================================
  19544. // Test: Successful connection and on_open callback
  19545. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  19546. // Add a simple endpoint that sends one event and closes
  19547. server_->Get("/simple-event", [](const Request &, Response &res) {
  19548. res.set_chunked_content_provider(
  19549. "text/event-stream", [](size_t offset, DataSink &sink) {
  19550. if (offset == 0) {
  19551. std::string event = "data: hello\n\n";
  19552. sink.write(event.data(), event.size());
  19553. }
  19554. return false; // Close stream after sending
  19555. });
  19556. });
  19557. Client client("localhost", get_port());
  19558. sse::SSEClient sse(client, "/simple-event");
  19559. std::atomic<bool> open_called{false};
  19560. std::atomic<bool> message_received{false};
  19561. sse.on_open([&open_called]() { open_called.store(true); });
  19562. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  19563. if (msg.data == "hello") { message_received.store(true); }
  19564. });
  19565. sse.set_reconnect_interval(100);
  19566. sse.set_max_reconnect_attempts(1);
  19567. // Start async
  19568. sse.start_async();
  19569. // Wait for message to be processed
  19570. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19571. sse.stop();
  19572. EXPECT_TRUE(open_called.load());
  19573. EXPECT_TRUE(message_received.load());
  19574. }
  19575. // Test: on_message callback
  19576. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  19577. // Endpoint that sends multiple events then closes
  19578. server_->Get("/multi-event", [](const Request &, Response &res) {
  19579. res.set_chunked_content_provider(
  19580. "text/event-stream", [](size_t offset, DataSink &sink) {
  19581. if (offset == 0) {
  19582. std::string events = "data: message1\n\ndata: message2\n\n";
  19583. sink.write(events.data(), events.size());
  19584. }
  19585. return false;
  19586. });
  19587. });
  19588. Client client("localhost", get_port());
  19589. sse::SSEClient sse(client, "/multi-event");
  19590. std::vector<std::string> received_messages;
  19591. std::mutex messages_mutex;
  19592. sse.on_message([&](const sse::SSEMessage &msg) {
  19593. std::lock_guard<std::mutex> lock(messages_mutex);
  19594. received_messages.push_back(msg.data);
  19595. });
  19596. sse.set_reconnect_interval(100);
  19597. sse.set_max_reconnect_attempts(1);
  19598. sse.start_async();
  19599. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19600. sse.stop();
  19601. std::lock_guard<std::mutex> lock(messages_mutex);
  19602. EXPECT_GE(received_messages.size(), 2u);
  19603. if (received_messages.size() >= 2) {
  19604. EXPECT_EQ(received_messages[0], "message1");
  19605. EXPECT_EQ(received_messages[1], "message2");
  19606. }
  19607. }
  19608. // Test: on_event for specific types
  19609. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  19610. Client client("localhost", get_port());
  19611. sse::SSEClient sse(client, "/custom-events");
  19612. std::atomic<bool> update_received{false};
  19613. std::atomic<bool> delete_received{false};
  19614. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  19615. if (msg.data == "updated") { update_received.store(true); }
  19616. });
  19617. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  19618. if (msg.data == "deleted") { delete_received.store(true); }
  19619. });
  19620. sse.set_max_reconnect_attempts(1);
  19621. sse.start_async();
  19622. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  19623. sse.stop();
  19624. EXPECT_TRUE(update_received.load());
  19625. EXPECT_TRUE(delete_received.load());
  19626. }
  19627. // Test: on_error callback on connection failure
  19628. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  19629. // Connect to a non-existent port
  19630. Client client("localhost", 59999);
  19631. sse::SSEClient sse(client, "/events");
  19632. std::atomic<bool> error_called{false};
  19633. Error received_error = Error::Success;
  19634. sse.on_error([&](Error err) {
  19635. error_called.store(true);
  19636. received_error = err;
  19637. });
  19638. sse.set_reconnect_interval(50);
  19639. sse.set_max_reconnect_attempts(1);
  19640. sse.start_async();
  19641. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  19642. sse.stop();
  19643. EXPECT_TRUE(error_called.load());
  19644. EXPECT_NE(received_error, Error::Success);
  19645. }
  19646. // Test: Last-Event-ID header sent on reconnect
  19647. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  19648. // Endpoint that sends event with ID
  19649. server_->Get("/event-with-id", [](const Request &, Response &res) {
  19650. res.set_chunked_content_provider(
  19651. "text/event-stream", [](size_t offset, DataSink &sink) {
  19652. if (offset == 0) {
  19653. std::string event = "id: evt-123\ndata: test\n\n";
  19654. sink.write(event.data(), event.size());
  19655. }
  19656. return false;
  19657. });
  19658. });
  19659. Client client("localhost", get_port());
  19660. sse::SSEClient sse(client, "/event-with-id");
  19661. std::atomic<bool> id_received{false};
  19662. sse.on_message([&](const sse::SSEMessage &msg) {
  19663. if (!msg.id.empty()) { id_received.store(true); }
  19664. });
  19665. sse.set_reconnect_interval(100);
  19666. sse.set_max_reconnect_attempts(1);
  19667. sse.start_async();
  19668. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19669. sse.stop();
  19670. EXPECT_TRUE(id_received.load());
  19671. EXPECT_EQ(sse.last_event_id(), "evt-123");
  19672. }
  19673. // Test: Manual stop
  19674. TEST_F(SSEIntegrationTest, ManualStop) {
  19675. // Endpoint that sends one event and stays open briefly
  19676. std::atomic<bool> handler_running{true};
  19677. server_->Get("/stay-open", [&handler_running](const Request &,
  19678. Response &res) {
  19679. res.set_chunked_content_provider(
  19680. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  19681. if (offset == 0) {
  19682. std::string event = "data: connected\n\n";
  19683. sink.write(event.data(), event.size());
  19684. }
  19685. // Keep connection open while handler_running is true
  19686. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  19687. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19688. }
  19689. return false;
  19690. });
  19691. });
  19692. Client client("localhost", get_port());
  19693. sse::SSEClient sse(client, "/stay-open");
  19694. std::atomic<bool> connected{false};
  19695. sse.on_open([&connected]() { connected.store(true); });
  19696. sse.set_reconnect_interval(100);
  19697. sse.set_max_reconnect_attempts(1);
  19698. sse.start_async();
  19699. // Wait for connection to establish
  19700. for (int i = 0; i < 20 && !connected.load(); ++i) {
  19701. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19702. }
  19703. EXPECT_TRUE(connected.load());
  19704. EXPECT_TRUE(sse.is_connected());
  19705. // Signal handler to stop
  19706. handler_running.store(false);
  19707. // Stop SSE client
  19708. sse.stop();
  19709. EXPECT_FALSE(sse.is_connected());
  19710. }
  19711. // Test: SSEClient with custom headers
  19712. TEST_F(SSEIntegrationTest, CustomHeaders) {
  19713. // Setup a server endpoint that checks for custom header
  19714. std::atomic<bool> header_received{false};
  19715. server_->Get("/header-check", [&](const Request &req, Response &res) {
  19716. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  19717. header_received.store(true);
  19718. }
  19719. res.set_chunked_content_provider("text/event-stream",
  19720. [](size_t, DataSink &) { return false; });
  19721. });
  19722. Client client("localhost", get_port());
  19723. Headers headers = {{"X-Custom-Header", "custom-value"}};
  19724. sse::SSEClient sse(client, "/header-check", headers);
  19725. sse.set_max_reconnect_attempts(1);
  19726. sse.start_async();
  19727. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  19728. sse.stop();
  19729. EXPECT_TRUE(header_received.load());
  19730. }
  19731. // Test: Reconnect interval configuration
  19732. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  19733. Client client("localhost", get_port());
  19734. sse::SSEClient sse(client, "/events");
  19735. auto &result = sse.set_reconnect_interval(500);
  19736. // Builder pattern should return reference to self
  19737. EXPECT_EQ(&result, &sse);
  19738. }
  19739. // Test: Max reconnect attempts
  19740. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  19741. // Connect to non-existent port to force reconnects
  19742. Client client("localhost", 59998);
  19743. sse::SSEClient sse(client, "/events");
  19744. std::atomic<int> error_count{0};
  19745. sse.on_error([&](Error) { error_count.fetch_add(1); });
  19746. sse.set_reconnect_interval(50);
  19747. sse.set_max_reconnect_attempts(2);
  19748. auto start = std::chrono::steady_clock::now();
  19749. sse.start(); // Blocking call
  19750. auto end = std::chrono::steady_clock::now();
  19751. // Should have stopped after 2 failed attempts
  19752. EXPECT_GE(error_count.load(), 2);
  19753. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  19754. auto duration =
  19755. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  19756. #ifdef _WIN32
  19757. // Windows is much slower for socket connection failures
  19758. EXPECT_LT(duration.count(), 7000);
  19759. #else
  19760. EXPECT_LT(duration.count(), 1000);
  19761. #endif
  19762. }
  19763. // Test: Multi-line data in integration
  19764. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  19765. // Endpoint with multi-line data
  19766. server_->Get("/multiline-data", [](const Request &, Response &res) {
  19767. res.set_chunked_content_provider(
  19768. "text/event-stream", [](size_t offset, DataSink &sink) {
  19769. if (offset == 0) {
  19770. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  19771. sink.write(event.data(), event.size());
  19772. }
  19773. return false;
  19774. });
  19775. });
  19776. Client client("localhost", get_port());
  19777. sse::SSEClient sse(client, "/multiline-data");
  19778. std::string received_data;
  19779. std::mutex data_mutex;
  19780. sse.on_message([&](const sse::SSEMessage &msg) {
  19781. std::lock_guard<std::mutex> lock(data_mutex);
  19782. received_data = msg.data;
  19783. });
  19784. sse.set_reconnect_interval(100);
  19785. sse.set_max_reconnect_attempts(1);
  19786. sse.start_async();
  19787. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19788. sse.stop();
  19789. std::lock_guard<std::mutex> lock(data_mutex);
  19790. EXPECT_EQ(received_data, "line1\nline2\nline3");
  19791. }
  19792. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  19793. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  19794. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  19795. DataSink &sink) {
  19796. if (offset == 0) {
  19797. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  19798. sink.write(events.data(), events.size());
  19799. }
  19800. return false;
  19801. });
  19802. });
  19803. Client client("localhost", get_port());
  19804. sse::SSEClient sse(client, "/empty-data-lines");
  19805. std::mutex mutex;
  19806. std::condition_variable cv;
  19807. std::vector<std::string> received;
  19808. sse.on_message([&](const sse::SSEMessage &msg) {
  19809. std::lock_guard<std::mutex> lock(mutex);
  19810. received.push_back(msg.data);
  19811. cv.notify_all();
  19812. });
  19813. sse.set_max_reconnect_attempts(1);
  19814. sse.start_async();
  19815. {
  19816. std::unique_lock<std::mutex> lock(mutex);
  19817. cv.wait_for(lock, std::chrono::seconds(2),
  19818. [&] { return received.size() >= 3; });
  19819. }
  19820. sse.stop();
  19821. ASSERT_GE(received.size(), 3u);
  19822. EXPECT_EQ(received[0], "");
  19823. EXPECT_EQ(received[1], "\nhello");
  19824. EXPECT_EQ(received[2], "");
  19825. }
  19826. // Test: Auto-reconnect after server disconnection
  19827. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  19828. std::atomic<int> connection_count{0};
  19829. std::atomic<int> message_count{0};
  19830. // Endpoint that sends one event and closes, forcing reconnect
  19831. server_->Get("/reconnect-test",
  19832. [&connection_count](const Request &, Response &res) {
  19833. connection_count.fetch_add(1);
  19834. res.set_chunked_content_provider(
  19835. "text/event-stream", [](size_t offset, DataSink &sink) {
  19836. if (offset == 0) {
  19837. std::string event = "data: hello\n\n";
  19838. sink.write(event.data(), event.size());
  19839. }
  19840. return false; // Close connection after sending
  19841. });
  19842. });
  19843. Client client("localhost", get_port());
  19844. sse::SSEClient sse(client, "/reconnect-test");
  19845. sse.on_message([&message_count](const sse::SSEMessage &) {
  19846. message_count.fetch_add(1);
  19847. });
  19848. sse.set_reconnect_interval(100);
  19849. sse.set_max_reconnect_attempts(3);
  19850. sse.start_async();
  19851. // Wait long enough for multiple reconnects
  19852. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19853. sse.stop();
  19854. // Should have connected multiple times (initial + reconnects)
  19855. EXPECT_GE(connection_count.load(), 2);
  19856. // Should have received messages from multiple connections
  19857. EXPECT_GE(message_count.load(), 2);
  19858. }
  19859. // Test: A retry field that is not all ASCII digits is ignored
  19860. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  19861. std::atomic<int> connection_count{0};
  19862. server_->Get("/bad-retry",
  19863. [&connection_count](const Request &, Response &res) {
  19864. connection_count.fetch_add(1);
  19865. res.set_chunked_content_provider(
  19866. "text/event-stream", [](size_t offset, DataSink &sink) {
  19867. if (offset == 0) {
  19868. std::string event = "retry: -1\ndata: hello\n\n";
  19869. sink.write(event.data(), event.size());
  19870. }
  19871. return false;
  19872. });
  19873. });
  19874. Client client("localhost", get_port());
  19875. sse::SSEClient sse(client, "/bad-retry");
  19876. sse.set_reconnect_interval(10000);
  19877. sse.start_async();
  19878. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19879. sse.stop();
  19880. EXPECT_EQ(connection_count.load(), 1);
  19881. }
  19882. // Test: A retry field of all ASCII digits sets the reconnection time
  19883. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  19884. std::mutex mutex;
  19885. std::condition_variable cv;
  19886. std::vector<std::chrono::steady_clock::time_point> connected_at;
  19887. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  19888. {
  19889. std::lock_guard<std::mutex> lock(mutex);
  19890. connected_at.push_back(std::chrono::steady_clock::now());
  19891. cv.notify_all();
  19892. }
  19893. res.set_chunked_content_provider(
  19894. "text/event-stream", [](size_t offset, DataSink &sink) {
  19895. if (offset == 0) {
  19896. std::string event = "retry: 0\ndata: hello\n\n";
  19897. sink.write(event.data(), event.size());
  19898. }
  19899. return false;
  19900. });
  19901. });
  19902. Client client("localhost", get_port());
  19903. sse::SSEClient sse(client, "/zero-retry");
  19904. sse.set_reconnect_interval(10000);
  19905. sse.start_async();
  19906. {
  19907. std::unique_lock<std::mutex> lock(mutex);
  19908. cv.wait_for(lock, std::chrono::seconds(5),
  19909. [&] { return connected_at.size() >= 2; });
  19910. }
  19911. sse.stop();
  19912. // The server-supplied interval is applied, but never below 100ms, so
  19913. // "retry: 0" does not cause a busy reconnect loop
  19914. std::lock_guard<std::mutex> lock(mutex);
  19915. ASSERT_GE(connected_at.size(), 2u);
  19916. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  19917. connected_at[1] - connected_at[0])
  19918. .count();
  19919. EXPECT_GE(interval_ms, 100);
  19920. }
  19921. // Test: Last-Event-ID sent on reconnect
  19922. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  19923. std::atomic<int> connection_count{0};
  19924. std::vector<std::string> received_last_event_ids;
  19925. std::mutex id_mutex;
  19926. // Endpoint that checks Last-Event-ID header and sends event with ID
  19927. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  19928. int conn = connection_count.fetch_add(1);
  19929. // Capture the Last-Event-ID header from each connection
  19930. {
  19931. std::lock_guard<std::mutex> lock(id_mutex);
  19932. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  19933. }
  19934. res.set_chunked_content_provider(
  19935. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  19936. if (offset == 0) {
  19937. std::string event =
  19938. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  19939. sink.write(event.data(), event.size());
  19940. }
  19941. return false;
  19942. });
  19943. });
  19944. Client client("localhost", get_port());
  19945. sse::SSEClient sse(client, "/reconnect-with-id");
  19946. sse.set_reconnect_interval(100);
  19947. sse.set_max_reconnect_attempts(3);
  19948. sse.start_async();
  19949. // Wait for at least 2 connections
  19950. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19951. sse.stop();
  19952. // Verify behavior
  19953. std::lock_guard<std::mutex> lock(id_mutex);
  19954. EXPECT_GE(received_last_event_ids.size(), 2u);
  19955. // First connection should have no Last-Event-ID
  19956. if (!received_last_event_ids.empty()) {
  19957. EXPECT_EQ(received_last_event_ids[0], "");
  19958. }
  19959. // Second connection should have Last-Event-ID from first connection
  19960. if (received_last_event_ids.size() >= 2) {
  19961. EXPECT_EQ(received_last_event_ids[1], "event-0");
  19962. }
  19963. }
  19964. // Test: set_headers updates headers used on reconnect
  19965. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  19966. std::vector<std::string> received_tokens;
  19967. std::mutex token_mutex;
  19968. // Endpoint that captures Authorization header
  19969. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  19970. {
  19971. std::lock_guard<std::mutex> lock(token_mutex);
  19972. received_tokens.push_back(req.get_header_value("Authorization"));
  19973. }
  19974. res.set_chunked_content_provider(
  19975. "text/event-stream", [](size_t offset, DataSink &sink) {
  19976. if (offset == 0) {
  19977. std::string event = "data: hello\n\n";
  19978. sink.write(event.data(), event.size());
  19979. }
  19980. return false; // Close connection to trigger reconnect
  19981. });
  19982. });
  19983. Client client("localhost", get_port());
  19984. Headers headers = {{"Authorization", "Bearer old-token"}};
  19985. sse::SSEClient sse(client, "/auth-check", headers);
  19986. // Update headers on each successful connection
  19987. sse.on_open(
  19988. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  19989. sse.set_reconnect_interval(100);
  19990. sse.set_max_reconnect_attempts(3);
  19991. sse.start_async();
  19992. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19993. sse.stop();
  19994. std::lock_guard<std::mutex> lock(token_mutex);
  19995. ASSERT_GE(received_tokens.size(), 2u);
  19996. // First connection uses original header
  19997. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  19998. // Second connection uses updated header from set_headers
  19999. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  20000. }
  20001. // Test: 401 allows reconnection (so on_error can refresh headers)
  20002. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  20003. std::atomic<int> connection_count{0};
  20004. // Endpoint: returns 401 on first attempt, 200 on second
  20005. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  20006. int conn = connection_count.fetch_add(1);
  20007. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  20008. res.status = StatusCode::Unauthorized_401;
  20009. res.set_content("Unauthorized", "text/plain");
  20010. return;
  20011. }
  20012. res.set_chunked_content_provider(
  20013. "text/event-stream", [](size_t offset, DataSink &sink) {
  20014. if (offset == 0) {
  20015. std::string event = "data: authenticated\n\n";
  20016. sink.write(event.data(), event.size());
  20017. }
  20018. return false;
  20019. });
  20020. });
  20021. Client client("localhost", get_port());
  20022. Headers headers = {{"Authorization", "Bearer expired"}};
  20023. sse::SSEClient sse(client, "/auth-retry", headers);
  20024. std::atomic<bool> message_received{false};
  20025. // Refresh token on error
  20026. sse.on_error(
  20027. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  20028. sse.on_message([&](const sse::SSEMessage &msg) {
  20029. if (msg.data == "authenticated") { message_received.store(true); }
  20030. });
  20031. sse.set_reconnect_interval(100);
  20032. sse.set_max_reconnect_attempts(3);
  20033. sse.start_async();
  20034. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20035. sse.stop();
  20036. // Should have reconnected after 401 and succeeded with new token
  20037. EXPECT_GE(connection_count.load(), 2);
  20038. EXPECT_TRUE(message_received.load());
  20039. }
  20040. TEST(Issue2318Test, EmptyHostString) {
  20041. {
  20042. httplib::Client cli_empty("", PORT);
  20043. auto res = cli_empty.Get("/");
  20044. ASSERT_FALSE(res);
  20045. EXPECT_EQ(httplib::Error::Connection, res.error());
  20046. }
  20047. {
  20048. httplib::Client cli(" ", PORT);
  20049. auto res = cli.Get("/");
  20050. ASSERT_FALSE(res);
  20051. EXPECT_EQ(httplib::Error::Connection, res.error());
  20052. }
  20053. }
  20054. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20055. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  20056. Server svr;
  20057. // Set a small payload limit (1KB)
  20058. svr.set_payload_max_length(1024);
  20059. svr.Post("/test", [&](const Request &req, Response &res) {
  20060. res.set_content("Body size: " + std::to_string(req.body.size()),
  20061. "text/plain");
  20062. });
  20063. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  20064. auto se = detail::scope_exit([&] {
  20065. svr.stop();
  20066. listen_thread.join();
  20067. });
  20068. svr.wait_until_ready();
  20069. // Create data that compresses well but exceeds limit when decompressed
  20070. // 8KB of repeated null bytes compresses to a very small size
  20071. std::string original_data(8 * 1024, '\0');
  20072. // Compress the data using gzip
  20073. std::string compressed_data;
  20074. detail::gzip_compressor compressor;
  20075. compressor.compress(original_data.data(), original_data.size(), true,
  20076. [&](const char *data, size_t size) {
  20077. compressed_data.append(data, size);
  20078. return true;
  20079. });
  20080. // Verify compression worked (compressed should be much smaller)
  20081. ASSERT_LT(compressed_data.size(), original_data.size());
  20082. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  20083. // Send compressed data with Content-Encoding: gzip
  20084. Client cli(HOST, PORT);
  20085. Headers headers = {{"Content-Encoding", "gzip"}};
  20086. auto res =
  20087. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  20088. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  20089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20090. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  20091. }
  20092. #endif
  20093. // ============================================================================
  20094. // OpenSSL-Specific Tests
  20095. // ============================================================================
  20096. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  20097. X509 *readCertificate(const std::string &strFileName) {
  20098. std::ifstream inStream(strFileName);
  20099. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  20100. std::istreambuf_iterator<char>());
  20101. if (strCertPEM.empty()) return (nullptr);
  20102. BIO *pbCert = BIO_new(BIO_s_mem());
  20103. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  20104. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  20105. BIO_free(pbCert);
  20106. return (pCert);
  20107. }
  20108. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  20109. std::ifstream inStream(strFileName);
  20110. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  20111. std::istreambuf_iterator<char>());
  20112. if (strPrivateKeyPEM.empty()) return (nullptr);
  20113. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  20114. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  20115. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  20116. BIO_free(pbPrivKey);
  20117. return (pPrivateKey);
  20118. }
  20119. TEST(BindServerTest, UpdateCerts) {
  20120. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20121. int port = svr.bind_to_any_port("0.0.0.0");
  20122. ASSERT_TRUE(svr.is_valid());
  20123. ASSERT_TRUE(port > 0);
  20124. X509 *cert = readCertificate(SERVER_CERT_FILE);
  20125. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  20126. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  20127. ASSERT_TRUE(cert != nullptr);
  20128. ASSERT_TRUE(ca_cert != nullptr);
  20129. ASSERT_TRUE(key != nullptr);
  20130. X509_STORE *cert_store = X509_STORE_new();
  20131. X509_STORE_add_cert(cert_store, ca_cert);
  20132. // svr.update_certs(cert, key, cert_store); // deprecated
  20133. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  20134. CLIENT_CA_CERT_FILE);
  20135. ASSERT_TRUE(svr.is_valid());
  20136. svr.stop();
  20137. X509_STORE_free(cert_store);
  20138. X509_free(cert);
  20139. X509_free(ca_cert);
  20140. EVP_PKEY_free(key);
  20141. }
  20142. // Test that update_certs() updates client CA list correctly
  20143. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  20144. // Start with file-based constructor
  20145. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20146. ASSERT_TRUE(svr.is_valid());
  20147. // Initially no client CA list should be set
  20148. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20149. ASSERT_TRUE(ssl_ctx != nullptr);
  20150. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  20151. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  20152. EXPECT_EQ(0, count_before);
  20153. // Now update with client CA (PEM string)
  20154. std::string cert_pem, key_pem, ca_pem;
  20155. read_file(SERVER_CERT_FILE, cert_pem);
  20156. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  20157. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  20158. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  20159. ASSERT_TRUE(svr.is_valid());
  20160. // Now client CA list should be set
  20161. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  20162. ASSERT_TRUE(ca_list_after != nullptr);
  20163. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  20164. }
  20165. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  20166. // Test that the file-path SSLServer constructor properly sets the client CA
  20167. // list that is sent to clients during the TLS handshake (CertificateRequest)
  20168. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20169. ASSERT_TRUE(svr.is_valid());
  20170. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20171. ASSERT_TRUE(ssl_ctx != nullptr);
  20172. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  20173. ASSERT_TRUE(ca_list != nullptr);
  20174. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  20175. }
  20176. #endif
  20177. // ============================================================================
  20178. // MbedTLS-Specific Tests
  20179. // ============================================================================
  20180. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  20181. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  20182. using namespace httplib::tls;
  20183. // Track if callback was invoked
  20184. bool callback_invoked = false;
  20185. // The callback receives void* ctx which is actually MbedTlsContext*
  20186. // We can access the mbedtls_ssl_config via the context
  20187. auto setup_callback = [&callback_invoked](void *ctx) {
  20188. callback_invoked = true;
  20189. // Cast to MbedTlsContext* to access the ssl config
  20190. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  20191. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  20192. // Use static variables to hold certificate data (simplified for test)
  20193. static mbedtls_x509_crt own_cert;
  20194. static mbedtls_pk_context own_key;
  20195. static mbedtls_x509_crt ca_chain;
  20196. static bool initialized = false;
  20197. if (!initialized) {
  20198. mbedtls_x509_crt_init(&own_cert);
  20199. mbedtls_pk_init(&own_key);
  20200. mbedtls_x509_crt_init(&ca_chain);
  20201. // Load server certificate
  20202. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  20203. return false;
  20204. }
  20205. // Load server private key.
  20206. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  20207. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  20208. #if MBEDTLS_VERSION_MAJOR == 3
  20209. ,
  20210. mbedtls_ctr_drbg_random, nullptr
  20211. #endif
  20212. ) != 0) {
  20213. return false;
  20214. }
  20215. // Load CA chain for client verification
  20216. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  20217. return false;
  20218. }
  20219. initialized = true;
  20220. }
  20221. // Configure the SSL config
  20222. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  20223. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  20224. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  20225. // Set minimum TLS version using mbedTLS native API
  20226. #if MBEDTLS_VERSION_MAJOR >= 3
  20227. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  20228. #else
  20229. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  20230. MBEDTLS_SSL_MINOR_VERSION_3);
  20231. #endif
  20232. return true;
  20233. };
  20234. SSLServer svr(setup_callback);
  20235. ASSERT_TRUE(svr.is_valid());
  20236. ASSERT_TRUE(callback_invoked);
  20237. svr.Get("/test", [&](const Request &req, Response &res) {
  20238. res.set_content("test", "text/plain");
  20239. auto cert = req.peer_cert();
  20240. ASSERT_TRUE(static_cast<bool>(cert));
  20241. auto common_name = cert.subject_cn();
  20242. EXPECT_EQ("Common Name", common_name);
  20243. });
  20244. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20245. auto se = detail::scope_exit([&] {
  20246. svr.stop();
  20247. t.join();
  20248. ASSERT_FALSE(svr.is_running());
  20249. });
  20250. svr.wait_until_ready();
  20251. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  20252. cli.enable_server_certificate_verification(false);
  20253. cli.set_connection_timeout(30);
  20254. auto res = cli.Get("/test");
  20255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20256. ASSERT_EQ(StatusCode::OK_200, res->status);
  20257. }
  20258. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  20259. // context (owning mbedtls_ssl_config) before shutting down a still-open
  20260. // keep-alive SSL session, which reads through that config in
  20261. // mbedtls_ssl_close_notify.
  20262. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  20263. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20264. ASSERT_TRUE(svr.is_valid());
  20265. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  20266. res.set_content("test", "text/plain");
  20267. });
  20268. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20269. auto se = detail::scope_exit([&] {
  20270. svr.stop();
  20271. t.join();
  20272. ASSERT_FALSE(svr.is_running());
  20273. });
  20274. svr.wait_until_ready();
  20275. {
  20276. SSLClient cli(HOST, PORT);
  20277. cli.enable_server_certificate_verification(false);
  20278. cli.set_keep_alive(true);
  20279. auto res = cli.Get("/test");
  20280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20281. ASSERT_EQ(StatusCode::OK_200, res->status);
  20282. // cli is destructed here with the keep-alive SSL session still open.
  20283. }
  20284. }
  20285. #endif
  20286. // WebSocket Tests
  20287. TEST(WebSocketTest, RSVBitsMustBeZero) {
  20288. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  20289. // defining the meaning of these bits has been negotiated.
  20290. auto make_frame = [](uint8_t first_byte) {
  20291. std::string frame;
  20292. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  20293. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  20294. frame += "Hello";
  20295. return frame;
  20296. };
  20297. // RSV1 set (0x40)
  20298. {
  20299. detail::BufferStream strm;
  20300. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  20301. ws::Opcode opcode;
  20302. std::string payload;
  20303. bool fin;
  20304. EXPECT_EQ(
  20305. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20306. ws::impl::FrameRead::Fail);
  20307. }
  20308. // RSV2 set (0x20)
  20309. {
  20310. detail::BufferStream strm;
  20311. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  20312. ws::Opcode opcode;
  20313. std::string payload;
  20314. bool fin;
  20315. EXPECT_EQ(
  20316. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20317. ws::impl::FrameRead::Fail);
  20318. }
  20319. // RSV3 set (0x10)
  20320. {
  20321. detail::BufferStream strm;
  20322. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  20323. ws::Opcode opcode;
  20324. std::string payload;
  20325. bool fin;
  20326. EXPECT_EQ(
  20327. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20328. ws::impl::FrameRead::Fail);
  20329. }
  20330. // No RSV bits set - should succeed
  20331. {
  20332. detail::BufferStream strm;
  20333. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  20334. ws::Opcode opcode;
  20335. std::string payload;
  20336. bool fin;
  20337. EXPECT_EQ(
  20338. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20339. ws::impl::FrameRead::Ok);
  20340. EXPECT_EQ(ws::Opcode::Text, opcode);
  20341. EXPECT_EQ("Hello", payload);
  20342. EXPECT_TRUE(fin);
  20343. }
  20344. }
  20345. TEST(WebSocketTest, ControlFrameValidation) {
  20346. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  20347. // payload length <= 125.
  20348. // Ping with FIN=0 - must be rejected
  20349. {
  20350. detail::BufferStream strm;
  20351. std::string frame;
  20352. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  20353. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20354. strm.write(frame.data(), frame.size());
  20355. ws::Opcode opcode;
  20356. std::string payload;
  20357. bool fin;
  20358. EXPECT_EQ(
  20359. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20360. ws::impl::FrameRead::Fail);
  20361. }
  20362. // Close with FIN=0 - must be rejected
  20363. {
  20364. detail::BufferStream strm;
  20365. std::string frame;
  20366. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  20367. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20368. strm.write(frame.data(), frame.size());
  20369. ws::Opcode opcode;
  20370. std::string payload;
  20371. bool fin;
  20372. EXPECT_EQ(
  20373. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20374. ws::impl::FrameRead::Fail);
  20375. }
  20376. // Ping with payload_len=126 (extended length) - must be rejected
  20377. {
  20378. detail::BufferStream strm;
  20379. std::string frame;
  20380. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20381. frame += static_cast<char>(126); // payload_len=126 (>125)
  20382. frame += static_cast<char>(0x00); // extended length high byte
  20383. frame += static_cast<char>(126); // extended length low byte
  20384. frame += std::string(126, 'x');
  20385. strm.write(frame.data(), frame.size());
  20386. ws::Opcode opcode;
  20387. std::string payload;
  20388. bool fin;
  20389. EXPECT_EQ(
  20390. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20391. ws::impl::FrameRead::Fail);
  20392. }
  20393. // Ping with FIN=1 and payload_len=125 - should succeed
  20394. {
  20395. detail::BufferStream strm;
  20396. std::string frame;
  20397. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20398. frame += static_cast<char>(125); // payload_len=125
  20399. frame += std::string(125, 'x');
  20400. strm.write(frame.data(), frame.size());
  20401. ws::Opcode opcode;
  20402. std::string payload;
  20403. bool fin;
  20404. EXPECT_EQ(
  20405. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20406. ws::impl::FrameRead::Ok);
  20407. EXPECT_EQ(ws::Opcode::Ping, opcode);
  20408. EXPECT_EQ(125u, payload.size());
  20409. EXPECT_TRUE(fin);
  20410. }
  20411. }
  20412. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  20413. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  20414. // length MUST be 0.
  20415. // MSB set - must be rejected
  20416. {
  20417. detail::BufferStream strm;
  20418. std::string frame;
  20419. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20420. frame += static_cast<char>(127); // 64-bit extended length
  20421. frame += static_cast<char>(0x80); // MSB set (invalid)
  20422. frame += std::string(7, '\0'); // remaining 7 bytes of length
  20423. strm.write(frame.data(), frame.size());
  20424. ws::Opcode opcode;
  20425. std::string payload;
  20426. bool fin;
  20427. EXPECT_EQ(
  20428. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20429. ws::impl::FrameRead::Fail);
  20430. }
  20431. // MSB clear - should pass length parsing (will be rejected by max_len,
  20432. // but that's a different check; use a small length to verify)
  20433. {
  20434. detail::BufferStream strm;
  20435. std::string frame;
  20436. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20437. frame += static_cast<char>(127); // 64-bit extended length
  20438. frame += std::string(7, '\0'); // high bytes = 0
  20439. frame += static_cast<char>(0x03); // length = 3
  20440. frame += "abc";
  20441. strm.write(frame.data(), frame.size());
  20442. ws::Opcode opcode;
  20443. std::string payload;
  20444. bool fin;
  20445. EXPECT_EQ(
  20446. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20447. ws::impl::FrameRead::Ok);
  20448. EXPECT_EQ(ws::Opcode::Text, opcode);
  20449. EXPECT_EQ("abc", payload);
  20450. }
  20451. }
  20452. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  20453. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  20454. // Valid UTF-8
  20455. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  20456. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  20457. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  20458. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  20459. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  20460. // Invalid UTF-8
  20461. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  20462. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  20463. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  20464. EXPECT_FALSE(
  20465. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  20466. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  20467. }
  20468. TEST(WebSocketTest, ConnectAndDisconnect) {
  20469. Server svr;
  20470. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20471. std::string msg;
  20472. while (ws.read(msg)) {}
  20473. });
  20474. auto port = svr.bind_to_any_port(HOST);
  20475. std::thread t([&]() { svr.listen_after_bind(); });
  20476. svr.wait_until_ready();
  20477. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20478. auto res = client.connect();
  20479. ASSERT_TRUE(res);
  20480. EXPECT_EQ(Error::Success, res.error());
  20481. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  20482. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  20483. EXPECT_TRUE(client.is_open());
  20484. client.close();
  20485. EXPECT_FALSE(client.is_open());
  20486. svr.stop();
  20487. t.join();
  20488. }
  20489. TEST(WebSocketTest, ValidURL) {
  20490. ws::WebSocketClient ws1("ws://localhost:8080/path");
  20491. EXPECT_TRUE(ws1.is_valid());
  20492. ws::WebSocketClient ws2("ws://example.com/path");
  20493. EXPECT_TRUE(ws2.is_valid());
  20494. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  20495. EXPECT_TRUE(ws3.is_valid());
  20496. #ifdef CPPHTTPLIB_SSL_ENABLED
  20497. ws::WebSocketClient wss1("wss://example.com/path");
  20498. EXPECT_TRUE(wss1.is_valid());
  20499. ws::WebSocketClient wss2("wss://example.com:443/path");
  20500. EXPECT_TRUE(wss2.is_valid());
  20501. #endif
  20502. }
  20503. TEST(WebSocketTest, InvalidURL) {
  20504. // No scheme
  20505. ws::WebSocketClient ws1("localhost:8080/path");
  20506. EXPECT_FALSE(ws1.is_valid());
  20507. // No path
  20508. ws::WebSocketClient ws2("ws://localhost:8080");
  20509. EXPECT_FALSE(ws2.is_valid());
  20510. // Empty string
  20511. ws::WebSocketClient ws3("");
  20512. EXPECT_FALSE(ws3.is_valid());
  20513. // Missing host
  20514. ws::WebSocketClient ws4("ws://:8080/path");
  20515. EXPECT_FALSE(ws4.is_valid());
  20516. // Port number overflow — should not crash
  20517. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  20518. EXPECT_FALSE(ws5.is_valid());
  20519. // Port out of range
  20520. ws::WebSocketClient ws6("ws://localhost:99999/path");
  20521. EXPECT_FALSE(ws6.is_valid());
  20522. }
  20523. TEST(WebSocketTest, UnsupportedScheme) {
  20524. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  20525. ws::WebSocketClient ws1("http://localhost:8080/path");
  20526. EXPECT_FALSE(ws1.is_valid());
  20527. ws::WebSocketClient ws2("https://localhost:8080/path");
  20528. EXPECT_FALSE(ws2.is_valid());
  20529. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  20530. EXPECT_FALSE(ws3.is_valid());
  20531. #else
  20532. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  20533. std::invalid_argument);
  20534. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  20535. std::invalid_argument);
  20536. #endif
  20537. }
  20538. TEST(WebSocketTest, ConnectWhenInvalid) {
  20539. ws::WebSocketClient ws("not a valid url");
  20540. EXPECT_FALSE(ws.is_valid());
  20541. auto res = ws.connect();
  20542. EXPECT_FALSE(res);
  20543. EXPECT_EQ(Error::Connection, res.error());
  20544. EXPECT_EQ(-1, res.status());
  20545. }
  20546. TEST(WebSocketTest, ConnectRefusedReportsError) {
  20547. // Grab a port that is free, then close it again so nothing listens there
  20548. Server svr;
  20549. auto port = svr.bind_to_any_port(HOST);
  20550. svr.stop();
  20551. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20552. auto res = client.connect();
  20553. ASSERT_FALSE(res);
  20554. EXPECT_EQ(Error::Connection, res.error());
  20555. EXPECT_EQ(-1, res.status());
  20556. }
  20557. TEST(WebSocketTest, DefaultPort) {
  20558. ws::WebSocketClient ws1("ws://example.com/path");
  20559. EXPECT_TRUE(ws1.is_valid());
  20560. // ws:// defaults to port 80 (verified by successful parse)
  20561. #ifdef CPPHTTPLIB_SSL_ENABLED
  20562. ws::WebSocketClient ws2("wss://example.com/path");
  20563. EXPECT_TRUE(ws2.is_valid());
  20564. // wss:// defaults to port 443 (verified by successful parse)
  20565. #endif
  20566. }
  20567. TEST(WebSocketTest, IPv6LiteralAddress) {
  20568. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  20569. EXPECT_TRUE(ws1.is_valid());
  20570. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  20571. EXPECT_TRUE(ws2.is_valid());
  20572. }
  20573. TEST(WebSocketTest, ComplexPath) {
  20574. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  20575. EXPECT_TRUE(ws1.is_valid());
  20576. ws::WebSocketClient ws2("ws://localhost:8080/");
  20577. EXPECT_TRUE(ws2.is_valid());
  20578. }
  20579. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  20580. Server svr;
  20581. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20582. std::string msg;
  20583. while (ws.read(msg)) {}
  20584. });
  20585. auto port = svr.bind_to_any_port(HOST);
  20586. std::thread t([&]() { svr.listen_after_bind(); });
  20587. svr.wait_until_ready();
  20588. auto another_host = "example.com";
  20589. auto wrong_ip = "192.0.2.1";
  20590. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20591. client.set_hostname_addr_map({{another_host, wrong_ip}});
  20592. ASSERT_TRUE(client.connect());
  20593. EXPECT_TRUE(client.is_open());
  20594. client.close();
  20595. svr.stop();
  20596. t.join();
  20597. }
  20598. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  20599. Server svr;
  20600. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20601. std::string msg;
  20602. while (ws.read(msg)) {}
  20603. });
  20604. auto port = svr.bind_to_any_port(HOST);
  20605. std::thread t([&]() { svr.listen_after_bind(); });
  20606. svr.wait_until_ready();
  20607. auto wrong_ip = "192.0.2.1";
  20608. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20609. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  20610. client.set_connection_timeout(1);
  20611. client.set_read_timeout(1);
  20612. client.set_write_timeout(1);
  20613. EXPECT_FALSE(client.connect());
  20614. EXPECT_FALSE(client.is_open());
  20615. svr.stop();
  20616. t.join();
  20617. }
  20618. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  20619. // A mapped value that is not an IP literal must be resolved. HOST resolves
  20620. // from the hosts file, so this test needs no external DNS. "target.invalid"
  20621. // (RFC 6761) is only a map key and the Host header value.
  20622. auto host = "target.invalid";
  20623. Server svr;
  20624. std::string received_host;
  20625. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20626. received_host = req.get_header_value("Host");
  20627. std::string msg;
  20628. while (ws.read(msg)) {}
  20629. });
  20630. auto port = svr.bind_to_any_port(HOST);
  20631. std::thread t([&]() { svr.listen_after_bind(); });
  20632. // ASSERT_* below returns from the test body, which would leave t joinable
  20633. // and make ~thread call std::terminate.
  20634. auto se = detail::scope_exit([&] {
  20635. svr.stop();
  20636. if (t.joinable()) { t.join(); }
  20637. });
  20638. svr.wait_until_ready();
  20639. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  20640. std::to_string(port) + "/ws");
  20641. client.set_hostname_addr_map({{host, HOST}});
  20642. ASSERT_TRUE(client.connect());
  20643. EXPECT_TRUE(client.is_open());
  20644. client.close();
  20645. svr.stop();
  20646. t.join();
  20647. // The mapping only redirects the connection; the identity stays host_.
  20648. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  20649. }
  20650. class WebSocketIntegrationTest : public ::testing::Test {
  20651. protected:
  20652. void SetUp() override {
  20653. server_ = httplib::detail::make_unique<Server>();
  20654. setup_server();
  20655. start_server();
  20656. }
  20657. void TearDown() override {
  20658. server_->stop();
  20659. if (server_thread_.joinable()) { server_thread_.join(); }
  20660. }
  20661. void setup_server() {
  20662. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  20663. std::string msg;
  20664. ws::ReadResult ret;
  20665. while ((ret = ws.read(msg))) {
  20666. if (ret == ws::Binary) {
  20667. ws.send(msg.data(), msg.size());
  20668. } else {
  20669. ws.send(msg);
  20670. }
  20671. }
  20672. });
  20673. server_->WebSocket("/ws-echo-string",
  20674. [](const Request &, ws::WebSocket &ws) {
  20675. std::string msg;
  20676. while (ws.read(msg)) {
  20677. ws.send("echo: " + msg);
  20678. }
  20679. });
  20680. server_->WebSocket(
  20681. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  20682. // Echo back request metadata
  20683. ws.send("path:" + req.path);
  20684. ws.send("header:" + req.get_header_value("X-Test-Header"));
  20685. std::string msg;
  20686. while (ws.read(msg)) {}
  20687. });
  20688. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  20689. std::string msg;
  20690. ws.read(msg); // wait for a message
  20691. ws.close();
  20692. });
  20693. server_->WebSocket("/ws-close-status",
  20694. [](const Request &, ws::WebSocket &ws) {
  20695. std::string msg;
  20696. ws.read(msg); // wait for a message
  20697. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  20698. });
  20699. server_->WebSocket(
  20700. "/ws-subprotocol",
  20701. [](const Request &, ws::WebSocket &ws) {
  20702. std::string msg;
  20703. while (ws.read(msg)) {
  20704. ws.send(msg);
  20705. }
  20706. },
  20707. [](const std::vector<std::string> &protocols) -> std::string {
  20708. for (const auto &p : protocols) {
  20709. if (p == "graphql-ws") { return p; }
  20710. }
  20711. return "";
  20712. });
  20713. server_->WebSocket(
  20714. "/ws-subprotocol-unoffered",
  20715. [](const Request &, ws::WebSocket &ws) {
  20716. std::string msg;
  20717. while (ws.read(msg)) {
  20718. ws.send(msg);
  20719. }
  20720. },
  20721. [](const std::vector<std::string> &) -> std::string {
  20722. return "admin";
  20723. });
  20724. }
  20725. void start_server() {
  20726. port_ = server_->bind_to_any_port(HOST);
  20727. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20728. server_->wait_until_ready();
  20729. }
  20730. std::unique_ptr<Server> server_;
  20731. std::thread server_thread_;
  20732. int port_ = 0;
  20733. };
  20734. TEST_F(WebSocketIntegrationTest, TextEcho) {
  20735. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20736. "/ws-echo");
  20737. ASSERT_TRUE(client.connect());
  20738. ASSERT_TRUE(client.is_open());
  20739. ASSERT_TRUE(client.send("Hello WebSocket"));
  20740. std::string msg;
  20741. EXPECT_EQ(ws::Text, client.read(msg));
  20742. EXPECT_EQ("Hello WebSocket", msg);
  20743. client.close();
  20744. }
  20745. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  20746. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20747. "/ws-echo");
  20748. ASSERT_TRUE(client.connect());
  20749. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  20750. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  20751. std::string msg;
  20752. EXPECT_EQ(ws::Binary, client.read(msg));
  20753. EXPECT_EQ(binary_data, msg);
  20754. client.close();
  20755. }
  20756. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  20757. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20758. "/ws-echo");
  20759. ASSERT_TRUE(client.connect());
  20760. for (int i = 0; i < 10; i++) {
  20761. auto text = "message " + std::to_string(i);
  20762. ASSERT_TRUE(client.send(text));
  20763. std::string msg;
  20764. ASSERT_TRUE(client.read(msg));
  20765. EXPECT_EQ(text, msg);
  20766. }
  20767. client.close();
  20768. }
  20769. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  20770. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20771. "/ws-close");
  20772. ASSERT_TRUE(client.connect());
  20773. // Send a message to trigger the server to close
  20774. ASSERT_TRUE(client.send("trigger close"));
  20775. // The server will close, so read should return false
  20776. std::string msg;
  20777. EXPECT_FALSE(client.read(msg));
  20778. EXPECT_FALSE(client.is_open());
  20779. }
  20780. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  20781. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20782. "/ws-echo");
  20783. ASSERT_TRUE(client.connect());
  20784. // 128KB message
  20785. std::string large_data(128 * 1024, 'X');
  20786. ASSERT_TRUE(client.send(large_data));
  20787. std::string msg;
  20788. ASSERT_TRUE(client.read(msg));
  20789. EXPECT_EQ(large_data, msg);
  20790. client.close();
  20791. }
  20792. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  20793. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20794. "/ws-echo");
  20795. ASSERT_TRUE(client.connect());
  20796. const int num_threads = 4;
  20797. std::vector<std::thread> threads;
  20798. std::atomic<int> send_count{0};
  20799. for (int t = 0; t < num_threads; t++) {
  20800. threads.emplace_back([&client, &send_count, t]() {
  20801. for (int i = 0; i < 5; i++) {
  20802. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  20803. if (client.send(text)) { send_count++; }
  20804. }
  20805. });
  20806. }
  20807. for (auto &th : threads) {
  20808. th.join();
  20809. }
  20810. int received = 0;
  20811. std::string msg;
  20812. while (received < send_count.load()) {
  20813. if (!client.read(msg)) { break; }
  20814. received++;
  20815. }
  20816. EXPECT_EQ(send_count.load(), received);
  20817. client.close();
  20818. }
  20819. TEST_F(WebSocketIntegrationTest, ReadString) {
  20820. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20821. "/ws-echo-string");
  20822. ASSERT_TRUE(client.connect());
  20823. ASSERT_TRUE(client.send("hello"));
  20824. std::string msg;
  20825. ASSERT_TRUE(client.read(msg));
  20826. EXPECT_EQ("echo: hello", msg);
  20827. ASSERT_TRUE(client.send("world"));
  20828. ASSERT_TRUE(client.read(msg));
  20829. EXPECT_EQ("echo: world", msg);
  20830. client.close();
  20831. }
  20832. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  20833. Headers headers = {{"X-Test-Header", "test-value"}};
  20834. ws::WebSocketClient client(
  20835. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  20836. ASSERT_TRUE(client.connect());
  20837. std::string msg;
  20838. ASSERT_TRUE(client.read(msg));
  20839. EXPECT_EQ("path:/ws-request-info", msg);
  20840. ASSERT_TRUE(client.read(msg));
  20841. EXPECT_EQ("header:test-value", msg);
  20842. client.close();
  20843. }
  20844. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  20845. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20846. "/ws-echo");
  20847. client.set_read_timeout(1, 0); // 1 second
  20848. ASSERT_TRUE(client.connect());
  20849. // Don't send anything — server echo handler waits for a message, so read()
  20850. // should time out. The connection survives it: nothing was consumed.
  20851. std::string msg;
  20852. EXPECT_EQ(client.read(msg), ws::Timeout);
  20853. EXPECT_TRUE(client.is_open());
  20854. // And it is still usable afterwards.
  20855. EXPECT_TRUE(client.send("after timeout"));
  20856. EXPECT_EQ(client.read(msg), ws::Text);
  20857. EXPECT_EQ(msg, "after timeout");
  20858. }
  20859. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  20860. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20861. "/ws-echo");
  20862. client.set_read_timeout(1, 0);
  20863. ASSERT_TRUE(client.connect());
  20864. ASSERT_TRUE(client.send("first"));
  20865. std::string msg;
  20866. ASSERT_EQ(client.read(msg), ws::Text);
  20867. ASSERT_EQ(msg, "first");
  20868. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  20869. // not be used with a read timeout: it would reprocess the previous message.
  20870. EXPECT_EQ(client.read(msg), ws::Timeout);
  20871. EXPECT_EQ(msg, "first");
  20872. }
  20873. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  20874. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20875. "/ws-echo");
  20876. ASSERT_TRUE(client.connect());
  20877. // Setting it once the connection is open reaches the live stream, not just
  20878. // the seed for the next connect().
  20879. client.set_read_timeout(1, 0);
  20880. std::string msg;
  20881. EXPECT_EQ(client.read(msg), ws::Timeout);
  20882. EXPECT_TRUE(client.is_open());
  20883. }
  20884. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  20885. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20886. "/ws-echo");
  20887. client.set_read_timeout(5, 0);
  20888. ASSERT_TRUE(client.connect());
  20889. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  20890. // The server should reject it and close the connection.
  20891. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  20892. client.send(oversized);
  20893. // The server's read() should have failed due to payload limit,
  20894. // so our read() should return false (connection closed).
  20895. std::string msg;
  20896. EXPECT_FALSE(client.read(msg));
  20897. }
  20898. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  20899. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20900. "/ws-echo");
  20901. client.set_read_timeout(10, 0);
  20902. ASSERT_TRUE(client.connect());
  20903. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  20904. // This should succeed.
  20905. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  20906. ASSERT_TRUE(client.send(at_limit));
  20907. std::string msg;
  20908. ASSERT_TRUE(client.read(msg));
  20909. EXPECT_EQ(at_limit.size(), msg.size());
  20910. client.close();
  20911. }
  20912. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  20913. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20914. "/nonexistent");
  20915. auto res = client.connect();
  20916. EXPECT_FALSE(res);
  20917. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  20918. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  20919. EXPECT_FALSE(client.is_open());
  20920. }
  20921. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  20922. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20923. "/ws-echo");
  20924. ASSERT_TRUE(client.connect());
  20925. ASSERT_TRUE(client.send(""));
  20926. std::string msg;
  20927. EXPECT_EQ(ws::Text, client.read(msg));
  20928. EXPECT_EQ("", msg);
  20929. client.close();
  20930. }
  20931. TEST_F(WebSocketIntegrationTest, Reconnect) {
  20932. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20933. "/ws-echo");
  20934. // First connection
  20935. ASSERT_TRUE(client.connect());
  20936. ASSERT_TRUE(client.send("first"));
  20937. std::string msg;
  20938. ASSERT_TRUE(client.read(msg));
  20939. EXPECT_EQ("first", msg);
  20940. client.close();
  20941. EXPECT_FALSE(client.is_open());
  20942. // Reconnect using the same client object
  20943. ASSERT_TRUE(client.connect());
  20944. ASSERT_TRUE(client.is_open());
  20945. ASSERT_TRUE(client.send("second"));
  20946. ASSERT_TRUE(client.read(msg));
  20947. EXPECT_EQ("second", msg);
  20948. client.close();
  20949. }
  20950. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  20951. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20952. "/ws-close-status");
  20953. ASSERT_TRUE(client.connect());
  20954. // Trigger the server to close with GoingAway status
  20955. ASSERT_TRUE(client.send("trigger"));
  20956. // read() should return false after receiving the close frame
  20957. std::string msg;
  20958. EXPECT_FALSE(client.read(msg));
  20959. EXPECT_FALSE(client.is_open());
  20960. }
  20961. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  20962. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20963. "/ws-echo");
  20964. ASSERT_TRUE(client.connect());
  20965. client.close(ws::CloseStatus::GoingAway, "client leaving");
  20966. EXPECT_FALSE(client.is_open());
  20967. }
  20968. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  20969. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  20970. ws::WebSocketClient client(
  20971. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20972. ASSERT_TRUE(client.connect());
  20973. // Server should have selected graphql-ws
  20974. EXPECT_EQ("graphql-ws", client.subprotocol());
  20975. client.close();
  20976. }
  20977. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  20978. Headers headers;
  20979. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  20980. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  20981. ws::WebSocketClient client(
  20982. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20983. ASSERT_TRUE(client.connect());
  20984. // The offer on the second field line counts too, so graphql-ws is selected
  20985. EXPECT_EQ("graphql-ws", client.subprotocol());
  20986. client.close();
  20987. }
  20988. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  20989. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  20990. ws::WebSocketClient client(
  20991. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20992. ASSERT_TRUE(client.connect());
  20993. // Server should not have selected any subprotocol
  20994. EXPECT_TRUE(client.subprotocol().empty());
  20995. client.close();
  20996. }
  20997. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  20998. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  20999. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21000. "/ws-subprotocol-unoffered",
  21001. headers);
  21002. ASSERT_TRUE(client.connect());
  21003. EXPECT_TRUE(client.subprotocol().empty());
  21004. client.close();
  21005. }
  21006. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  21007. // Connect without requesting any subprotocol
  21008. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21009. "/ws-subprotocol");
  21010. ASSERT_TRUE(client.connect());
  21011. EXPECT_TRUE(client.subprotocol().empty());
  21012. client.close();
  21013. }
  21014. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  21015. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21016. "/ws-echo");
  21017. client.set_tcp_nodelay(true);
  21018. client.set_connection_timeout(3, 0);
  21019. bool socket_options_called = false;
  21020. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  21021. ASSERT_TRUE(client.connect());
  21022. ASSERT_TRUE(client.is_open());
  21023. EXPECT_TRUE(socket_options_called);
  21024. ASSERT_TRUE(client.send("hello"));
  21025. std::string msg;
  21026. auto result = client.read(msg);
  21027. EXPECT_EQ(result, ws::ReadResult::Text);
  21028. EXPECT_EQ(msg, "hello");
  21029. client.close();
  21030. }
  21031. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  21032. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21033. "/ws-echo");
  21034. client.set_connection_timeout(std::chrono::seconds(3));
  21035. client.set_write_timeout(std::chrono::seconds(3));
  21036. // A sub-second remainder exercises the seconds/microseconds split.
  21037. client.set_read_timeout(std::chrono::milliseconds(1500));
  21038. ASSERT_TRUE(client.connect());
  21039. auto start = std::chrono::steady_clock::now();
  21040. std::string msg;
  21041. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  21042. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  21043. std::chrono::steady_clock::now() - start)
  21044. .count();
  21045. // Above 1s so that dropping the microseconds half of the split fails here.
  21046. // Ignoring the setter altogether would not reach this line at all: a client
  21047. // waits forever by default.
  21048. EXPECT_GE(elapsed, 1400);
  21049. EXPECT_LT(elapsed, 30000);
  21050. }
  21051. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  21052. Server svr;
  21053. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  21054. if (!req.has_header("Authorization")) {
  21055. res.status = StatusCode::Unauthorized_401;
  21056. res.set_content("Unauthorized", "text/plain");
  21057. return Server::HandlerResponse::Handled;
  21058. }
  21059. return Server::HandlerResponse::Unhandled;
  21060. });
  21061. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21062. std::string msg;
  21063. while (ws.read(msg)) {
  21064. ws.send(msg);
  21065. }
  21066. });
  21067. auto port = svr.bind_to_any_port("localhost");
  21068. std::thread t([&]() { svr.listen_after_bind(); });
  21069. svr.wait_until_ready();
  21070. // Without Authorization header - should be rejected before upgrade
  21071. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  21072. EXPECT_FALSE(client1.connect());
  21073. // The rejection is framed like any other HTTP response
  21074. {
  21075. Client cli("localhost", port);
  21076. Headers headers = {{"Upgrade", "websocket"},
  21077. {"Connection", "Upgrade"},
  21078. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21079. {"Sec-WebSocket-Version", "13"}};
  21080. auto res = cli.Get("/ws", headers);
  21081. ASSERT_TRUE(res);
  21082. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21083. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21084. EXPECT_EQ("Unauthorized", res->body);
  21085. }
  21086. // With Authorization header - should succeed
  21087. Headers headers = {{"Authorization", "Bearer token123"}};
  21088. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  21089. headers);
  21090. ASSERT_TRUE(client2.connect());
  21091. ASSERT_TRUE(client2.send("hello"));
  21092. std::string msg;
  21093. ASSERT_TRUE(client2.read(msg));
  21094. EXPECT_EQ("hello", msg);
  21095. client2.close();
  21096. svr.stop();
  21097. t.join();
  21098. }
  21099. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  21100. Server svr;
  21101. std::atomic<int> pre_request_calls{0};
  21102. std::atomic<bool> route_matched{false};
  21103. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  21104. pre_request_calls++;
  21105. if (req.matched_route == "/ws/:id") { route_matched = true; }
  21106. if (req.get_header_value("Authorization") != "Bearer token123") {
  21107. res.status = StatusCode::Unauthorized_401;
  21108. res.set_content("Unauthorized", "text/plain");
  21109. return Server::HandlerResponse::Handled;
  21110. }
  21111. return Server::HandlerResponse::Unhandled;
  21112. });
  21113. std::atomic<bool> handler_called{false};
  21114. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  21115. handler_called = true;
  21116. ws.send(req.matched_route + " " + req.path_params.at("id"));
  21117. });
  21118. auto port = svr.bind_to_any_port("localhost");
  21119. std::thread t([&]() { svr.listen_after_bind(); });
  21120. svr.wait_until_ready();
  21121. // Without Authorization header - should be rejected before upgrade
  21122. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  21123. "/ws/1");
  21124. EXPECT_FALSE(client1.connect());
  21125. EXPECT_FALSE(handler_called);
  21126. EXPECT_EQ(1, pre_request_calls);
  21127. EXPECT_TRUE(route_matched);
  21128. // The rejection is an ordinary HTTP response, not a protocol switch
  21129. {
  21130. Client cli("localhost", port);
  21131. Headers headers = {{"Upgrade", "websocket"},
  21132. {"Connection", "Upgrade"},
  21133. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21134. {"Sec-WebSocket-Version", "13"}};
  21135. auto res = cli.Get("/ws/1", headers);
  21136. ASSERT_TRUE(res);
  21137. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21138. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21139. EXPECT_EQ("Unauthorized", res->body);
  21140. }
  21141. EXPECT_FALSE(handler_called);
  21142. // With Authorization header - should succeed
  21143. Headers headers = {{"Authorization", "Bearer token123"}};
  21144. ws::WebSocketClient client2(
  21145. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  21146. ASSERT_TRUE(client2.connect());
  21147. std::string msg;
  21148. ASSERT_TRUE(client2.read(msg));
  21149. EXPECT_EQ("/ws/:id 2", msg);
  21150. EXPECT_TRUE(handler_called);
  21151. client2.close();
  21152. svr.stop();
  21153. t.join();
  21154. }
  21155. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  21156. Server svr;
  21157. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21158. // A read timeout is how a handler gets control back. Without it, a handler
  21159. // parked in read() can never write on the connection it is reading.
  21160. ws.set_read_timeout(std::chrono::milliseconds(100));
  21161. std::string msg;
  21162. while (ws.is_open()) {
  21163. auto r = ws.read(msg);
  21164. if (r == httplib::ws::Timeout) {
  21165. ws.send("tick");
  21166. continue;
  21167. }
  21168. if (r == httplib::ws::Fail) { break; }
  21169. ws.send(msg);
  21170. }
  21171. });
  21172. auto port = svr.bind_to_any_port("localhost");
  21173. std::thread t([&]() { svr.listen_after_bind(); });
  21174. svr.wait_until_ready();
  21175. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21176. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  21177. ASSERT_TRUE(client.connect());
  21178. // The client sends nothing, so anything it receives came out of the
  21179. // handler's timeout path.
  21180. std::string msg;
  21181. ASSERT_EQ(client.read(msg), ws::Text);
  21182. EXPECT_EQ("tick", msg);
  21183. client.close();
  21184. svr.stop();
  21185. t.join();
  21186. }
  21187. // Stream::read may return fewer bytes than asked for. This is that contract at
  21188. // its worst -- one byte per call -- which is what a frame header straddling a
  21189. // read buffer's boundary looks like to the frame parser.
  21190. class WsByteAtATimeStream : public Stream {
  21191. public:
  21192. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  21193. bool is_readable() const override { return true; }
  21194. bool wait_readable() const override { return true; }
  21195. bool wait_writable() const override { return true; }
  21196. ssize_t read(char *ptr, size_t size) override {
  21197. if (size == 0 || pos_ >= data_.size()) { return 0; }
  21198. *ptr = data_[pos_++];
  21199. return 1;
  21200. }
  21201. ssize_t write(const char *, size_t size) override {
  21202. return static_cast<ssize_t>(size);
  21203. }
  21204. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  21205. ip = "127.0.0.1";
  21206. port = 0;
  21207. }
  21208. void get_local_ip_and_port(std::string &ip, int &port) const override {
  21209. ip = "127.0.0.1";
  21210. port = 0;
  21211. }
  21212. socket_t socket() const override { return INVALID_SOCKET; }
  21213. time_t duration() const override { return 0; }
  21214. private:
  21215. std::string data_;
  21216. size_t pos_ = 0;
  21217. };
  21218. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  21219. // A 200-byte payload uses the 16-bit extended length, so the header, the
  21220. // length and the mask key are all multi-byte fields here. Each used to be
  21221. // read with a single read() call, which fails as soon as one is split.
  21222. std::string body(200, 'x');
  21223. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  21224. std::string frame;
  21225. frame += static_cast<char>(0x81); // FIN + Text
  21226. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  21227. frame += static_cast<char>(body.size() >> 8);
  21228. frame += static_cast<char>(body.size() & 0xff);
  21229. for (size_t i = 0; i < 4; i++) {
  21230. frame += static_cast<char>(mask[i]);
  21231. }
  21232. for (size_t i = 0; i < body.size(); i++) {
  21233. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  21234. }
  21235. WsByteAtATimeStream strm(frame);
  21236. ws::Opcode opcode;
  21237. std::string payload;
  21238. bool fin = false;
  21239. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  21240. /*expect_masked=*/true, 1024),
  21241. ws::impl::FrameRead::Ok);
  21242. EXPECT_TRUE(fin);
  21243. EXPECT_EQ(opcode, ws::Opcode::Text);
  21244. EXPECT_EQ(payload, body);
  21245. }
  21246. TEST(WebSocketTest, QueryStringInHandshake) {
  21247. Server svr;
  21248. std::mutex mtx;
  21249. std::string received_target;
  21250. std::string received_token;
  21251. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21252. {
  21253. std::lock_guard<std::mutex> lock(mtx);
  21254. received_target = req.target;
  21255. if (req.has_param("token")) {
  21256. received_token = req.get_param_value("token");
  21257. }
  21258. }
  21259. std::string msg;
  21260. while (ws.read(msg)) {
  21261. ws.send(msg);
  21262. }
  21263. });
  21264. auto port = svr.bind_to_any_port("localhost");
  21265. std::thread t([&]() { svr.listen_after_bind(); });
  21266. svr.wait_until_ready();
  21267. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  21268. "/ws?token=ABC&session=123");
  21269. ASSERT_TRUE(client.connect());
  21270. // Round-trip ensures the handler has run and captured the request.
  21271. ASSERT_TRUE(client.send("hello"));
  21272. std::string msg;
  21273. ASSERT_TRUE(client.read(msg));
  21274. EXPECT_EQ("hello", msg);
  21275. client.close();
  21276. {
  21277. std::lock_guard<std::mutex> lock(mtx);
  21278. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  21279. EXPECT_EQ("ABC", received_token);
  21280. }
  21281. svr.stop();
  21282. t.join();
  21283. }
  21284. // Run a handshake against a throwaway server and hand the request the server
  21285. // received back to the caller, so tests can assert on the headers the client
  21286. // actually put on the wire.
  21287. static void capture_websocket_handshake_request(
  21288. const Headers &client_headers,
  21289. std::function<void(const Request &, int port)> verify) {
  21290. Server svr;
  21291. std::mutex mtx;
  21292. Request received;
  21293. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21294. {
  21295. std::lock_guard<std::mutex> lock(mtx);
  21296. received = req;
  21297. }
  21298. std::string msg;
  21299. while (ws.read(msg)) {
  21300. ws.send(msg);
  21301. }
  21302. });
  21303. auto port = svr.bind_to_any_port("localhost");
  21304. std::thread t([&]() { svr.listen_after_bind(); });
  21305. auto se = detail::scope_exit([&] {
  21306. svr.stop();
  21307. t.join();
  21308. });
  21309. svr.wait_until_ready();
  21310. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  21311. client_headers);
  21312. ASSERT_TRUE(client.connect());
  21313. ASSERT_TRUE(client.send("hello"));
  21314. std::string msg;
  21315. ASSERT_TRUE(client.read(msg));
  21316. client.close();
  21317. {
  21318. std::lock_guard<std::mutex> lock(mtx);
  21319. verify(received, port);
  21320. }
  21321. }
  21322. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  21323. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  21324. // Non-default port must be present in the Host header. Default ports
  21325. // (80/443) are omitted; that logic is covered by
  21326. // MakeHostAndPortStringTest.
  21327. EXPECT_EQ("localhost:" + std::to_string(port),
  21328. req.get_header_value("Host"));
  21329. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  21330. req.get_header_value("User-Agent"));
  21331. EXPECT_FALSE(req.has_header("Accept"));
  21332. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  21333. EXPECT_FALSE(req.has_header("Content-Length"));
  21334. });
  21335. }
  21336. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  21337. capture_websocket_handshake_request(
  21338. {{"Host", "example.com"},
  21339. {"User-Agent", "custom-agent"},
  21340. {"X-Custom", "value"}},
  21341. [](const Request &req, int) {
  21342. EXPECT_EQ("example.com", req.get_header_value("Host"));
  21343. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  21344. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  21345. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  21346. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  21347. });
  21348. }
  21349. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  21350. capture_websocket_handshake_request(
  21351. {{"Upgrade", "bogus"},
  21352. {"Connection", "close"},
  21353. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  21354. {"Sec-WebSocket-Version", "8"}},
  21355. [](const Request &req, int) {
  21356. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  21357. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  21358. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  21359. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  21360. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  21361. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  21362. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  21363. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  21364. req.get_header_value("Sec-WebSocket-Key"));
  21365. });
  21366. }
  21367. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  21368. // A header the client refuses to send must abort the handshake before any
  21369. // part of it reaches the wire; a lone request line would otherwise sit in
  21370. // the peer's buffer as a truncated request.
  21371. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21372. ASSERT_NE(INVALID_SOCKET, srv);
  21373. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  21374. sockaddr_in addr{};
  21375. addr.sin_family = AF_INET;
  21376. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  21377. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21378. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  21379. ASSERT_EQ(0, ::listen(srv, 1));
  21380. sockaddr_in bound{};
  21381. socklen_t bound_len = sizeof(bound);
  21382. ASSERT_EQ(
  21383. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  21384. auto port = ntohs(bound.sin_port);
  21385. ssize_t received = -1;
  21386. std::thread t([&] {
  21387. // Bound every blocking call so a regression fails the test with a bad
  21388. // value instead of hanging the suite.
  21389. fd_set rfds;
  21390. FD_ZERO(&rfds);
  21391. FD_SET(srv, &rfds);
  21392. timeval tv{5, 0};
  21393. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  21394. 0) {
  21395. return;
  21396. }
  21397. sockaddr_in cli_addr{};
  21398. socklen_t cli_len = sizeof(cli_addr);
  21399. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  21400. if (cli == INVALID_SOCKET) { return; }
  21401. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  21402. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21403. char buf[4096];
  21404. received = ::recv(cli, buf, sizeof(buf), 0);
  21405. });
  21406. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  21407. // connect() has already shut the socket down by the time it returns false,
  21408. // so the peer sees EOF without waiting for the client to be destroyed.
  21409. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  21410. {{"X-Bad", "a\r\nInjected: 1"}});
  21411. EXPECT_FALSE(client.connect());
  21412. t.join();
  21413. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  21414. EXPECT_EQ(0, received);
  21415. }
  21416. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  21417. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  21418. // contains "upgrade" as a substring is a different token and must not
  21419. // start a WebSocket handshake.
  21420. auto make_request = [](const std::vector<std::string> &connection_values) {
  21421. Request req;
  21422. req.method = "GET";
  21423. req.headers.emplace("Upgrade", "websocket");
  21424. for (const auto &value : connection_values) {
  21425. req.headers.emplace("Connection", value);
  21426. }
  21427. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21428. req.headers.emplace("Sec-WebSocket-Version", "13");
  21429. return req;
  21430. };
  21431. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  21432. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  21433. EXPECT_TRUE(
  21434. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  21435. EXPECT_TRUE(
  21436. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  21437. EXPECT_TRUE(
  21438. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  21439. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  21440. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  21441. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  21442. EXPECT_FALSE(
  21443. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  21444. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  21445. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21446. }
  21447. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  21448. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  21449. // asks recipients to match each protocol-name case-insensitively, and RFC
  21450. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  21451. // client naming websocket alongside another protocol, or on a second field
  21452. // line, is offering websocket; a value that merely contains "websocket" as a
  21453. // substring is a different protocol name and is not.
  21454. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  21455. Request req;
  21456. req.method = "GET";
  21457. for (const auto &value : upgrade_values) {
  21458. req.headers.emplace("Upgrade", value);
  21459. }
  21460. req.headers.emplace("Connection", "Upgrade");
  21461. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21462. req.headers.emplace("Sec-WebSocket-Version", "13");
  21463. return req;
  21464. };
  21465. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  21466. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  21467. EXPECT_TRUE(
  21468. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  21469. EXPECT_TRUE(
  21470. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  21471. EXPECT_TRUE(
  21472. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  21473. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  21474. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  21475. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  21476. EXPECT_FALSE(
  21477. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  21478. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  21479. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21480. }
  21481. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  21482. Server svr;
  21483. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  21484. auto port = svr.bind_to_any_port("localhost");
  21485. std::thread t([&]() { svr.listen_after_bind(); });
  21486. auto se = detail::scope_exit([&] {
  21487. svr.stop();
  21488. t.join();
  21489. });
  21490. svr.wait_until_ready();
  21491. Headers headers = {{"Upgrade", "websocket"},
  21492. {"Connection", "notupgrade"},
  21493. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21494. {"Sec-WebSocket-Version", "13"}};
  21495. Client cli("localhost", port);
  21496. auto res = cli.Get("/ws", headers);
  21497. // The route exists only as a WebSocket route, so a request that fails the
  21498. // handshake check falls through to ordinary routing.
  21499. ASSERT_TRUE(res);
  21500. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  21501. }
  21502. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  21503. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  21504. // Connection value is the only thing left for the client to reject.
  21505. Server svr;
  21506. svr.Get("/ws", [](const Request &req, Response &res) {
  21507. res.status = StatusCode::SwitchingProtocol_101;
  21508. res.set_header("Upgrade", "websocket");
  21509. res.set_header("Connection", "notupgrade");
  21510. res.set_header("Sec-WebSocket-Accept",
  21511. detail::websocket_accept_key(
  21512. req.get_header_value("Sec-WebSocket-Key")));
  21513. });
  21514. auto port = svr.bind_to_any_port("localhost");
  21515. std::thread t([&]() { svr.listen_after_bind(); });
  21516. auto se = detail::scope_exit([&] {
  21517. svr.stop();
  21518. t.join();
  21519. });
  21520. svr.wait_until_ready();
  21521. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21522. auto res = client.connect();
  21523. EXPECT_FALSE(res);
  21524. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21525. EXPECT_FALSE(client.is_open());
  21526. }
  21527. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  21528. Server svr;
  21529. svr.Get("/ws", [](const Request &req, Response &res) {
  21530. res.status = StatusCode::SwitchingProtocol_101;
  21531. res.set_header("Upgrade", "websocket");
  21532. res.set_header("Connection", "Upgrade");
  21533. res.set_header("Sec-WebSocket-Accept",
  21534. detail::websocket_accept_key(
  21535. req.get_header_value("Sec-WebSocket-Key")));
  21536. res.set_header("Sec-WebSocket-Protocol", "admin");
  21537. });
  21538. auto port = svr.bind_to_any_port("localhost");
  21539. std::thread t([&]() { svr.listen_after_bind(); });
  21540. auto se = detail::scope_exit([&] {
  21541. svr.stop();
  21542. t.join();
  21543. });
  21544. svr.wait_until_ready();
  21545. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  21546. // Server selects a subprotocol the client never offered
  21547. {
  21548. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21549. ws::WebSocketClient client(url, headers);
  21550. auto res = client.connect();
  21551. EXPECT_FALSE(res);
  21552. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21553. EXPECT_FALSE(client.is_open());
  21554. EXPECT_TRUE(client.subprotocol().empty());
  21555. }
  21556. // Client offered none but the server named one anyway
  21557. {
  21558. ws::WebSocketClient client(url);
  21559. auto res = client.connect();
  21560. EXPECT_FALSE(res);
  21561. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21562. EXPECT_FALSE(client.is_open());
  21563. EXPECT_TRUE(client.subprotocol().empty());
  21564. }
  21565. }
  21566. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  21567. // The socket path doubles as the URL host, so it must not contain '/'.
  21568. const char *shard = getenv("GTEST_SHARD_INDEX");
  21569. const std::string sock_path =
  21570. shard ? std::string("httplib-ws-") + shard + ".sock"
  21571. : std::string("httplib-ws.sock");
  21572. std::remove(sock_path.c_str());
  21573. Server svr;
  21574. std::mutex mtx;
  21575. std::string received_host;
  21576. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21577. {
  21578. std::lock_guard<std::mutex> lock(mtx);
  21579. received_host = req.get_header_value("Host");
  21580. }
  21581. std::string msg;
  21582. while (ws.read(msg)) {
  21583. ws.send(msg);
  21584. }
  21585. });
  21586. svr.set_address_family(AF_UNIX);
  21587. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  21588. auto se = detail::scope_exit([&] {
  21589. svr.stop();
  21590. t.join();
  21591. std::remove(sock_path.c_str());
  21592. });
  21593. svr.wait_until_ready();
  21594. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  21595. client.set_address_family(AF_UNIX);
  21596. ASSERT_TRUE(client.connect());
  21597. ASSERT_TRUE(client.send("hello"));
  21598. std::string msg;
  21599. ASSERT_TRUE(client.read(msg));
  21600. client.close();
  21601. {
  21602. std::lock_guard<std::mutex> lock(mtx);
  21603. // There is no host:port for a Unix socket, so the same "localhost"
  21604. // placeholder the HTTP client uses is expected.
  21605. EXPECT_EQ("localhost", received_host);
  21606. }
  21607. }
  21608. // Two threads must never parse WebSocket frames from the same stream.
  21609. // close() used to read the peer's Close reply with its own frame read, so it
  21610. // raced a reader thread that was in the middle of a payload: the payload loop
  21611. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  21612. // so bytes taken by close() were replaced with bytes from further along the
  21613. // stream. The message kept its length and silently changed content.
  21614. //
  21615. // The raw peer below sends a frame header plus part of the payload, waits for
  21616. // the handler to call close(), and only then sends the rest. Whichever thread
  21617. // would win the race for those bytes, the message must arrive intact, because
  21618. // close() must not touch the stream while read() owns it.
  21619. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  21620. #ifndef _WIN32
  21621. signal(SIGPIPE, SIG_IGN);
  21622. #endif
  21623. const size_t payload_len = 120; // fits the 7-bit length field
  21624. const size_t prefix_len = 8;
  21625. const int attempts = 8;
  21626. std::string expected(payload_len, '\0');
  21627. for (size_t i = 0; i < payload_len; i++) {
  21628. expected[i] = static_cast<char>('a' + i % 26);
  21629. }
  21630. std::atomic<bool> peer_stalled{false};
  21631. std::atomic<bool> handler_done{false};
  21632. std::mutex received_mutex;
  21633. std::vector<std::string> received;
  21634. // Bound every wait, so a regression fails the test instead of hanging the
  21635. // suite.
  21636. auto wait_for = [](const std::atomic<bool> &flag) {
  21637. for (int i = 0; i < 500 && !flag; i++) {
  21638. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21639. }
  21640. };
  21641. Server svr;
  21642. svr.set_websocket_ping_interval(0);
  21643. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  21644. std::thread reader([&]() {
  21645. std::string msg;
  21646. while (ws.read(msg)) {
  21647. std::lock_guard<std::mutex> guard(received_mutex);
  21648. received.push_back(msg);
  21649. }
  21650. });
  21651. // Wait until the peer stalls mid-payload, so the reader thread is parked
  21652. // inside read_websocket_frame() when close() runs.
  21653. wait_for(peer_stalled);
  21654. ws.close();
  21655. reader.join();
  21656. handler_done = true;
  21657. });
  21658. auto port = svr.bind_to_any_port("127.0.0.1");
  21659. std::thread t([&]() { svr.listen_after_bind(); });
  21660. auto se = detail::scope_exit([&] {
  21661. svr.stop();
  21662. t.join();
  21663. });
  21664. svr.wait_until_ready();
  21665. auto send_bytes = [](socket_t s, const std::string &data) {
  21666. #ifdef _WIN32
  21667. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  21668. #else
  21669. auto n = ::send(s, data.data(), data.size(), 0);
  21670. #endif
  21671. return n == static_cast<decltype(n)>(data.size());
  21672. };
  21673. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  21674. // Every length used here fits the 7-bit length field.
  21675. auto masked_header = [](uint8_t first_byte, size_t len) {
  21676. std::string h;
  21677. h += static_cast<char>(first_byte);
  21678. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  21679. h.append(4, '\0'); // mask key
  21680. return h;
  21681. };
  21682. for (int attempt = 0; attempt < attempts; attempt++) {
  21683. peer_stalled = false;
  21684. handler_done = false;
  21685. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  21686. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  21687. auto se_sock = detail::scope_exit([&] {
  21688. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  21689. });
  21690. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21691. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  21692. sockaddr_in addr{};
  21693. addr.sin_family = AF_INET;
  21694. addr.sin_port = htons(static_cast<uint16_t>(port));
  21695. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21696. ASSERT_EQ(
  21697. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  21698. << "attempt " << attempt;
  21699. ASSERT_TRUE(send_bytes(sock,
  21700. "GET /ws HTTP/1.1\r\n"
  21701. "Host: 127.0.0.1\r\n"
  21702. "Upgrade: websocket\r\n"
  21703. "Connection: Upgrade\r\n"
  21704. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  21705. "Sec-WebSocket-Version: 13\r\n"
  21706. "\r\n"))
  21707. << "attempt " << attempt;
  21708. std::string response;
  21709. while (response.find("\r\n\r\n") == std::string::npos) {
  21710. char buf[512];
  21711. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  21712. if (n <= 0) { break; }
  21713. response.append(buf, static_cast<size_t>(n));
  21714. }
  21715. ASSERT_NE(std::string::npos, response.find(" 101 "))
  21716. << "attempt " << attempt;
  21717. // Send the header of a Binary message but only the first prefix_len bytes
  21718. // of its payload, leaving the reader thread stalled inside the payload.
  21719. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  21720. expected.substr(0, prefix_len)))
  21721. << "attempt " << attempt;
  21722. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21723. peer_stalled = true;
  21724. // Let close() send its Close frame and park in its own read before the
  21725. // rest of the payload arrives, so both threads are waiting for it.
  21726. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21727. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  21728. close_frame += static_cast<char>(0x03); // status 1000
  21729. close_frame += static_cast<char>(0xE8);
  21730. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  21731. << "attempt " << attempt;
  21732. // Closing the peer releases the reader thread even on the buggy path,
  21733. // where it waits for bytes another thread already consumed.
  21734. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21735. detail::close_socket(sock);
  21736. sock = INVALID_SOCKET;
  21737. wait_for(handler_done);
  21738. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  21739. }
  21740. std::lock_guard<std::mutex> guard(received_mutex);
  21741. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  21742. << "a message in flight when close() ran was dropped";
  21743. for (size_t i = 0; i < received.size(); i++) {
  21744. EXPECT_EQ(expected, received[i]) << "message " << i;
  21745. }
  21746. }
  21747. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  21748. class WebSocketSSLIntegrationTest : public ::testing::Test {
  21749. protected:
  21750. void SetUp() override {
  21751. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  21752. SERVER_PRIVATE_KEY_FILE);
  21753. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21754. std::string msg;
  21755. ws::ReadResult ret;
  21756. while ((ret = ws.read(msg))) {
  21757. if (ret == ws::Binary) {
  21758. ws.send(msg.data(), msg.size());
  21759. } else {
  21760. ws.send(msg);
  21761. }
  21762. }
  21763. });
  21764. port_ = server_->bind_to_any_port(HOST);
  21765. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21766. server_->wait_until_ready();
  21767. }
  21768. void TearDown() override {
  21769. server_->stop();
  21770. if (server_thread_.joinable()) { server_thread_.join(); }
  21771. }
  21772. std::unique_ptr<SSLServer> server_;
  21773. std::thread server_thread_;
  21774. int port_ = 0;
  21775. };
  21776. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  21777. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21778. "/ws-echo");
  21779. client.enable_server_certificate_verification(false);
  21780. ASSERT_TRUE(client.connect());
  21781. ASSERT_TRUE(client.is_open());
  21782. ASSERT_TRUE(client.send("Hello WSS"));
  21783. std::string msg;
  21784. EXPECT_EQ(ws::Text, client.read(msg));
  21785. EXPECT_EQ("Hello WSS", msg);
  21786. client.close();
  21787. }
  21788. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  21789. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  21790. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  21791. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  21792. // client (without calling close() first) is the only path that runs
  21793. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  21794. // bug exactly.
  21795. //
  21796. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  21797. // when linked against an instrumented libssl; run under Valgrind to catch it
  21798. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  21799. // suite (the freed session otherwise stalls on the close handshake) — this test
  21800. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  21801. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  21802. {
  21803. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21804. "/ws-echo");
  21805. client.enable_server_certificate_verification(false);
  21806. client.set_read_timeout(2, 0);
  21807. client.set_write_timeout(2, 0);
  21808. ASSERT_TRUE(client.connect());
  21809. ASSERT_TRUE(client.is_open());
  21810. ASSERT_TRUE(client.send("still open"));
  21811. // Intentionally do NOT call client.close(): leaving scope runs
  21812. // shutdown_and_close() with the WebSocket still open, which must send the
  21813. // close frame while the TLS session is still alive.
  21814. }
  21815. }
  21816. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  21817. // shutdown_and_close() at the start of connect(), reproducing the same
  21818. // use-after-free within the test body rather than at scope exit. The second
  21819. // connect must succeed and echo, proving the close handshake ran over a live
  21820. // session. See the note above about memory-tool requirements.
  21821. TEST_F(WebSocketSSLIntegrationTest,
  21822. ReconnectWhileOpenSendsCloseOverLiveSession) {
  21823. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21824. "/ws-echo");
  21825. client.enable_server_certificate_verification(false);
  21826. client.set_read_timeout(2, 0);
  21827. client.set_write_timeout(2, 0);
  21828. ASSERT_TRUE(client.connect());
  21829. ASSERT_TRUE(client.is_open());
  21830. ASSERT_TRUE(client.send("still open"));
  21831. // Reconnect without closing first: connect() calls shutdown_and_close() on
  21832. // the still-open connection, which must not touch a freed TLS session.
  21833. ASSERT_TRUE(client.connect());
  21834. ASSERT_TRUE(client.is_open());
  21835. ASSERT_TRUE(client.send("after reconnect"));
  21836. std::string msg;
  21837. EXPECT_EQ(ws::Text, client.read(msg));
  21838. EXPECT_EQ("after reconnect", msg);
  21839. client.close();
  21840. }
  21841. #endif
  21842. #ifdef CPPHTTPLIB_SSL_ENABLED
  21843. class WebSocketSSLCATest : public ::testing::Test {
  21844. protected:
  21845. void SetUp() override {
  21846. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  21847. SERVER_PRIVATE_KEY_FILE);
  21848. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21849. std::string msg;
  21850. while (ws.read(msg)) {
  21851. ws.send(msg);
  21852. }
  21853. });
  21854. port_ = server_->bind_to_any_port("127.0.0.1");
  21855. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21856. server_->wait_until_ready();
  21857. }
  21858. void TearDown() override {
  21859. server_->stop();
  21860. if (server_thread_.joinable()) { server_thread_.join(); }
  21861. }
  21862. std::string url() const {
  21863. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  21864. }
  21865. std::unique_ptr<SSLServer> server_;
  21866. std::thread server_thread_;
  21867. int port_ = 0;
  21868. };
  21869. // A custom CA loaded as PEM verifies the server with full certificate
  21870. // verification enabled
  21871. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  21872. ws::WebSocketClient client(url());
  21873. std::string cert;
  21874. read_file(SERVER_CERT2_FILE, cert);
  21875. client.load_ca_cert_store(cert.c_str(), cert.size());
  21876. ASSERT_TRUE(client.connect());
  21877. ASSERT_TRUE(client.send("hello"));
  21878. std::string msg;
  21879. EXPECT_EQ(ws::Text, client.read(msg));
  21880. EXPECT_EQ("hello", msg);
  21881. client.close();
  21882. }
  21883. // A custom CA that does not cover the server must fail verification (the
  21884. // custom CA is exclusive; system certs are not loaded alongside it)
  21885. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  21886. ws::WebSocketClient client(url());
  21887. std::string cert;
  21888. read_file(CLIENT_CA_CERT_FILE, cert);
  21889. client.load_ca_cert_store(cert.c_str(), cert.size());
  21890. auto res = client.connect();
  21891. ASSERT_FALSE(res);
  21892. EXPECT_EQ(Error::SSLServerVerification, res.error());
  21893. EXPECT_EQ(-1, res.status());
  21894. EXPECT_NE(0u, res.ssl_backend_error());
  21895. }
  21896. // The same CA as a file path rather than PEM in memory
  21897. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  21898. ws::WebSocketClient client(url());
  21899. client.set_ca_cert_path(SERVER_CERT2_FILE);
  21900. ASSERT_TRUE(client.connect());
  21901. ASSERT_TRUE(client.send("hello"));
  21902. std::string msg;
  21903. EXPECT_EQ(ws::Text, client.read(msg));
  21904. EXPECT_EQ("hello", msg);
  21905. client.close();
  21906. }
  21907. // ...and a CA file that does not cover the server still fails, so it is the
  21908. // path above that decides the outcome
  21909. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  21910. ws::WebSocketClient client(url());
  21911. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  21912. ASSERT_FALSE(client.connect());
  21913. }
  21914. // Regression test: reconnecting with a native custom CA store used to reuse
  21915. // a store handle the previous TLS context had already freed (use-after-free
  21916. // under the OpenSSL backend). The context now lives as long as the client.
  21917. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  21918. ws::WebSocketClient client(url());
  21919. std::string cert;
  21920. read_file(SERVER_CERT2_FILE, cert);
  21921. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  21922. ASSERT_TRUE(client.connect());
  21923. client.close();
  21924. ASSERT_TRUE(client.connect());
  21925. ASSERT_TRUE(client.send("again"));
  21926. std::string msg;
  21927. EXPECT_EQ(ws::Text, client.read(msg));
  21928. EXPECT_EQ("again", msg);
  21929. client.close();
  21930. }
  21931. // Regression test: a certificate with a trusted chain but no identity match
  21932. // for the server IP must be rejected. The Mbed TLS backend used to skip
  21933. // verification entirely for IP hosts, so this connection succeeded there.
  21934. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  21935. // chain verification while the identity check must still fail.
  21936. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  21937. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21938. ASSERT_TRUE(svr.is_valid());
  21939. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21940. std::string msg;
  21941. while (ws.read(msg)) {
  21942. ws.send(msg);
  21943. }
  21944. });
  21945. auto port = svr.bind_to_any_port("127.0.0.1");
  21946. auto t = std::thread([&]() { svr.listen_after_bind(); });
  21947. auto se = detail::scope_exit([&] {
  21948. svr.stop();
  21949. t.join();
  21950. });
  21951. svr.wait_until_ready();
  21952. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  21953. "/echo");
  21954. std::string cert;
  21955. read_file(SERVER_CERT_FILE, cert);
  21956. client.load_ca_cert_store(cert.c_str(), cert.size());
  21957. ASSERT_FALSE(client.connect());
  21958. }
  21959. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  21960. // SNI, so nothing binds the host name to the TLS session. These bind the
  21961. // server to "localhost" instead, the only shape that exercises the SNI and
  21962. // hostname-verification path with certificate verification left enabled.
  21963. class WebSocketSSLDnsHostTest : public ::testing::Test {
  21964. protected:
  21965. void Start(const char *cert_file) {
  21966. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  21967. SERVER_PRIVATE_KEY_FILE);
  21968. ASSERT_TRUE(server_->is_valid());
  21969. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21970. std::string msg;
  21971. while (ws.read(msg)) {
  21972. ws.send(msg);
  21973. }
  21974. });
  21975. port_ = server_->bind_to_any_port("localhost");
  21976. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21977. server_->wait_until_ready();
  21978. }
  21979. void TearDown() override {
  21980. if (server_) { server_->stop(); }
  21981. if (server_thread_.joinable()) { server_thread_.join(); }
  21982. }
  21983. std::string url() const {
  21984. return "wss://localhost:" + std::to_string(port_) + "/echo";
  21985. }
  21986. std::unique_ptr<SSLServer> server_;
  21987. std::thread server_thread_;
  21988. int port_ = 0;
  21989. };
  21990. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  21991. // out and the connection is usable
  21992. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  21993. Start(SERVER_CERT2_FILE);
  21994. ws::WebSocketClient client(url());
  21995. client.set_ca_cert_path(SERVER_CERT2_FILE);
  21996. ASSERT_TRUE(client.connect());
  21997. ASSERT_TRUE(client.send("hello"));
  21998. std::string msg;
  21999. EXPECT_EQ(ws::Text, client.read(msg));
  22000. EXPECT_EQ("hello", msg);
  22001. client.close();
  22002. }
  22003. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  22004. // while the identity check must still reject "localhost"
  22005. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  22006. Start(SERVER_CERT_FILE);
  22007. ws::WebSocketClient client(url());
  22008. client.set_ca_cert_path(SERVER_CERT_FILE);
  22009. auto res = client.connect();
  22010. ASSERT_FALSE(res);
  22011. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  22012. EXPECT_EQ(-1, res.status());
  22013. }
  22014. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  22015. // disabled: the chain is still checked, only the identity check is skipped
  22016. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  22017. Start(SERVER_CERT_FILE);
  22018. ws::WebSocketClient client(url());
  22019. client.set_ca_cert_path(SERVER_CERT_FILE);
  22020. client.enable_server_hostname_verification(false);
  22021. ASSERT_TRUE(client.connect());
  22022. ASSERT_TRUE(client.send("hello"));
  22023. std::string msg;
  22024. EXPECT_EQ(ws::Text, client.read(msg));
  22025. EXPECT_EQ("hello", msg);
  22026. client.close();
  22027. }
  22028. // A CA that did not sign the server certificate fails the chain, even though
  22029. // the name would match
  22030. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  22031. Start(SERVER_CERT2_FILE);
  22032. ws::WebSocketClient client(url());
  22033. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22034. ASSERT_FALSE(client.connect());
  22035. }
  22036. // With verification disabled, neither the chain nor the name is checked
  22037. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  22038. Start(SERVER_CERT_FILE);
  22039. ws::WebSocketClient client(url());
  22040. client.enable_server_certificate_verification(false);
  22041. ASSERT_TRUE(client.connect());
  22042. ASSERT_TRUE(client.send("hello"));
  22043. std::string msg;
  22044. EXPECT_EQ(ws::Text, client.read(msg));
  22045. EXPECT_EQ("hello", msg);
  22046. client.close();
  22047. }
  22048. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  22049. protected:
  22050. void SetUp() override {
  22051. server_ = httplib::detail::make_unique<SSLServer>(
  22052. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22053. ASSERT_TRUE(server_->is_valid());
  22054. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22055. std::string msg;
  22056. while (ws.read(msg)) {
  22057. ws.send(msg);
  22058. }
  22059. });
  22060. port_ = server_->bind_to_any_port("localhost");
  22061. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22062. server_->wait_until_ready();
  22063. }
  22064. void TearDown() override {
  22065. server_->stop();
  22066. if (server_thread_.joinable()) { server_thread_.join(); }
  22067. }
  22068. std::string url() const {
  22069. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  22070. }
  22071. void ConnectWithClientCert(const std::string &client_cert_file,
  22072. const std::string &client_private_key_file,
  22073. const char *private_key_password) {
  22074. std::string cert_pem, key_pem;
  22075. read_file(client_cert_file, cert_pem);
  22076. read_file(client_private_key_file, key_pem);
  22077. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  22078. key_pem.c_str(), key_pem.size(),
  22079. private_key_password};
  22080. ws::WebSocketClient client(url(), pem);
  22081. ASSERT_TRUE(client.is_valid());
  22082. client.enable_server_certificate_verification(false);
  22083. ASSERT_TRUE(client.connect());
  22084. ASSERT_TRUE(client.send("hello"));
  22085. std::string msg;
  22086. EXPECT_EQ(ws::Text, client.read(msg));
  22087. EXPECT_EQ("hello", msg);
  22088. client.close();
  22089. }
  22090. std::unique_ptr<SSLServer> server_;
  22091. std::thread server_thread_;
  22092. int port_ = 0;
  22093. };
  22094. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  22095. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  22096. }
  22097. // Control for the tests above: the fixture's server really does require a
  22098. // client certificate, so it is the PEM the constructor installed that decides
  22099. // the outcome.
  22100. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  22101. ws::WebSocketClient client(url());
  22102. ASSERT_TRUE(client.is_valid());
  22103. client.enable_server_certificate_verification(false);
  22104. EXPECT_FALSE(client.connect());
  22105. }
  22106. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  22107. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  22108. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  22109. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  22110. }
  22111. #endif
  22112. #if !defined(_WIN32)
  22113. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  22114. auto secret_dir = std::string("./symlink_test_secret");
  22115. auto served_dir = std::string("./symlink_test_served");
  22116. auto secret_file = secret_dir + "/secret.txt";
  22117. auto symlink_path = served_dir + "/escape";
  22118. // Setup: create directories and files
  22119. mkdir(secret_dir.c_str(), 0755);
  22120. mkdir(served_dir.c_str(), 0755);
  22121. {
  22122. std::ofstream ofs(secret_file);
  22123. ofs << "SECRET_DATA";
  22124. }
  22125. // Create symlink using absolute path so it resolves correctly
  22126. #ifdef PATH_MAX
  22127. char abs_secret[PATH_MAX];
  22128. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  22129. #else
  22130. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  22131. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  22132. ASSERT_NE(nullptr, abs_secret);
  22133. #endif
  22134. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  22135. auto se = detail::scope_exit([&] {
  22136. unlink(symlink_path.c_str());
  22137. unlink(secret_file.c_str());
  22138. rmdir(served_dir.c_str());
  22139. rmdir(secret_dir.c_str());
  22140. });
  22141. Server svr;
  22142. svr.set_mount_point("/", served_dir);
  22143. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  22144. auto se2 = detail::scope_exit([&] {
  22145. svr.stop();
  22146. listen_thread.join();
  22147. });
  22148. svr.wait_until_ready();
  22149. Client cli("localhost", PORT);
  22150. // Symlink pointing outside base dir should be blocked
  22151. auto res = cli.Get("/escape/secret.txt");
  22152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22153. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  22154. }
  22155. #endif
  22156. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  22157. // "GET /smuggled" request), reads the first response, and only then sends the
  22158. // embedded request as the body. Returns how many times /smuggled ran.
  22159. //
  22160. // The body is sent AFTER receiving the first response (as in the original
  22161. // PoC) so that the stream_line_reader cannot buffer it together with the
  22162. // headers of the first request.
  22163. static int count_smuggled_requests(const std::string &outer_head,
  22164. std::string &first_response) {
  22165. Server svr;
  22166. svr.set_mount_point("/", "./www");
  22167. std::atomic<int> smuggled_count(0);
  22168. svr.Get("/smuggled", [&](const Request &, Response &res) {
  22169. smuggled_count++;
  22170. res.set_content("oops", "text/plain");
  22171. });
  22172. svr.Post("/post", [&](const Request &req, Response &res) {
  22173. res.set_content(req.body, "text/plain");
  22174. });
  22175. auto port = svr.bind_to_any_port("localhost");
  22176. thread t = thread([&] { svr.listen_after_bind(); });
  22177. auto se = detail::scope_exit([&] {
  22178. svr.stop();
  22179. t.join();
  22180. });
  22181. svr.wait_until_ready();
  22182. auto error = Error::Success;
  22183. auto sock = detail::create_client_socket(
  22184. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  22185. /*connection_timeout_sec=*/2, 0,
  22186. /*read_timeout_sec=*/2, 0,
  22187. /*write_timeout_sec=*/2, 0, std::string(), error);
  22188. EXPECT_NE(INVALID_SOCKET, sock);
  22189. if (sock == INVALID_SOCKET) { return -1; }
  22190. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22191. // The "smuggled" request will be sent as the body of the outer request
  22192. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  22193. "Host: localhost\r\n"
  22194. "Connection: close\r\n"
  22195. "\r\n";
  22196. auto head = outer_head;
  22197. auto len = std::to_string(smuggled.size());
  22198. for (auto pos = head.find("{len}"); pos != std::string::npos;
  22199. pos = head.find("{len}", pos + len.size())) {
  22200. head.replace(pos, 5, len);
  22201. }
  22202. // Step 1: Send only the outer request headers (no body yet)
  22203. auto sent = send(sock, head.data(), head.size(), 0);
  22204. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  22205. // Step 2: Read the first response
  22206. char buf[4096];
  22207. for (;;) {
  22208. auto n = recv(sock, buf, sizeof(buf), 0);
  22209. if (n <= 0) break;
  22210. first_response.append(buf, static_cast<size_t>(n));
  22211. // Stop once we have a complete response (headers + body)
  22212. auto hdr_end = first_response.find("\r\n\r\n");
  22213. if (hdr_end != std::string::npos) {
  22214. // Check for Content-Length to know when the body is complete
  22215. auto cl_pos = first_response.find("Content-Length:");
  22216. if (cl_pos != std::string::npos) {
  22217. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  22218. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  22219. auto cl = std::stoul(
  22220. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  22221. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  22222. } else {
  22223. break; // No Content-Length, assume headers-only response
  22224. }
  22225. }
  22226. }
  22227. // Step 3: Now send the body, which looks like a new HTTP request. On a
  22228. // vulnerable server the keep-alive loop reads this as a second request. The
  22229. // server may already have closed the connection, so the result is ignored.
  22230. send(sock, smuggled.data(), smuggled.size(), 0);
  22231. // Half-close so that a server which drained the body sees EOF and closes,
  22232. // instead of the read below waiting for the read timeout.
  22233. #ifdef _WIN32
  22234. ::shutdown(sock, SD_SEND);
  22235. #else
  22236. ::shutdown(sock, SHUT_WR);
  22237. #endif
  22238. // Step 4: Read until the server closes the connection
  22239. for (;;) {
  22240. auto n = recv(sock, buf, sizeof(buf), 0);
  22241. if (n <= 0) break;
  22242. }
  22243. return smuggled_count.load();
  22244. }
  22245. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  22246. // A GET request with Content-Length to a static file handler must have its
  22247. // body drained before the keep-alive connection is reused. Otherwise the
  22248. // unread body bytes are interpreted as the next HTTP request.
  22249. std::string first_response;
  22250. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22251. "Host: localhost\r\n"
  22252. "Content-Length: {len}\r\n"
  22253. "\r\n",
  22254. first_response));
  22255. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  22256. }
  22257. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  22258. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  22259. // be answered with 400 and the connection closed. Treating it as "no body"
  22260. // leaves the body to be parsed as the next request.
  22261. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  22262. const char *targets[] = {
  22263. "GET /file", // handler that never reads the body
  22264. "GET /not-found", // no handler matches (404)
  22265. "POST /post", // handler that reads the body
  22266. };
  22267. for (auto target : targets) {
  22268. for (auto value : values) {
  22269. std::string first_response;
  22270. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  22271. " HTTP/1.1\r\n"
  22272. "Host: localhost\r\n"
  22273. "Content-Length: " +
  22274. value + "\r\n\r\n",
  22275. first_response))
  22276. << target << " with Content-Length: " << value;
  22277. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  22278. << target << " with Content-Length: " << value;
  22279. }
  22280. }
  22281. }
  22282. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  22283. // A 400 for an unparseable request line leaves the rest of the message
  22284. // unread, so the connection must be closed rather than reused.
  22285. std::string first_response;
  22286. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  22287. "Host: localhost\r\n"
  22288. "Content-Length: {len}\r\n"
  22289. "\r\n",
  22290. first_response));
  22291. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22292. }
  22293. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  22294. // Same as above for a header block that fails to parse.
  22295. std::string first_response;
  22296. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22297. "Host: localhost\r\n"
  22298. "Bad Header\r\n"
  22299. "Content-Length: {len}\r\n"
  22300. "\r\n",
  22301. first_response));
  22302. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22303. }
  22304. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  22305. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  22306. // server must not read another request on that connection, even when the
  22307. // request had no body to drain.
  22308. std::string first_response;
  22309. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  22310. "Host: localhost\r\n"
  22311. "\r\n",
  22312. first_response));
  22313. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  22314. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  22315. }
  22316. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  22317. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  22318. // must be rejected with 400 Bad Request.
  22319. Server svr;
  22320. svr.Post("/test", [&](const Request &, Response &res) {
  22321. res.set_content("ok", "text/plain");
  22322. });
  22323. thread t = thread([&] { svr.listen(HOST, PORT); });
  22324. auto se = detail::scope_exit([&] {
  22325. svr.stop();
  22326. t.join();
  22327. ASSERT_FALSE(svr.is_running());
  22328. });
  22329. svr.wait_until_ready();
  22330. // Exact "chunked"
  22331. {
  22332. auto req = "POST /test HTTP/1.1\r\n"
  22333. "Host: localhost\r\n"
  22334. "Content-Length: 5\r\n"
  22335. "Transfer-Encoding: chunked\r\n"
  22336. "Connection: close\r\n"
  22337. "\r\n"
  22338. "hello";
  22339. std::string response;
  22340. ASSERT_TRUE(send_request(1, req, &response));
  22341. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22342. response.substr(0, response.find("\r\n")));
  22343. }
  22344. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  22345. {
  22346. auto req = "POST /test HTTP/1.1\r\n"
  22347. "Host: localhost\r\n"
  22348. "Content-Length: 5\r\n"
  22349. "Transfer-Encoding: gzip, chunked\r\n"
  22350. "Connection: close\r\n"
  22351. "\r\n"
  22352. "hello";
  22353. std::string response;
  22354. ASSERT_TRUE(send_request(1, req, &response));
  22355. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22356. response.substr(0, response.find("\r\n")));
  22357. }
  22358. }
  22359. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  22360. Server svr;
  22361. svr.Post("/test", [&](const Request &, Response &res) {
  22362. res.set_content("ok", "text/plain");
  22363. });
  22364. thread t = thread([&] { svr.listen(HOST, PORT); });
  22365. auto se = detail::scope_exit([&] {
  22366. svr.stop();
  22367. t.join();
  22368. ASSERT_FALSE(svr.is_running());
  22369. });
  22370. svr.wait_until_ready();
  22371. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  22372. // length cannot be determined, so the server must answer 400 and close
  22373. // rather than treat the request as bodyless and leave the body in the
  22374. // socket for the next request to pick up.
  22375. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  22376. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  22377. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  22378. std::string response;
  22379. ASSERT_TRUE(send_request(1, req, &response));
  22380. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22381. response.substr(0, response.find("\r\n")))
  22382. << transfer_encoding;
  22383. }
  22384. // RFC 9110 5.3: the codings may also be split across several
  22385. // Transfer-Encoding lines, which combine in the order they were received.
  22386. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  22387. // just like the single-line "chunked, gzip" above.
  22388. {
  22389. auto req = "POST /test HTTP/1.1\r\n"
  22390. "Host: localhost\r\n"
  22391. "Transfer-Encoding: chunked\r\n"
  22392. "Transfer-Encoding: gzip\r\n"
  22393. "\r\n"
  22394. "0\r\n\r\n";
  22395. std::string response;
  22396. ASSERT_TRUE(send_request(1, req, &response));
  22397. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22398. response.substr(0, response.find("\r\n")));
  22399. }
  22400. // A sequence ending in chunked stays valid.
  22401. auto req = "POST /test HTTP/1.1\r\n"
  22402. "Host: localhost\r\n"
  22403. "Transfer-Encoding: gzip, chunked\r\n"
  22404. "Connection: close\r\n"
  22405. "\r\n"
  22406. "0\r\n\r\n";
  22407. std::string response;
  22408. ASSERT_TRUE(send_request(1, req, &response));
  22409. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  22410. // ...including when it is spread over several lines.
  22411. auto split_req = "POST /test HTTP/1.1\r\n"
  22412. "Host: localhost\r\n"
  22413. "Transfer-Encoding: gzip\r\n"
  22414. "Transfer-Encoding: chunked\r\n"
  22415. "Connection: close\r\n"
  22416. "\r\n"
  22417. "0\r\n\r\n";
  22418. std::string split_response;
  22419. ASSERT_TRUE(send_request(1, split_req, &split_response));
  22420. EXPECT_EQ("HTTP/1.1 200 OK",
  22421. split_response.substr(0, split_response.find("\r\n")));
  22422. }
  22423. // Regression for issue #2450: a DELETE without Content-Length on a
  22424. // keep-alive connection must not let the post-response drain consume the
  22425. // next request's bytes.
  22426. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  22427. Server svr;
  22428. std::atomic<int> delete_count(0);
  22429. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  22430. delete_count++;
  22431. res.status = StatusCode::NoContent_204;
  22432. });
  22433. auto port = svr.bind_to_any_port(HOST);
  22434. thread t = thread([&] { svr.listen_after_bind(); });
  22435. auto se = detail::scope_exit([&] {
  22436. svr.stop();
  22437. t.join();
  22438. });
  22439. svr.wait_until_ready();
  22440. auto error = Error::Success;
  22441. auto sock = detail::create_client_socket(
  22442. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  22443. /*connection_timeout_sec=*/2, 0,
  22444. /*read_timeout_sec=*/2, 0,
  22445. /*write_timeout_sec=*/2, 0, std::string(), error);
  22446. ASSERT_NE(INVALID_SOCKET, sock);
  22447. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22448. auto send_request_and_read_response = [&](const std::string &req,
  22449. std::string &out) -> bool {
  22450. auto sent = send(sock, req.data(), req.size(), 0);
  22451. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  22452. char buf[4096];
  22453. for (;;) {
  22454. auto n = recv(sock, buf, sizeof(buf), 0);
  22455. if (n <= 0) { return !out.empty(); }
  22456. out.append(buf, static_cast<size_t>(n));
  22457. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  22458. }
  22459. };
  22460. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  22461. "Host: localhost\r\n"
  22462. "\r\n";
  22463. std::string resp1;
  22464. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  22465. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  22466. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  22467. "Host: localhost\r\n"
  22468. "Connection: close\r\n"
  22469. "\r\n";
  22470. std::string resp2;
  22471. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  22472. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  22473. EXPECT_EQ(2, delete_count.load());
  22474. }
  22475. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  22476. Server svr;
  22477. svr.Post("/ingest", [&](const Request &, Response &res,
  22478. const ContentReader &content_reader) {
  22479. auto consumed = content_reader([](const char *, size_t) { return false; });
  22480. EXPECT_FALSE(consumed);
  22481. res.status = StatusCode::Conflict_409;
  22482. res.set_header("Connection", "close");
  22483. });
  22484. auto port = svr.bind_to_any_port(HOST);
  22485. thread t = thread([&] { svr.listen_after_bind(); });
  22486. auto se = detail::scope_exit([&] {
  22487. svr.stop();
  22488. t.join();
  22489. });
  22490. svr.wait_until_ready();
  22491. auto error = Error::Success;
  22492. auto sock = detail::create_client_socket(
  22493. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  22494. /*connection_timeout_sec=*/2, 0,
  22495. /*read_timeout_sec=*/1, 0,
  22496. /*write_timeout_sec=*/2, 0, std::string(), error);
  22497. ASSERT_NE(INVALID_SOCKET, sock);
  22498. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22499. std::string request = "POST /ingest HTTP/1.1\r\n"
  22500. "Host: localhost\r\n"
  22501. "Transfer-Encoding: chunked\r\n"
  22502. "\r\n"
  22503. "4\r\n"
  22504. "data\r\n";
  22505. auto sent = send(sock, request.data(), request.size(), 0);
  22506. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  22507. std::string response;
  22508. ssize_t received = 0;
  22509. do {
  22510. char buf[4096];
  22511. received = recv(sock, buf, sizeof(buf), 0);
  22512. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  22513. } while (received > 0);
  22514. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  22515. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  22516. EXPECT_EQ(0, received);
  22517. }
  22518. namespace no_proxy_test {
  22519. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  22520. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  22521. // calling listen().
  22522. class ScopedServer {
  22523. public:
  22524. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  22525. ~ScopedServer() {
  22526. svr_.stop();
  22527. if (th_.joinable()) { th_.join(); }
  22528. }
  22529. Server &svr() { return svr_; }
  22530. int port() const { return port_; }
  22531. void listen() {
  22532. th_ = std::thread([this] { svr_.listen_after_bind(); });
  22533. svr_.wait_until_ready();
  22534. }
  22535. private:
  22536. Server svr_;
  22537. std::thread th_;
  22538. int port_ = 0;
  22539. };
  22540. class ProxyAndTargetServers {
  22541. public:
  22542. ProxyAndTargetServers() {
  22543. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  22544. proxy_hits_++;
  22545. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  22546. res.set_content("via-proxy", "text/plain");
  22547. });
  22548. target_.Get(".*", [this](const Request &req, Response &res) {
  22549. target_hits_++;
  22550. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  22551. res.set_content("direct", "text/plain");
  22552. });
  22553. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  22554. target_port_ = target_.bind_to_any_port("127.0.0.1");
  22555. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  22556. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  22557. proxy_mock_.wait_until_ready();
  22558. target_.wait_until_ready();
  22559. }
  22560. ~ProxyAndTargetServers() {
  22561. proxy_mock_.stop();
  22562. target_.stop();
  22563. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  22564. if (target_thread_.joinable()) { target_thread_.join(); }
  22565. }
  22566. Server &proxy_mock() { return proxy_mock_; }
  22567. Server &target() { return target_; }
  22568. int proxy_port() const { return proxy_port_; }
  22569. int target_port() const { return target_port_; }
  22570. int proxy_hits() const { return proxy_hits_.load(); }
  22571. int target_hits() const { return target_hits_.load(); }
  22572. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  22573. void reset_counters() {
  22574. proxy_hits_ = 0;
  22575. target_hits_ = 0;
  22576. last_had_proxy_authz_ = false;
  22577. }
  22578. private:
  22579. Server proxy_mock_;
  22580. Server target_;
  22581. std::thread proxy_thread_;
  22582. std::thread target_thread_;
  22583. int proxy_port_ = 0;
  22584. int target_port_ = 0;
  22585. std::atomic<int> proxy_hits_{0};
  22586. std::atomic<int> target_hits_{0};
  22587. std::atomic<bool> last_had_proxy_authz_{false};
  22588. };
  22589. inline std::unique_ptr<Client> make_client(const std::string &host,
  22590. ProxyAndTargetServers &s) {
  22591. auto cli = detail::make_unique<Client>(host, s.target_port());
  22592. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  22593. cli->set_proxy("127.0.0.1", s.proxy_port());
  22594. return cli;
  22595. }
  22596. } // namespace no_proxy_test
  22597. using no_proxy_test::make_client;
  22598. using no_proxy_test::ProxyAndTargetServers;
  22599. TEST(NoProxyTest, ExactHostnameBypasses) {
  22600. ProxyAndTargetServers s;
  22601. auto cli = make_client("example.com", s);
  22602. cli->set_no_proxy({"example.com"});
  22603. auto res = cli->Get("/");
  22604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22605. EXPECT_EQ(0, s.proxy_hits());
  22606. EXPECT_EQ(1, s.target_hits());
  22607. }
  22608. TEST(NoProxyTest, SubdomainBypasses) {
  22609. ProxyAndTargetServers s;
  22610. auto cli = make_client("foo.example.com", s);
  22611. cli->set_no_proxy({"example.com"});
  22612. auto res = cli->Get("/");
  22613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22614. EXPECT_EQ(0, s.proxy_hits());
  22615. EXPECT_EQ(1, s.target_hits());
  22616. }
  22617. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  22618. // Regression guard: "evilexample.com" must not be considered a subdomain
  22619. // of "example.com". Without the dot-boundary rule, a naive endsWith
  22620. // check would let traffic bypass the proxy and leak credentials direct
  22621. // to the attacker host.
  22622. ProxyAndTargetServers s;
  22623. auto cli = make_client("evilexample.com", s);
  22624. cli->set_no_proxy({"example.com"});
  22625. auto res = cli->Get("/");
  22626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22627. EXPECT_GE(s.proxy_hits(), 1);
  22628. EXPECT_EQ(0, s.target_hits());
  22629. }
  22630. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  22631. ProxyAndTargetServers s;
  22632. auto cli = make_client("example.com.evil.com", s);
  22633. cli->set_no_proxy({"example.com"});
  22634. auto res = cli->Get("/");
  22635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22636. EXPECT_GE(s.proxy_hits(), 1);
  22637. EXPECT_EQ(0, s.target_hits());
  22638. }
  22639. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  22640. ProxyAndTargetServers s;
  22641. auto cli = make_client("example.com", s);
  22642. cli->set_no_proxy({".example.com"});
  22643. auto res = cli->Get("/");
  22644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22645. EXPECT_EQ(0, s.proxy_hits());
  22646. EXPECT_EQ(1, s.target_hits());
  22647. }
  22648. TEST(NoProxyTest, CaseInsensitiveHostname) {
  22649. ProxyAndTargetServers s;
  22650. auto cli = make_client("Example.COM", s);
  22651. cli->set_no_proxy({"EXAMPLE.com"});
  22652. auto res = cli->Get("/");
  22653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22654. EXPECT_EQ(0, s.proxy_hits());
  22655. EXPECT_EQ(1, s.target_hits());
  22656. }
  22657. TEST(NoProxyTest, TrailingDotIsNormalized) {
  22658. ProxyAndTargetServers s;
  22659. auto cli = make_client("example.com.", s);
  22660. cli->set_no_proxy({"example.com"});
  22661. auto res = cli->Get("/");
  22662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22663. EXPECT_EQ(0, s.proxy_hits());
  22664. EXPECT_EQ(1, s.target_hits());
  22665. }
  22666. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  22667. // Trailing dots must be normalized on BOTH sides — host and entry.
  22668. // An implementation that only strips the host-side trailing dot would
  22669. // fail to match host "example.com" against entry "example.com." because
  22670. // a literal substring search would compare 11 chars against 12.
  22671. ProxyAndTargetServers s;
  22672. auto cli = make_client("example.com", s);
  22673. cli->set_no_proxy({"example.com."});
  22674. auto res = cli->Get("/");
  22675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22676. EXPECT_EQ(0, s.proxy_hits());
  22677. EXPECT_EQ(1, s.target_hits());
  22678. }
  22679. TEST(NoProxyTest, WildcardBypassesEverything) {
  22680. ProxyAndTargetServers s;
  22681. auto cli = make_client("anything.invalid.test", s);
  22682. cli->set_no_proxy({"*"});
  22683. auto res = cli->Get("/");
  22684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22685. EXPECT_EQ(0, s.proxy_hits());
  22686. EXPECT_EQ(1, s.target_hits());
  22687. }
  22688. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  22689. ProxyAndTargetServers s;
  22690. Client cli("127.0.0.1", s.target_port());
  22691. cli.set_proxy("127.0.0.1", s.proxy_port());
  22692. cli.set_no_proxy({"127.0.0.1"});
  22693. auto res = cli.Get("/");
  22694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22695. EXPECT_EQ(0, s.proxy_hits());
  22696. EXPECT_EQ(1, s.target_hits());
  22697. }
  22698. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  22699. ProxyAndTargetServers s;
  22700. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  22701. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  22702. cli.set_proxy("127.0.0.1", s.proxy_port());
  22703. cli.set_no_proxy({"::1"});
  22704. auto res = cli.Get("/");
  22705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22706. EXPECT_EQ(0, s.proxy_hits());
  22707. EXPECT_EQ(1, s.target_hits());
  22708. }
  22709. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  22710. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  22711. // must still be recognized as IPv6 for CIDR matching. Implementations
  22712. // that detect IPv6 only when the host begins with '[' would parse the
  22713. // host as a hostname and miss the match.
  22714. ProxyAndTargetServers s;
  22715. Client cli("fe80::1", s.target_port());
  22716. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  22717. cli.set_proxy("127.0.0.1", s.proxy_port());
  22718. cli.set_no_proxy({"fe80::/10"});
  22719. auto res = cli.Get("/");
  22720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22721. EXPECT_EQ(0, s.proxy_hits());
  22722. EXPECT_EQ(1, s.target_hits());
  22723. }
  22724. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  22725. ProxyAndTargetServers s;
  22726. Client cli("::1", s.target_port());
  22727. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  22728. cli.set_proxy("127.0.0.1", s.proxy_port());
  22729. cli.set_no_proxy({"[::1]"});
  22730. auto res = cli.Get("/");
  22731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22732. EXPECT_EQ(0, s.proxy_hits());
  22733. EXPECT_EQ(1, s.target_hits());
  22734. }
  22735. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  22736. ProxyAndTargetServers s;
  22737. Client cli("fe80::1", s.target_port());
  22738. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  22739. cli.set_proxy("127.0.0.1", s.proxy_port());
  22740. cli.set_no_proxy({"[fe80::]/10"});
  22741. auto res = cli.Get("/");
  22742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22743. EXPECT_EQ(0, s.proxy_hits());
  22744. EXPECT_EQ(1, s.target_hits());
  22745. }
  22746. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  22747. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  22748. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  22749. // tricks via address-family conversion.
  22750. ProxyAndTargetServers s;
  22751. Client cli("::ffff:127.0.0.1", s.target_port());
  22752. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  22753. cli.set_proxy("127.0.0.1", s.proxy_port());
  22754. cli.set_no_proxy({"127.0.0.1"});
  22755. auto res = cli.Get("/");
  22756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22757. EXPECT_GE(s.proxy_hits(), 1);
  22758. EXPECT_EQ(0, s.target_hits());
  22759. }
  22760. TEST(NoProxyTest, IPv4CidrMatch) {
  22761. ProxyAndTargetServers s;
  22762. Client cli("127.0.0.1", s.target_port());
  22763. cli.set_proxy("127.0.0.1", s.proxy_port());
  22764. cli.set_no_proxy({"127.0.0.0/8"});
  22765. auto res = cli.Get("/");
  22766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22767. EXPECT_EQ(0, s.proxy_hits());
  22768. EXPECT_EQ(1, s.target_hits());
  22769. }
  22770. TEST(NoProxyTest, IPv4CidrNonMatch) {
  22771. ProxyAndTargetServers s;
  22772. Client cli("127.0.0.1", s.target_port());
  22773. cli.set_proxy("127.0.0.1", s.proxy_port());
  22774. cli.set_no_proxy({"10.0.0.0/8"});
  22775. auto res = cli.Get("/");
  22776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22777. EXPECT_GE(s.proxy_hits(), 1);
  22778. EXPECT_EQ(0, s.target_hits());
  22779. }
  22780. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  22781. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  22782. // IPv4 target matches.
  22783. ProxyAndTargetServers s;
  22784. Client cli("127.0.0.1", s.target_port());
  22785. cli.set_proxy("127.0.0.1", s.proxy_port());
  22786. cli.set_no_proxy({"0.0.0.0/0"});
  22787. auto res = cli.Get("/");
  22788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22789. EXPECT_EQ(0, s.proxy_hits());
  22790. EXPECT_EQ(1, s.target_hits());
  22791. }
  22792. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  22793. ProxyAndTargetServers s;
  22794. Client cli("127.0.0.1", s.target_port());
  22795. cli.set_proxy("127.0.0.1", s.proxy_port());
  22796. cli.set_no_proxy({"127.0.0.1"});
  22797. auto res = cli.Get("/");
  22798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22799. EXPECT_EQ(0, s.proxy_hits());
  22800. EXPECT_EQ(1, s.target_hits());
  22801. }
  22802. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  22803. ProxyAndTargetServers s;
  22804. Client cli("127.0.0.1", s.target_port());
  22805. cli.set_proxy("127.0.0.1", s.proxy_port());
  22806. cli.set_no_proxy({"127.0.0.0/33"});
  22807. auto res = cli.Get("/");
  22808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22809. EXPECT_GE(s.proxy_hits(), 1);
  22810. EXPECT_EQ(0, s.target_hits());
  22811. }
  22812. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  22813. // Empty prefix after the slash must be rejected, not silently treated as /32.
  22814. ProxyAndTargetServers s;
  22815. Client cli("127.0.0.1", s.target_port());
  22816. cli.set_proxy("127.0.0.1", s.proxy_port());
  22817. cli.set_no_proxy({"127.0.0.1/"});
  22818. auto res = cli.Get("/");
  22819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22820. EXPECT_GE(s.proxy_hits(), 1);
  22821. EXPECT_EQ(0, s.target_hits());
  22822. }
  22823. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  22824. ProxyAndTargetServers s;
  22825. auto cli = make_client("internal.corp", s);
  22826. cli->set_proxy_basic_auth("u", "p");
  22827. cli->set_no_proxy({"internal.corp"});
  22828. auto res = cli->Get("/");
  22829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22830. EXPECT_EQ(1, s.target_hits());
  22831. EXPECT_EQ(0, s.proxy_hits());
  22832. EXPECT_FALSE(s.last_had_proxy_authz())
  22833. << "Proxy-Authorization must not be sent direct to the target";
  22834. }
  22835. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  22836. ProxyAndTargetServers s;
  22837. auto cli = make_client("public.example", s);
  22838. cli->set_proxy_basic_auth("u", "p");
  22839. cli->set_no_proxy({"internal.corp"}); // does not match
  22840. auto res = cli->Get("/");
  22841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22842. EXPECT_GE(s.proxy_hits(), 1);
  22843. EXPECT_TRUE(s.last_had_proxy_authz());
  22844. }
  22845. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  22846. std::atomic<int> hits{0};
  22847. std::atomic<int> hits_with_authz{0};
  22848. no_proxy_test::ScopedServer proxy_mock;
  22849. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  22850. hits++;
  22851. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  22852. if (req.target.find("/redir") != std::string::npos) {
  22853. res.set_redirect("http://other.example/landed");
  22854. } else {
  22855. res.set_content("via-proxy", "text/plain");
  22856. }
  22857. });
  22858. proxy_mock.listen();
  22859. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  22860. hits = 0;
  22861. hits_with_authz = 0;
  22862. Client cli("public.example", 80);
  22863. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22864. cli.set_proxy_basic_auth(c.first, c.second);
  22865. cli.set_follow_location(true);
  22866. // The redirect to another host goes through the proxy as well
  22867. auto res = cli.Get("/redir");
  22868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22869. EXPECT_EQ(2, hits.load());
  22870. EXPECT_EQ(2, hits_with_authz.load());
  22871. }
  22872. }
  22873. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  22874. ProxyAndTargetServers s;
  22875. auto cli = make_client("anything.test", s);
  22876. auto res = cli->Get("/");
  22877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22878. EXPECT_GE(s.proxy_hits(), 1);
  22879. EXPECT_EQ(0, s.target_hits());
  22880. }
  22881. TEST(NoProxyTest, PortSpecificEntryRejected) {
  22882. ProxyAndTargetServers s;
  22883. auto cli = make_client("example.com", s);
  22884. cli->set_no_proxy({"example.com:8080"});
  22885. auto res = cli->Get("/");
  22886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22887. EXPECT_GE(s.proxy_hits(), 1);
  22888. EXPECT_EQ(0, s.target_hits());
  22889. }
  22890. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  22891. ProxyAndTargetServers s;
  22892. auto cli = make_client("anything.test", s);
  22893. cli->set_no_proxy({"", " ", "\t"});
  22894. auto res = cli->Get("/");
  22895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22896. EXPECT_GE(s.proxy_hits(), 1);
  22897. EXPECT_EQ(0, s.target_hits());
  22898. }
  22899. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  22900. // An entry with leading/trailing whitespace must still match — env-style
  22901. // values are commonly pasted with stray spaces and an implementation
  22902. // that feeds the raw token directly to inet_pton would fail to match
  22903. // valid CIDRs because of the spaces.
  22904. ProxyAndTargetServers s;
  22905. Client cli("127.0.0.1", s.target_port());
  22906. cli.set_proxy("127.0.0.1", s.proxy_port());
  22907. cli.set_no_proxy({" 127.0.0.0/8 "});
  22908. auto res = cli.Get("/");
  22909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22910. EXPECT_EQ(0, s.proxy_hits());
  22911. EXPECT_EQ(1, s.target_hits());
  22912. }
  22913. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  22914. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  22915. // go direct and must NOT carry Proxy-Authorization.
  22916. std::atomic<int> proxy_hits{0};
  22917. std::atomic<int> target_hits{0};
  22918. std::atomic<bool> target_saw_authz{false};
  22919. no_proxy_test::ScopedServer proxy_mock, target;
  22920. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  22921. proxy_hits++;
  22922. res.status = 302;
  22923. res.set_header("Location", "http://127.0.0.1:" +
  22924. std::to_string(target.port()) + "/landed");
  22925. });
  22926. target.svr().Get(".*", [&](const Request &req, Response &res) {
  22927. target_hits++;
  22928. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  22929. res.set_content("direct", "text/plain");
  22930. });
  22931. proxy_mock.listen();
  22932. target.listen();
  22933. Client cli("public.example", target.port());
  22934. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  22935. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22936. cli.set_proxy_basic_auth("u", "p");
  22937. cli.set_no_proxy({"127.0.0.1"});
  22938. cli.set_follow_location(true);
  22939. auto res = cli.Get("/redir");
  22940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22941. EXPECT_GE(proxy_hits.load(), 1);
  22942. EXPECT_GE(target_hits.load(), 1);
  22943. EXPECT_FALSE(target_saw_authz.load());
  22944. }
  22945. #ifdef CPPHTTPLIB_SSL_ENABLED
  22946. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  22947. // Direct origin replying 407 must not trigger the digest retry; otherwise
  22948. // proxy creds would be sent to the (possibly hostile) origin.
  22949. std::atomic<int> target_hits{0};
  22950. std::atomic<bool> target_saw_proxy_authz{false};
  22951. no_proxy_test::ScopedServer target;
  22952. target.svr().Get(".*", [&](const Request &req, Response &res) {
  22953. target_hits++;
  22954. if (req.has_header("Proxy-Authorization")) {
  22955. target_saw_proxy_authz = true;
  22956. }
  22957. res.status = StatusCode::ProxyAuthenticationRequired_407;
  22958. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  22959. "nonce=\"abc\", algorithm=MD5");
  22960. });
  22961. target.listen();
  22962. // The proxy address is set to the target's port: the bypass MUST kick in;
  22963. // if it doesn't, the test still routes "via proxy" to the same server and
  22964. // the Proxy-Authorization assertion below catches the leak.
  22965. Client cli("evil.example", target.port());
  22966. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  22967. cli.set_proxy("127.0.0.1", target.port());
  22968. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  22969. cli.set_no_proxy({"evil.example"});
  22970. auto res = cli.Get("/x");
  22971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22972. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  22973. EXPECT_EQ(1, target_hits.load());
  22974. EXPECT_FALSE(target_saw_proxy_authz.load());
  22975. }
  22976. #endif
  22977. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  22978. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  22979. std::atomic<int> proxy_hits{0};
  22980. std::atomic<int> bypass_hits{0};
  22981. std::atomic<bool> proxy_saw_c_url{false};
  22982. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  22983. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  22984. proxy_hits++;
  22985. if (req.path.find("/start") != std::string::npos) {
  22986. res.status = 302;
  22987. res.set_header("Location", "http://127.0.0.1:" +
  22988. std::to_string(bypass_server.port()) +
  22989. "/middle");
  22990. return;
  22991. }
  22992. if (req.path.find("/end") != std::string::npos) {
  22993. proxy_saw_c_url = true;
  22994. res.set_content("c-via-proxy", "text/plain");
  22995. return;
  22996. }
  22997. res.set_content("unexpected", "text/plain");
  22998. });
  22999. // public.example's "advertised" port is arbitrary (the request never lands
  23000. // there — it goes through the proxy), but use a dynamic value to stay
  23001. // friendly with sharded parallel runs.
  23002. int public_port = bypass_server.port();
  23003. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  23004. bypass_hits++;
  23005. res.status = 302;
  23006. res.set_header("Location", "http://public.example:" +
  23007. std::to_string(public_port) + "/end");
  23008. });
  23009. proxy_mock.listen();
  23010. bypass_server.listen();
  23011. Client cli("public.example", public_port);
  23012. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23013. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23014. cli.set_no_proxy({"127.0.0.1"});
  23015. cli.set_follow_location(true);
  23016. auto res = cli.Get("/start");
  23017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23018. EXPECT_EQ(StatusCode::OK_200, res->status);
  23019. EXPECT_EQ("c-via-proxy", res->body);
  23020. EXPECT_GE(proxy_hits.load(), 2);
  23021. EXPECT_GE(bypass_hits.load(), 1);
  23022. EXPECT_TRUE(proxy_saw_c_url.load());
  23023. }
  23024. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  23025. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  23026. // request reconnects to the correct endpoint.
  23027. std::atomic<int> proxy_hits{0};
  23028. std::atomic<int> target_hits{0};
  23029. no_proxy_test::ScopedServer proxy_mock, target;
  23030. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23031. proxy_hits++;
  23032. res.set_content("via-proxy", "text/plain");
  23033. });
  23034. target.svr().Get(".*", [&](const Request &, Response &res) {
  23035. target_hits++;
  23036. res.set_content("direct", "text/plain");
  23037. });
  23038. proxy_mock.listen();
  23039. target.listen();
  23040. Client cli("public.example", target.port());
  23041. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23042. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23043. cli.set_keep_alive(true);
  23044. auto res1 = cli.Get("/a");
  23045. ASSERT_TRUE(res1);
  23046. EXPECT_EQ("via-proxy", res1->body);
  23047. EXPECT_EQ(1, proxy_hits.load());
  23048. EXPECT_EQ(0, target_hits.load());
  23049. cli.set_no_proxy({"public.example"});
  23050. auto res2 = cli.Get("/b");
  23051. ASSERT_TRUE(res2);
  23052. EXPECT_EQ("direct", res2->body);
  23053. EXPECT_EQ(1, proxy_hits.load());
  23054. EXPECT_EQ(1, target_hits.load());
  23055. }
  23056. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  23057. namespace proxy_tunnel_test {
  23058. // SSLServer counterpart to no_proxy_test::ScopedServer.
  23059. class ScopedSSLServer {
  23060. public:
  23061. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  23062. port_ = svr_.bind_to_any_port("127.0.0.1");
  23063. }
  23064. ~ScopedSSLServer() {
  23065. svr_.stop();
  23066. if (th_.joinable()) { th_.join(); }
  23067. }
  23068. SSLServer &svr() { return svr_; }
  23069. int port() const { return port_; }
  23070. void listen() {
  23071. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23072. svr_.wait_until_ready();
  23073. }
  23074. private:
  23075. SSLServer svr_;
  23076. std::thread th_;
  23077. int port_ = 0;
  23078. };
  23079. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  23080. class ScopedConnectProxy {
  23081. public:
  23082. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  23083. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  23084. if (listen_fd_ < 0) { return; }
  23085. int yes = 1;
  23086. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  23087. sockaddr_in a{};
  23088. a.sin_family = AF_INET;
  23089. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23090. a.sin_port = 0;
  23091. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  23092. return;
  23093. }
  23094. socklen_t alen = sizeof(a);
  23095. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  23096. 0) {
  23097. return;
  23098. }
  23099. port_ = ntohs(a.sin_port);
  23100. if (::listen(listen_fd_, 1) != 0) { return; }
  23101. th_ = std::thread([this] { run(); });
  23102. }
  23103. ~ScopedConnectProxy() {
  23104. stop_ = true;
  23105. if (listen_fd_ >= 0) {
  23106. ::shutdown(listen_fd_, SHUT_RDWR);
  23107. ::close(listen_fd_);
  23108. }
  23109. if (th_.joinable()) { th_.join(); }
  23110. }
  23111. int port() const { return port_; }
  23112. int connect_hits() const { return connect_hits_.load(); }
  23113. // Head of the last CONNECT request, as the proxy saw it on the wire.
  23114. std::string connect_request() const {
  23115. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23116. return connect_request_;
  23117. }
  23118. private:
  23119. void run() {
  23120. while (!stop_.load()) {
  23121. fd_set rfds;
  23122. FD_ZERO(&rfds);
  23123. FD_SET(listen_fd_, &rfds);
  23124. timeval tv{0, 100 * 1000};
  23125. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  23126. if (sel <= 0) { continue; }
  23127. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  23128. if (client_fd < 0) { continue; }
  23129. std::string req;
  23130. char buf[2048];
  23131. while (req.find("\r\n\r\n") == std::string::npos) {
  23132. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  23133. if (n <= 0) { break; }
  23134. req.append(buf, static_cast<size_t>(n));
  23135. }
  23136. if (req.compare(0, 7, "CONNECT") != 0) {
  23137. ::close(client_fd);
  23138. continue;
  23139. }
  23140. connect_hits_++;
  23141. {
  23142. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23143. connect_request_ = req;
  23144. }
  23145. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  23146. ::send(client_fd, ok, std::strlen(ok), 0);
  23147. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  23148. sockaddr_in o{};
  23149. o.sin_family = AF_INET;
  23150. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23151. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  23152. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  23153. 0) {
  23154. ::close(client_fd);
  23155. ::close(origin_fd);
  23156. continue;
  23157. }
  23158. auto forward = [](int from, int to) {
  23159. char b[8192];
  23160. for (;;) {
  23161. ssize_t n = ::recv(from, b, sizeof(b), 0);
  23162. if (n <= 0) { break; }
  23163. ssize_t off = 0;
  23164. while (off < n) {
  23165. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  23166. if (s <= 0) {
  23167. off = n;
  23168. break;
  23169. }
  23170. off += s;
  23171. }
  23172. }
  23173. ::shutdown(to, SHUT_WR);
  23174. };
  23175. std::thread t1([&] { forward(client_fd, origin_fd); });
  23176. std::thread t2([&] { forward(origin_fd, client_fd); });
  23177. t1.join();
  23178. t2.join();
  23179. ::close(client_fd);
  23180. ::close(origin_fd);
  23181. }
  23182. }
  23183. int forward_port_ = -1;
  23184. int listen_fd_ = -1;
  23185. int port_ = 0;
  23186. std::thread th_;
  23187. std::atomic<bool> stop_{false};
  23188. std::atomic<int> connect_hits_{0};
  23189. mutable std::mutex connect_request_mutex_;
  23190. std::string connect_request_;
  23191. };
  23192. // Sends one request through the CONNECT proxy to the TLS origin with a
  23193. // credential configured for each hop, and checks that each credential reaches
  23194. // only the hop it was configured for: the proxy's on the CONNECT request, the
  23195. // origin's (every header in origin_headers) on the tunnelled request.
  23196. void CredentialsStayWithTheirHop(
  23197. const std::function<void(SSLClient &)> &set_credentials,
  23198. const std::string &scheme,
  23199. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  23200. std::atomic<int> origin_hits{0};
  23201. std::atomic<bool> origin_saw_proxy_authz{false};
  23202. std::atomic<bool> origin_saw_headers{false};
  23203. ScopedSSLServer origin;
  23204. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23205. origin_hits++;
  23206. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  23207. origin_saw_headers =
  23208. std::all_of(origin_headers.begin(), origin_headers.end(),
  23209. [&](const std::string &h) { return req.has_header(h); });
  23210. res.set_content("ok", "text/plain");
  23211. });
  23212. origin.listen();
  23213. ScopedConnectProxy proxy(origin.port());
  23214. ASSERT_NE(0, proxy.port());
  23215. // Pinned to 127.0.0.1 for the same reason as the test below.
  23216. SSLClient cli("127.0.0.1", origin.port());
  23217. cli.enable_server_certificate_verification(false);
  23218. cli.set_proxy("127.0.0.1", proxy.port());
  23219. set_credentials(cli);
  23220. auto res = cli.Get("/x");
  23221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23222. EXPECT_EQ(StatusCode::OK_200, res->status);
  23223. EXPECT_EQ(1, origin_hits.load());
  23224. EXPECT_EQ(1, proxy.connect_hits());
  23225. EXPECT_TRUE(origin_saw_headers.load());
  23226. EXPECT_FALSE(origin_saw_proxy_authz.load())
  23227. << "Proxy-Authorization must not be sent inside the tunnel";
  23228. auto connect_req = proxy.connect_request();
  23229. EXPECT_NE(std::string::npos,
  23230. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  23231. for (const auto &h : origin_headers) {
  23232. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  23233. << h << " must not be sent to the proxy on CONNECT";
  23234. }
  23235. }
  23236. } // namespace proxy_tunnel_test
  23237. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  23238. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23239. [](SSLClient &cli) {
  23240. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  23241. cli.set_basic_auth("origin-user", "origin-pass");
  23242. },
  23243. "Basic");
  23244. }
  23245. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  23246. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23247. [](SSLClient &cli) {
  23248. cli.set_proxy_bearer_token_auth("proxy-token");
  23249. cli.set_bearer_token_auth("origin-token");
  23250. },
  23251. "Bearer");
  23252. }
  23253. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  23254. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23255. [](SSLClient &cli) {
  23256. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  23257. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  23258. {"Cookie", "sid=origin-session"},
  23259. {"X-Api-Key", "origin-key"}});
  23260. },
  23261. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  23262. }
  23263. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  23264. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  23265. // retry; otherwise proxy creds would be sent to the origin.
  23266. std::atomic<int> origin_hits{0};
  23267. std::atomic<bool> origin_saw_proxy_authz{false};
  23268. proxy_tunnel_test::ScopedSSLServer origin;
  23269. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23270. origin_hits++;
  23271. if (req.has_header("Proxy-Authorization")) {
  23272. origin_saw_proxy_authz = true;
  23273. }
  23274. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23275. res.set_header("Proxy-Authenticate",
  23276. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  23277. "algorithm=MD5");
  23278. });
  23279. origin.listen();
  23280. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  23281. ASSERT_NE(0, proxy.port());
  23282. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  23283. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  23284. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  23285. // and answer with its own status, making this test flaky.
  23286. SSLClient cli("127.0.0.1", origin.port());
  23287. cli.enable_server_certificate_verification(false);
  23288. cli.set_proxy("127.0.0.1", proxy.port());
  23289. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23290. auto res = cli.Get("/x");
  23291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23292. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23293. EXPECT_EQ(1, origin_hits.load());
  23294. EXPECT_FALSE(origin_saw_proxy_authz.load());
  23295. EXPECT_EQ(1, proxy.connect_hits());
  23296. }
  23297. #endif