test.cc 936 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definition is linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. } // namespace tls
  68. } // namespace httplib
  69. #endif
  70. using namespace std;
  71. using namespace httplib;
  72. const char *HOST = "localhost";
  73. static int get_base_port() {
  74. const char *shard = getenv("GTEST_SHARD_INDEX");
  75. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  76. }
  77. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  78. // New standalone tests MUST use svr.bind_to_any_port() instead.
  79. const int PORT = get_base_port();
  80. const string LONG_QUERY_VALUE = string(25000, '@');
  81. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  82. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  83. const string TOO_LONG_QUERY_URL =
  84. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  85. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  86. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  87. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  88. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  89. return file.name == key;
  90. });
  91. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  92. return *it;
  93. #else
  94. if (it != items.end()) { return *it; }
  95. throw std::runtime_error("invalid multipart form data name error");
  96. #endif
  97. }
  98. static void read_file(const std::string &path, std::string &out) {
  99. std::ifstream fs(path, std::ios_base::binary);
  100. if (!fs) {
  101. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  102. return;
  103. #else
  104. throw std::runtime_error("File not found: " + path);
  105. #endif
  106. }
  107. fs.seekg(0, std::ios_base::end);
  108. auto size = fs.tellg();
  109. fs.seekg(0);
  110. out.resize(static_cast<size_t>(size));
  111. fs.read(&out[0], static_cast<std::streamsize>(size));
  112. }
  113. class UnixSocketTest : public ::testing::Test {
  114. protected:
  115. void TearDown() override { std::remove(pathname_.c_str()); }
  116. void client_GET(const std::string &addr) {
  117. httplib::Client cli{addr};
  118. cli.set_address_family(AF_UNIX);
  119. ASSERT_TRUE(cli.is_valid());
  120. const auto &result = cli.Get(pattern_);
  121. ASSERT_TRUE(result) << "error: " << result.error();
  122. const auto &resp = result.value();
  123. EXPECT_EQ(resp.status, StatusCode::OK_200);
  124. EXPECT_EQ(resp.body, content_);
  125. }
  126. static std::string make_sock_path() {
  127. const char *shard = getenv("GTEST_SHARD_INDEX");
  128. return shard ? std::string("./httplib-server-") + shard + ".sock"
  129. : "./httplib-server.sock";
  130. }
  131. const std::string pathname_{make_sock_path()};
  132. const std::string pattern_{"/hi"};
  133. const std::string content_{"Hello World!"};
  134. };
  135. TEST_F(UnixSocketTest, pathname) {
  136. httplib::Server svr;
  137. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  138. res.set_content(content_, "text/plain");
  139. });
  140. std::thread t{[&] {
  141. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  142. }};
  143. auto se = detail::scope_exit([&] {
  144. svr.stop();
  145. t.join();
  146. ASSERT_FALSE(svr.is_running());
  147. });
  148. svr.wait_until_ready();
  149. ASSERT_TRUE(svr.is_running());
  150. client_GET(pathname_);
  151. }
  152. #if defined(__linux__) || \
  153. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  154. TEST_F(UnixSocketTest, PeerPid) {
  155. httplib::Server svr;
  156. std::string remote_port_val;
  157. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  158. res.set_content(content_, "text/plain");
  159. remote_port_val = std::to_string(req.remote_port);
  160. });
  161. std::thread t{[&] {
  162. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  163. }};
  164. auto se = detail::scope_exit([&] {
  165. svr.stop();
  166. t.join();
  167. ASSERT_FALSE(svr.is_running());
  168. });
  169. svr.wait_until_ready();
  170. ASSERT_TRUE(svr.is_running());
  171. client_GET(pathname_);
  172. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  173. }
  174. #endif
  175. #ifdef __linux__
  176. TEST_F(UnixSocketTest, abstract) {
  177. constexpr char svr_path[]{"\x00httplib-server.sock"};
  178. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  179. httplib::Server svr;
  180. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  181. res.set_content(content_, "text/plain");
  182. });
  183. std::thread t{[&] {
  184. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  185. }};
  186. auto se = detail::scope_exit([&] {
  187. svr.stop();
  188. t.join();
  189. ASSERT_FALSE(svr.is_running());
  190. });
  191. svr.wait_until_ready();
  192. ASSERT_TRUE(svr.is_running());
  193. client_GET(abstract_addr);
  194. }
  195. #endif
  196. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  197. httplib::Server svr;
  198. std::string received_host_header;
  199. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  200. // Capture the Host header sent by the client
  201. auto host_iter = req.headers.find("Host");
  202. if (host_iter != req.headers.end()) {
  203. received_host_header = host_iter->second;
  204. }
  205. res.set_content(content_, "text/plain");
  206. });
  207. std::thread t{[&] {
  208. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  209. }};
  210. auto se = detail::scope_exit([&] {
  211. svr.stop();
  212. t.join();
  213. ASSERT_FALSE(svr.is_running());
  214. });
  215. svr.wait_until_ready();
  216. ASSERT_TRUE(svr.is_running());
  217. // Test that Host header is automatically set to "localhost" for Unix socket
  218. // connections
  219. httplib::Client cli{pathname_};
  220. cli.set_address_family(AF_UNIX);
  221. ASSERT_TRUE(cli.is_valid());
  222. const auto &result = cli.Get(pattern_);
  223. ASSERT_TRUE(result) << "error: " << result.error();
  224. const auto &resp = result.value();
  225. EXPECT_EQ(resp.status, StatusCode::OK_200);
  226. EXPECT_EQ(resp.body, content_);
  227. // Verify that Host header was automatically set to "localhost"
  228. EXPECT_EQ(received_host_header, "localhost");
  229. }
  230. #ifndef _WIN32
  231. TEST(SocketStream, wait_writable_UNIX) {
  232. int fds[2];
  233. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  234. const auto asSocketStream = [&](socket_t fd,
  235. std::function<bool(Stream &)> func) {
  236. return detail::process_client_socket(
  237. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  238. };
  239. asSocketStream(fds[0], [&](Stream &s0) {
  240. EXPECT_EQ(s0.socket(), fds[0]);
  241. EXPECT_TRUE(s0.wait_writable());
  242. EXPECT_TRUE(s0.is_peer_alive());
  243. EXPECT_EQ(0, close(fds[1]));
  244. EXPECT_FALSE(s0.is_peer_alive());
  245. return true;
  246. });
  247. EXPECT_EQ(0, close(fds[0]));
  248. }
  249. TEST(SocketStream, wait_writable_INET) {
  250. sockaddr_in addr;
  251. memset(&addr, 0, sizeof(addr));
  252. addr.sin_family = AF_INET;
  253. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  254. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  255. int disconnected_svr_sock = -1;
  256. std::thread svr{[&] {
  257. const int s = socket(AF_INET, SOCK_STREAM, 0);
  258. ASSERT_LE(0, s);
  259. // PORT + 1 is shared with the SSL redirect tests and with
  260. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  261. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  262. // because that happens on a worker thread the ASSERT does not stop the
  263. // test: it runs on and fails at the disconnected_svr_sock check instead.
  264. default_socket_options(s);
  265. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  266. ASSERT_EQ(0, listen(s, 1));
  267. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  268. ASSERT_EQ(0, close(s));
  269. }};
  270. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  271. std::thread cli{[&] {
  272. const int s = socket(AF_INET, SOCK_STREAM, 0);
  273. ASSERT_LE(0, s);
  274. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  275. ASSERT_EQ(0, close(s));
  276. }};
  277. cli.join();
  278. svr.join();
  279. ASSERT_NE(disconnected_svr_sock, -1);
  280. const auto asSocketStream = [&](socket_t fd,
  281. std::function<bool(Stream &)> func) {
  282. return detail::process_client_socket(
  283. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  284. };
  285. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  286. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  287. // wait_writable() returns true because select_write() only checks if the
  288. // send buffer has space. Peer disconnection is detected later by send().
  289. EXPECT_TRUE(ss.wait_writable());
  290. return true;
  291. });
  292. ASSERT_EQ(0, close(disconnected_svr_sock));
  293. }
  294. #endif // #ifndef _WIN32
  295. TEST(SetSocketOptTest, TcpNoDelay) {
  296. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  297. ASSERT_NE(sock, INVALID_SOCKET);
  298. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  299. int val = 0;
  300. socklen_t len = sizeof(val);
  301. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  302. reinterpret_cast<char *>(&val), &len));
  303. EXPECT_NE(val, 0);
  304. detail::close_socket(sock);
  305. }
  306. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  307. // accept() reports failures through WSAGetLastError() on Windows and through
  308. // errno everywhere else. Asking the wrong one is what made the accept loop
  309. // treat every recoverable failure as fatal on Windows.
  310. struct Classification {
  311. bool resource;
  312. bool transient;
  313. };
  314. auto classify = [](int err) {
  315. #ifdef _WIN32
  316. WSASetLastError(err);
  317. #else
  318. errno = err;
  319. #endif
  320. // Read both before asserting: an assertion may clobber the error slot.
  321. Classification c;
  322. c.resource = detail::is_accept_resource_error();
  323. c.transient = detail::is_accept_transient_error();
  324. return c;
  325. };
  326. #ifdef _WIN32
  327. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  328. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  329. WSAECONNRESET, WSAECONNABORTED};
  330. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  331. #else
  332. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  333. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  334. ECONNABORTED};
  335. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  336. #endif
  337. for (auto err : resource_errors) {
  338. const auto c = classify(err);
  339. EXPECT_TRUE(c.resource) << "error " << err;
  340. EXPECT_FALSE(c.transient) << "error " << err;
  341. }
  342. for (auto err : transient_errors) {
  343. const auto c = classify(err);
  344. EXPECT_TRUE(c.transient) << "error " << err;
  345. EXPECT_FALSE(c.resource) << "error " << err;
  346. }
  347. for (auto err : fatal_errors) {
  348. const auto c = classify(err);
  349. EXPECT_FALSE(c.resource) << "error " << err;
  350. EXPECT_FALSE(c.transient) << "error " << err;
  351. }
  352. #ifdef _WIN32
  353. WSASetLastError(0);
  354. #else
  355. errno = 0;
  356. #endif
  357. }
  358. TEST(ClientTest, MoveConstructible) {
  359. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  360. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  361. }
  362. TEST(ClientTest, MoveAssignable) {
  363. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  364. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  365. }
  366. #ifdef _WIN32
  367. TEST(StartupTest, WSAStartup) {
  368. WSADATA wsaData;
  369. int ret = WSAStartup(0x0002, &wsaData);
  370. ASSERT_EQ(0, ret);
  371. }
  372. #endif
  373. TEST(DecodePathTest, PercentCharacter) {
  374. EXPECT_EQ(
  375. decode_path_component(
  376. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  377. U8("descrip=Gastos áéíóúñÑ 6"));
  378. }
  379. TEST(DecodePathTest, PercentCharacterNUL) {
  380. string expected;
  381. expected.push_back('x');
  382. expected.push_back('\0');
  383. expected.push_back('x');
  384. EXPECT_EQ(decode_path_component("x%00x"), expected);
  385. }
  386. TEST(DecodePathTest, UnicodeEncoding) {
  387. // %u0041 = 'A' (1-byte UTF-8)
  388. EXPECT_EQ("A", decode_path_component("%u0041"));
  389. // %u00E9 = 'é' (2-byte UTF-8)
  390. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  391. // %u3042 = 'あ' (3-byte UTF-8)
  392. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  393. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  394. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  395. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  396. // neighbours)
  397. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  398. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  399. }
  400. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  401. // A sign or whitespace inside the two-character escape window must not be
  402. // accepted as a valid percent-encoding; the sequence is passed through
  403. // literally, matching decode_uri_component / decode_path_component.
  404. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  405. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  406. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  407. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  408. // Well-formed escapes still decode.
  409. EXPECT_EQ("-", decode_query_component("%2D", false));
  410. EXPECT_EQ("A", decode_query_component("%41", false));
  411. }
  412. TEST(SanitizeFilenameTest, VariousPatterns) {
  413. // Path traversal
  414. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  415. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  416. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  417. // Normal and edge cases
  418. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  419. EXPECT_EQ("filename.txt",
  420. httplib::sanitize_filename("/path/to/filename.txt"));
  421. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  422. EXPECT_EQ("", httplib::sanitize_filename(".."));
  423. EXPECT_EQ("", httplib::sanitize_filename(""));
  424. // Null bytes stripped
  425. EXPECT_EQ("safe.txt",
  426. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  427. // Whitespace-only rejected
  428. EXPECT_EQ("", httplib::sanitize_filename(" "));
  429. }
  430. // Forward declaration (see the base64_encode note below): split builds move the
  431. // definition into httplib.cc, so re-declaring it here lets the test link.
  432. namespace httplib {
  433. namespace detail {
  434. bool is_chunked_transfer_encoding(const Headers &headers);
  435. } // namespace detail
  436. } // namespace httplib
  437. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  438. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  439. auto make = [](std::initializer_list<const char *> lines) {
  440. Headers h;
  441. for (auto te : lines) {
  442. if (te) { h.emplace("Transfer-Encoding", te); }
  443. }
  444. return h;
  445. };
  446. // Sole coding, matched case-insensitively.
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  448. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  450. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  452. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  453. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  454. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  455. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  456. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  457. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  458. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  459. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  460. // were received, into one list. Headers preserves that order, so the answer
  461. // is decided by the last coding of the last line and the order the lines
  462. // arrived in is significant.
  463. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  464. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  465. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  466. // The split can fall anywhere in the list.
  467. EXPECT_TRUE(
  468. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  469. EXPECT_FALSE(
  470. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  471. // A trailing line naming no coding leaves the list ending in nothing, so it
  472. // must not inherit the chunked from the line before it.
  473. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  474. }
  475. // Forward declarations (see the base64_encode note below).
  476. namespace httplib {
  477. namespace detail {
  478. bool parse_status_line(const char *line, std::string &version, int &status,
  479. std::string &reason);
  480. std::string file_extension(const std::string &path);
  481. std::string
  482. find_content_type(const std::string &path,
  483. const std::map<std::string, std::string> &user_data,
  484. const std::string &default_content_type);
  485. bool can_compress_content_type(const std::string &content_type);
  486. bool is_prohibited_header_name(const std::string &name);
  487. #ifdef CPPHTTPLIB_SSL_ENABLED
  488. bool match_hostname(const std::string &pattern, const std::string &hostname);
  489. #endif
  490. } // namespace detail
  491. } // namespace httplib
  492. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  493. struct {
  494. const char *line;
  495. const char *version;
  496. int status;
  497. const char *reason;
  498. } cases[] = {
  499. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  500. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  501. // The reason phrase may be empty, or left out along with its space.
  502. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  503. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  504. };
  505. for (const auto &c : cases) {
  506. std::string version;
  507. int status = 0;
  508. std::string reason = "unset";
  509. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  510. << c.line;
  511. EXPECT_EQ(c.version, version);
  512. EXPECT_EQ(c.status, status);
  513. EXPECT_EQ(c.reason, reason);
  514. }
  515. }
  516. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  517. const char *lines[] = {
  518. "HTTP/2 200 OK\r\n",
  519. "HTTP/1.2 200 OK\r\n",
  520. "HTTP/1.1 20 OK\r\n",
  521. "HTTP/1.1 2000 OK\r\n",
  522. "HTTP/1.1 2x0 OK\r\n",
  523. "HTTP/1.1 200 OK\r\n",
  524. "HTTP/1.1 200OK\r\n",
  525. "HTTP/1.1 200 O\rK\r\n",
  526. "HTTP/1.1 200 OK",
  527. "HTTP/1.1 200 OK\r\nX",
  528. "",
  529. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  530. "HTTP/1.1 200 OK\n",
  531. #endif
  532. };
  533. for (auto line : lines) {
  534. std::string version;
  535. int status = 0;
  536. std::string reason;
  537. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  538. << line;
  539. }
  540. }
  541. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  542. // Long enough to overflow the stack when matched with std::regex.
  543. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  544. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  545. std::string version;
  546. int status = 0;
  547. std::string reason;
  548. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  549. EXPECT_EQ(200, status);
  550. EXPECT_EQ(long_reason, reason);
  551. }
  552. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  553. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  554. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  555. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  556. EXPECT_EQ("", detail::file_extension("noext"));
  557. EXPECT_EQ("", detail::file_extension("a."));
  558. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  559. EXPECT_EQ("", detail::file_extension("a.b-c"));
  560. // Long enough to overflow the stack when matched with std::regex.
  561. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  562. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  563. }
  564. #ifdef CPPHTTPLIB_SSL_ENABLED
  565. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  566. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  567. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  568. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  569. // A wildcard needs two labels after it, in the leftmost label only
  570. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  571. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  572. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  573. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  574. EXPECT_FALSE(
  575. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  576. // No name may have an empty label
  577. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  578. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  579. }
  580. #endif
  581. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  582. detail::case_ignore::hash hash;
  583. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  584. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  585. // Long enough to overflow the stack if hashed one call per character.
  586. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  587. }
  588. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  589. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  590. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  591. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  592. // Same 26-bit hash as html, svg and js.
  593. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  594. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  595. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  596. }
  597. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  598. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  599. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  600. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  601. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  602. // Same 26-bit hash as application/json.
  603. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  604. }
  605. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  606. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  607. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  608. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  609. // Same 26-bit hash as REMOTE_ADDR.
  610. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  611. }
  612. // Forward declaration: in split builds split.py strips `inline` and moves the
  613. // definition into httplib.cc, so detail::base64_encode is not visible from the
  614. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  615. // in both header-only and split builds.
  616. namespace httplib {
  617. namespace detail {
  618. std::string base64_encode(const std::string &in);
  619. } // namespace detail
  620. } // namespace httplib
  621. TEST(Base64EncodeTest, KnownAnswers) {
  622. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  623. // where the accumulator's top bit is already set before the next shift.
  624. EXPECT_EQ("", detail::base64_encode(""));
  625. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  626. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  627. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  628. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  629. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  630. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  631. // High bytes keep the top bit set across several rounds.
  632. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  633. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  634. }
  635. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  636. string unescapedCharacters = "-_.!~*'()";
  637. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  638. }
  639. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  640. string reservedCharacters = ";,/?:@&=+$";
  641. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  642. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  643. }
  644. TEST(ClientQueryOrder, PreserveOrder) {
  645. // This test reproduces Issue #2259: client may reorder query parameters
  646. // when sending a GET request. The expected behavior is that the client
  647. // preserves the original query string order when the caller supplied it
  648. // as part of the path.
  649. Server svr;
  650. svr.Get("/", [&](const Request &req, Response &res) {
  651. // Echo back the raw target so the test can assert ordering
  652. res.set_content(req.target, "text/plain");
  653. });
  654. std::thread t{[&] { svr.listen(HOST, PORT); }};
  655. auto se = detail::scope_exit([&] {
  656. svr.stop();
  657. t.join();
  658. ASSERT_FALSE(svr.is_running());
  659. });
  660. svr.wait_until_ready();
  661. Client cli(HOST, PORT);
  662. ASSERT_TRUE(cli.is_valid());
  663. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  664. auto res = cli.Get(original);
  665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  666. // Expect the echoed target to exactly match the original path (order
  667. // preserved)
  668. EXPECT_EQ(res->body, original);
  669. }
  670. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  671. string chineseCharacters = U8("中国語");
  672. string russianCharacters = U8("дом");
  673. string brazilianCharacters = U8("óculos");
  674. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  675. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  676. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  677. "%D0%B4%D0%BE%D0%BC");
  678. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  679. }
  680. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  681. string unescapedCharacters = "-_.!~*'()";
  682. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  683. }
  684. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  685. string reservedCharacters = ";,/?:@&=+$";
  686. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  687. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  688. }
  689. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  690. string chineseCharacters = U8("中国語");
  691. string russianCharacters = U8("дом");
  692. string brazilianCharacters = U8("óculos");
  693. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  694. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  695. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  696. "%D0%B4%D0%BE%D0%BC");
  697. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  698. }
  699. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  700. // Issue #2082 use case: encoding path component with ampersand
  701. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  702. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  703. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  704. }
  705. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  706. string unescapedCharacters = "-_.!~*'()";
  707. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  708. }
  709. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  710. string reservedCharacters = ";,/?:@&=+$#";
  711. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  712. }
  713. TEST(EncodeUriTest, TestUTF8Characters) {
  714. string chineseCharacters = U8("中国語");
  715. string russianCharacters = U8("дом");
  716. string brazilianCharacters = U8("óculos");
  717. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  718. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  719. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  720. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  721. }
  722. TEST(EncodeUriTest, TestCompleteUri) {
  723. string uri =
  724. "https://example.com/path/to/resource?query=value&param=test#fragment";
  725. EXPECT_EQ(
  726. httplib::encode_uri(uri),
  727. "https://example.com/path/to/resource?query=value&param=test#fragment");
  728. }
  729. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  730. string uri =
  731. "https://example.com/path with spaces/file name.html?q=hello world";
  732. EXPECT_EQ(httplib::encode_uri(uri),
  733. "https://example.com/path%20with%20spaces/"
  734. "file%20name.html?q=hello%20world");
  735. }
  736. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  737. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  738. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  739. }
  740. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  741. string unescapedCharacters = "-_.!~*'()";
  742. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  743. }
  744. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  745. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  746. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  747. string encodedBrazilian = "%C3%B3culos";
  748. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  749. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  750. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  751. }
  752. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  753. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  754. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  755. "Piri Tommy Villiers - on & on");
  756. }
  757. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  758. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  759. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  760. }
  761. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  762. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  763. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  764. }
  765. TEST(DecodeUriTest, TestUTF8Characters) {
  766. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  767. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  768. string encodedBrazilian = "%C3%B3culos";
  769. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  770. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  771. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  772. }
  773. TEST(DecodeUriTest, TestCompleteUri) {
  774. string encodedUri = "https://example.com/path%20with%20spaces/"
  775. "file%20name.html?q=hello%20world";
  776. EXPECT_EQ(
  777. httplib::decode_uri(encodedUri),
  778. "https://example.com/path with spaces/file name.html?q=hello world");
  779. }
  780. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  781. string original =
  782. "https://example.com/path with spaces/file name.html?q=hello world";
  783. string encoded = httplib::encode_uri(original);
  784. string decoded = httplib::decode_uri(encoded);
  785. EXPECT_EQ(decoded, original);
  786. }
  787. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  788. // decode_uri is the inverse of encode_uri: an escaped reserved character
  789. // stays encoded so it is not promoted into a real delimiter, while
  790. // non-reserved escapes still decode (like JS decodeURI).
  791. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  792. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  793. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  794. "%3F%3A%40%26%3D%2B%24%2C%3B");
  795. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  796. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  797. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  798. "http://example.com/a%2Fb");
  799. // decode_uri_component still decodes the reserved character.
  800. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  801. }
  802. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  803. string original = "Piri Tommy Villiers - on & on";
  804. string encoded = httplib::encode_uri_component(original);
  805. string decoded = httplib::decode_uri_component(encoded);
  806. EXPECT_EQ(decoded, original);
  807. }
  808. TEST(TrimTests, TrimStringTests) {
  809. EXPECT_EQ("abc", detail::trim_copy("abc"));
  810. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  811. EXPECT_TRUE(detail::trim_copy("").empty());
  812. }
  813. TEST(AsciiTest, LocaleIndependentClassification) {
  814. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  815. // which consult the global C locale: std::isalnum(0xC5) can return true
  816. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  817. // helpers must classify every byte by the ASCII grammar alone.
  818. for (int i = 0; i < 256; i++) {
  819. auto c = static_cast<char>(i);
  820. auto is_digit = i >= '0' && i <= '9';
  821. auto is_upper = i >= 'A' && i <= 'Z';
  822. auto is_lower = i >= 'a' && i <= 'z';
  823. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  824. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  825. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  826. << "byte " << i;
  827. }
  828. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  829. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  830. // Non-ASCII bytes must be percent-encoded, never passed through as
  831. // alphanumeric.
  832. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  833. }
  834. TEST(FromCharsTest, Double) {
  835. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  836. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  837. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  838. auto parse = [](const std::string &s, double &v) {
  839. return detail::from_chars(s.data(), s.data() + s.size(), v);
  840. };
  841. double v = -1.0;
  842. // Representative quality values.
  843. EXPECT_EQ(parse("0", v).ec, std::errc{});
  844. EXPECT_DOUBLE_EQ(v, 0.0);
  845. EXPECT_EQ(parse("1", v).ec, std::errc{});
  846. EXPECT_DOUBLE_EQ(v, 1.0);
  847. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  848. EXPECT_DOUBLE_EQ(v, 0.8);
  849. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  850. EXPECT_DOUBLE_EQ(v, 0.001);
  851. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  852. EXPECT_DOUBLE_EQ(v, 1.0);
  853. // A missing integer or fractional part is tolerated.
  854. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  855. EXPECT_DOUBLE_EQ(v, 0.5);
  856. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  857. EXPECT_DOUBLE_EQ(v, 5.0);
  858. // Values outside [0, 1] still parse; the caller range-checks them.
  859. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  860. EXPECT_DOUBLE_EQ(v, 123.456);
  861. // Stops at the first byte that is not part of the number and reports where.
  862. std::string trailing = "0.9, text/html";
  863. auto r = parse(trailing, v);
  864. EXPECT_EQ(r.ec, std::errc{});
  865. EXPECT_DOUBLE_EQ(v, 0.9);
  866. EXPECT_EQ(*r.ptr, ',');
  867. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  868. // outright, and an 'e'/'E' simply ends the number.
  869. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  870. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  871. std::string exp_input = "1.5e3";
  872. r = parse(exp_input, v);
  873. EXPECT_EQ(r.ec, std::errc{});
  874. EXPECT_DOUBLE_EQ(v, 1.5);
  875. EXPECT_EQ(*r.ptr, 'e');
  876. // Invalid inputs.
  877. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  878. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  879. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  880. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  881. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  882. // Pathological but well-formed inputs must stay bounded (no overflow, no
  883. // out-of-bounds table access) and stay within [0, 1] for the caller.
  884. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  885. std::errc{});
  886. EXPECT_DOUBLE_EQ(v, 0.0);
  887. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  888. std::errc{});
  889. EXPECT_GE(v, 0.0);
  890. EXPECT_LE(v, 1.0);
  891. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  892. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  893. }
  894. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  895. // Simple case without quality values
  896. std::vector<std::string> result1;
  897. EXPECT_TRUE(detail::parse_accept_header(
  898. "text/html,application/json,text/plain", result1));
  899. EXPECT_EQ(result1.size(), 3U);
  900. EXPECT_EQ(result1[0], "text/html");
  901. EXPECT_EQ(result1[1], "application/json");
  902. EXPECT_EQ(result1[2], "text/plain");
  903. // With quality values
  904. std::vector<std::string> result2;
  905. EXPECT_TRUE(detail::parse_accept_header(
  906. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  907. EXPECT_EQ(result2.size(), 3U);
  908. EXPECT_EQ(result2[0], "application/json"); // highest q value
  909. EXPECT_EQ(result2[1], "text/html");
  910. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  911. }
  912. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  913. // Mixed with and without quality values
  914. std::vector<std::string> result;
  915. EXPECT_TRUE(detail::parse_accept_header(
  916. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  917. EXPECT_EQ(result.size(), 3U);
  918. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  919. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  920. EXPECT_EQ(result[2], "application/json"); // q=0.5
  921. }
  922. TEST(ParseAcceptHeaderTest, EdgeCases) {
  923. // Empty header
  924. std::vector<std::string> empty_result;
  925. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  926. EXPECT_TRUE(empty_result.empty());
  927. // Single type
  928. std::vector<std::string> single_result;
  929. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  930. EXPECT_EQ(single_result.size(), 1U);
  931. EXPECT_EQ(single_result[0], "application/json");
  932. // Wildcard types
  933. std::vector<std::string> wildcard_result;
  934. EXPECT_TRUE(detail::parse_accept_header(
  935. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  936. EXPECT_EQ(wildcard_result.size(), 3U);
  937. EXPECT_EQ(wildcard_result[0], "application/json");
  938. EXPECT_EQ(wildcard_result[1], "text/*");
  939. EXPECT_EQ(wildcard_result[2], "*/*");
  940. }
  941. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  942. // Common browser Accept header
  943. std::vector<std::string> browser_result;
  944. EXPECT_TRUE(
  945. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  946. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  947. browser_result));
  948. EXPECT_EQ(browser_result.size(), 6U);
  949. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  950. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  951. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  952. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  953. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  954. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  955. // API client header
  956. std::vector<std::string> api_result;
  957. EXPECT_TRUE(detail::parse_accept_header(
  958. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  959. api_result));
  960. EXPECT_EQ(api_result.size(), 3U);
  961. EXPECT_EQ(api_result[0], "application/json");
  962. EXPECT_EQ(api_result[1], "application/xml");
  963. EXPECT_EQ(api_result[2], "text/plain");
  964. }
  965. TEST(ParseAcceptHeaderTest, SpecialCases) {
  966. // Quality value with 3 decimal places
  967. std::vector<std::string> decimal_result;
  968. EXPECT_TRUE(detail::parse_accept_header(
  969. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  970. EXPECT_EQ(decimal_result.size(), 2U);
  971. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  972. EXPECT_EQ(decimal_result[1], "text/html");
  973. // Zero quality (should still be included but with lowest priority)
  974. std::vector<std::string> zero_q_result;
  975. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  976. zero_q_result));
  977. EXPECT_EQ(zero_q_result.size(), 2U);
  978. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  979. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  980. // No spaces around commas
  981. std::vector<std::string> no_space_result;
  982. EXPECT_TRUE(detail::parse_accept_header(
  983. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  984. no_space_result));
  985. EXPECT_EQ(no_space_result.size(), 3U);
  986. EXPECT_EQ(no_space_result[0], "text/html");
  987. EXPECT_EQ(no_space_result[1], "application/json");
  988. EXPECT_EQ(no_space_result[2], "text/plain");
  989. }
  990. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  991. // Quality values always use '.' as the decimal separator, so parsing must
  992. // not depend on the process locale. An embedding application may have
  993. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  994. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  995. std::string saved = cur ? cur : "C";
  996. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  997. "fr_FR.UTF-8"};
  998. bool switched = false;
  999. for (const auto loc : comma_locales) {
  1000. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1001. std::localeconv()->decimal_point[0] == ',') {
  1002. switched = true;
  1003. break;
  1004. }
  1005. }
  1006. if (!switched) {
  1007. std::setlocale(LC_NUMERIC, saved.c_str());
  1008. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1009. }
  1010. // The higher-weighted type appears later in the list, so a correct parse
  1011. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1012. // sensitive parse reads both weights as 0 and leaves the original order.
  1013. std::vector<std::string> result;
  1014. EXPECT_TRUE(detail::parse_accept_header(
  1015. "application/json;q=0.1,text/html;q=0.9", result));
  1016. ASSERT_EQ(result.size(), 2U);
  1017. EXPECT_EQ(result[0], "text/html");
  1018. EXPECT_EQ(result[1], "application/json");
  1019. std::setlocale(LC_NUMERIC, saved.c_str());
  1020. }
  1021. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1022. std::vector<std::string> result;
  1023. // Invalid quality value (> 1.0)
  1024. EXPECT_FALSE(
  1025. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1026. // Invalid quality value (< 0.0)
  1027. EXPECT_FALSE(
  1028. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1029. // Invalid quality value (not a number)
  1030. EXPECT_FALSE(detail::parse_accept_header(
  1031. "text/html;q=invalid,application/json", result));
  1032. // A valid numeric prefix does not make the entire quality value valid.
  1033. EXPECT_FALSE(detail::parse_accept_header(
  1034. "text/html;q=0.5junk,application/json", result));
  1035. // Empty quality value
  1036. EXPECT_FALSE(
  1037. detail::parse_accept_header("text/html;q=,application/json", result));
  1038. // Invalid media type format (no slash and not wildcard)
  1039. EXPECT_FALSE(
  1040. detail::parse_accept_header("invalidtype,application/json", result));
  1041. // Valid cases should still work
  1042. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1043. EXPECT_EQ(result.size(), 1U);
  1044. EXPECT_EQ(result[0], "*/*");
  1045. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1046. EXPECT_EQ(result.size(), 1U);
  1047. EXPECT_EQ(result[0], "*");
  1048. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1049. EXPECT_EQ(result.size(), 1U);
  1050. EXPECT_EQ(result[0], "text/*");
  1051. }
  1052. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1053. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1054. // and must not be answered with 400 Bad Request.
  1055. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1056. struct {
  1057. const char *value;
  1058. std::vector<std::string> expected;
  1059. } cases[] = {
  1060. {",application/json", {"application/json"}},
  1061. {"text/html,", {"text/html"}},
  1062. {"text/html,,*/*", {"text/html", "*/*"}},
  1063. // An empty element may be spelled with whitespace in it
  1064. {"text/html, , application/json", {"text/html", "application/json"}},
  1065. // Nothing but empty elements is an empty list, which means the same
  1066. // thing as no Accept header at all
  1067. {",,,", {}},
  1068. // Quality values still apply across ignored empty elements
  1069. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1070. };
  1071. for (const auto &c : cases) {
  1072. std::vector<std::string> result;
  1073. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1074. << "value: " << c.value;
  1075. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1076. }
  1077. // An invalid entry is still rejected when empty elements surround it
  1078. std::vector<std::string> result;
  1079. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1080. }
  1081. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1082. // or ';' inside one does not end the list element or the parameter. Section
  1083. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1084. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1085. struct {
  1086. const char *value;
  1087. std::vector<std::string> expected;
  1088. } cases[] = {
  1089. {"text/html;profile=\"a,b\",application/json",
  1090. {"text/html", "application/json"}},
  1091. // A "q=" inside a quoted value is not the weight
  1092. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1093. {"text/html", "application/json"}},
  1094. // The weight after a quoted value still applies
  1095. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1096. {"application/json", "text/html"}},
  1097. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1098. {"application/json", "text/html"}},
  1099. {"text/html;profile=\"a\\\"b\",application/json",
  1100. {"text/html", "application/json"}},
  1101. // An escaped backslash does not escape the '"' after it
  1102. {"text/html;profile=\"a\\\\\",application/json",
  1103. {"text/html", "application/json"}},
  1104. };
  1105. for (const auto &c : cases) {
  1106. std::vector<std::string> result;
  1107. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1108. << "value: " << c.value;
  1109. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1110. }
  1111. }
  1112. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1113. Server svr;
  1114. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1115. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1116. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1117. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1118. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1119. res.set_content("ok", "text/plain");
  1120. });
  1121. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1122. EXPECT_TRUE(false);
  1123. res.set_content("bad request", "text/plain");
  1124. });
  1125. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1126. auto se = detail::scope_exit([&] {
  1127. svr.stop();
  1128. listen_thread.join();
  1129. ASSERT_FALSE(svr.is_running());
  1130. });
  1131. svr.wait_until_ready();
  1132. Client cli("localhost", PORT);
  1133. {
  1134. auto res = cli.Get(
  1135. "/accept_ok",
  1136. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1138. EXPECT_EQ(StatusCode::OK_200, res->status);
  1139. }
  1140. {
  1141. auto res = cli.Get("/accept_bad_request",
  1142. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1144. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1145. }
  1146. }
  1147. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1148. Server svr;
  1149. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1150. res.set_content("ok", "text/plain");
  1151. });
  1152. std::atomic<int> start_count{0};
  1153. std::atomic<bool> running_when_called{false};
  1154. svr.set_start_handler([&]() {
  1155. running_when_called = svr.is_running();
  1156. start_count++;
  1157. });
  1158. auto port = svr.bind_to_any_port(HOST);
  1159. std::thread t([&]() { svr.listen_after_bind(); });
  1160. auto se = detail::scope_exit([&] {
  1161. svr.stop();
  1162. t.join();
  1163. ASSERT_FALSE(svr.is_running());
  1164. });
  1165. svr.wait_until_ready();
  1166. // A successful request proves the accept loop is running, which the start
  1167. // handler precedes; so by now the handler must have run exactly once.
  1168. Client cli(HOST, port);
  1169. cli.set_connection_timeout(std::chrono::seconds(5));
  1170. auto res = cli.Get("/");
  1171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1172. EXPECT_EQ(StatusCode::OK_200, res->status);
  1173. EXPECT_EQ(1, start_count.load());
  1174. EXPECT_TRUE(running_when_called.load());
  1175. }
  1176. TEST(DivideTest, DivideStringTests) {
  1177. auto divide = [](const std::string &str, char d) {
  1178. std::string lhs;
  1179. std::string rhs;
  1180. detail::divide(str, d,
  1181. [&](const char *lhs_data, std::size_t lhs_size,
  1182. const char *rhs_data, std::size_t rhs_size) {
  1183. lhs.assign(lhs_data, lhs_size);
  1184. rhs.assign(rhs_data, rhs_size);
  1185. });
  1186. return std::make_pair(std::move(lhs), std::move(rhs));
  1187. };
  1188. {
  1189. const auto res = divide("", '=');
  1190. EXPECT_EQ(res.first, "");
  1191. EXPECT_EQ(res.second, "");
  1192. }
  1193. {
  1194. const auto res = divide("=", '=');
  1195. EXPECT_EQ(res.first, "");
  1196. EXPECT_EQ(res.second, "");
  1197. }
  1198. {
  1199. const auto res = divide(" ", '=');
  1200. EXPECT_EQ(res.first, " ");
  1201. EXPECT_EQ(res.second, "");
  1202. }
  1203. {
  1204. const auto res = divide("a", '=');
  1205. EXPECT_EQ(res.first, "a");
  1206. EXPECT_EQ(res.second, "");
  1207. }
  1208. {
  1209. const auto res = divide("a=", '=');
  1210. EXPECT_EQ(res.first, "a");
  1211. EXPECT_EQ(res.second, "");
  1212. }
  1213. {
  1214. const auto res = divide("=b", '=');
  1215. EXPECT_EQ(res.first, "");
  1216. EXPECT_EQ(res.second, "b");
  1217. }
  1218. {
  1219. const auto res = divide("a=b", '=');
  1220. EXPECT_EQ(res.first, "a");
  1221. EXPECT_EQ(res.second, "b");
  1222. }
  1223. {
  1224. const auto res = divide("a=b=", '=');
  1225. EXPECT_EQ(res.first, "a");
  1226. EXPECT_EQ(res.second, "b=");
  1227. }
  1228. {
  1229. const auto res = divide("a=b=c", '=');
  1230. EXPECT_EQ(res.first, "a");
  1231. EXPECT_EQ(res.second, "b=c");
  1232. }
  1233. }
  1234. TEST(SplitTest, ParseQueryString) {
  1235. string s = "key1=val1&key2=val2&key3=val3";
  1236. Params dic;
  1237. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1238. [&](const char *b, const char *e) {
  1239. string key, val;
  1240. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1241. if (key.empty()) {
  1242. key.assign(b2, e2);
  1243. } else {
  1244. val.assign(b2, e2);
  1245. }
  1246. });
  1247. dic.emplace(key, val);
  1248. });
  1249. EXPECT_EQ("val1", dic.find("key1")->second);
  1250. EXPECT_EQ("val2", dic.find("key2")->second);
  1251. EXPECT_EQ("val3", dic.find("key3")->second);
  1252. }
  1253. TEST(SplitTest, ParseInvalidQueryTests) {
  1254. {
  1255. string s = " ";
  1256. Params dict;
  1257. detail::parse_query_text(s, dict);
  1258. EXPECT_TRUE(dict.empty());
  1259. }
  1260. {
  1261. string s = " = =";
  1262. Params dict;
  1263. detail::parse_query_text(s, dict);
  1264. EXPECT_TRUE(dict.empty());
  1265. }
  1266. }
  1267. TEST(ParseQueryTest, ParseQueryString) {
  1268. {
  1269. std::string s = "key1=val1&key2=val2&key3=val3";
  1270. Params dic;
  1271. detail::parse_query_text(s, dic);
  1272. EXPECT_EQ("val1", dic.find("key1")->second);
  1273. EXPECT_EQ("val2", dic.find("key2")->second);
  1274. EXPECT_EQ("val3", dic.find("key3")->second);
  1275. }
  1276. {
  1277. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1278. Params dic;
  1279. detail::parse_query_text(s, dic);
  1280. EXPECT_EQ("", dic.find("key1")->second);
  1281. EXPECT_EQ("val1", dic.find("key2")->second);
  1282. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1283. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1284. }
  1285. }
  1286. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1287. Params dic;
  1288. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1289. dic.emplace("key1", "val1");
  1290. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1291. dic.emplace("key2", "val2");
  1292. dic.emplace("key3", "val3");
  1293. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1294. }
  1295. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1296. Params params;
  1297. params.emplace("a", "1");
  1298. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1299. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1300. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1301. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1302. // Long enough to overflow the stack when matched with std::regex.
  1303. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1304. EXPECT_EQ("/p?" + long_query + "&a=1",
  1305. append_query_params("/p?" + long_query, params));
  1306. }
  1307. // Joins every entry of a Headers or Params into "key=value " so a whole
  1308. // traversal can be compared in one assertion. Both are instantiations of the
  1309. // same insertion-ordered container, so one helper serves both.
  1310. template <typename Map> static std::string entries_to_string(const Map &m) {
  1311. std::string s;
  1312. for (const auto &entry : m) {
  1313. s += entry.first + "=" + entry.second + " ";
  1314. }
  1315. return s;
  1316. }
  1317. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1318. // Params used to be a std::multimap, which sorted by name and handed the
  1319. // caller's query back alphabetised. A client signing its query string could
  1320. // not reproduce the order it asked for.
  1321. Params dic;
  1322. dic.emplace("zulu", "1");
  1323. dic.emplace("alpha", "2");
  1324. dic.emplace("mike", "3");
  1325. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1326. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1327. }
  1328. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1329. Params dic;
  1330. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1331. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1332. }
  1333. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1334. Request req;
  1335. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1336. req.params);
  1337. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1338. EXPECT_EQ("first", req.get_param_value("tag"));
  1339. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1340. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1341. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1342. EXPECT_EQ("", req.get_param_value("tag", 3));
  1343. }
  1344. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1345. // Params shares its container with Headers, which matches field names
  1346. // case-insensitively. Parameter names must not pick that up.
  1347. Params dic;
  1348. dic.emplace("Key", "upper");
  1349. dic.emplace("key", "lower");
  1350. EXPECT_EQ(2U, dic.size());
  1351. EXPECT_EQ(1U, dic.count("Key"));
  1352. EXPECT_EQ(1U, dic.count("key"));
  1353. EXPECT_EQ("upper", dic.find("Key")->second);
  1354. EXPECT_EQ("lower", dic.find("key")->second);
  1355. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1356. }
  1357. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1358. Server svr;
  1359. std::string order;
  1360. svr.Get("/order", [&](const Request &req, Response &res) {
  1361. order = entries_to_string(req.params);
  1362. res.set_content("ok", "text/plain");
  1363. });
  1364. auto port = svr.bind_to_any_port(HOST);
  1365. thread t = thread([&] { svr.listen_after_bind(); });
  1366. auto se = detail::scope_exit([&] {
  1367. svr.stop();
  1368. t.join();
  1369. ASSERT_FALSE(svr.is_running());
  1370. });
  1371. svr.wait_until_ready();
  1372. Client cli(HOST, port);
  1373. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1374. ASSERT_TRUE(res);
  1375. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1376. }
  1377. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1378. Server svr;
  1379. std::string field_order, file_order;
  1380. svr.Post("/order", [&](const Request &req, Response &res) {
  1381. for (const auto &field : req.form.fields) {
  1382. field_order += field.first + "=" + field.second.content + " ";
  1383. }
  1384. for (const auto &file : req.form.files) {
  1385. file_order += file.first + "=" + file.second.filename + " ";
  1386. }
  1387. res.set_content("ok", "text/plain");
  1388. });
  1389. auto port = svr.bind_to_any_port(HOST);
  1390. thread t = thread([&] { svr.listen_after_bind(); });
  1391. auto se = detail::scope_exit([&] {
  1392. svr.stop();
  1393. t.join();
  1394. ASSERT_FALSE(svr.is_running());
  1395. });
  1396. svr.wait_until_ready();
  1397. UploadFormDataItems items = {
  1398. {"zulu", "1", "", ""},
  1399. {"alpha", "2", "", ""},
  1400. {"mike", "3", "", ""},
  1401. {"zebra", "z", "z.txt", "text/plain"},
  1402. {"apple", "a", "a.txt", "text/plain"},
  1403. };
  1404. Client cli(HOST, port);
  1405. auto res = cli.Post("/order", items);
  1406. ASSERT_TRUE(res);
  1407. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1408. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1409. }
  1410. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1411. Server svr;
  1412. std::vector<std::string> values;
  1413. std::string first, second, out_of_range, order;
  1414. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1415. values = req.form.get_fields("tag");
  1416. first = req.form.get_field("tag", 0);
  1417. second = req.form.get_field("tag", 1);
  1418. out_of_range = req.form.get_field("tag", 2);
  1419. for (const auto &field : req.form.fields) {
  1420. order += field.first + "=" + field.second.content + " ";
  1421. }
  1422. res.set_content("ok", "text/plain");
  1423. });
  1424. auto port = svr.bind_to_any_port(HOST);
  1425. thread t = thread([&] { svr.listen_after_bind(); });
  1426. auto se = detail::scope_exit([&] {
  1427. svr.stop();
  1428. t.join();
  1429. ASSERT_FALSE(svr.is_running());
  1430. });
  1431. svr.wait_until_ready();
  1432. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1433. // not adjacent in the container.
  1434. UploadFormDataItems items = {
  1435. {"tag", "first", "", ""},
  1436. {"other", "x", "", ""},
  1437. {"tag", "second", "", ""},
  1438. };
  1439. Client cli(HOST, port);
  1440. auto res = cli.Post("/repeated", items);
  1441. ASSERT_TRUE(res);
  1442. ASSERT_EQ(2U, values.size());
  1443. EXPECT_EQ("first", values[0]);
  1444. EXPECT_EQ("second", values[1]);
  1445. EXPECT_EQ("first", first);
  1446. EXPECT_EQ("second", second);
  1447. // std::multimap already kept entries sharing a name in insertion order, so
  1448. // everything above passes without this change too. The whole traversal is
  1449. // what tells the two apart: sorting by name would hoist "other" to the front
  1450. // and the two "tag" parts would end up adjacent.
  1451. EXPECT_EQ("tag=first other=x tag=second ", order);
  1452. // Advancing past the last entry of a name used to run off the container;
  1453. // the container's saturating increment makes it return the default instead.
  1454. EXPECT_EQ("", out_of_range);
  1455. }
  1456. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1457. // Server::read_content() keeps a FormFields::iterator alive across the
  1458. // content callbacks that fill the part it points at. The container is
  1459. // vector-backed, so a later emplace can reallocate and invalidate an older
  1460. // iterator; 64 parts grow the vector through seven reallocations, which
  1461. // checks that every part's content still lands in its own entry.
  1462. const size_t part_count = 64;
  1463. // One formula for both the parts sent and the values expected back, so the
  1464. // two cannot drift apart.
  1465. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1466. auto content_of = [](size_t i) {
  1467. return std::string(64, static_cast<char>('a' + (i % 26)));
  1468. };
  1469. Server svr;
  1470. std::vector<std::pair<std::string, std::string>> received;
  1471. svr.Post("/many", [&](const Request &req, Response &res) {
  1472. for (const auto &field : req.form.fields) {
  1473. received.emplace_back(field.first, field.second.content);
  1474. }
  1475. res.set_content("ok", "text/plain");
  1476. });
  1477. auto port = svr.bind_to_any_port(HOST);
  1478. thread t = thread([&] { svr.listen_after_bind(); });
  1479. auto se = detail::scope_exit([&] {
  1480. svr.stop();
  1481. t.join();
  1482. ASSERT_FALSE(svr.is_running());
  1483. });
  1484. svr.wait_until_ready();
  1485. UploadFormDataItems items;
  1486. for (size_t i = 0; i < part_count; i++) {
  1487. items.push_back({name_of(i), content_of(i), "", ""});
  1488. }
  1489. Client cli(HOST, port);
  1490. auto res = cli.Post("/many", items);
  1491. ASSERT_TRUE(res);
  1492. ASSERT_EQ(part_count, received.size());
  1493. for (size_t i = 0; i < part_count; i++) {
  1494. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1495. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1496. }
  1497. }
  1498. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1499. string content_type = "multipart/form-data; boundary=something";
  1500. string boundary;
  1501. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1502. EXPECT_TRUE(ret);
  1503. EXPECT_EQ(boundary, "something");
  1504. }
  1505. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1506. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1507. string boundary;
  1508. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1509. EXPECT_TRUE(ret);
  1510. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1511. }
  1512. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1513. string content_type =
  1514. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1515. string boundary;
  1516. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1517. EXPECT_TRUE(ret);
  1518. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1519. }
  1520. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1521. string content_type =
  1522. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1523. string boundary;
  1524. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1525. EXPECT_TRUE(ret);
  1526. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1527. }
  1528. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1529. const string boundary(70, 'a');
  1530. string content_type = "multipart/form-data; boundary=" + boundary;
  1531. string parsed;
  1532. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1533. EXPECT_TRUE(ret);
  1534. EXPECT_EQ(parsed, boundary);
  1535. }
  1536. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1537. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1538. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1539. string parsed;
  1540. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1541. EXPECT_FALSE(ret);
  1542. }
  1543. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1544. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1545. // is 72 characters on the wire and still valid.
  1546. const string boundary(70, 'a');
  1547. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1548. string parsed;
  1549. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1550. EXPECT_EQ(parsed, boundary);
  1551. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1552. parsed.clear();
  1553. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1554. }
  1555. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1556. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1557. // The parameter parser must not treat that '=' as the key/value separator.
  1558. string content_type =
  1559. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1560. "charset=UTF-8";
  1561. string parsed;
  1562. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1563. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1564. }
  1565. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1566. // A ';' inside the quoted-string is part of the value, not a parameter
  1567. // separator, so it must not truncate the boundary.
  1568. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1569. string parsed;
  1570. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1571. EXPECT_EQ(parsed, "a;b");
  1572. }
  1573. TEST(ParseDispositionParamsTest, QuotedValues) {
  1574. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1575. // ';' and '=' are ordinary characters inside one.
  1576. struct {
  1577. const char *value;
  1578. std::vector<std::pair<const char *, const char *>> expected;
  1579. } cases[] = {
  1580. {"name=\"file1\"; filename=\"a.txt\"",
  1581. {{"name", "file1"}, {"filename", "a.txt"}}},
  1582. // Whitespace around '=' and ';' is still trimmed
  1583. {"name=\"file2\" ;filename = \"a.html\"",
  1584. {{"name", "file2"}, {"filename", "a.html"}}},
  1585. // '=' inside the value used to leave only the text after the last one
  1586. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1587. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1588. {"name=\"x=y\"", {{"name", "x=y"}}},
  1589. // ';' inside the value used to truncate the pair and leave a bogus one
  1590. {"name=\"file3\"; filename=\"a;b.txt\"",
  1591. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1592. // An unquoted value keeps working, and so does filename*
  1593. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1594. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1595. // A parameter with no key is dropped rather than turned into one whose
  1596. // key is the value
  1597. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1598. // An escaped quote does not end the value
  1599. {"name=\"a\\\"; filename=evil.php\"",
  1600. {{"name", "a\"; filename=evil.php"}}},
  1601. // Other backslashes, as in a Windows path, are kept
  1602. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1603. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1604. };
  1605. for (const auto &c : cases) {
  1606. Params params;
  1607. detail::parse_disposition_params(c.value, params);
  1608. for (const auto &kv : c.expected) {
  1609. auto it = params.find(kv.first);
  1610. ASSERT_NE(it, params.end())
  1611. << "value: " << c.value << ", key: " << kv.first;
  1612. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1613. }
  1614. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1615. }
  1616. }
  1617. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1618. Server svr;
  1619. std::string filename;
  1620. std::string content;
  1621. svr.Post("/upload", [&](const Request &req, Response &) {
  1622. const auto &file = req.form.get_file("file");
  1623. filename = file.filename;
  1624. content = file.content;
  1625. });
  1626. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1627. auto se = detail::scope_exit([&] {
  1628. svr.stop();
  1629. thread.join();
  1630. ASSERT_FALSE(svr.is_running());
  1631. });
  1632. svr.wait_until_ready();
  1633. std::string body = "--B\r\n"
  1634. "Content-Disposition: form-data; name=\"file\"; "
  1635. "filename=\"a.txt\"\r\n"
  1636. "Content-Type: text/plain\r\n"
  1637. "\r\n"
  1638. "hello\r\n"
  1639. "--B--\r\n";
  1640. Client cli(HOST, PORT);
  1641. auto res = cli.Post(
  1642. "/upload",
  1643. [&](size_t offset, DataSink &sink) {
  1644. if (offset < body.size()) {
  1645. sink.write(&body[offset], 1);
  1646. } else {
  1647. sink.done();
  1648. }
  1649. return true;
  1650. },
  1651. "multipart/form-data; boundary=B");
  1652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1653. EXPECT_EQ(StatusCode::OK_200, res->status);
  1654. EXPECT_EQ("a.txt", filename);
  1655. EXPECT_EQ("hello", content);
  1656. }
  1657. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1658. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1659. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1660. Server svr;
  1661. std::string field_value, file_name, file_filename;
  1662. bool has_field = false, has_file = false;
  1663. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1664. has_field = req.form.has_field("x=y");
  1665. field_value = req.form.get_field("x=y");
  1666. has_file = req.form.has_file("file1");
  1667. const auto &file = req.form.get_file("file1");
  1668. file_name = file.name;
  1669. file_filename = file.filename;
  1670. res.set_content("ok", "text/plain");
  1671. });
  1672. auto port = svr.bind_to_any_port(HOST);
  1673. thread t = thread([&] { svr.listen_after_bind(); });
  1674. auto se = detail::scope_exit([&] {
  1675. svr.stop();
  1676. t.join();
  1677. ASSERT_FALSE(svr.is_running());
  1678. });
  1679. svr.wait_until_ready();
  1680. UploadFormDataItems items = {
  1681. {"x=y", "field-value", "", ""},
  1682. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1683. };
  1684. Client cli(HOST, port);
  1685. auto res = cli.Post("/quoted", items);
  1686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1687. ASSERT_EQ(StatusCode::OK_200, res->status);
  1688. EXPECT_TRUE(has_field);
  1689. EXPECT_EQ("field-value", field_value);
  1690. EXPECT_TRUE(has_file);
  1691. EXPECT_EQ("file1", file_name);
  1692. EXPECT_EQ("a;b=report.pdf", file_filename);
  1693. }
  1694. TEST(GetHeaderValueTest, DefaultValue) {
  1695. Headers headers = {{"Dummy", "Dummy"}};
  1696. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1697. EXPECT_STREQ("text/plain", val);
  1698. }
  1699. TEST(GetHeaderValueTest, DefaultValueInt) {
  1700. Headers headers = {{"Dummy", "Dummy"}};
  1701. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1702. EXPECT_EQ(100ull, val);
  1703. }
  1704. TEST(GetHeaderValueTest, RegularValue) {
  1705. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1706. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1707. EXPECT_STREQ("text/html", val);
  1708. }
  1709. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1710. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1711. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1712. EXPECT_STREQ("text/html", val);
  1713. }
  1714. TEST(GetHeaderValueTest, SetContent) {
  1715. Response res;
  1716. res.set_content("html", "text/html");
  1717. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1718. res.set_content("text", "text/plain");
  1719. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1720. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1721. }
  1722. TEST(GetHeaderValueTest, RegularValueInt) {
  1723. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1724. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1725. EXPECT_EQ(100ull, val);
  1726. }
  1727. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1728. Headers headers = {{"Content-Length", "x"}};
  1729. auto is_invalid_value = false;
  1730. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1731. is_invalid_value);
  1732. EXPECT_EQ(0ull, val);
  1733. EXPECT_TRUE(is_invalid_value);
  1734. }
  1735. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1736. // An all-digit value that overflows size_t must be reported as invalid, not
  1737. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1738. // a large length to a small one on 32-bit builds, leaving the framing length
  1739. // wrong while is_invalid_value stayed false.
  1740. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1741. auto is_invalid_value = false;
  1742. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1743. is_invalid_value);
  1744. EXPECT_TRUE(is_invalid_value);
  1745. // A well-formed length is unaffected.
  1746. Headers ok = {{"Content-Length", "1234"}};
  1747. is_invalid_value = false;
  1748. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1749. is_invalid_value);
  1750. EXPECT_EQ(1234ull, val);
  1751. EXPECT_FALSE(is_invalid_value);
  1752. }
  1753. TEST(GetHeaderValueTest, Range) {
  1754. {
  1755. Headers headers = {make_range_header({{1, -1}})};
  1756. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1757. EXPECT_STREQ("bytes=1-", val);
  1758. }
  1759. {
  1760. Headers headers = {make_range_header({{-1, 1}})};
  1761. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1762. EXPECT_STREQ("bytes=-1", val);
  1763. }
  1764. {
  1765. Headers headers = {make_range_header({{1, 10}})};
  1766. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1767. EXPECT_STREQ("bytes=1-10", val);
  1768. }
  1769. {
  1770. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1771. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1772. EXPECT_STREQ("bytes=1-10, 100-", val);
  1773. }
  1774. {
  1775. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1776. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1777. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1778. }
  1779. {
  1780. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1781. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1782. EXPECT_STREQ("bytes=0-0, -1", val);
  1783. }
  1784. }
  1785. TEST(BearerTokenAuthTest, SchemeValidation) {
  1786. // A value shorter than "Bearer " must not throw from the fixed-length
  1787. // substr, and a non-Bearer scheme must not be reported as a token.
  1788. struct {
  1789. const char *value;
  1790. const char *expected;
  1791. } cases[] = {
  1792. {"x", ""},
  1793. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1794. {"Bearer abc123", "abc123"},
  1795. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1796. };
  1797. for (const auto &c : cases) {
  1798. Request req;
  1799. req.set_header("Authorization", c.value);
  1800. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1801. }
  1802. }
  1803. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1804. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1805. // to depend on the standard library (libstdc++ handed back duplicates in
  1806. // reverse insertion order, libc++ in insertion order).
  1807. Request req;
  1808. req.set_header("Accept-Encoding", "gzip");
  1809. req.set_header("Accept-Encoding", "deflate");
  1810. req.set_header("Accept-Encoding", "br");
  1811. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1812. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1813. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1814. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1815. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1816. }
  1817. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1818. Request req;
  1819. req.set_header("X-Test", "only");
  1820. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1821. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1822. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1823. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1824. }
  1825. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1826. Request req;
  1827. req.set_header("X-First", "1");
  1828. req.set_header("X-Test", "2");
  1829. req.params.emplace("first", "1");
  1830. req.params.emplace("test", "2");
  1831. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1832. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1833. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1834. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1835. // The second one is negative when read as a signed value
  1836. const auto max_id = (std::numeric_limits<size_t>::max)();
  1837. for (auto id : {max_id / 2, max_id}) {
  1838. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1839. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1840. EXPECT_EQ("", req.get_param_value("test", id));
  1841. EXPECT_EQ("", req.form.get_field("test", id));
  1842. EXPECT_EQ("", req.form.get_file("test", id).content);
  1843. }
  1844. }
  1845. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1846. Headers headers;
  1847. headers.emplace("Host", "example.com");
  1848. headers.emplace("Accept-Encoding", "gzip");
  1849. headers.emplace("User-Agent", "test");
  1850. headers.emplace("Accept-Encoding", "deflate");
  1851. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1852. "Accept-Encoding=deflate ",
  1853. entries_to_string(headers));
  1854. }
  1855. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1856. Headers headers = {{"Content-Type", "text/html"},
  1857. {"CONTENT-TYPE", "text/xml"}};
  1858. EXPECT_EQ(2U, headers.count("content-type"));
  1859. auto it = headers.find("content-type");
  1860. ASSERT_TRUE(it != headers.end());
  1861. EXPECT_EQ("text/html", it->second);
  1862. }
  1863. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1864. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1865. // drop only those fields and leave everything positioned between them.
  1866. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1867. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1868. auto rng = headers.equal_range("a");
  1869. headers.erase(rng.first, rng.second);
  1870. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1871. }
  1872. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1873. Headers headers = {
  1874. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1875. EXPECT_EQ(3U, headers.erase("A"));
  1876. EXPECT_EQ(0U, headers.count("A"));
  1877. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1878. }
  1879. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1880. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1881. headers.emplace_front("Host", "example.com");
  1882. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1883. entries_to_string(headers));
  1884. }
  1885. TEST(ParseHeaderValueTest, Range) {
  1886. {
  1887. Ranges ranges;
  1888. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1889. EXPECT_TRUE(ret);
  1890. EXPECT_EQ(1u, ranges.size());
  1891. EXPECT_EQ(1u, ranges[0].first);
  1892. EXPECT_EQ(-1, ranges[0].second);
  1893. }
  1894. {
  1895. Ranges ranges;
  1896. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1897. EXPECT_TRUE(ret);
  1898. EXPECT_EQ(1u, ranges.size());
  1899. EXPECT_EQ(-1, ranges[0].first);
  1900. EXPECT_EQ(1u, ranges[0].second);
  1901. }
  1902. {
  1903. Ranges ranges;
  1904. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1905. EXPECT_TRUE(ret);
  1906. EXPECT_EQ(1u, ranges.size());
  1907. EXPECT_EQ(1u, ranges[0].first);
  1908. EXPECT_EQ(10u, ranges[0].second);
  1909. }
  1910. {
  1911. Ranges ranges;
  1912. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1913. EXPECT_FALSE(ret);
  1914. }
  1915. {
  1916. Ranges ranges;
  1917. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1918. EXPECT_TRUE(ret);
  1919. EXPECT_EQ(2u, ranges.size());
  1920. EXPECT_EQ(1u, ranges[0].first);
  1921. EXPECT_EQ(10u, ranges[0].second);
  1922. EXPECT_EQ(100u, ranges[1].first);
  1923. EXPECT_EQ(-1, ranges[1].second);
  1924. }
  1925. {
  1926. Ranges ranges;
  1927. auto ret =
  1928. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1929. EXPECT_TRUE(ret);
  1930. EXPECT_EQ(3u, ranges.size());
  1931. EXPECT_EQ(1u, ranges[0].first);
  1932. EXPECT_EQ(10u, ranges[0].second);
  1933. EXPECT_EQ(100u, ranges[1].first);
  1934. EXPECT_EQ(200u, ranges[1].second);
  1935. EXPECT_EQ(300u, ranges[2].first);
  1936. EXPECT_EQ(400u, ranges[2].second);
  1937. }
  1938. {
  1939. Ranges ranges;
  1940. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1941. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1942. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1943. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1944. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1945. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1946. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1947. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1948. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1949. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1950. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1951. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1952. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1953. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1954. EXPECT_FALSE(
  1955. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1956. EXPECT_TRUE(ranges.empty());
  1957. }
  1958. {
  1959. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1960. // remainder of the representation, so it stays accepted.
  1961. Ranges ranges;
  1962. auto ret =
  1963. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1964. EXPECT_TRUE(ret);
  1965. ASSERT_EQ(1u, ranges.size());
  1966. EXPECT_EQ(0, ranges[0].first);
  1967. EXPECT_EQ(-1, ranges[0].second);
  1968. }
  1969. // RFC 9110 14.1: range unit names are case-insensitive.
  1970. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  1971. Ranges ranges;
  1972. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  1973. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  1974. }
  1975. }
  1976. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1977. Request req;
  1978. req.set_header("Accept-Encoding", "gzip");
  1979. Response res;
  1980. res.set_header("Content-Type", "text/plain");
  1981. auto ret = detail::encoding_type(req, res);
  1982. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1983. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1984. #else
  1985. EXPECT_TRUE(ret == detail::EncodingType::None);
  1986. #endif
  1987. }
  1988. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1989. Request req;
  1990. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1991. Response res;
  1992. res.set_header("Content-Type", "text/plain");
  1993. auto ret = detail::encoding_type(req, res);
  1994. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1995. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1996. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1997. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1998. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1999. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2000. #else
  2001. EXPECT_TRUE(ret == detail::EncodingType::None);
  2002. #endif
  2003. }
  2004. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2005. Request req;
  2006. req.set_header("Accept-Encoding",
  2007. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2008. Response res;
  2009. res.set_header("Content-Type", "text/plain");
  2010. auto ret = detail::encoding_type(req, res);
  2011. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2012. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2013. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2014. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2015. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2016. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2017. #else
  2018. EXPECT_TRUE(ret == detail::EncodingType::None);
  2019. #endif
  2020. }
  2021. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2022. // All supported encodings rejected with q=0 should return None
  2023. Request req;
  2024. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2025. Response res;
  2026. res.set_header("Content-Type", "text/plain");
  2027. auto ret = detail::encoding_type(req, res);
  2028. EXPECT_TRUE(ret == detail::EncodingType::None);
  2029. }
  2030. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2031. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2032. Request req;
  2033. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2034. Response res;
  2035. res.set_header("Content-Type", "text/plain");
  2036. auto ret = detail::encoding_type(req, res);
  2037. EXPECT_TRUE(ret == detail::EncodingType::None);
  2038. }
  2039. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2040. Request req;
  2041. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2042. Response res;
  2043. res.set_header("Content-Type", "text/plain");
  2044. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2045. }
  2046. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2047. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2048. Request req;
  2049. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2050. Response res;
  2051. res.set_header("Content-Type", "text/plain");
  2052. auto ret = detail::encoding_type(req, res);
  2053. EXPECT_TRUE(ret == detail::EncodingType::None);
  2054. }
  2055. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2056. // RFC 7231: Accept-Encoding values are case-insensitive
  2057. Request req;
  2058. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2059. Response res;
  2060. res.set_header("Content-Type", "text/plain");
  2061. auto ret = detail::encoding_type(req, res);
  2062. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2063. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2064. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2065. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2066. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2067. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2068. #else
  2069. EXPECT_TRUE(ret == detail::EncodingType::None);
  2070. #endif
  2071. }
  2072. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2073. // q value should determine priority, not hardcoded order
  2074. Request req;
  2075. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2076. Response res;
  2077. res.set_header("Content-Type", "text/plain");
  2078. auto ret = detail::encoding_type(req, res);
  2079. // gzip has highest q=1.0, so it should be selected even though
  2080. // br and zstd are also supported
  2081. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2082. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2083. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2084. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2085. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2086. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2087. #else
  2088. EXPECT_TRUE(ret == detail::EncodingType::None);
  2089. #endif
  2090. }
  2091. TEST(BufferStreamTest, read) {
  2092. detail::BufferStream strm1;
  2093. Stream &strm = strm1;
  2094. EXPECT_EQ(5, strm.write("hello"));
  2095. char buf[512];
  2096. EXPECT_EQ(2, strm.read(buf, 2));
  2097. EXPECT_EQ('h', buf[0]);
  2098. EXPECT_EQ('e', buf[1]);
  2099. EXPECT_EQ(2, strm.read(buf, 2));
  2100. EXPECT_EQ('l', buf[0]);
  2101. EXPECT_EQ('l', buf[1]);
  2102. EXPECT_EQ(1, strm.read(buf, 1));
  2103. EXPECT_EQ('o', buf[0]);
  2104. EXPECT_EQ(0, strm.read(buf, 1));
  2105. }
  2106. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2107. auto host = "www.httpwatch.com";
  2108. auto ip = hosted_at(host);
  2109. EXPECT_EQ("23.96.13.243", ip);
  2110. std::vector<std::string> addrs;
  2111. hosted_at(host, addrs);
  2112. EXPECT_EQ(1u, addrs.size());
  2113. }
  2114. #if 0 // It depends on each test environment...
  2115. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2116. auto host = "www.youtube.com";
  2117. std::vector<std::string> addrs;
  2118. hosted_at(host, addrs);
  2119. EXPECT_EQ(20u, addrs.size());
  2120. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2121. EXPECT_TRUE(it != addrs.end());
  2122. }
  2123. #endif
  2124. class ChunkedEncodingTest : public ::testing::Test {
  2125. protected:
  2126. ChunkedEncodingTest()
  2127. : cli_(HOST, PORT)
  2128. #ifdef CPPHTTPLIB_SSL_ENABLED
  2129. ,
  2130. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2131. #endif
  2132. {
  2133. cli_.set_connection_timeout(2);
  2134. #ifdef CPPHTTPLIB_SSL_ENABLED
  2135. cli_.enable_server_certificate_verification(false);
  2136. #endif
  2137. }
  2138. virtual void SetUp() {
  2139. read_file("./image.jpg", image_data_);
  2140. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2141. res.set_content("Hello World!", "text/plain");
  2142. });
  2143. svr_.Get(
  2144. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2145. res.set_chunked_content_provider(
  2146. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2147. size_t remaining = image_data_.size() - offset;
  2148. if (remaining == 0) {
  2149. sink.done();
  2150. } else {
  2151. constexpr size_t CHUNK_SIZE = 1024;
  2152. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2153. sink.write(&image_data_[offset], send_size);
  2154. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2155. }
  2156. return true;
  2157. });
  2158. });
  2159. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2160. svr_.wait_until_ready();
  2161. }
  2162. virtual void TearDown() {
  2163. svr_.stop();
  2164. if (!request_threads_.empty()) {
  2165. std::this_thread::sleep_for(std::chrono::seconds(1));
  2166. for (auto &t : request_threads_) {
  2167. t.join();
  2168. }
  2169. }
  2170. t_.join();
  2171. }
  2172. #ifdef CPPHTTPLIB_SSL_ENABLED
  2173. SSLClient cli_;
  2174. SSLServer svr_;
  2175. #else
  2176. Client cli_;
  2177. Server svr_;
  2178. #endif
  2179. thread t_;
  2180. std::vector<thread> request_threads_;
  2181. std::string image_data_;
  2182. };
  2183. TEST_F(ChunkedEncodingTest, NormalGet) {
  2184. auto res = cli_.Get("/chunked");
  2185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2186. std::string out;
  2187. read_file("./image.jpg", out);
  2188. EXPECT_EQ(StatusCode::OK_200, res->status);
  2189. EXPECT_EQ(out, res->body);
  2190. }
  2191. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2192. std::string body;
  2193. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2194. body.append(data, data_length);
  2195. return true;
  2196. });
  2197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2198. std::string out;
  2199. read_file("./image.jpg", out);
  2200. EXPECT_EQ(StatusCode::OK_200, res->status);
  2201. EXPECT_EQ(out, body);
  2202. }
  2203. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2204. std::string body;
  2205. auto res = cli_.Get(
  2206. "/chunked",
  2207. [&](const Response &response) {
  2208. EXPECT_EQ(StatusCode::OK_200, response.status);
  2209. return true;
  2210. },
  2211. [&](const char *data, size_t data_length) {
  2212. body.append(data, data_length);
  2213. return true;
  2214. });
  2215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2216. std::string out;
  2217. read_file("./image.jpg", out);
  2218. EXPECT_EQ(StatusCode::OK_200, res->status);
  2219. EXPECT_EQ(out, body);
  2220. }
  2221. TEST(RangeTest, FromHTTPBin_Online) {
  2222. auto host = "httpbingo.org";
  2223. auto path = std::string{"/range/32"};
  2224. #ifdef CPPHTTPLIB_SSL_ENABLED
  2225. auto port = 443;
  2226. SSLClient cli(host, port);
  2227. #else
  2228. auto port = 80;
  2229. Client cli(host, port);
  2230. #endif
  2231. cli.set_connection_timeout(5);
  2232. {
  2233. auto res = cli.Get(path);
  2234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2235. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2236. EXPECT_EQ(StatusCode::OK_200, res->status);
  2237. }
  2238. {
  2239. Headers headers = {make_range_header({{1, -1}})};
  2240. auto res = cli.Get(path, headers);
  2241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2242. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2243. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2244. }
  2245. {
  2246. Headers headers = {make_range_header({{1, 10}})};
  2247. auto res = cli.Get(path, headers);
  2248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2249. EXPECT_EQ("bcdefghijk", res->body);
  2250. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2251. }
  2252. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2253. // entire resource, while the original httpbin returned 200. Both are
  2254. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2255. {
  2256. Headers headers = {make_range_header({{0, 31}})};
  2257. auto res = cli.Get(path, headers);
  2258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2259. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2260. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2261. res->status == StatusCode::PartialContent_206);
  2262. }
  2263. {
  2264. Headers headers = {make_range_header({{0, -1}})};
  2265. auto res = cli.Get(path, headers);
  2266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2267. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2268. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2269. res->status == StatusCode::PartialContent_206);
  2270. }
  2271. // go-httpbin returns 206 with clamped range for over-range requests,
  2272. // while the original httpbin returned 416. Both behaviors are observed
  2273. // in real servers, so we only verify the request succeeds.
  2274. {
  2275. Headers headers = {make_range_header({{0, 32}})};
  2276. auto res = cli.Get(path, headers);
  2277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2278. }
  2279. }
  2280. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2281. auto host = "unresolvableaddress.local";
  2282. auto path = std::string{"/"};
  2283. #ifdef CPPHTTPLIB_SSL_ENABLED
  2284. auto port = 443;
  2285. SSLClient cli(host, port);
  2286. #else
  2287. auto port = 80;
  2288. Client cli(host, port);
  2289. #endif
  2290. cli.set_connection_timeout(1);
  2291. {
  2292. auto res = cli.Get(path);
  2293. ASSERT_FALSE(res);
  2294. }
  2295. std::this_thread::sleep_for(std::chrono::seconds(8));
  2296. }
  2297. #if defined(__linux__) && defined(__GLIBC__) && \
  2298. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2299. // Forward declaration: in split builds split.py strips `inline` and moves the
  2300. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2301. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2302. // against the symbol in both header-only and split builds.
  2303. namespace httplib {
  2304. namespace detail {
  2305. int getaddrinfo_with_timeout(const char *node, const char *service,
  2306. const struct addrinfo *hints,
  2307. struct addrinfo **res, time_t timeout_sec);
  2308. } // namespace detail
  2309. } // namespace httplib
  2310. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2311. //
  2312. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2313. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2314. // gai_suspend() call hits the connection timeout the function calls
  2315. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2316. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2317. // still alive and still references the now-destroyed stack frame.
  2318. //
  2319. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2320. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2321. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2322. // and runs them in a container.
  2323. namespace {
  2324. bool should_run_issue_2431_tests() {
  2325. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2326. return v && *v && std::string(v) != "0";
  2327. }
  2328. std::string unique_unresolvable_host(int n) {
  2329. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2330. // glibc still asks the configured nameserver — which is exactly the path
  2331. // we want to exercise. A unique label per call avoids the resolver cache.
  2332. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2333. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2334. std::to_string(n) + ".invalid";
  2335. }
  2336. } // namespace
  2337. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2338. if (!should_run_issue_2431_tests()) {
  2339. GTEST_SKIP()
  2340. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2341. }
  2342. for (int i = 0; i < 8; ++i) {
  2343. struct addrinfo hints;
  2344. memset(&hints, 0, sizeof(hints));
  2345. hints.ai_family = AF_UNSPEC;
  2346. hints.ai_socktype = SOCK_STREAM;
  2347. auto host = unique_unresolvable_host(i);
  2348. struct addrinfo *result = nullptr;
  2349. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2350. &result, /*timeout_sec=*/1);
  2351. if (rc == 0 && result) { freeaddrinfo(result); }
  2352. }
  2353. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2354. // stack region they still believe holds their gaicb.
  2355. std::this_thread::sleep_for(std::chrono::seconds(3));
  2356. }
  2357. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2358. if (!should_run_issue_2431_tests()) {
  2359. GTEST_SKIP()
  2360. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2361. }
  2362. std::atomic<bool> stop{false};
  2363. std::vector<std::thread> threads;
  2364. for (int t = 0; t < 8; ++t) {
  2365. threads.emplace_back([t, &stop] {
  2366. int i = 0;
  2367. while (!stop.load(std::memory_order_relaxed)) {
  2368. struct addrinfo hints;
  2369. memset(&hints, 0, sizeof(hints));
  2370. hints.ai_family = AF_UNSPEC;
  2371. hints.ai_socktype = SOCK_STREAM;
  2372. auto host = unique_unresolvable_host(t * 100000 + i++);
  2373. struct addrinfo *result = nullptr;
  2374. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2375. &result, /*timeout_sec=*/1);
  2376. if (rc == 0 && result) { freeaddrinfo(result); }
  2377. }
  2378. });
  2379. }
  2380. std::this_thread::sleep_for(std::chrono::seconds(8));
  2381. stop.store(true, std::memory_order_relaxed);
  2382. for (auto &th : threads) {
  2383. th.join();
  2384. }
  2385. std::this_thread::sleep_for(std::chrono::seconds(3));
  2386. }
  2387. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2388. if (!should_run_issue_2431_tests()) {
  2389. GTEST_SKIP()
  2390. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2391. }
  2392. std::atomic<bool> stop{false};
  2393. std::vector<std::thread> threads;
  2394. for (int t = 0; t < 8; ++t) {
  2395. threads.emplace_back([t, &stop] {
  2396. int i = 0;
  2397. while (!stop.load(std::memory_order_relaxed)) {
  2398. auto host = unique_unresolvable_host(t * 100000 + i++);
  2399. Client cli(host, 80);
  2400. cli.set_connection_timeout(1, 0);
  2401. cli.set_read_timeout(1, 0);
  2402. cli.set_write_timeout(1, 0);
  2403. (void)cli.Get("/");
  2404. }
  2405. });
  2406. }
  2407. std::this_thread::sleep_for(std::chrono::seconds(8));
  2408. stop.store(true, std::memory_order_relaxed);
  2409. for (auto &th : threads) {
  2410. th.join();
  2411. }
  2412. std::this_thread::sleep_for(std::chrono::seconds(3));
  2413. }
  2414. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2415. TEST(ConnectionErrorTest, InvalidHost) {
  2416. auto host = "-abcde.com";
  2417. #ifdef CPPHTTPLIB_SSL_ENABLED
  2418. auto port = 443;
  2419. SSLClient cli(host, port);
  2420. #else
  2421. auto port = 80;
  2422. Client cli(host, port);
  2423. #endif
  2424. cli.set_connection_timeout(std::chrono::seconds(2));
  2425. auto res = cli.Get("/");
  2426. ASSERT_TRUE(!res);
  2427. EXPECT_EQ(Error::Connection, res.error());
  2428. }
  2429. TEST(ConnectionErrorTest, InvalidHost2) {
  2430. auto host = "httpcan.org/";
  2431. #ifdef CPPHTTPLIB_SSL_ENABLED
  2432. SSLClient cli(host);
  2433. #else
  2434. Client cli(host);
  2435. #endif
  2436. cli.set_connection_timeout(std::chrono::seconds(2));
  2437. auto res = cli.Get("/");
  2438. ASSERT_TRUE(!res);
  2439. EXPECT_EQ(Error::Connection, res.error());
  2440. }
  2441. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2442. auto host = "httpcan.org/";
  2443. #ifdef CPPHTTPLIB_SSL_ENABLED
  2444. SSLClient cli(host);
  2445. #else
  2446. Client cli(host);
  2447. #endif
  2448. cli.set_connection_timeout(std::chrono::seconds(2));
  2449. auto res = cli.Get("/");
  2450. ASSERT_TRUE(!res);
  2451. stringstream s;
  2452. s << "error code: " << res.error();
  2453. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2454. }
  2455. TEST(ConnectionErrorTest, InvalidPort) {
  2456. auto host = "localhost";
  2457. auto port = 44380;
  2458. #ifdef CPPHTTPLIB_SSL_ENABLED
  2459. SSLClient cli(host, port);
  2460. #else
  2461. Client cli(host, port);
  2462. #endif
  2463. cli.set_connection_timeout(std::chrono::seconds(2));
  2464. auto res = cli.Get("/");
  2465. ASSERT_TRUE(!res);
  2466. EXPECT_TRUE(Error::Connection == res.error() ||
  2467. Error::ConnectionTimeout == res.error());
  2468. }
  2469. TEST(ConnectionErrorTest, Timeout_Online) {
  2470. auto host = "google.com";
  2471. #ifdef CPPHTTPLIB_SSL_ENABLED
  2472. auto port = 44380;
  2473. SSLClient cli(host, port);
  2474. #else
  2475. auto port = 8080;
  2476. Client cli(host, port);
  2477. #endif
  2478. cli.set_connection_timeout(std::chrono::seconds(2));
  2479. // only probe one address type so that the error reason
  2480. // correlates to the timed-out IPv4, not the unsupported
  2481. // IPv6 connection attempt
  2482. cli.set_address_family(AF_INET);
  2483. auto res = cli.Get("/");
  2484. ASSERT_TRUE(!res);
  2485. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2486. }
  2487. TEST(CancelTest, NoCancel_Online) {
  2488. auto host = "httpbingo.org";
  2489. auto path = std::string{"/range/32"};
  2490. #ifdef CPPHTTPLIB_SSL_ENABLED
  2491. auto port = 443;
  2492. SSLClient cli(host, port);
  2493. #else
  2494. auto port = 80;
  2495. Client cli(host, port);
  2496. #endif
  2497. cli.set_connection_timeout(std::chrono::seconds(5));
  2498. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2500. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2501. EXPECT_EQ(StatusCode::OK_200, res->status);
  2502. }
  2503. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2504. // Use /bytes with a large payload so that the DownloadProgress callback
  2505. // (which only fires for Content-Length responses) is invoked before the
  2506. // entire body is received, giving cancellation a chance to fire.
  2507. auto host = "httpbingo.org";
  2508. auto path = std::string{"/bytes/524288"};
  2509. #ifdef CPPHTTPLIB_SSL_ENABLED
  2510. auto port = 443;
  2511. SSLClient cli(host, port);
  2512. #else
  2513. auto port = 80;
  2514. Client cli(host, port);
  2515. #endif
  2516. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2517. cli.set_connection_timeout(std::chrono::seconds(5));
  2518. ASSERT_TRUE(!res);
  2519. EXPECT_EQ(Error::Canceled, res.error());
  2520. }
  2521. TEST(CancelTest, WithCancelLargePayload_Online) {
  2522. auto host = "httpbingo.org";
  2523. auto path = std::string{"/bytes/524288"};
  2524. #ifdef CPPHTTPLIB_SSL_ENABLED
  2525. auto port = 443;
  2526. SSLClient cli(host, port);
  2527. #else
  2528. auto port = 80;
  2529. Client cli(host, port);
  2530. #endif
  2531. cli.set_connection_timeout(std::chrono::seconds(5));
  2532. uint32_t count = 0;
  2533. auto res =
  2534. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2535. ASSERT_TRUE(!res);
  2536. EXPECT_EQ(Error::Canceled, res.error());
  2537. }
  2538. TEST(CancelTest, NoCancelPost) {
  2539. Server svr;
  2540. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2541. res.set_content("Hello World!", "text/plain");
  2542. });
  2543. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2544. auto se = detail::scope_exit([&] {
  2545. svr.stop();
  2546. thread.join();
  2547. ASSERT_FALSE(svr.is_running());
  2548. });
  2549. svr.wait_until_ready();
  2550. Client cli(HOST, PORT);
  2551. cli.set_connection_timeout(std::chrono::seconds(5));
  2552. auto res =
  2553. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2554. "application/json", [](uint64_t, uint64_t) { return true; });
  2555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2556. EXPECT_EQ("Hello World!", res->body);
  2557. EXPECT_EQ(StatusCode::OK_200, res->status);
  2558. }
  2559. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2560. Server svr;
  2561. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2562. res.set_content("Hello World!", "text/plain");
  2563. });
  2564. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2565. auto se = detail::scope_exit([&] {
  2566. svr.stop();
  2567. thread.join();
  2568. ASSERT_FALSE(svr.is_running());
  2569. });
  2570. svr.wait_until_ready();
  2571. Client cli(HOST, PORT);
  2572. cli.set_connection_timeout(std::chrono::seconds(5));
  2573. auto res =
  2574. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2575. "application/json", [](uint64_t, uint64_t) { return false; });
  2576. ASSERT_TRUE(!res);
  2577. EXPECT_EQ(Error::Canceled, res.error());
  2578. }
  2579. TEST(CancelTest, WithCancelLargePayloadPost) {
  2580. Server svr;
  2581. svr.set_payload_max_length(200 * 1024 * 1024);
  2582. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2583. res.set_content(LARGE_DATA, "text/plain");
  2584. });
  2585. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2586. auto se = detail::scope_exit([&] {
  2587. svr.stop();
  2588. thread.join();
  2589. ASSERT_FALSE(svr.is_running());
  2590. });
  2591. svr.wait_until_ready();
  2592. Client cli(HOST, PORT);
  2593. cli.set_payload_max_length(200 * 1024 * 1024);
  2594. cli.set_connection_timeout(std::chrono::seconds(5));
  2595. auto res =
  2596. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2597. "application/json", [](uint64_t, uint64_t) { return false; });
  2598. ASSERT_TRUE(!res);
  2599. EXPECT_EQ(Error::Canceled, res.error());
  2600. }
  2601. TEST(CancelTest, NoCancelPut) {
  2602. Server svr;
  2603. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2604. res.set_content("Hello World!", "text/plain");
  2605. });
  2606. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2607. auto se = detail::scope_exit([&] {
  2608. svr.stop();
  2609. thread.join();
  2610. ASSERT_FALSE(svr.is_running());
  2611. });
  2612. svr.wait_until_ready();
  2613. Client cli(HOST, PORT);
  2614. cli.set_connection_timeout(std::chrono::seconds(5));
  2615. auto res =
  2616. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2617. "application/json", [](uint64_t, uint64_t) { return true; });
  2618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2619. EXPECT_EQ("Hello World!", res->body);
  2620. EXPECT_EQ(StatusCode::OK_200, res->status);
  2621. }
  2622. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2623. Server svr;
  2624. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2625. res.set_content("Hello World!", "text/plain");
  2626. });
  2627. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2628. auto se = detail::scope_exit([&] {
  2629. svr.stop();
  2630. thread.join();
  2631. ASSERT_FALSE(svr.is_running());
  2632. });
  2633. svr.wait_until_ready();
  2634. Client cli(HOST, PORT);
  2635. cli.set_connection_timeout(std::chrono::seconds(5));
  2636. auto res =
  2637. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2638. "application/json", [](uint64_t, uint64_t) { return false; });
  2639. ASSERT_TRUE(!res);
  2640. EXPECT_EQ(Error::Canceled, res.error());
  2641. }
  2642. TEST(CancelTest, WithCancelLargePayloadPut) {
  2643. Server svr;
  2644. svr.set_payload_max_length(200 * 1024 * 1024);
  2645. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2646. res.set_content(LARGE_DATA, "text/plain");
  2647. });
  2648. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2649. auto se = detail::scope_exit([&] {
  2650. svr.stop();
  2651. thread.join();
  2652. ASSERT_FALSE(svr.is_running());
  2653. });
  2654. svr.wait_until_ready();
  2655. Client cli(HOST, PORT);
  2656. cli.set_payload_max_length(200 * 1024 * 1024);
  2657. cli.set_connection_timeout(std::chrono::seconds(5));
  2658. auto res =
  2659. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2660. "application/json", [](uint64_t, uint64_t) { return false; });
  2661. ASSERT_TRUE(!res);
  2662. EXPECT_EQ(Error::Canceled, res.error());
  2663. }
  2664. TEST(CancelTest, NoCancelPatch) {
  2665. Server svr;
  2666. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2667. res.set_content("Hello World!", "text/plain");
  2668. });
  2669. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2670. auto se = detail::scope_exit([&] {
  2671. svr.stop();
  2672. thread.join();
  2673. ASSERT_FALSE(svr.is_running());
  2674. });
  2675. svr.wait_until_ready();
  2676. Client cli(HOST, PORT);
  2677. cli.set_connection_timeout(std::chrono::seconds(5));
  2678. auto res =
  2679. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2680. "application/json", [](uint64_t, uint64_t) { return true; });
  2681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2682. EXPECT_EQ("Hello World!", res->body);
  2683. EXPECT_EQ(StatusCode::OK_200, res->status);
  2684. }
  2685. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2686. Server svr;
  2687. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2688. res.set_content("Hello World!", "text/plain");
  2689. });
  2690. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2691. auto se = detail::scope_exit([&] {
  2692. svr.stop();
  2693. thread.join();
  2694. ASSERT_FALSE(svr.is_running());
  2695. });
  2696. svr.wait_until_ready();
  2697. Client cli(HOST, PORT);
  2698. cli.set_connection_timeout(std::chrono::seconds(5));
  2699. auto res =
  2700. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2701. "application/json", [](uint64_t, uint64_t) { return false; });
  2702. ASSERT_TRUE(!res);
  2703. EXPECT_EQ(Error::Canceled, res.error());
  2704. }
  2705. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2706. Server svr;
  2707. svr.set_payload_max_length(200 * 1024 * 1024);
  2708. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2709. res.set_content(LARGE_DATA, "text/plain");
  2710. });
  2711. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2712. auto se = detail::scope_exit([&] {
  2713. svr.stop();
  2714. thread.join();
  2715. ASSERT_FALSE(svr.is_running());
  2716. });
  2717. svr.wait_until_ready();
  2718. Client cli(HOST, PORT);
  2719. cli.set_payload_max_length(200 * 1024 * 1024);
  2720. cli.set_connection_timeout(std::chrono::seconds(5));
  2721. auto res =
  2722. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2723. "application/json", [](uint64_t, uint64_t) { return false; });
  2724. ASSERT_TRUE(!res);
  2725. EXPECT_EQ(Error::Canceled, res.error());
  2726. }
  2727. TEST(CancelTest, NoCancelDelete) {
  2728. Server svr;
  2729. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2730. res.set_content("Hello World!", "text/plain");
  2731. });
  2732. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2733. auto se = detail::scope_exit([&] {
  2734. svr.stop();
  2735. thread.join();
  2736. ASSERT_FALSE(svr.is_running());
  2737. });
  2738. svr.wait_until_ready();
  2739. Client cli(HOST, PORT);
  2740. cli.set_connection_timeout(std::chrono::seconds(5));
  2741. auto res =
  2742. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2743. "application/json", [](uint64_t, uint64_t) { return true; });
  2744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2745. EXPECT_EQ("Hello World!", res->body);
  2746. EXPECT_EQ(StatusCode::OK_200, res->status);
  2747. }
  2748. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2749. Server svr;
  2750. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2751. res.set_content("Hello World!", "text/plain");
  2752. });
  2753. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2754. auto se = detail::scope_exit([&] {
  2755. svr.stop();
  2756. thread.join();
  2757. ASSERT_FALSE(svr.is_running());
  2758. });
  2759. svr.wait_until_ready();
  2760. Client cli(HOST, PORT);
  2761. cli.set_connection_timeout(std::chrono::seconds(5));
  2762. auto res =
  2763. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2764. "application/json", [](uint64_t, uint64_t) { return false; });
  2765. ASSERT_TRUE(!res);
  2766. EXPECT_EQ(Error::Canceled, res.error());
  2767. }
  2768. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2769. Server svr;
  2770. svr.set_payload_max_length(200 * 1024 * 1024);
  2771. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2772. res.set_content(LARGE_DATA, "text/plain");
  2773. });
  2774. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2775. auto se = detail::scope_exit([&] {
  2776. svr.stop();
  2777. thread.join();
  2778. ASSERT_FALSE(svr.is_running());
  2779. });
  2780. svr.wait_until_ready();
  2781. Client cli(HOST, PORT);
  2782. cli.set_payload_max_length(200 * 1024 * 1024);
  2783. cli.set_connection_timeout(std::chrono::seconds(5));
  2784. auto res =
  2785. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2786. "application/json", [](uint64_t, uint64_t) { return false; });
  2787. ASSERT_TRUE(!res);
  2788. EXPECT_EQ(Error::Canceled, res.error());
  2789. }
  2790. static std::string remove_whitespace(const std::string &input) {
  2791. std::string output;
  2792. output.reserve(input.size());
  2793. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2794. [](unsigned char c) { return !std::isspace(c); });
  2795. return output;
  2796. }
  2797. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2798. auto host = "httpbingo.org";
  2799. auto path = std::string{"/basic-auth/hello/world"};
  2800. #ifdef CPPHTTPLIB_SSL_ENABLED
  2801. auto port = 443;
  2802. SSLClient cli(host, port);
  2803. #else
  2804. auto port = 80;
  2805. Client cli(host, port);
  2806. #endif
  2807. {
  2808. auto res = cli.Get(path);
  2809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2810. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2811. }
  2812. {
  2813. auto res = cli.Get(
  2814. path, Headers{make_basic_authentication_header("hello", "world")});
  2815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2816. auto body = remove_whitespace(res->body);
  2817. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2818. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2819. EXPECT_EQ(StatusCode::OK_200, res->status);
  2820. }
  2821. {
  2822. cli.set_basic_auth("hello", "world");
  2823. auto res = cli.Get(path);
  2824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2825. auto body = remove_whitespace(res->body);
  2826. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2827. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2828. EXPECT_EQ(StatusCode::OK_200, res->status);
  2829. }
  2830. {
  2831. cli.set_basic_auth("hello", "bad");
  2832. auto res = cli.Get(path);
  2833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2834. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2835. }
  2836. {
  2837. cli.set_basic_auth("bad", "world");
  2838. auto res = cli.Get(path);
  2839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2840. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2841. }
  2842. }
  2843. #ifdef CPPHTTPLIB_SSL_ENABLED
  2844. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2845. auto host = "httpbingo.org";
  2846. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2847. auto paths = std::vector<std::string>{
  2848. "/digest-auth/auth/hello/world/MD5",
  2849. "/digest-auth/auth/hello/world/SHA-256",
  2850. };
  2851. auto port = 443;
  2852. SSLClient cli(host, port);
  2853. {
  2854. auto res = cli.Get(unauth_path);
  2855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2856. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2857. }
  2858. {
  2859. cli.set_digest_auth("hello", "world");
  2860. for (const auto &path : paths) {
  2861. auto res = cli.Get(path.c_str());
  2862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2863. auto body = remove_whitespace(res->body);
  2864. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2865. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2866. EXPECT_EQ(StatusCode::OK_200, res->status);
  2867. }
  2868. cli.set_digest_auth("hello", "bad");
  2869. for (const auto &path : paths) {
  2870. auto res = cli.Get(path.c_str());
  2871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2872. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2873. }
  2874. }
  2875. }
  2876. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2877. // comma-separated list of challenges, and each challenge may itself carry a
  2878. // comma-separated auth-param list, so a server can legally offer Basic
  2879. // before Digest, either as two field lines or packed into one. Runs one 401
  2880. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2881. // value() joins them in receipt order) and checks that the retry carries a
  2882. // well-formed Digest Authorization header naming expected_realm.
  2883. static void
  2884. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2885. const std::string &expected_realm) {
  2886. std::atomic<int> hits{0};
  2887. Server svr;
  2888. svr.Get("/x", [&](const Request &req, Response &res) {
  2889. if (++hits == 1) {
  2890. res.status = StatusCode::Unauthorized_401;
  2891. for (const auto &challenge : challenges) {
  2892. res.set_header("WWW-Authenticate", challenge);
  2893. }
  2894. } else {
  2895. auto authorization = req.get_header_value("Authorization");
  2896. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2897. EXPECT_NE(std::string::npos,
  2898. authorization.find("realm=\"" + expected_realm + "\""));
  2899. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2900. res.set_content("ok", "text/plain");
  2901. }
  2902. });
  2903. auto port = svr.bind_to_any_port(HOST);
  2904. std::thread t([&]() { svr.listen_after_bind(); });
  2905. auto se = detail::scope_exit([&] {
  2906. svr.stop();
  2907. t.join();
  2908. });
  2909. svr.wait_until_ready();
  2910. Client cli(HOST, port);
  2911. cli.set_digest_auth("hello", "world");
  2912. auto res = cli.Get("/x");
  2913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2914. EXPECT_EQ(2, hits.load());
  2915. }
  2916. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2917. static const char *kDigestChallenge =
  2918. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2919. "algorithm=MD5";
  2920. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2921. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2922. "testrealm");
  2923. }
  2924. // Same challenge list with the schemes in the opposite order, to make sure
  2925. // the fix above didn't just special-case "Basic first".
  2926. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2927. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2928. "testrealm");
  2929. }
  2930. // A comma inside a quoted auth-param value must not be mistaken for the
  2931. // separator between two challenges (or two auth-params).
  2932. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2933. run_digest_challenge_list_test(
  2934. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2935. "algorithm=MD5"},
  2936. "test,realm");
  2937. }
  2938. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2939. // make_digest_authentication_header() dereferences both unconditionally, so
  2940. // a server sending a challenge missing either one must not be treated as
  2941. // usable -- doing so used to crash the client with std::out_of_range.
  2942. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2943. Server svr;
  2944. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2945. res.status = StatusCode::Unauthorized_401;
  2946. res.set_header("WWW-Authenticate", challenge);
  2947. });
  2948. auto port = svr.bind_to_any_port(HOST);
  2949. std::thread t([&]() { svr.listen_after_bind(); });
  2950. auto se = detail::scope_exit([&] {
  2951. svr.stop();
  2952. t.join();
  2953. });
  2954. svr.wait_until_ready();
  2955. Client cli(HOST, port);
  2956. cli.set_digest_auth("hello", "world");
  2957. auto res = cli.Get("/x");
  2958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2959. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2960. }
  2961. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2962. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2963. }
  2964. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2965. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2966. }
  2967. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2968. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2969. }
  2970. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  2971. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  2972. // when storing the values, so the header builder has to re-escape them (and
  2973. // keep algorithm a bare token); otherwise the value breaks out of its
  2974. // quoted-string and injects extra auth-params into the client's Authorization.
  2975. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  2976. std::atomic<int> hits{0};
  2977. std::string authorization;
  2978. Server svr;
  2979. svr.Get("/x", [&](const Request &req, Response &res) {
  2980. if (++hits == 1) {
  2981. res.status = StatusCode::Unauthorized_401;
  2982. // On the wire the quotes embedded in the values are backslash-escaped.
  2983. res.set_header("WWW-Authenticate",
  2984. "Digest realm=\"testrealm\", "
  2985. "nonce=\"n\\\"; injected=\\\"x\", "
  2986. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  2987. } else {
  2988. authorization = req.get_header_value("Authorization");
  2989. res.set_content("ok", "text/plain");
  2990. }
  2991. });
  2992. auto port = svr.bind_to_any_port(HOST);
  2993. std::thread t([&]() { svr.listen_after_bind(); });
  2994. auto se = detail::scope_exit([&] {
  2995. svr.stop();
  2996. t.join();
  2997. });
  2998. svr.wait_until_ready();
  2999. Client cli(HOST, port);
  3000. cli.set_digest_auth("hello", "world");
  3001. auto res = cli.Get("/x");
  3002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3003. EXPECT_EQ(2, hits.load());
  3004. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3005. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3006. // inside its quoted-string rather than starting an "injected" auth-param.
  3007. EXPECT_NE(std::string::npos,
  3008. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3009. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3010. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3011. }
  3012. #endif
  3013. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3014. auto host = "google.com";
  3015. auto another_host = "example.com";
  3016. auto wrong_ip = "0.0.0.0";
  3017. #ifdef CPPHTTPLIB_SSL_ENABLED
  3018. SSLClient cli(host);
  3019. #else
  3020. Client cli(host);
  3021. #endif
  3022. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3023. auto res = cli.Get("/");
  3024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3025. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3026. }
  3027. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3028. auto host = "google.com";
  3029. auto wrong_ip = "0.0.0.0";
  3030. #ifdef CPPHTTPLIB_SSL_ENABLED
  3031. SSLClient cli(host);
  3032. #else
  3033. Client cli(host);
  3034. #endif
  3035. cli.set_hostname_addr_map({{host, wrong_ip}});
  3036. auto res = cli.Get("/");
  3037. ASSERT_TRUE(!res);
  3038. EXPECT_EQ(Error::Connection, res.error());
  3039. }
  3040. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3041. // A mapped value that is not an IP literal must be resolved. "localhost"
  3042. // resolves from the hosts file, so this test needs no external DNS.
  3043. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3044. auto host = "target.invalid";
  3045. Server svr;
  3046. std::string received_host;
  3047. svr.Get("/hi", [&](const Request &req, Response &res) {
  3048. received_host = req.get_header_value("Host");
  3049. res.set_content("Hello World!", "text/plain");
  3050. });
  3051. auto port = svr.bind_to_any_port(HOST);
  3052. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3053. auto se = detail::scope_exit([&] {
  3054. svr.stop();
  3055. thread.join();
  3056. ASSERT_FALSE(svr.is_running());
  3057. });
  3058. svr.wait_until_ready();
  3059. Client cli(host, port);
  3060. cli.set_hostname_addr_map({{host, HOST}});
  3061. auto res = cli.Get("/hi");
  3062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3063. EXPECT_EQ(StatusCode::OK_200, res->status);
  3064. // The mapping only redirects the connection; the identity stays host_.
  3065. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3066. }
  3067. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3068. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3069. auto host = "target.invalid";
  3070. Server svr;
  3071. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3072. res.set_content("Hello World!", "text/plain");
  3073. });
  3074. auto port = svr.bind_to_any_port("127.0.0.1");
  3075. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3076. auto se = detail::scope_exit([&] {
  3077. svr.stop();
  3078. thread.join();
  3079. ASSERT_FALSE(svr.is_running());
  3080. });
  3081. svr.wait_until_ready();
  3082. Client cli(host, port);
  3083. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3084. auto res = cli.Get("/hi");
  3085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3086. EXPECT_EQ(StatusCode::OK_200, res->status);
  3087. }
  3088. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3089. // An empty mapped value must leave host_ as the connection target. Without
  3090. // that guard the empty value would become the host argument, getaddrinfo
  3091. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3092. // loopback - silently connecting somewhere the caller never asked for.
  3093. // The server listens on loopback, so such a fallback would succeed and is
  3094. // therefore observable as a failure of this test.
  3095. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3096. Server svr;
  3097. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3098. res.set_content("Hello World!", "text/plain");
  3099. });
  3100. auto port = svr.bind_to_any_port(HOST);
  3101. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3102. auto se = detail::scope_exit([&] {
  3103. svr.stop();
  3104. thread.join();
  3105. ASSERT_FALSE(svr.is_running());
  3106. });
  3107. svr.wait_until_ready();
  3108. Client cli(blackhole, port);
  3109. cli.set_hostname_addr_map({{blackhole, ""}});
  3110. cli.set_connection_timeout(1);
  3111. auto res = cli.Get("/hi");
  3112. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3113. }
  3114. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3115. auto host = "httpbingo.org";
  3116. auto path = std::string{"/absolute-redirect/3"};
  3117. #ifdef CPPHTTPLIB_SSL_ENABLED
  3118. SSLClient cli(host);
  3119. #else
  3120. Client cli(host);
  3121. #endif
  3122. cli.set_follow_location(true);
  3123. auto res = cli.Get(path);
  3124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3125. EXPECT_EQ(StatusCode::OK_200, res->status);
  3126. }
  3127. TEST(RedirectTest, Redirect_Online) {
  3128. auto host = "httpbingo.org";
  3129. auto path = std::string{"/redirect/3"};
  3130. #ifdef CPPHTTPLIB_SSL_ENABLED
  3131. SSLClient cli(host);
  3132. #else
  3133. Client cli(host);
  3134. #endif
  3135. cli.set_follow_location(true);
  3136. auto res = cli.Get(path);
  3137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3138. EXPECT_EQ(StatusCode::OK_200, res->status);
  3139. }
  3140. TEST(RelativeRedirectTest, Redirect_Online) {
  3141. auto host = "httpbingo.org";
  3142. auto path = std::string{"/relative-redirect/3"};
  3143. #ifdef CPPHTTPLIB_SSL_ENABLED
  3144. SSLClient cli(host);
  3145. #else
  3146. Client cli(host);
  3147. #endif
  3148. cli.set_follow_location(true);
  3149. auto res = cli.Get(path);
  3150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3151. EXPECT_EQ(StatusCode::OK_200, res->status);
  3152. }
  3153. TEST(TooManyRedirectTest, Redirect_Online) {
  3154. auto host = "httpbingo.org";
  3155. auto path = std::string{"/redirect/21"};
  3156. #ifdef CPPHTTPLIB_SSL_ENABLED
  3157. SSLClient cli(host);
  3158. #else
  3159. Client cli(host);
  3160. #endif
  3161. cli.set_follow_location(true);
  3162. auto res = cli.Get(path);
  3163. ASSERT_TRUE(!res);
  3164. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3165. }
  3166. #ifdef CPPHTTPLIB_SSL_ENABLED
  3167. TEST(YahooRedirectTest, Redirect_Online) {
  3168. Client cli("yahoo.com");
  3169. auto res = cli.Get("/");
  3170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3171. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3172. cli.set_follow_location(true);
  3173. res = cli.Get("/");
  3174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3175. EXPECT_EQ(StatusCode::OK_200, res->status);
  3176. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3177. }
  3178. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3179. #define REDIR_HOST "httpbingo.org"
  3180. #define REDIR_PATH "/redirect-to"
  3181. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3182. SSLClient cli(REDIR_HOST);
  3183. cli.set_follow_location(true);
  3184. auto res =
  3185. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3187. EXPECT_EQ(StatusCode::OK_200, res->status);
  3188. }
  3189. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3190. SSLClient cli(REDIR_HOST);
  3191. cli.set_follow_location(true);
  3192. Params params;
  3193. params.emplace("url", "http://example.com");
  3194. params.emplace("status_code", "302");
  3195. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3197. EXPECT_EQ(StatusCode::OK_200, res->status);
  3198. }
  3199. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3200. SSLClient cli(REDIR_HOST);
  3201. cli.set_follow_location(true);
  3202. Params params;
  3203. params.emplace("url", "http://example.com");
  3204. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3206. EXPECT_EQ(StatusCode::OK_200, res->status);
  3207. }
  3208. TEST(UrlWithSpace, Redirect_Online) {
  3209. SSLClient cli("edge.forgecdn.net");
  3210. cli.set_follow_location(true);
  3211. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3213. EXPECT_EQ(StatusCode::OK_200, res->status);
  3214. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3215. }
  3216. #endif
  3217. #if !defined(_WIN32) && !defined(_WIN64)
  3218. TEST(ReceiveSignals, Signal) {
  3219. auto setupSignalHandlers = []() {
  3220. struct sigaction act;
  3221. sigemptyset(&act.sa_mask);
  3222. act.sa_flags = SA_SIGINFO;
  3223. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3224. switch (sig) {
  3225. case SIGINT:
  3226. default: break;
  3227. }
  3228. };
  3229. ::sigaction(SIGINT, &act, nullptr);
  3230. };
  3231. Server svr;
  3232. int port = 0;
  3233. auto thread = std::thread([&]() {
  3234. setupSignalHandlers();
  3235. port = svr.bind_to_any_port(HOST);
  3236. svr.listen_after_bind();
  3237. });
  3238. auto se = detail::scope_exit([&] {
  3239. svr.stop();
  3240. thread.join();
  3241. ASSERT_FALSE(svr.is_running());
  3242. });
  3243. svr.wait_until_ready();
  3244. ASSERT_TRUE(svr.is_running());
  3245. pthread_kill(thread.native_handle(), SIGINT);
  3246. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3247. ASSERT_TRUE(svr.is_running());
  3248. }
  3249. #endif
  3250. TEST(RedirectToDifferentPort, Redirect) {
  3251. Server svr1;
  3252. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3253. res.set_content("Hello World!", "text/plain");
  3254. });
  3255. int svr1_port = 0;
  3256. auto thread1 = std::thread([&]() {
  3257. svr1_port = svr1.bind_to_any_port(HOST);
  3258. svr1.listen_after_bind();
  3259. });
  3260. Server svr2;
  3261. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3262. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3263. });
  3264. int svr2_port = 0;
  3265. auto thread2 = std::thread([&]() {
  3266. svr2_port = svr2.bind_to_any_port(HOST);
  3267. svr2.listen_after_bind();
  3268. });
  3269. auto se = detail::scope_exit([&] {
  3270. svr2.stop();
  3271. thread2.join();
  3272. svr1.stop();
  3273. thread1.join();
  3274. ASSERT_FALSE(svr2.is_running());
  3275. ASSERT_FALSE(svr1.is_running());
  3276. });
  3277. svr1.wait_until_ready();
  3278. svr2.wait_until_ready();
  3279. Client cli("localhost", svr2_port);
  3280. cli.set_follow_location(true);
  3281. auto res = cli.Get("/2");
  3282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3283. EXPECT_EQ(StatusCode::OK_200, res->status);
  3284. EXPECT_EQ("Hello World!", res->body);
  3285. }
  3286. // GET /redir on one server redirects to /target on another port, so the
  3287. // client follows it with a new client.
  3288. static Result
  3289. GetThroughRedirectToDifferentPort(Server::Handler target,
  3290. const std::function<void(Client &)> &setup,
  3291. const Headers &headers = Headers()) {
  3292. Server target_svr;
  3293. target_svr.Get("/target", target);
  3294. int target_port = 0;
  3295. auto target_thread = std::thread([&]() {
  3296. target_port = target_svr.bind_to_any_port(HOST);
  3297. target_svr.listen_after_bind();
  3298. });
  3299. Server origin_svr;
  3300. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3301. res.set_redirect(
  3302. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3303. });
  3304. int origin_port = 0;
  3305. auto origin_thread = std::thread([&]() {
  3306. origin_port = origin_svr.bind_to_any_port(HOST);
  3307. origin_svr.listen_after_bind();
  3308. });
  3309. auto se = detail::scope_exit([&] {
  3310. origin_svr.stop();
  3311. origin_thread.join();
  3312. target_svr.stop();
  3313. target_thread.join();
  3314. });
  3315. target_svr.wait_until_ready();
  3316. origin_svr.wait_until_ready();
  3317. Client cli("localhost", origin_port);
  3318. cli.set_follow_location(true);
  3319. setup(cli);
  3320. return cli.Get("/redir", headers);
  3321. }
  3322. static void
  3323. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3324. std::string captured_authorization;
  3325. auto result = GetThroughRedirectToDifferentPort(
  3326. [&](const Request &req, Response &res) {
  3327. captured_authorization = req.get_header_value("Authorization");
  3328. res.set_content("OK", "text/plain");
  3329. },
  3330. set_auth);
  3331. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3332. EXPECT_EQ(StatusCode::OK_200, result->status);
  3333. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3334. EXPECT_TRUE(captured_authorization.empty());
  3335. }
  3336. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3337. TestDoNotForwardCredentialsOnRedirect(
  3338. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3339. }
  3340. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3341. TestDoNotForwardCredentialsOnRedirect(
  3342. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3343. }
  3344. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3345. std::string captured_cookie;
  3346. auto result = GetThroughRedirectToDifferentPort(
  3347. [&](const Request &req, Response &res) {
  3348. captured_cookie = req.get_header_value("Cookie");
  3349. res.set_content("OK", "text/plain");
  3350. },
  3351. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3352. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3353. EXPECT_EQ(StatusCode::OK_200, result->status);
  3354. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3355. EXPECT_TRUE(captured_cookie.empty());
  3356. }
  3357. TEST(RedirectToSamePort, ForwardCookie) {
  3358. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3359. // header so that ordinary session flows keep working.
  3360. Server svr;
  3361. std::string captured_cookie;
  3362. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3363. res.set_redirect("/target", 302);
  3364. });
  3365. svr.Get("/target", [&](const Request &req, Response &res) {
  3366. captured_cookie = req.get_header_value("Cookie");
  3367. res.set_content("OK", "text/plain");
  3368. });
  3369. auto port = svr.bind_to_any_port(HOST);
  3370. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3371. auto se = detail::scope_exit([&] {
  3372. svr.stop();
  3373. thread.join();
  3374. ASSERT_FALSE(svr.is_running());
  3375. });
  3376. svr.wait_until_ready();
  3377. Client cli(HOST, port);
  3378. cli.set_follow_location(true);
  3379. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3380. auto res = cli.Get("/redir", headers);
  3381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3382. EXPECT_EQ(StatusCode::OK_200, res->status);
  3383. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3384. }
  3385. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3386. std::string authorization;
  3387. std::string trace_id;
  3388. auto result = GetThroughRedirectToDifferentPort(
  3389. [&](const Request &req, Response &res) {
  3390. authorization = req.get_header_value("Authorization");
  3391. trace_id = req.get_header_value("X-Trace-Id");
  3392. res.set_content("OK", "text/plain");
  3393. },
  3394. [](Client &cli) {
  3395. cli.set_default_headers(
  3396. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3397. });
  3398. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3399. EXPECT_EQ(StatusCode::OK_200, result->status);
  3400. // Like a header given with the request, a default one goes along unless it
  3401. // carries credentials (RFC 9110 15.4).
  3402. EXPECT_TRUE(authorization.empty());
  3403. EXPECT_EQ("42", trace_id);
  3404. }
  3405. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3406. auto result = GetThroughRedirectToDifferentPort(
  3407. [](const Request &, Response &res) {
  3408. res.set_content(std::string(2048, 'x'), "text/plain");
  3409. },
  3410. [](Client &cli) { cli.set_payload_max_length(1024); });
  3411. EXPECT_FALSE(result);
  3412. }
  3413. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3414. auto result = GetThroughRedirectToDifferentPort(
  3415. [](const Request &req, Response &res) {
  3416. // Answer after a second, or once the client gives up.
  3417. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3418. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3419. }
  3420. res.set_content("late", "text/plain");
  3421. },
  3422. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3423. ASSERT_FALSE(result);
  3424. EXPECT_EQ(Error::Read, result.error());
  3425. }
  3426. #ifdef CPPHTTPLIB_SSL_ENABLED
  3427. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3428. auto result = GetThroughRedirectToDifferentPort(
  3429. [](const Request &, Response &res) {
  3430. res.status = StatusCode::Unauthorized_401;
  3431. res.set_header("WWW-Authenticate",
  3432. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3433. },
  3434. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3435. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3436. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3437. }
  3438. #endif
  3439. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3440. Server svr;
  3441. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3442. // Port number that overflows int — should not crash
  3443. res.set_redirect("http://localhost:99999999999999999999/target");
  3444. });
  3445. auto port = svr.bind_to_any_port(HOST);
  3446. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3447. auto se = detail::scope_exit([&] {
  3448. svr.stop();
  3449. thread.join();
  3450. ASSERT_FALSE(svr.is_running());
  3451. });
  3452. svr.wait_until_ready();
  3453. Client cli(HOST, port);
  3454. cli.set_follow_location(true);
  3455. auto res = cli.Get("/redir");
  3456. // Should fail gracefully, not crash (no valid response due to bad port)
  3457. EXPECT_FALSE(res);
  3458. }
  3459. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3460. Server svr;
  3461. auto port = svr.bind_to_any_port(HOST);
  3462. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3463. // The server's own port followed by junk must not be followed
  3464. res.set_redirect("http://" + std::string(HOST) + ":" +
  3465. std::to_string(port) + "junk/target");
  3466. });
  3467. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3468. res.set_content("target", "text/plain");
  3469. });
  3470. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3471. auto se = detail::scope_exit([&] {
  3472. svr.stop();
  3473. thread.join();
  3474. ASSERT_FALSE(svr.is_running());
  3475. });
  3476. svr.wait_until_ready();
  3477. Client cli(HOST, port);
  3478. cli.set_follow_location(true);
  3479. auto res = cli.Get("/redir");
  3480. EXPECT_FALSE(res);
  3481. }
  3482. TEST(RedirectFromPageWithContent, Redirect) {
  3483. Server svr;
  3484. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3485. res.set_content("___", "text/plain");
  3486. res.set_redirect("/2");
  3487. });
  3488. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3489. res.set_content("Hello World!", "text/plain");
  3490. });
  3491. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3492. auto se = detail::scope_exit([&] {
  3493. svr.stop();
  3494. th.join();
  3495. ASSERT_FALSE(svr.is_running());
  3496. });
  3497. svr.wait_until_ready();
  3498. {
  3499. Client cli("localhost", PORT);
  3500. cli.set_follow_location(true);
  3501. std::string body;
  3502. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3503. body.append(data, data_length);
  3504. return true;
  3505. });
  3506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3507. EXPECT_EQ(StatusCode::OK_200, res->status);
  3508. EXPECT_EQ("Hello World!", body);
  3509. }
  3510. {
  3511. Client cli("localhost", PORT);
  3512. std::string body;
  3513. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3514. body.append(data, data_length);
  3515. return true;
  3516. });
  3517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3518. EXPECT_EQ(StatusCode::Found_302, res->status);
  3519. EXPECT_EQ("___", body);
  3520. }
  3521. }
  3522. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3523. Server svr;
  3524. auto port_str = std::to_string(PORT);
  3525. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3526. auto expected_host = "[::1]:" + port_str;
  3527. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3528. res.set_content("___", "text/plain");
  3529. // res.set_redirect("/2");
  3530. res.set_redirect(redirect_url);
  3531. });
  3532. svr.Get("/2", [&](const Request &req, Response &res) {
  3533. auto host_header = req.headers.find("Host");
  3534. ASSERT_TRUE(host_header != req.headers.end());
  3535. EXPECT_EQ(expected_host, host_header->second);
  3536. res.set_content("Hello World!", "text/plain");
  3537. });
  3538. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3539. auto se = detail::scope_exit([&] {
  3540. svr.stop();
  3541. th.join();
  3542. ASSERT_FALSE(svr.is_running());
  3543. });
  3544. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3545. // actually starts anything, so the condition !svr.is_running() will
  3546. // always remain true, and the loop never stops.
  3547. // This basically counts how many milliseconds have passed since the
  3548. // call to svr.listen(), and if after 5 seconds nothing started yet
  3549. // aborts the test.
  3550. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3551. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3552. ASSERT_LT(milliseconds, 5000U);
  3553. }
  3554. {
  3555. Client cli("::1", PORT);
  3556. cli.set_follow_location(true);
  3557. std::string body;
  3558. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3559. body.append(data, data_length);
  3560. return true;
  3561. });
  3562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3563. EXPECT_EQ(StatusCode::OK_200, res->status);
  3564. EXPECT_EQ("Hello World!", body);
  3565. }
  3566. {
  3567. Client cli("::1", PORT);
  3568. std::string body;
  3569. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3570. body.append(data, data_length);
  3571. return true;
  3572. });
  3573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3574. EXPECT_EQ(StatusCode::Found_302, res->status);
  3575. EXPECT_EQ("___", body);
  3576. }
  3577. }
  3578. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3579. Server svr;
  3580. svr.Get("/foo", [](const Request &req, Response &res) {
  3581. auto a = req.params.find("a");
  3582. if (a != req.params.end()) {
  3583. res.set_content((*a).second, "text/plain");
  3584. res.status = StatusCode::OK_200;
  3585. } else {
  3586. res.status = StatusCode::BadRequest_400;
  3587. }
  3588. });
  3589. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3590. auto se = detail::scope_exit([&] {
  3591. svr.stop();
  3592. thread.join();
  3593. ASSERT_FALSE(svr.is_running());
  3594. });
  3595. svr.wait_until_ready();
  3596. {
  3597. Client cli(HOST, PORT);
  3598. cli.set_path_encode(false);
  3599. auto res = cli.Get("/foo?a=explicitly+encoded");
  3600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3601. EXPECT_EQ(StatusCode::OK_200, res->status);
  3602. // This expects it back with a space, as the `+` won't have been
  3603. // url-encoded, and server-side the params get decoded turning `+`
  3604. // into spaces.
  3605. EXPECT_EQ("explicitly encoded", res->body);
  3606. }
  3607. }
  3608. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3609. // When path encoding is disabled the client must transmit the supplied
  3610. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3611. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3612. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3613. // than a space (0x20). Assert on the raw wire target to catch this.
  3614. Server svr;
  3615. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3616. svr.Get("/foo", [&](const Request &req, Response &res) {
  3617. EXPECT_EQ(expected_target, req.target);
  3618. res.status = StatusCode::OK_200;
  3619. });
  3620. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3621. auto se = detail::scope_exit([&] {
  3622. svr.stop();
  3623. thread.join();
  3624. ASSERT_FALSE(svr.is_running());
  3625. });
  3626. svr.wait_until_ready();
  3627. {
  3628. Client cli(HOST, PORT);
  3629. cli.set_path_encode(false);
  3630. auto res = cli.Get(expected_target.c_str());
  3631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3632. EXPECT_EQ(StatusCode::OK_200, res->status);
  3633. }
  3634. }
  3635. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3636. // `open_stream()` used to skip the path encoding that the buffered send
  3637. // path applies, so the same `path` produced different bytes in the request
  3638. // line depending on which API was used. Assert the two agree.
  3639. Server svr;
  3640. std::string target;
  3641. svr.Get(".*", [&](const Request &req, Response &res) {
  3642. target = req.target;
  3643. res.status = StatusCode::OK_200;
  3644. });
  3645. auto port = svr.bind_to_any_port(HOST);
  3646. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3647. auto se = detail::scope_exit([&] {
  3648. svr.stop();
  3649. thread.join();
  3650. ASSERT_FALSE(svr.is_running());
  3651. });
  3652. svr.wait_until_ready();
  3653. struct {
  3654. const char *path;
  3655. const char *expected;
  3656. } cases[] = {
  3657. {"/a b?x=1", "/a%20b?x=1"},
  3658. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3659. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3660. };
  3661. for (const auto &c : cases) {
  3662. Client cli(HOST, port);
  3663. target.clear();
  3664. auto res = cli.Get(c.path);
  3665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3666. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3667. auto buffered_target = target;
  3668. target.clear();
  3669. auto handle = cli.open_stream("GET", c.path);
  3670. EXPECT_TRUE(handle.is_valid())
  3671. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3672. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3673. }
  3674. }
  3675. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3676. // The `set_path_encode(false)` contract — transmit the supplied target
  3677. // verbatim — must hold for the streaming API too.
  3678. Server svr;
  3679. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3680. std::string target;
  3681. svr.Get("/foo", [&](const Request &req, Response &res) {
  3682. target = req.target;
  3683. res.status = StatusCode::OK_200;
  3684. });
  3685. auto port = svr.bind_to_any_port(HOST);
  3686. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3687. auto se = detail::scope_exit([&] {
  3688. svr.stop();
  3689. thread.join();
  3690. ASSERT_FALSE(svr.is_running());
  3691. });
  3692. svr.wait_until_ready();
  3693. {
  3694. Client cli(HOST, port);
  3695. cli.set_path_encode(false);
  3696. auto handle = cli.open_stream("GET", expected_target);
  3697. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3698. EXPECT_EQ(expected_target, target);
  3699. }
  3700. }
  3701. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3702. // With path encoding enabled a CR/LF in the target is percent-encoded
  3703. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3704. // write_request_line still backstops `set_path_encode(false)`, which is
  3705. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3706. Server svr;
  3707. // Captured before routing: the decoded path contains a newline, which a
  3708. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3709. std::string target;
  3710. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3711. target = req.target;
  3712. res.status = StatusCode::OK_200;
  3713. return Server::HandlerResponse::Handled;
  3714. });
  3715. auto port = svr.bind_to_any_port(HOST);
  3716. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3717. auto se = detail::scope_exit([&] {
  3718. svr.stop();
  3719. thread.join();
  3720. ASSERT_FALSE(svr.is_running());
  3721. });
  3722. svr.wait_until_ready();
  3723. {
  3724. Client cli(HOST, port);
  3725. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3726. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3727. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3728. }
  3729. }
  3730. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3731. // Every control character is percent-encoded, not just CR/LF, so the target
  3732. // passes the request-target check in write_request_line.
  3733. Server svr;
  3734. std::string target;
  3735. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3736. target = req.target;
  3737. res.status = StatusCode::OK_200;
  3738. return Server::HandlerResponse::Handled;
  3739. });
  3740. auto port = svr.bind_to_any_port(HOST);
  3741. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3742. auto se = detail::scope_exit([&] {
  3743. svr.stop();
  3744. thread.join();
  3745. ASSERT_FALSE(svr.is_running());
  3746. });
  3747. svr.wait_until_ready();
  3748. {
  3749. Client cli(HOST, port);
  3750. auto res = cli.Get("/a\tb\x1b\x7f");
  3751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3752. EXPECT_EQ("/a%09b%1B%7F", target);
  3753. }
  3754. }
  3755. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3756. // Nothing may reach the wire: a raw CR/LF target would split the request
  3757. // line and inject headers.
  3758. Server svr;
  3759. // Pre-routing so that "not called" means nothing reached the server at all,
  3760. // rather than merely failing to match a handler pattern.
  3761. auto handler_called = false;
  3762. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3763. handler_called = true;
  3764. res.status = StatusCode::OK_200;
  3765. return Server::HandlerResponse::Handled;
  3766. });
  3767. auto port = svr.bind_to_any_port(HOST);
  3768. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3769. auto se = detail::scope_exit([&] {
  3770. svr.stop();
  3771. thread.join();
  3772. ASSERT_FALSE(svr.is_running());
  3773. });
  3774. svr.wait_until_ready();
  3775. {
  3776. Client cli(HOST, port);
  3777. cli.set_path_encode(false);
  3778. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3779. EXPECT_FALSE(handle.is_valid());
  3780. EXPECT_EQ(Error::Write, handle.error);
  3781. EXPECT_FALSE(handler_called);
  3782. }
  3783. }
  3784. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3785. // Which of the two branches runs is decided by whether the query component
  3786. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3787. // an empty query and must still fall back to building one from
  3788. // `req.params`, while a non-empty query must win over `req.params`.
  3789. Server svr;
  3790. std::string target;
  3791. svr.Get("/foo", [&](const Request &req, Response &res) {
  3792. target = req.target;
  3793. res.status = StatusCode::OK_200;
  3794. });
  3795. auto port = svr.bind_to_any_port(HOST);
  3796. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3797. auto se = detail::scope_exit([&] {
  3798. svr.stop();
  3799. thread.join();
  3800. ASSERT_FALSE(svr.is_running());
  3801. });
  3802. svr.wait_until_ready();
  3803. {
  3804. // Trailing `?` -> empty query component -> `req.params` is used.
  3805. Client cli(HOST, port);
  3806. Request req;
  3807. req.method = "GET";
  3808. req.path = "/foo?";
  3809. req.params.emplace("a", "1");
  3810. target.clear();
  3811. auto res = cli.send(req);
  3812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3813. EXPECT_EQ("/foo?a=1", target);
  3814. }
  3815. {
  3816. // Non-empty query in `req.path` -> `req.params` is not appended.
  3817. Client cli(HOST, port);
  3818. Request req;
  3819. req.method = "GET";
  3820. req.path = "/foo?b=2";
  3821. req.params.emplace("a", "1");
  3822. target.clear();
  3823. auto res = cli.send(req);
  3824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3825. EXPECT_EQ("/foo?b=2", target);
  3826. }
  3827. }
  3828. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3829. Server svr;
  3830. svr.Get("/", [](const Request &req, Response &) {
  3831. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3832. });
  3833. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3834. auto se = detail::scope_exit([&] {
  3835. svr.stop();
  3836. thread.join();
  3837. ASSERT_FALSE(svr.is_running());
  3838. });
  3839. svr.wait_until_ready();
  3840. {
  3841. Client cli(HOST, PORT);
  3842. cli.set_path_encode(false);
  3843. auto res = cli.Get("/?something=%0A");
  3844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3845. EXPECT_EQ(StatusCode::OK_200, res->status);
  3846. }
  3847. }
  3848. TEST(BindServerTest, BindDualStack) {
  3849. Server svr;
  3850. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3851. res.set_content("Hello World!", "text/plain");
  3852. });
  3853. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3854. auto se = detail::scope_exit([&] {
  3855. svr.stop();
  3856. thread.join();
  3857. ASSERT_FALSE(svr.is_running());
  3858. });
  3859. svr.wait_until_ready();
  3860. {
  3861. Client cli("127.0.0.1", PORT);
  3862. auto res = cli.Get("/1");
  3863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3864. EXPECT_EQ(StatusCode::OK_200, res->status);
  3865. EXPECT_EQ("Hello World!", res->body);
  3866. }
  3867. {
  3868. Client cli("::1", PORT);
  3869. auto res = cli.Get("/1");
  3870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3871. EXPECT_EQ(StatusCode::OK_200, res->status);
  3872. EXPECT_EQ("Hello World!", res->body);
  3873. }
  3874. }
  3875. TEST(BindServerTest, BindAndListenSeparately) {
  3876. Server svr;
  3877. int port = svr.bind_to_any_port("0.0.0.0");
  3878. ASSERT_TRUE(svr.is_valid());
  3879. ASSERT_TRUE(port > 0);
  3880. svr.stop();
  3881. }
  3882. // Reports whether anything is still listening on a loopback port. A plain
  3883. // connect() is used instead of a Client request because a socket left bound by
  3884. // mistake accepts the connection into its backlog and never answers, which
  3885. // would hang the test instead of failing it.
  3886. static bool is_loopback_port_accepting(int port) {
  3887. sockaddr_in addr{};
  3888. addr.sin_family = AF_INET;
  3889. addr.sin_port = htons(static_cast<uint16_t>(port));
  3890. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3891. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3892. EXPECT_NE(sock, INVALID_SOCKET);
  3893. if (sock == INVALID_SOCKET) { return false; }
  3894. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3895. static_cast<socklen_t>(sizeof(addr)));
  3896. detail::close_socket(sock);
  3897. return ret == 0;
  3898. }
  3899. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3900. Server svr;
  3901. auto port = svr.bind_to_any_port("127.0.0.1");
  3902. ASSERT_TRUE(port > 0);
  3903. svr.stop();
  3904. // bind_to_any_port() already called listen(2), so until stop() closed the
  3905. // descriptor the port kept accepting connections into the backlog. ASSERT
  3906. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3907. // below blocks forever in the accept loop.
  3908. ASSERT_FALSE(is_loopback_port_accepting(port));
  3909. // Nothing is left to accept on, so listen_after_bind() must report failure
  3910. // instead of returning success without ever serving.
  3911. EXPECT_FALSE(svr.listen_after_bind());
  3912. // The failed listen marks the server decommissioned, so a waiter returns
  3913. // instead of spinning forever.
  3914. svr.wait_until_ready();
  3915. }
  3916. #ifdef CPPHTTPLIB_SSL_ENABLED
  3917. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3918. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3919. CLIENT_CA_CERT_DIR);
  3920. int port = svr.bind_to_any_port("0.0.0.0");
  3921. ASSERT_TRUE(svr.is_valid());
  3922. ASSERT_TRUE(port > 0);
  3923. svr.stop();
  3924. }
  3925. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3926. // or a rejected CustomRoute() registration would not stop the server binding.
  3927. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3928. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3929. CLIENT_CA_CERT_DIR);
  3930. ASSERT_TRUE(svr.is_valid());
  3931. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3932. EXPECT_FALSE(svr.is_valid());
  3933. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3934. }
  3935. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3936. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3937. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3938. int port = svr.bind_to_any_port("0.0.0.0");
  3939. ASSERT_TRUE(svr.is_valid());
  3940. ASSERT_TRUE(port > 0);
  3941. svr.stop();
  3942. }
  3943. TEST(BindServerTest, UpdateCertsPem) {
  3944. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3945. int port = svr.bind_to_any_port("0.0.0.0");
  3946. ASSERT_TRUE(svr.is_valid());
  3947. ASSERT_TRUE(port > 0);
  3948. // Read PEM files
  3949. std::string cert_pem, key_pem, ca_pem;
  3950. read_file(SERVER_CERT_FILE, cert_pem);
  3951. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3952. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3953. // Update server certificates using PEM API
  3954. ASSERT_TRUE(
  3955. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3956. ASSERT_TRUE(svr.is_valid());
  3957. svr.stop();
  3958. }
  3959. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3960. // Start server with client CA (enables client auth)
  3961. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3962. ASSERT_TRUE(svr.is_valid());
  3963. bool handler_called = false;
  3964. svr.Get("/test", [&](const Request &req, Response &res) {
  3965. handler_called = true;
  3966. // Verify client certificate is present
  3967. auto cert = req.peer_cert();
  3968. EXPECT_TRUE(static_cast<bool>(cert));
  3969. res.set_content("ok", "text/plain");
  3970. });
  3971. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3972. auto se = detail::scope_exit([&] {
  3973. svr.stop();
  3974. t.join();
  3975. ASSERT_FALSE(svr.is_running());
  3976. });
  3977. svr.wait_until_ready();
  3978. // Read PEM files
  3979. std::string cert_pem, key_pem, ca_pem;
  3980. read_file(SERVER_CERT_FILE, cert_pem);
  3981. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3982. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3983. // Update server certificates and client CA using PEM API while server running
  3984. ASSERT_TRUE(
  3985. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3986. // Connect with client certificate
  3987. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3988. cli.enable_server_certificate_verification(false);
  3989. cli.set_connection_timeout(30);
  3990. auto res = cli.Get("/test");
  3991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3992. ASSERT_EQ(StatusCode::OK_200, res->status);
  3993. ASSERT_TRUE(handler_called);
  3994. EXPECT_EQ("ok", res->body);
  3995. }
  3996. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  3997. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3998. ASSERT_TRUE(svr.is_valid());
  3999. svr.Get("/test", [](const Request &, Response &res) {
  4000. res.set_content("ok", "text/plain");
  4001. });
  4002. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4003. auto se = detail::scope_exit([&] {
  4004. svr.stop();
  4005. t.join();
  4006. ASSERT_FALSE(svr.is_running());
  4007. });
  4008. svr.wait_until_ready();
  4009. auto get = [] {
  4010. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4011. cli.enable_server_certificate_verification(false);
  4012. return cli.Get("/test");
  4013. };
  4014. ASSERT_TRUE(get());
  4015. // A CA that did not sign the client's certificate takes the old one's place.
  4016. std::string cert_pem, key_pem, ca_pem;
  4017. read_file(SERVER_CERT_FILE, cert_pem);
  4018. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4019. read_file(SERVER_CERT2_FILE, ca_pem);
  4020. ASSERT_TRUE(
  4021. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4022. EXPECT_FALSE(get());
  4023. }
  4024. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4025. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4026. ASSERT_TRUE(svr.is_valid());
  4027. svr.Get("/test", [](const Request &, Response &res) {
  4028. res.set_content("ok", "text/plain");
  4029. });
  4030. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4031. auto se = detail::scope_exit([&] {
  4032. svr.stop();
  4033. t.join();
  4034. ASSERT_FALSE(svr.is_running());
  4035. });
  4036. svr.wait_until_ready();
  4037. // A connection that sends no ClientHello keeps its handshake in progress,
  4038. // once the server has had a moment to start it.
  4039. auto error = Error::Success;
  4040. auto sock = detail::create_client_socket(
  4041. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4042. /*connection_timeout_sec=*/5, 0,
  4043. /*read_timeout_sec=*/5, 0,
  4044. /*write_timeout_sec=*/5, 0, std::string(), error);
  4045. ASSERT_NE(INVALID_SOCKET, sock);
  4046. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4047. std::string cert_pem, key_pem;
  4048. read_file(SERVER_CERT_FILE, cert_pem);
  4049. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4050. auto update = std::async(std::launch::async, [&]() {
  4051. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4052. });
  4053. EXPECT_EQ(std::future_status::timeout,
  4054. update.wait_for(std::chrono::milliseconds(200)));
  4055. detail::close_socket(sock);
  4056. EXPECT_TRUE(update.get());
  4057. SSLClient cli(HOST, PORT);
  4058. cli.enable_server_certificate_verification(false);
  4059. auto res = cli.Get("/test");
  4060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4061. EXPECT_EQ(StatusCode::OK_200, res->status);
  4062. }
  4063. #endif
  4064. TEST(ErrorHandlerTest, ContentLength) {
  4065. Server svr;
  4066. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4067. res.status = StatusCode::OK_200;
  4068. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4069. "text/html"); // <= Content-Length still 13
  4070. });
  4071. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4072. res.set_content("Hello World!\n", "text/plain");
  4073. res.status = 524;
  4074. });
  4075. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4076. auto se = detail::scope_exit([&] {
  4077. svr.stop();
  4078. thread.join();
  4079. ASSERT_FALSE(svr.is_running());
  4080. });
  4081. svr.wait_until_ready();
  4082. {
  4083. Client cli(HOST, PORT);
  4084. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4086. EXPECT_EQ(StatusCode::OK_200, res->status);
  4087. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4088. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4089. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4090. }
  4091. }
  4092. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4093. TEST(ExceptionTest, WithoutExceptionHandler) {
  4094. Server svr;
  4095. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4096. throw std::runtime_error("exception...");
  4097. });
  4098. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4099. throw std::runtime_error("exception\r\n...");
  4100. });
  4101. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4102. auto se = detail::scope_exit([&] {
  4103. svr.stop();
  4104. listen_thread.join();
  4105. ASSERT_FALSE(svr.is_running());
  4106. });
  4107. svr.wait_until_ready();
  4108. Client cli("localhost", PORT);
  4109. {
  4110. auto res = cli.Get("/exception");
  4111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4112. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4113. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4114. }
  4115. {
  4116. auto res = cli.Get("/unknown");
  4117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4118. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4119. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4120. }
  4121. }
  4122. TEST(ExceptionTest, WithExceptionHandler) {
  4123. Server svr;
  4124. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4125. std::exception_ptr ep) {
  4126. EXPECT_FALSE(ep == nullptr);
  4127. try {
  4128. std::rethrow_exception(ep);
  4129. } catch (std::exception &e) {
  4130. EXPECT_EQ("abc", std::string(e.what()));
  4131. } catch (...) {}
  4132. res.status = StatusCode::InternalServerError_500;
  4133. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4134. "text/html"); // <= Content-Length still 13 at this point
  4135. });
  4136. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4137. res.set_content("Hello World!\n", "text/plain");
  4138. throw std::runtime_error("abc");
  4139. });
  4140. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4141. auto se = detail::scope_exit([&] {
  4142. svr.stop();
  4143. thread.join();
  4144. ASSERT_FALSE(svr.is_running());
  4145. });
  4146. svr.wait_until_ready();
  4147. for (size_t i = 0; i < 10; i++) {
  4148. Client cli(HOST, PORT);
  4149. for (size_t j = 0; j < 100; j++) {
  4150. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4152. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4153. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4154. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4155. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4156. }
  4157. cli.set_keep_alive(true);
  4158. for (size_t j = 0; j < 100; j++) {
  4159. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4161. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4162. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4163. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4164. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4165. }
  4166. }
  4167. }
  4168. TEST(ExceptionTest, AndErrorHandler) {
  4169. Server svr;
  4170. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4171. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4172. });
  4173. svr.set_exception_handler(
  4174. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4175. EXPECT_FALSE(ep == nullptr);
  4176. try {
  4177. std::rethrow_exception(ep);
  4178. } catch (std::exception &e) {
  4179. res.set_content(e.what(), "text/html");
  4180. } catch (...) {}
  4181. res.status = StatusCode::InternalServerError_500;
  4182. });
  4183. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4184. throw std::runtime_error("EXCEPTION");
  4185. });
  4186. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4187. res.set_content("ERROR", "text/html");
  4188. res.status = StatusCode::InternalServerError_500;
  4189. });
  4190. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4191. auto se = detail::scope_exit([&] {
  4192. svr.stop();
  4193. thread.join();
  4194. ASSERT_FALSE(svr.is_running());
  4195. });
  4196. svr.wait_until_ready();
  4197. Client cli(HOST, PORT);
  4198. {
  4199. auto res = cli.Get("/exception");
  4200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4201. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4202. EXPECT_EQ("EXCEPTION", res->body);
  4203. }
  4204. {
  4205. auto res = cli.Get("/error");
  4206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4207. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4208. EXPECT_EQ("ERROR", res->body);
  4209. }
  4210. {
  4211. auto res = cli.Get("/invalid");
  4212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4213. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4214. EXPECT_EQ("NOT_FOUND", res->body);
  4215. }
  4216. }
  4217. #endif
  4218. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4219. // process_request() wraps only routing() in a try/catch, so an exception from
  4220. // any other user callback used to unwind into the task queue - which does not
  4221. // catch - and terminate the process. Each test below runs the server on a
  4222. // single worker thread: a guard that catches the exception but still loses the
  4223. // thread would otherwise be hidden by a spare worker serving the follow-up
  4224. // request. Note that a regression here aborts the whole test binary rather
  4225. // than failing one test.
  4226. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4227. Server svr;
  4228. svr.new_task_queue = [] { return new ThreadPool(1); };
  4229. std::atomic<int> reported{0};
  4230. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4231. if (err == Error::UserCallbackException) { reported++; }
  4232. });
  4233. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4234. res.set_content_provider(
  4235. 1024, "text/plain",
  4236. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4237. sink.write("hello", 5);
  4238. throw std::runtime_error("from the content provider");
  4239. });
  4240. });
  4241. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4242. res.set_content("ok", "text/plain");
  4243. });
  4244. auto port = svr.bind_to_any_port(HOST);
  4245. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4246. auto se = detail::scope_exit([&] {
  4247. svr.stop();
  4248. listen_thread.join();
  4249. ASSERT_FALSE(svr.is_running());
  4250. });
  4251. svr.wait_until_ready();
  4252. {
  4253. Client cli(HOST, port);
  4254. cli.set_read_timeout(5, 0);
  4255. EXPECT_FALSE(cli.Get("/throw"));
  4256. }
  4257. EXPECT_TRUE(svr.is_running());
  4258. EXPECT_EQ(1, reported.load());
  4259. // A request on a fresh connection is still served.
  4260. {
  4261. Client cli(HOST, port);
  4262. auto res = cli.Get("/ok");
  4263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4264. EXPECT_EQ(StatusCode::OK_200, res->status);
  4265. EXPECT_EQ("ok", res->body);
  4266. }
  4267. }
  4268. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4269. Server svr;
  4270. svr.new_task_queue = [] { return new ThreadPool(1); };
  4271. std::atomic<bool> should_throw{true};
  4272. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4273. res.set_content("hi", "text/plain");
  4274. });
  4275. svr.set_post_routing_handler(
  4276. [&](const Request & /*req*/, Response & /*res*/) {
  4277. if (should_throw) {
  4278. throw std::runtime_error("from the post-routing handler");
  4279. }
  4280. });
  4281. auto port = svr.bind_to_any_port(HOST);
  4282. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4283. auto se = detail::scope_exit([&] {
  4284. svr.stop();
  4285. listen_thread.join();
  4286. ASSERT_FALSE(svr.is_running());
  4287. });
  4288. svr.wait_until_ready();
  4289. {
  4290. Client cli(HOST, port);
  4291. cli.set_read_timeout(5, 0);
  4292. EXPECT_FALSE(cli.Get("/hi"));
  4293. }
  4294. EXPECT_TRUE(svr.is_running());
  4295. should_throw = false;
  4296. {
  4297. Client cli(HOST, port);
  4298. auto res = cli.Get("/hi");
  4299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4300. EXPECT_EQ(StatusCode::OK_200, res->status);
  4301. EXPECT_EQ("hi", res->body);
  4302. }
  4303. }
  4304. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4305. // The guard reports the caught exception through the error logger, which is
  4306. // a user callback too. A logger that throws has to be contained as well, or
  4307. // the process would terminate from inside the catch.
  4308. Server svr;
  4309. svr.new_task_queue = [] { return new ThreadPool(1); };
  4310. std::atomic<int> reported{0};
  4311. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4312. if (err == Error::UserCallbackException) {
  4313. reported++;
  4314. throw std::runtime_error("from the error logger");
  4315. }
  4316. });
  4317. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4318. res.set_content_provider(
  4319. 1024, "text/plain",
  4320. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4321. sink.write("hello", 5);
  4322. throw std::runtime_error("from the content provider");
  4323. });
  4324. });
  4325. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4326. res.set_content("ok", "text/plain");
  4327. });
  4328. auto port = svr.bind_to_any_port(HOST);
  4329. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4330. auto se = detail::scope_exit([&] {
  4331. svr.stop();
  4332. listen_thread.join();
  4333. ASSERT_FALSE(svr.is_running());
  4334. });
  4335. svr.wait_until_ready();
  4336. {
  4337. Client cli(HOST, port);
  4338. cli.set_read_timeout(5, 0);
  4339. EXPECT_FALSE(cli.Get("/throw"));
  4340. }
  4341. EXPECT_TRUE(svr.is_running());
  4342. EXPECT_EQ(1, reported.load());
  4343. {
  4344. Client cli(HOST, port);
  4345. auto res = cli.Get("/ok");
  4346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4347. EXPECT_EQ(StatusCode::OK_200, res->status);
  4348. EXPECT_EQ("ok", res->body);
  4349. }
  4350. }
  4351. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4352. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4353. // so the exception unwinds through the ws::WebSocket object on its way to
  4354. // the guard. None of the HTTP cases above cross that.
  4355. Server svr;
  4356. svr.new_task_queue = [] { return new ThreadPool(1); };
  4357. std::atomic<int> reported{0};
  4358. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4359. if (err == Error::UserCallbackException) { reported++; }
  4360. });
  4361. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4362. throw std::runtime_error("from the WebSocket handler");
  4363. });
  4364. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4365. res.set_content("ok", "text/plain");
  4366. });
  4367. auto port = svr.bind_to_any_port(HOST);
  4368. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4369. auto se = detail::scope_exit([&] {
  4370. svr.stop();
  4371. listen_thread.join();
  4372. ASSERT_FALSE(svr.is_running());
  4373. });
  4374. svr.wait_until_ready();
  4375. {
  4376. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4377. "/ws");
  4378. auto res = client.connect();
  4379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4380. // The server dropped the connection instead of dying.
  4381. std::string msg;
  4382. EXPECT_FALSE(client.read(msg));
  4383. client.close();
  4384. }
  4385. EXPECT_TRUE(svr.is_running());
  4386. EXPECT_EQ(1, reported.load());
  4387. {
  4388. Client cli(HOST, port);
  4389. auto res = cli.Get("/ok");
  4390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4391. EXPECT_EQ(StatusCode::OK_200, res->status);
  4392. EXPECT_EQ("ok", res->body);
  4393. }
  4394. }
  4395. #ifdef CPPHTTPLIB_SSL_ENABLED
  4396. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4397. // SSLServer::process_and_close_socket() is a separate overload with its own
  4398. // guard, so it is exercised on its own.
  4399. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4400. ASSERT_TRUE(svr.is_valid());
  4401. svr.new_task_queue = [] { return new ThreadPool(1); };
  4402. std::atomic<int> reported{0};
  4403. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4404. if (err == Error::UserCallbackException) { reported++; }
  4405. });
  4406. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4407. res.set_content_provider(
  4408. 1024, "text/plain",
  4409. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4410. sink.write("hello", 5);
  4411. throw std::runtime_error("from the content provider");
  4412. });
  4413. });
  4414. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4415. res.set_content("ok", "text/plain");
  4416. });
  4417. auto port = svr.bind_to_any_port(HOST);
  4418. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4419. auto se = detail::scope_exit([&] {
  4420. svr.stop();
  4421. listen_thread.join();
  4422. ASSERT_FALSE(svr.is_running());
  4423. });
  4424. svr.wait_until_ready();
  4425. {
  4426. SSLClient cli(HOST, port);
  4427. cli.enable_server_certificate_verification(false);
  4428. cli.set_read_timeout(5, 0);
  4429. EXPECT_FALSE(cli.Get("/throw"));
  4430. }
  4431. EXPECT_TRUE(svr.is_running());
  4432. EXPECT_EQ(1, reported.load());
  4433. {
  4434. SSLClient cli(HOST, port);
  4435. cli.enable_server_certificate_verification(false);
  4436. auto res = cli.Get("/ok");
  4437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4438. EXPECT_EQ(StatusCode::OK_200, res->status);
  4439. EXPECT_EQ("ok", res->body);
  4440. }
  4441. }
  4442. #endif
  4443. #endif
  4444. TEST(NoContentTest, ContentLength) {
  4445. Server svr;
  4446. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4447. res.status = StatusCode::NoContent_204;
  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");
  4459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4460. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4461. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4462. }
  4463. }
  4464. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4465. #ifdef CPPHTTPLIB_SSL_ENABLED
  4466. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4467. ASSERT_TRUE(svr.is_valid());
  4468. #else
  4469. Server svr;
  4470. #endif
  4471. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4472. if (req.path == "/routing_handler") {
  4473. res.set_header("PRE_ROUTING", "on");
  4474. res.set_content("Routing Handler", "text/plain");
  4475. return httplib::Server::HandlerResponse::Handled;
  4476. }
  4477. return httplib::Server::HandlerResponse::Unhandled;
  4478. });
  4479. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4480. res.set_content("Error", "text/html");
  4481. });
  4482. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4483. if (req.path == "/routing_handler") {
  4484. res.set_header("POST_ROUTING", "on");
  4485. }
  4486. });
  4487. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4488. res.set_content("Hello World!\n", "text/plain");
  4489. });
  4490. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4491. auto se = detail::scope_exit([&] {
  4492. svr.stop();
  4493. thread.join();
  4494. ASSERT_FALSE(svr.is_running());
  4495. });
  4496. svr.wait_until_ready();
  4497. {
  4498. #ifdef CPPHTTPLIB_SSL_ENABLED
  4499. SSLClient cli(HOST, PORT);
  4500. cli.enable_server_certificate_verification(false);
  4501. #else
  4502. Client cli(HOST, PORT);
  4503. #endif
  4504. auto res = cli.Get("/routing_handler");
  4505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4506. EXPECT_EQ(StatusCode::OK_200, res->status);
  4507. EXPECT_EQ("Routing Handler", res->body);
  4508. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4509. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4510. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4511. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4512. }
  4513. {
  4514. #ifdef CPPHTTPLIB_SSL_ENABLED
  4515. SSLClient cli(HOST, PORT);
  4516. cli.enable_server_certificate_verification(false);
  4517. #else
  4518. Client cli(HOST, PORT);
  4519. #endif
  4520. auto res = cli.Get("/hi");
  4521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4522. EXPECT_EQ(StatusCode::OK_200, res->status);
  4523. EXPECT_EQ("Hello World!\n", res->body);
  4524. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4525. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4526. }
  4527. {
  4528. #ifdef CPPHTTPLIB_SSL_ENABLED
  4529. SSLClient cli(HOST, PORT);
  4530. cli.enable_server_certificate_verification(false);
  4531. #else
  4532. Client cli(HOST, PORT);
  4533. #endif
  4534. auto res = cli.Get("/aaa");
  4535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4536. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4537. EXPECT_EQ("Error", res->body);
  4538. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4539. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4540. }
  4541. }
  4542. TEST(RequestHandlerTest, PreRequestHandler) {
  4543. auto route_path = "/user/:user";
  4544. Server svr;
  4545. svr.Get("/hi", [](const Request &, Response &res) {
  4546. res.set_content("hi", "text/plain");
  4547. });
  4548. svr.Get(route_path, [](const Request &req, Response &res) {
  4549. res.set_content(req.path_params.at("user"), "text/plain");
  4550. });
  4551. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4552. if (req.matched_route == route_path) {
  4553. auto user = req.path_params.at("user");
  4554. if (user != "john") {
  4555. res.status = StatusCode::Forbidden_403;
  4556. res.set_content("error", "text/html");
  4557. return Server::HandlerResponse::Handled;
  4558. }
  4559. }
  4560. return Server::HandlerResponse::Unhandled;
  4561. });
  4562. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4563. auto se = detail::scope_exit([&] {
  4564. svr.stop();
  4565. thread.join();
  4566. ASSERT_FALSE(svr.is_running());
  4567. });
  4568. svr.wait_until_ready();
  4569. Client cli(HOST, PORT);
  4570. {
  4571. auto res = cli.Get("/hi");
  4572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4573. EXPECT_EQ(StatusCode::OK_200, res->status);
  4574. EXPECT_EQ("hi", res->body);
  4575. }
  4576. {
  4577. auto res = cli.Get("/user/john");
  4578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4579. EXPECT_EQ(StatusCode::OK_200, res->status);
  4580. EXPECT_EQ("john", res->body);
  4581. }
  4582. {
  4583. auto res = cli.Get("/user/invalid-user");
  4584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4585. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4586. EXPECT_EQ("error", res->body);
  4587. }
  4588. }
  4589. // The pre-request handler must run before the request body is read, so a
  4590. // rejected request never forces the server to buffer a (potentially large)
  4591. // body. Here the posted body is larger than the payload limit: if the body
  4592. // were read first the server would answer 413, but because the pre-request
  4593. // handler runs first it answers 403 and the body is never read.
  4594. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4595. Server svr;
  4596. svr.set_payload_max_length(8);
  4597. auto handler_ran = false;
  4598. svr.Post("/reject", [&](const Request &req, Response &res) {
  4599. handler_ran = true;
  4600. res.set_content(req.body, "text/plain");
  4601. });
  4602. svr.Post("/accept", [](const Request &req, Response &res) {
  4603. res.set_content(req.body, "text/plain");
  4604. });
  4605. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4606. if (req.matched_route == "/reject") {
  4607. res.status = StatusCode::Forbidden_403;
  4608. res.set_content("denied", "text/plain");
  4609. return Server::HandlerResponse::Handled;
  4610. }
  4611. return Server::HandlerResponse::Unhandled;
  4612. });
  4613. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4614. auto se = detail::scope_exit([&] {
  4615. svr.stop();
  4616. thread.join();
  4617. ASSERT_FALSE(svr.is_running());
  4618. });
  4619. svr.wait_until_ready();
  4620. Client cli(HOST, PORT);
  4621. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4622. // rejects with 403 before the body is read, so 413 is never reached.
  4623. {
  4624. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4626. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4627. EXPECT_EQ("denied", res->body);
  4628. EXPECT_FALSE(handler_ran);
  4629. }
  4630. // An approved route still reads the body and enforces the payload limit.
  4631. {
  4632. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4634. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4635. }
  4636. }
  4637. TEST(UserDataTest, BasicOperations) {
  4638. httplib::UserData ud;
  4639. // Initially empty
  4640. EXPECT_FALSE(ud.has("key"));
  4641. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4642. // set and get
  4643. ud.set("key", 42);
  4644. EXPECT_TRUE(ud.has("key"));
  4645. auto *p = ud.get<int>("key");
  4646. ASSERT_NE(nullptr, p);
  4647. EXPECT_EQ(42, *p);
  4648. // Type mismatch → nullptr
  4649. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4650. // Overwrite with different type
  4651. ud.set("key", std::string("hello"));
  4652. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4653. auto *s = ud.get<std::string>("key");
  4654. ASSERT_NE(nullptr, s);
  4655. EXPECT_EQ("hello", *s);
  4656. // erase
  4657. ud.erase("key");
  4658. EXPECT_FALSE(ud.has("key"));
  4659. // clear
  4660. ud.set("a", 1);
  4661. ud.set("b", 2);
  4662. ud.clear();
  4663. EXPECT_FALSE(ud.has("a"));
  4664. EXPECT_FALSE(ud.has("b"));
  4665. }
  4666. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4667. struct AuthCtx {
  4668. std::string user_id;
  4669. };
  4670. Server svr;
  4671. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4672. res.user_data.set("auth", AuthCtx{"alice"});
  4673. return Server::HandlerResponse::Unhandled;
  4674. });
  4675. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4676. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4677. ASSERT_NE(nullptr, ctx);
  4678. res.set_content("Hello " + ctx->user_id, "text/plain");
  4679. });
  4680. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4681. auto se = detail::scope_exit([&] {
  4682. svr.stop();
  4683. thread.join();
  4684. ASSERT_FALSE(svr.is_running());
  4685. });
  4686. svr.wait_until_ready();
  4687. Client cli(HOST, PORT);
  4688. auto res = cli.Get("/me");
  4689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4690. EXPECT_EQ(StatusCode::OK_200, res->status);
  4691. EXPECT_EQ("Hello alice", res->body);
  4692. }
  4693. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4694. struct RoleCtx {
  4695. std::string role;
  4696. };
  4697. Server svr;
  4698. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4699. res.user_data.set("role", RoleCtx{"admin"});
  4700. return Server::HandlerResponse::Unhandled;
  4701. });
  4702. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4703. auto *ctx = res.user_data.get<RoleCtx>("role");
  4704. ASSERT_NE(nullptr, ctx);
  4705. res.set_content(ctx->role, "text/plain");
  4706. });
  4707. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4708. auto se = detail::scope_exit([&] {
  4709. svr.stop();
  4710. thread.join();
  4711. ASSERT_FALSE(svr.is_running());
  4712. });
  4713. svr.wait_until_ready();
  4714. Client cli(HOST, PORT);
  4715. auto res = cli.Get("/role");
  4716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4717. EXPECT_EQ(StatusCode::OK_200, res->status);
  4718. EXPECT_EQ("admin", res->body);
  4719. }
  4720. TEST(InvalidFormatTest, StatusCode) {
  4721. Server svr;
  4722. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4723. res.set_content("Hello World!\n", "text/plain");
  4724. res.status = 9999; // Status should be a three-digit code...
  4725. });
  4726. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4727. auto se = detail::scope_exit([&] {
  4728. svr.stop();
  4729. thread.join();
  4730. ASSERT_FALSE(svr.is_running());
  4731. });
  4732. svr.wait_until_ready();
  4733. {
  4734. Client cli(HOST, PORT);
  4735. auto res = cli.Get("/hi");
  4736. ASSERT_FALSE(res);
  4737. }
  4738. }
  4739. TEST(URLFragmentTest, WithFragment) {
  4740. Server svr;
  4741. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4742. EXPECT_TRUE(req.target == "/hi");
  4743. });
  4744. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4745. auto se = detail::scope_exit([&] {
  4746. svr.stop();
  4747. thread.join();
  4748. ASSERT_FALSE(svr.is_running());
  4749. });
  4750. svr.wait_until_ready();
  4751. {
  4752. Client cli(HOST, PORT);
  4753. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4754. EXPECT_TRUE(res);
  4755. EXPECT_EQ(StatusCode::OK_200, res->status);
  4756. res = cli.Get("/hi%23key1=val1=key2=val2");
  4757. EXPECT_TRUE(res);
  4758. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4759. }
  4760. }
  4761. TEST(HeaderWriter, SetHeaderWriter) {
  4762. Server svr;
  4763. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4764. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4765. return detail::write_headers(strm, hdrs);
  4766. });
  4767. svr.Get("/hi", [](const Request &req, Response &res) {
  4768. auto it = req.headers.find("CustomClientHeader");
  4769. EXPECT_TRUE(it != req.headers.end());
  4770. EXPECT_EQ(it->second, "CustomClientValue");
  4771. res.set_content("Hello World!\n", "text/plain");
  4772. });
  4773. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4774. auto se = detail::scope_exit([&] {
  4775. svr.stop();
  4776. thread.join();
  4777. ASSERT_FALSE(svr.is_running());
  4778. });
  4779. svr.wait_until_ready();
  4780. {
  4781. Client cli(HOST, PORT);
  4782. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4783. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4784. return detail::write_headers(strm, hdrs);
  4785. });
  4786. auto res = cli.Get("/hi");
  4787. EXPECT_TRUE(res);
  4788. EXPECT_EQ(StatusCode::OK_200, res->status);
  4789. auto it = res->headers.find("CustomServerHeader");
  4790. EXPECT_TRUE(it != res->headers.end());
  4791. EXPECT_EQ(it->second, "CustomServerValue");
  4792. }
  4793. }
  4794. class ServerTest : public ::testing::Test {
  4795. protected:
  4796. ServerTest()
  4797. : cli_(HOST, PORT)
  4798. #ifdef CPPHTTPLIB_SSL_ENABLED
  4799. ,
  4800. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4801. #endif
  4802. {
  4803. #ifdef CPPHTTPLIB_SSL_ENABLED
  4804. cli_.enable_server_certificate_verification(false);
  4805. #endif
  4806. // Allow LARGE_DATA (100MB) responses
  4807. cli_.set_payload_max_length(200 * 1024 * 1024);
  4808. }
  4809. virtual void SetUp() {
  4810. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4811. svr_.set_payload_max_length(200 * 1024 * 1024);
  4812. svr_.set_mount_point("/", "./www");
  4813. svr_.set_mount_point("/mount", "./www2");
  4814. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4815. svr_.Get("/hi",
  4816. [&](const Request & /*req*/, Response &res) {
  4817. res.set_content("Hello World!", "text/plain");
  4818. })
  4819. .Get("/file_content",
  4820. [&](const Request & /*req*/, Response &res) {
  4821. res.set_file_content("./www/dir/test.html");
  4822. })
  4823. .Get("/file_content_with_content_type",
  4824. [&](const Request & /*req*/, Response &res) {
  4825. res.set_file_content("./www/file", "text/plain");
  4826. })
  4827. .Get("/invalid_file_content",
  4828. [&](const Request & /*req*/, Response &res) {
  4829. res.set_file_content("./www/dir/invalid_file_path");
  4830. })
  4831. .Get("/http_response_splitting",
  4832. [&](const Request & /*req*/, Response &res) {
  4833. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4834. EXPECT_EQ(0U, res.headers.size());
  4835. EXPECT_FALSE(res.has_header("a"));
  4836. res.set_header("a", "1\nSet-Cookie: a=1");
  4837. EXPECT_EQ(0U, res.headers.size());
  4838. EXPECT_FALSE(res.has_header("a"));
  4839. res.set_header("a", "1\rSet-Cookie: a=1");
  4840. EXPECT_EQ(0U, res.headers.size());
  4841. EXPECT_FALSE(res.has_header("a"));
  4842. res.set_header("a\r\nb", "0");
  4843. EXPECT_EQ(0U, res.headers.size());
  4844. EXPECT_FALSE(res.has_header("a"));
  4845. res.set_header("a\rb", "0");
  4846. EXPECT_EQ(0U, res.headers.size());
  4847. EXPECT_FALSE(res.has_header("a"));
  4848. res.set_header("a\nb", "0");
  4849. EXPECT_EQ(0U, res.headers.size());
  4850. EXPECT_FALSE(res.has_header("a"));
  4851. res.set_redirect("1\r\nSet-Cookie: a=1");
  4852. EXPECT_EQ(0U, res.headers.size());
  4853. EXPECT_FALSE(res.has_header("Location"));
  4854. })
  4855. .Get("/slow",
  4856. [&](const Request & /*req*/, Response &res) {
  4857. std::this_thread::sleep_for(std::chrono::seconds(4));
  4858. res.set_content("slow", "text/plain");
  4859. })
  4860. #if 0
  4861. .Post("/slowpost",
  4862. [&](const Request & /*req*/, Response &res) {
  4863. std::this_thread::sleep_for(std::chrono::seconds(2));
  4864. res.set_content("slow", "text/plain");
  4865. })
  4866. #endif
  4867. .Get("/remote_addr",
  4868. [&](const Request &req, Response &res) {
  4869. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4870. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4871. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4872. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4873. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4874. #endif
  4875. res.set_content(req.remote_addr, "text/plain");
  4876. })
  4877. .Get("/local_addr",
  4878. [&](const Request &req, Response &res) {
  4879. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4880. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4881. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4882. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4883. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4884. #endif
  4885. auto local_addr = req.local_addr;
  4886. auto local_port = std::to_string(req.local_port);
  4887. res.set_content(local_addr.append(":").append(local_port),
  4888. "text/plain");
  4889. })
  4890. .Get("/endwith%",
  4891. [&](const Request & /*req*/, Response &res) {
  4892. res.set_content("Hello World!", "text/plain");
  4893. })
  4894. .Get("/a\\+\\+b",
  4895. [&](const Request &req, Response &res) {
  4896. ASSERT_TRUE(req.has_param("a +b"));
  4897. auto val = req.get_param_value("a +b");
  4898. res.set_content(val, "text/plain");
  4899. })
  4900. .Get("/", [&](const Request & /*req*/,
  4901. Response &res) { res.set_redirect("/hi"); })
  4902. .Post("/1",
  4903. [](const Request & /*req*/, Response &res) {
  4904. res.set_redirect("/2", StatusCode::SeeOther_303);
  4905. })
  4906. .Get("/2",
  4907. [](const Request & /*req*/, Response &res) {
  4908. res.set_content("redirected.", "text/plain");
  4909. res.status = StatusCode::OK_200;
  4910. })
  4911. .Post("/person",
  4912. [&](const Request &req, Response &res) {
  4913. if (req.has_param("name") && req.has_param("note")) {
  4914. persons_[req.get_param_value("name")] =
  4915. req.get_param_value("note");
  4916. } else {
  4917. res.status = StatusCode::BadRequest_400;
  4918. }
  4919. })
  4920. .Put("/person",
  4921. [&](const Request &req, Response &res) {
  4922. if (req.has_param("name") && req.has_param("note")) {
  4923. persons_[req.get_param_value("name")] =
  4924. req.get_param_value("note");
  4925. } else {
  4926. res.status = StatusCode::BadRequest_400;
  4927. }
  4928. })
  4929. .Get("/person/(.*)",
  4930. [&](const Request &req, Response &res) {
  4931. string name = req.matches[1];
  4932. if (persons_.find(name) != persons_.end()) {
  4933. auto note = persons_[name];
  4934. res.set_content(note, "text/plain");
  4935. } else {
  4936. res.status = StatusCode::NotFound_404;
  4937. }
  4938. })
  4939. .Delete("/person",
  4940. [&](const Request &req, Response &res) {
  4941. if (req.has_param("name")) {
  4942. string name = req.get_param_value("name");
  4943. if (persons_.find(name) != persons_.end()) {
  4944. persons_.erase(name);
  4945. res.set_content("DELETED", "text/plain");
  4946. } else {
  4947. res.status = StatusCode::NotFound_404;
  4948. }
  4949. } else {
  4950. res.status = StatusCode::BadRequest_400;
  4951. }
  4952. })
  4953. .Post("/x-www-form-urlencoded-json",
  4954. [&](const Request &req, Response &res) {
  4955. auto json = req.get_param_value("json");
  4956. ASSERT_EQ(JSON_DATA, json);
  4957. res.set_content(json, "appliation/json");
  4958. res.status = StatusCode::OK_200;
  4959. })
  4960. .Get("/streamed-chunked",
  4961. [&](const Request & /*req*/, Response &res) {
  4962. res.set_chunked_content_provider(
  4963. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4964. sink.os << "123";
  4965. sink.os << "456";
  4966. sink.os << "789";
  4967. sink.done();
  4968. return true;
  4969. });
  4970. })
  4971. .Get("/streamed-chunked-with-prohibited-trailer",
  4972. [&](const Request & /*req*/, Response &res) {
  4973. auto i = new int(0);
  4974. // Declare both a prohibited trailer (Content-Length) and an
  4975. // allowed one
  4976. res.set_header("Trailer", "Content-Length, X-Allowed");
  4977. res.set_chunked_content_provider(
  4978. "text/plain",
  4979. [i](size_t /*offset*/, DataSink &sink) {
  4980. switch (*i) {
  4981. case 0: sink.os << "123"; break;
  4982. case 1: sink.os << "456"; break;
  4983. case 2: sink.os << "789"; break;
  4984. case 3: {
  4985. sink.done_with_trailer(
  4986. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4987. } break;
  4988. }
  4989. (*i)++;
  4990. return true;
  4991. },
  4992. [i](bool success) {
  4993. EXPECT_TRUE(success);
  4994. delete i;
  4995. });
  4996. })
  4997. .Get("/streamed-chunked2",
  4998. [&](const Request & /*req*/, Response &res) {
  4999. auto i = new int(0);
  5000. res.set_chunked_content_provider(
  5001. "text/plain",
  5002. [i](size_t /*offset*/, DataSink &sink) {
  5003. switch (*i) {
  5004. case 0: sink.os << "123"; break;
  5005. case 1: sink.os << "456"; break;
  5006. case 2: sink.os << "789"; break;
  5007. case 3: sink.done(); break;
  5008. }
  5009. (*i)++;
  5010. return true;
  5011. },
  5012. [i](bool success) {
  5013. EXPECT_TRUE(success);
  5014. delete i;
  5015. });
  5016. })
  5017. .Get("/streamed-chunked-with-trailer",
  5018. [&](const Request & /*req*/, Response &res) {
  5019. auto i = new int(0);
  5020. res.set_header("Trailer", "Dummy1, Dummy2");
  5021. res.set_chunked_content_provider(
  5022. "text/plain",
  5023. [i](size_t /*offset*/, DataSink &sink) {
  5024. switch (*i) {
  5025. case 0: sink.os << "123"; break;
  5026. case 1: sink.os << "456"; break;
  5027. case 2: sink.os << "789"; break;
  5028. case 3: {
  5029. sink.done_with_trailer(
  5030. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5031. } break;
  5032. }
  5033. (*i)++;
  5034. return true;
  5035. },
  5036. [i](bool success) {
  5037. EXPECT_TRUE(success);
  5038. delete i;
  5039. });
  5040. })
  5041. .Get("/streamed",
  5042. [&](const Request & /*req*/, Response &res) {
  5043. res.set_content_provider(
  5044. 6, "text/plain",
  5045. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5046. sink.os << (offset < 3 ? "a" : "b");
  5047. return true;
  5048. });
  5049. })
  5050. .Get("/streamed-without-length",
  5051. [&](const Request & /*req*/, Response &res) {
  5052. auto data = new std::string("abcdefg");
  5053. res.set_content_provider(
  5054. "text/plain",
  5055. [data](size_t offset, DataSink &sink) {
  5056. if (offset < data->size()) {
  5057. sink.os << data->substr(offset);
  5058. }
  5059. sink.done();
  5060. return true;
  5061. },
  5062. [data](bool success) {
  5063. EXPECT_TRUE(success);
  5064. delete data;
  5065. });
  5066. })
  5067. .Get("/streamed-with-range",
  5068. [&](const Request &req, Response &res) {
  5069. auto data = new std::string("abcdefg");
  5070. // An explicit status keeps the server from picking the 206 it
  5071. // would otherwise choose for a ranged request, so the response
  5072. // is not a partial representation.
  5073. auto status = req.get_param_value("status");
  5074. if (status == "200") {
  5075. res.status = StatusCode::OK_200;
  5076. } else if (status == "403") {
  5077. res.status = StatusCode::Forbidden_403;
  5078. }
  5079. res.set_content_provider(
  5080. data->size(), "text/plain",
  5081. [data](size_t offset, size_t length, DataSink &sink) {
  5082. size_t DATA_CHUNK_SIZE = 4;
  5083. const auto &d = *data;
  5084. auto out_len =
  5085. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5086. auto ret =
  5087. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5088. EXPECT_TRUE(ret);
  5089. return true;
  5090. },
  5091. [data, &req](bool success) {
  5092. EXPECT_EQ(success, !req.has_param("error"));
  5093. delete data;
  5094. });
  5095. })
  5096. .Get("/streamed-cancel",
  5097. [&](const Request & /*req*/, Response &res) {
  5098. res.set_content_provider(
  5099. size_t(-1), "text/plain",
  5100. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5101. sink.os << "data_chunk";
  5102. return true;
  5103. });
  5104. })
  5105. .Get("/regex-with-delimiter",
  5106. [&](const Request &req, Response & /*res*/) {
  5107. ASSERT_TRUE(req.has_param("key"));
  5108. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5109. })
  5110. .Get("/with-range",
  5111. [&](const Request & /*req*/, Response &res) {
  5112. res.set_content("abcdefg", "text/plain");
  5113. })
  5114. .Get("/test-start-time",
  5115. [&](const Request &req, Response & /*res*/) {
  5116. EXPECT_NE(req.start_time_,
  5117. std::chrono::steady_clock::time_point::min());
  5118. })
  5119. .Get("/with-range-customized-response",
  5120. [&](const Request & /*req*/, Response &res) {
  5121. res.status = StatusCode::BadRequest_400;
  5122. res.set_content(JSON_DATA, "application/json");
  5123. })
  5124. .Post("/chunked",
  5125. [&](const Request &req, Response & /*res*/) {
  5126. EXPECT_EQ(req.body, "dechunked post body");
  5127. })
  5128. .Post("/large-chunked",
  5129. [&](const Request &req, Response & /*res*/) {
  5130. std::string expected(6 * 30 * 1024u, 'a');
  5131. EXPECT_EQ(req.body, expected);
  5132. })
  5133. .Post("/multipart",
  5134. [&](const Request &req, Response & /*res*/) {
  5135. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5136. req.form.get_field_count("text2") +
  5137. req.form.get_field_count("file3") +
  5138. req.form.get_field_count("file4"));
  5139. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5140. req.form.get_file_count("file2"));
  5141. ASSERT_TRUE(!req.form.has_file("???"));
  5142. ASSERT_TRUE(!req.form.has_field("???"));
  5143. ASSERT_TRUE(req.body.empty());
  5144. {
  5145. const auto &text = req.form.get_field("text1");
  5146. EXPECT_EQ("text default", text);
  5147. }
  5148. {
  5149. const auto &text = req.form.get_field("text2");
  5150. EXPECT_EQ("aωb", text);
  5151. }
  5152. {
  5153. const auto &file = req.form.get_file("file1");
  5154. EXPECT_EQ("hello.txt", file.filename);
  5155. EXPECT_EQ("text/plain", file.content_type);
  5156. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5157. }
  5158. {
  5159. const auto &file = req.form.get_file("file2");
  5160. EXPECT_EQ("world.json", file.filename);
  5161. EXPECT_EQ("application/json", file.content_type);
  5162. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5163. }
  5164. {
  5165. const auto &text = req.form.get_field("file3");
  5166. EXPECT_EQ(0u, text.size());
  5167. }
  5168. {
  5169. const auto &text = req.form.get_field("file4");
  5170. EXPECT_EQ(0u, text.size());
  5171. }
  5172. })
  5173. .Post("/multipart/multi_file_values",
  5174. [&](const Request &req, Response & /*res*/) {
  5175. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5176. req.form.get_field_count("multi_text1"));
  5177. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5178. ASSERT_TRUE(!req.form.has_file("???"));
  5179. ASSERT_TRUE(!req.form.has_field("???"));
  5180. ASSERT_TRUE(req.body.empty());
  5181. {
  5182. const auto &text = req.form.get_field("text");
  5183. EXPECT_EQ("default text", text);
  5184. }
  5185. {
  5186. const auto &text1_values = req.form.get_fields("multi_text1");
  5187. EXPECT_EQ(2u, text1_values.size());
  5188. EXPECT_EQ("aaaaa", text1_values[0]);
  5189. EXPECT_EQ("bbbbb", text1_values[1]);
  5190. }
  5191. {
  5192. const auto &file1_values = req.form.get_files("multi_file1");
  5193. EXPECT_EQ(2u, file1_values.size());
  5194. auto file1 = file1_values[0];
  5195. EXPECT_EQ(file1.filename, "hello.txt");
  5196. EXPECT_EQ(file1.content_type, "text/plain");
  5197. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5198. auto file2 = file1_values[1];
  5199. EXPECT_EQ(file2.filename, "world.json");
  5200. EXPECT_EQ(file2.content_type, "application/json");
  5201. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5202. }
  5203. })
  5204. .Post("/empty",
  5205. [&](const Request &req, Response &res) {
  5206. EXPECT_EQ(req.body, "");
  5207. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5208. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5209. res.set_content("empty", "text/plain");
  5210. })
  5211. .Post("/empty-no-content-type",
  5212. [&](const Request &req, Response &res) {
  5213. EXPECT_EQ(req.body, "");
  5214. EXPECT_FALSE(req.has_header("Content-Type"));
  5215. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5216. res.set_content("empty-no-content-type", "text/plain");
  5217. })
  5218. .Post("/path-only",
  5219. [&](const Request &req, Response &res) {
  5220. EXPECT_EQ(req.body, "");
  5221. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5222. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5223. res.set_content("path-only", "text/plain");
  5224. })
  5225. .Post("/path-headers-only",
  5226. [&](const Request &req, Response &res) {
  5227. EXPECT_EQ(req.body, "");
  5228. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5229. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5230. EXPECT_EQ("world", req.get_header_value("hello"));
  5231. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5232. res.set_content("path-headers-only", "text/plain");
  5233. })
  5234. .Post("/post-large",
  5235. [&](const Request &req, Response &res) {
  5236. EXPECT_EQ(req.body, LARGE_DATA);
  5237. res.set_content(req.body, "text/plain");
  5238. })
  5239. .Post("/post-loopback",
  5240. [&](const Request &, Response &res,
  5241. ContentReader const &content_reader) {
  5242. std::string body;
  5243. content_reader([&](const char *data, size_t data_length) {
  5244. body.append(data, data_length);
  5245. return true;
  5246. });
  5247. res.set_content(body, "text/plain");
  5248. })
  5249. .Put("/put-loopback",
  5250. [&](const Request &, Response &res,
  5251. ContentReader const &content_reader) {
  5252. std::string body;
  5253. content_reader([&](const char *data, size_t data_length) {
  5254. body.append(data, data_length);
  5255. return true;
  5256. });
  5257. res.set_content(body, "text/plain");
  5258. })
  5259. .Patch("/patch-loopback",
  5260. [&](const Request &, Response &res,
  5261. ContentReader const &content_reader) {
  5262. std::string body;
  5263. content_reader([&](const char *data, size_t data_length) {
  5264. body.append(data, data_length);
  5265. return true;
  5266. });
  5267. res.set_content(body, "text/plain");
  5268. })
  5269. .Put("/empty-no-content-type",
  5270. [&](const Request &req, Response &res) {
  5271. EXPECT_EQ(req.body, "");
  5272. EXPECT_FALSE(req.has_header("Content-Type"));
  5273. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5274. res.set_content("empty-no-content-type", "text/plain");
  5275. })
  5276. .Put("/put",
  5277. [&](const Request &req, Response &res) {
  5278. EXPECT_EQ(req.body, "PUT");
  5279. res.set_content(req.body, "text/plain");
  5280. })
  5281. .Put("/put-large",
  5282. [&](const Request &req, Response &res) {
  5283. EXPECT_EQ(req.body, LARGE_DATA);
  5284. res.set_content(req.body, "text/plain");
  5285. })
  5286. .Patch("/patch",
  5287. [&](const Request &req, Response &res) {
  5288. EXPECT_EQ(req.body, "PATCH");
  5289. res.set_content(req.body, "text/plain");
  5290. })
  5291. .Delete("/delete",
  5292. [&](const Request & /*req*/, Response &res) {
  5293. res.set_content("DELETE", "text/plain");
  5294. })
  5295. .Delete("/delete-body",
  5296. [&](const Request &req, Response &res) {
  5297. EXPECT_EQ(req.body, "content");
  5298. res.set_content(req.body, "text/plain");
  5299. })
  5300. .Options(R"(\*)",
  5301. [&](const Request & /*req*/, Response &res) {
  5302. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5303. })
  5304. .CustomRoute("PROPFIND", "/dav/:id",
  5305. [&](const Request &req, Response &res) {
  5306. res.set_header("x-body-size",
  5307. std::to_string(req.body.size()));
  5308. res.set_header("x-matched-route", req.matched_route);
  5309. res.set_header("x-dav-id", req.path_params.at("id"));
  5310. res.status = StatusCode::MultiStatus_207;
  5311. res.set_content(req.body, "application/xml");
  5312. })
  5313. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5314. [&](const Request &req, Response &res) {
  5315. res.set_header("x-dav-match", req.matches[1]);
  5316. res.status = StatusCode::MultiStatus_207;
  5317. })
  5318. .CustomRoute("MKCOL", "/dav-mkcol",
  5319. [&](const Request &req, Response &res) {
  5320. EXPECT_TRUE(req.body.empty());
  5321. res.status = StatusCode::Created_201;
  5322. })
  5323. .CustomRoute(
  5324. "REPORT", "/dav-report",
  5325. [&](const Request & /*req*/, Response &res,
  5326. const ContentReader &content_reader) {
  5327. std::string body;
  5328. content_reader([&](const char *data, size_t data_length) {
  5329. body.append(data, data_length);
  5330. return true;
  5331. });
  5332. res.set_header("x-body-size", std::to_string(body.size()));
  5333. res.status = StatusCode::MultiStatus_207;
  5334. res.set_content(body, "application/xml");
  5335. })
  5336. .Get("/request-target",
  5337. [&](const Request &req, Response & /*res*/) {
  5338. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5339. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5340. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5341. })
  5342. .Get("/long-query-value",
  5343. [&](const Request &req, Response & /*res*/) {
  5344. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5345. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5346. })
  5347. .Get("/too-long-query-value",
  5348. [&](const Request &req, Response & /*res*/) {
  5349. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5350. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5351. })
  5352. .Get("/array-param",
  5353. [&](const Request &req, Response & /*res*/) {
  5354. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5355. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5356. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5357. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5358. })
  5359. .Get("/array-param-values",
  5360. [&](const Request &req, Response & /*res*/) {
  5361. auto values = req.get_param_values("array");
  5362. EXPECT_EQ(3u, values.size());
  5363. EXPECT_EQ("value1", values[0]);
  5364. EXPECT_EQ("value2", values[1]);
  5365. EXPECT_EQ("value3", values[2]);
  5366. auto empty = req.get_param_values("nonexistent");
  5367. EXPECT_TRUE(empty.empty());
  5368. })
  5369. .Post("/validate-no-multiple-headers",
  5370. [&](const Request &req, Response & /*res*/) {
  5371. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5372. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5373. })
  5374. .Post("/content_receiver",
  5375. [&](const Request &req, Response &res,
  5376. const ContentReader &content_reader) {
  5377. if (req.is_multipart_form_data()) {
  5378. std::vector<FormData> items;
  5379. content_reader(
  5380. [&](const FormData &file) {
  5381. items.push_back(file);
  5382. return true;
  5383. },
  5384. [&](const char *data, size_t data_length) {
  5385. items.back().content.append(data, data_length);
  5386. return true;
  5387. });
  5388. EXPECT_EQ(5u, items.size());
  5389. {
  5390. const auto &file = get_file_value(items, "text1");
  5391. EXPECT_TRUE(file.filename.empty());
  5392. EXPECT_EQ("text default", file.content);
  5393. }
  5394. {
  5395. const auto &file = get_file_value(items, "text2");
  5396. EXPECT_TRUE(file.filename.empty());
  5397. EXPECT_EQ("aωb", file.content);
  5398. }
  5399. {
  5400. const auto &file = get_file_value(items, "file1");
  5401. EXPECT_EQ("hello.txt", file.filename);
  5402. EXPECT_EQ("text/plain", file.content_type);
  5403. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5404. }
  5405. {
  5406. const auto &file = get_file_value(items, "file2");
  5407. EXPECT_EQ("world.json", file.filename);
  5408. EXPECT_EQ("application/json", file.content_type);
  5409. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5410. }
  5411. {
  5412. const auto &file = get_file_value(items, "file3");
  5413. EXPECT_TRUE(file.filename.empty());
  5414. EXPECT_EQ("application/octet-stream", file.content_type);
  5415. EXPECT_EQ(0u, file.content.size());
  5416. }
  5417. } else {
  5418. std::string body;
  5419. content_reader([&](const char *data, size_t data_length) {
  5420. EXPECT_EQ(7U, data_length);
  5421. body.append(data, data_length);
  5422. return true;
  5423. });
  5424. EXPECT_EQ(body, "content");
  5425. res.set_content(body, "text/plain");
  5426. }
  5427. })
  5428. .Put("/content_receiver",
  5429. [&](const Request & /*req*/, Response &res,
  5430. const ContentReader &content_reader) {
  5431. std::string body;
  5432. content_reader([&](const char *data, size_t data_length) {
  5433. body.append(data, data_length);
  5434. return true;
  5435. });
  5436. EXPECT_EQ(body, "content");
  5437. res.set_content(body, "text/plain");
  5438. })
  5439. .Patch("/content_receiver",
  5440. [&](const Request & /*req*/, Response &res,
  5441. const ContentReader &content_reader) {
  5442. std::string body;
  5443. content_reader([&](const char *data, size_t data_length) {
  5444. body.append(data, data_length);
  5445. return true;
  5446. });
  5447. EXPECT_EQ(body, "content");
  5448. res.set_content(body, "text/plain");
  5449. })
  5450. .Post("/query-string-and-body",
  5451. [&](const Request &req, Response & /*res*/) {
  5452. ASSERT_TRUE(req.has_param("key"));
  5453. EXPECT_EQ(req.get_param_value("key"), "value");
  5454. EXPECT_EQ(req.body, "content");
  5455. })
  5456. .Get("/last-request",
  5457. [&](const Request &req, Response & /*res*/) {
  5458. EXPECT_EQ("close", req.get_header_value("Connection"));
  5459. })
  5460. .Get(R"(/redirect/(\d+))",
  5461. [&](const Request &req, Response &res) {
  5462. auto num = std::stoi(req.matches[1]) + 1;
  5463. std::string url = "/redirect/" + std::to_string(num);
  5464. res.set_redirect(url);
  5465. })
  5466. .Post("/binary",
  5467. [&](const Request &req, Response &res) {
  5468. EXPECT_EQ(4U, req.body.size());
  5469. EXPECT_EQ("application/octet-stream",
  5470. req.get_header_value("Content-Type"));
  5471. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5472. res.set_content(req.body, "application/octet-stream");
  5473. })
  5474. .Put("/binary",
  5475. [&](const Request &req, Response &res) {
  5476. EXPECT_EQ(4U, req.body.size());
  5477. EXPECT_EQ("application/octet-stream",
  5478. req.get_header_value("Content-Type"));
  5479. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5480. res.set_content(req.body, "application/octet-stream");
  5481. })
  5482. .Patch("/binary",
  5483. [&](const Request &req, Response &res) {
  5484. EXPECT_EQ(4U, req.body.size());
  5485. EXPECT_EQ("application/octet-stream",
  5486. req.get_header_value("Content-Type"));
  5487. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5488. res.set_content(req.body, "application/octet-stream");
  5489. })
  5490. .Delete("/binary",
  5491. [&](const Request &req, Response &res) {
  5492. EXPECT_EQ(4U, req.body.size());
  5493. EXPECT_EQ("application/octet-stream",
  5494. req.get_header_value("Content-Type"));
  5495. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5496. res.set_content(req.body, "application/octet-stream");
  5497. })
  5498. .Get("/issue1772",
  5499. [&](const Request & /*req*/, Response &res) {
  5500. res.status = 401;
  5501. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5502. })
  5503. .Delete("/issue609",
  5504. [](const httplib::Request &, httplib::Response &res,
  5505. const httplib::ContentReader &) {
  5506. res.set_content("ok", "text/plain");
  5507. })
  5508. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5509. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5510. .Get("/compress",
  5511. [&](const Request & /*req*/, Response &res) {
  5512. res.set_content(
  5513. "12345678901234567890123456789012345678901234567890123456789"
  5514. "01234567890123456789012345678901234567890",
  5515. "text/plain");
  5516. })
  5517. .Get("/compress-with-charset",
  5518. [&](const Request & /*req*/, Response &res) {
  5519. res.set_content(
  5520. "12345678901234567890123456789012345678901234567890123456789"
  5521. "01234567890123456789012345678901234567890",
  5522. "application/json; charset=utf-8");
  5523. })
  5524. .Get("/nocompress",
  5525. [&](const Request & /*req*/, Response &res) {
  5526. res.set_content(
  5527. "12345678901234567890123456789012345678901234567890123456789"
  5528. "01234567890123456789012345678901234567890",
  5529. "application/octet-stream");
  5530. })
  5531. .Post("/compress-multipart",
  5532. [&](const Request &req, Response & /*res*/) {
  5533. EXPECT_EQ(2u, req.form.fields.size());
  5534. ASSERT_TRUE(!req.form.has_field("???"));
  5535. {
  5536. const auto &text = req.form.get_field("key1");
  5537. EXPECT_EQ("test", text);
  5538. }
  5539. {
  5540. const auto &text = req.form.get_field("key2");
  5541. EXPECT_EQ("--abcdefg123", text);
  5542. }
  5543. })
  5544. #endif
  5545. ;
  5546. persons_["john"] = "programmer";
  5547. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5548. svr_.wait_until_ready();
  5549. }
  5550. virtual void TearDown() {
  5551. svr_.stop();
  5552. if (!request_threads_.empty()) {
  5553. std::this_thread::sleep_for(std::chrono::seconds(1));
  5554. for (auto &t : request_threads_) {
  5555. t.join();
  5556. }
  5557. }
  5558. t_.join();
  5559. }
  5560. map<string, string> persons_;
  5561. #ifdef CPPHTTPLIB_SSL_ENABLED
  5562. SSLClient cli_;
  5563. SSLServer svr_;
  5564. #else
  5565. Client cli_;
  5566. Server svr_;
  5567. #endif
  5568. thread t_;
  5569. std::vector<thread> request_threads_;
  5570. };
  5571. TEST_F(ServerTest, GetMethod200) {
  5572. auto res = cli_.Get("/hi");
  5573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5574. EXPECT_EQ("HTTP/1.1", res->version);
  5575. EXPECT_EQ(StatusCode::OK_200, res->status);
  5576. EXPECT_EQ("OK", res->reason);
  5577. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5578. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5579. EXPECT_EQ("Hello World!", res->body);
  5580. }
  5581. TEST_F(ServerTest, GetEmptyFile) {
  5582. auto res = cli_.Get("/empty_file");
  5583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5584. EXPECT_EQ(StatusCode::OK_200, res->status);
  5585. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5586. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5587. EXPECT_EQ("", res->body);
  5588. }
  5589. TEST_F(ServerTest, GetFileContent) {
  5590. auto res = cli_.Get("/file_content");
  5591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5592. EXPECT_EQ(StatusCode::OK_200, res->status);
  5593. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5594. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5595. EXPECT_EQ("test.html", res->body);
  5596. }
  5597. TEST_F(ServerTest, GetFileContentWithRange) {
  5598. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5600. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5601. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5602. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5603. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5604. EXPECT_EQ("est", res->body);
  5605. }
  5606. TEST_F(ServerTest, GetFileContentWithContentType) {
  5607. auto res = cli_.Get("/file_content_with_content_type");
  5608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5609. EXPECT_EQ(StatusCode::OK_200, res->status);
  5610. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5611. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5612. EXPECT_EQ("file\n", res->body);
  5613. }
  5614. TEST_F(ServerTest, GetInvalidFileContent) {
  5615. auto res = cli_.Get("/invalid_file_content");
  5616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5617. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5618. }
  5619. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5620. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5622. EXPECT_EQ("HTTP/1.1", res->version);
  5623. EXPECT_EQ(StatusCode::OK_200, res->status);
  5624. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5625. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5626. EXPECT_EQ("Hello World!", res->body);
  5627. }
  5628. TEST_F(ServerTest, GetMethod302) {
  5629. auto res = cli_.Get("/");
  5630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5631. EXPECT_EQ(StatusCode::Found_302, res->status);
  5632. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5633. }
  5634. TEST_F(ServerTest, GetMethod302Redirect) {
  5635. cli_.set_follow_location(true);
  5636. auto res = cli_.Get("/");
  5637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5638. EXPECT_EQ(StatusCode::OK_200, res->status);
  5639. EXPECT_EQ("Hello World!", res->body);
  5640. EXPECT_EQ("/hi", res->location);
  5641. }
  5642. TEST_F(ServerTest, GetMethod404) {
  5643. auto res = cli_.Get("/invalid");
  5644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5645. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5646. }
  5647. TEST_F(ServerTest, HeadMethod200) {
  5648. auto res = cli_.Head("/hi");
  5649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5650. EXPECT_EQ(StatusCode::OK_200, res->status);
  5651. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5652. EXPECT_TRUE(res->body.empty());
  5653. }
  5654. TEST_F(ServerTest, HeadMethod200Static) {
  5655. auto res = cli_.Head("/mount/dir/index.html");
  5656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5657. EXPECT_EQ(StatusCode::OK_200, res->status);
  5658. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5659. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5660. EXPECT_TRUE(res->body.empty());
  5661. }
  5662. TEST_F(ServerTest, HeadMethod404) {
  5663. auto res = cli_.Head("/invalid");
  5664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5665. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5666. EXPECT_TRUE(res->body.empty());
  5667. }
  5668. TEST_F(ServerTest, GetMethodPersonJohn) {
  5669. auto res = cli_.Get("/person/john");
  5670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5671. EXPECT_EQ(StatusCode::OK_200, res->status);
  5672. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5673. EXPECT_EQ("programmer", res->body);
  5674. }
  5675. TEST_F(ServerTest, PostMethod1) {
  5676. auto res = cli_.Get("/person/john1");
  5677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5678. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5679. res = cli_.Post("/person", "name=john1&note=coder",
  5680. "application/x-www-form-urlencoded");
  5681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5682. ASSERT_EQ(StatusCode::OK_200, res->status);
  5683. res = cli_.Get("/person/john1");
  5684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5685. ASSERT_EQ(StatusCode::OK_200, res->status);
  5686. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5687. ASSERT_EQ("coder", res->body);
  5688. }
  5689. TEST_F(ServerTest, PostMethod2) {
  5690. auto res = cli_.Get("/person/john2");
  5691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5692. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5693. Params params;
  5694. params.emplace("name", "john2");
  5695. params.emplace("note", "coder");
  5696. res = cli_.Post("/person", params);
  5697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5698. ASSERT_EQ(StatusCode::OK_200, res->status);
  5699. res = cli_.Get("/person/john2");
  5700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5701. ASSERT_EQ(StatusCode::OK_200, res->status);
  5702. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5703. ASSERT_EQ("coder", res->body);
  5704. }
  5705. TEST_F(ServerTest, PutMethod3) {
  5706. auto res = cli_.Get("/person/john3");
  5707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5708. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5709. Params params;
  5710. params.emplace("name", "john3");
  5711. params.emplace("note", "coder");
  5712. res = cli_.Put("/person", params);
  5713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5714. ASSERT_EQ(StatusCode::OK_200, res->status);
  5715. res = cli_.Get("/person/john3");
  5716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5717. ASSERT_EQ(StatusCode::OK_200, res->status);
  5718. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5719. ASSERT_EQ("coder", res->body);
  5720. }
  5721. TEST_F(ServerTest, DeleteMethod1) {
  5722. auto res = cli_.Get("/person/john4");
  5723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5724. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5725. Params params;
  5726. params.emplace("name", "john4");
  5727. params.emplace("note", "coder");
  5728. res = cli_.Post("/person", params);
  5729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5730. ASSERT_EQ(StatusCode::OK_200, res->status);
  5731. res = cli_.Get("/person/john4");
  5732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5733. ASSERT_EQ(StatusCode::OK_200, res->status);
  5734. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5735. ASSERT_EQ("coder", res->body);
  5736. Params delete_params;
  5737. delete_params.emplace("name", "john4");
  5738. res = cli_.Delete("/person", delete_params);
  5739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5740. ASSERT_EQ(StatusCode::OK_200, res->status);
  5741. ASSERT_EQ("DELETED", res->body);
  5742. res = cli_.Get("/person/john4");
  5743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5744. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5745. }
  5746. TEST_F(ServerTest, DeleteMethod2) {
  5747. auto res = cli_.Get("/person/john5");
  5748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5749. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5750. Params params;
  5751. params.emplace("name", "john5");
  5752. params.emplace("note", "developer");
  5753. res = cli_.Post("/person", params);
  5754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5755. ASSERT_EQ(StatusCode::OK_200, res->status);
  5756. res = cli_.Get("/person/john5");
  5757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5758. ASSERT_EQ(StatusCode::OK_200, res->status);
  5759. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5760. ASSERT_EQ("developer", res->body);
  5761. Params delete_params;
  5762. delete_params.emplace("name", "john5");
  5763. Headers headers;
  5764. headers.emplace("Custom-Header", "test-value");
  5765. res = cli_.Delete("/person", headers, delete_params);
  5766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5767. ASSERT_EQ(StatusCode::OK_200, res->status);
  5768. ASSERT_EQ("DELETED", res->body);
  5769. res = cli_.Get("/person/john5");
  5770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5771. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5772. }
  5773. TEST_F(ServerTest, DeleteMethod3) {
  5774. auto res = cli_.Get("/person/john6");
  5775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5776. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5777. Params params;
  5778. params.emplace("name", "john6");
  5779. params.emplace("note", "tester");
  5780. res = cli_.Post("/person", params);
  5781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5782. ASSERT_EQ(StatusCode::OK_200, res->status);
  5783. res = cli_.Get("/person/john6");
  5784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5785. ASSERT_EQ(StatusCode::OK_200, res->status);
  5786. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5787. ASSERT_EQ("tester", res->body);
  5788. Params delete_params;
  5789. delete_params.emplace("name", "john6");
  5790. Headers headers;
  5791. headers.emplace("Custom-Header", "test-value");
  5792. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5794. ASSERT_EQ(StatusCode::OK_200, res->status);
  5795. ASSERT_EQ("DELETED", res->body);
  5796. res = cli_.Get("/person/john6");
  5797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5798. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5799. }
  5800. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5801. Params params;
  5802. params.emplace("json", JSON_DATA);
  5803. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5805. ASSERT_EQ(StatusCode::OK_200, res->status);
  5806. ASSERT_EQ(JSON_DATA, res->body);
  5807. }
  5808. TEST_F(ServerTest, PostEmptyContent) {
  5809. auto res = cli_.Post("/empty", "", "text/plain");
  5810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5811. ASSERT_EQ(StatusCode::OK_200, res->status);
  5812. ASSERT_EQ("empty", res->body);
  5813. }
  5814. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5815. auto res = cli_.Post("/empty-no-content-type");
  5816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5817. ASSERT_EQ(StatusCode::OK_200, res->status);
  5818. ASSERT_EQ("empty-no-content-type", res->body);
  5819. }
  5820. TEST_F(ServerTest, PostPathOnly) {
  5821. auto res = cli_.Post("/path-only");
  5822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5823. ASSERT_EQ(StatusCode::OK_200, res->status);
  5824. ASSERT_EQ("path-only", res->body);
  5825. }
  5826. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5827. auto res = cli_.Post("/path-headers-only",
  5828. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5830. ASSERT_EQ(StatusCode::OK_200, res->status);
  5831. ASSERT_EQ("path-headers-only", res->body);
  5832. }
  5833. TEST_F(ServerTest, PostLarge) {
  5834. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5836. ASSERT_EQ(StatusCode::OK_200, res->status);
  5837. EXPECT_EQ(LARGE_DATA, res->body);
  5838. }
  5839. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5840. auto res = cli_.Put("/empty-no-content-type");
  5841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5842. ASSERT_EQ(StatusCode::OK_200, res->status);
  5843. ASSERT_EQ("empty-no-content-type", res->body);
  5844. }
  5845. TEST_F(ServerTest, GetMethodDir) {
  5846. auto res = cli_.Get("/dir/");
  5847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5848. EXPECT_EQ(StatusCode::OK_200, res->status);
  5849. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5850. auto body = R"(<html>
  5851. <head>
  5852. </head>
  5853. <body>
  5854. <a href="/dir/test.html">Test</a>
  5855. <a href="/hi">hi</a>
  5856. </body>
  5857. </html>
  5858. )";
  5859. EXPECT_EQ(body, res->body);
  5860. }
  5861. TEST_F(ServerTest, GetMethodDirTest) {
  5862. auto res = cli_.Get("/dir/test.html");
  5863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5864. EXPECT_EQ(StatusCode::OK_200, res->status);
  5865. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5866. EXPECT_EQ("test.html", res->body);
  5867. }
  5868. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5869. auto res = cli_.Get("/dir/../dir/test.html");
  5870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5871. EXPECT_EQ(StatusCode::OK_200, res->status);
  5872. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5873. EXPECT_EQ("test.html", res->body);
  5874. }
  5875. TEST_F(ServerTest, GetMethodInvalidPath) {
  5876. auto res = cli_.Get("/dir/../test.html");
  5877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5878. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5879. }
  5880. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5881. auto res = cli_.Get("/../www/dir/test.html");
  5882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5883. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5884. }
  5885. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5886. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5888. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5889. }
  5890. TEST_F(ServerTest, GetMethodDirMountTest) {
  5891. auto res = cli_.Get("/mount/dir/test.html");
  5892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5893. EXPECT_EQ(StatusCode::OK_200, res->status);
  5894. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5895. EXPECT_EQ("test.html", res->body);
  5896. }
  5897. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5898. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5900. EXPECT_EQ(StatusCode::OK_200, res->status);
  5901. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5902. EXPECT_EQ("test.html", res->body);
  5903. }
  5904. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5905. auto res = cli_.Get("/mount/dir/../test.html");
  5906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5907. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5908. }
  5909. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5910. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5912. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5913. }
  5914. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5915. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5917. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5918. }
  5919. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5920. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5922. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5923. }
  5924. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5925. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5927. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5928. }
  5929. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  5930. auto res = cli_.Get("/mount/dir");
  5931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5932. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5933. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5934. }
  5935. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  5936. auto res = cli_.Get("//dir");
  5937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5938. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5939. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5940. }
  5941. TEST_F(ServerTest, PostMethod303) {
  5942. auto res = cli_.Post("/1", "body", "text/plain");
  5943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5944. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5945. EXPECT_EQ("/2", res->get_header_value("Location"));
  5946. }
  5947. TEST_F(ServerTest, PostMethod303Redirect) {
  5948. cli_.set_follow_location(true);
  5949. auto res = cli_.Post("/1", "body", "text/plain");
  5950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5951. EXPECT_EQ(StatusCode::OK_200, res->status);
  5952. EXPECT_EQ("redirected.", res->body);
  5953. EXPECT_EQ("/2", res->location);
  5954. }
  5955. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5956. auto res = cli_.Get("/dir/test.abcde");
  5957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5958. EXPECT_EQ(StatusCode::OK_200, res->status);
  5959. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5960. EXPECT_EQ("abcde", res->body);
  5961. }
  5962. TEST_F(ServerTest, StaticFileRange) {
  5963. auto res =
  5964. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5966. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5967. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5968. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5969. EXPECT_EQ(true, res->has_header("Content-Range"));
  5970. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5971. EXPECT_EQ(std::string("cd"), res->body);
  5972. }
  5973. TEST_F(ServerTest, StaticFileRanges) {
  5974. auto res = cli_.Get("/dir/test.abcde",
  5975. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5977. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5978. EXPECT_TRUE(
  5979. res->get_header_value("Content-Type")
  5980. .find(
  5981. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5982. 0);
  5983. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5984. }
  5985. TEST_F(ServerTest, StaticFileRangeHead) {
  5986. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5988. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5989. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5990. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5991. EXPECT_EQ(true, res->has_header("Content-Range"));
  5992. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5993. }
  5994. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5995. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5997. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5998. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5999. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6000. EXPECT_EQ(true, res->has_header("Content-Range"));
  6001. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6002. res->get_header_value("Content-Range"));
  6003. EXPECT_EQ("LAST\n", res->body);
  6004. }
  6005. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6006. auto res =
  6007. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6009. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6010. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6011. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6012. EXPECT_EQ(true, res->has_header("Content-Range"));
  6013. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6014. }
  6015. TEST_F(ServerTest, StaticFileBigFile) {
  6016. auto res = cli_.Get("/dir/1MB.txt");
  6017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6018. EXPECT_EQ(StatusCode::OK_200, res->status);
  6019. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6020. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6021. }
  6022. TEST_F(ServerTest, InvalidBaseDirMount) {
  6023. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6024. }
  6025. TEST_F(ServerTest, Binary) {
  6026. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6027. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6028. "application/octet-stream");
  6029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6030. ASSERT_EQ(StatusCode::OK_200, res->status);
  6031. ASSERT_EQ(4U, res->body.size());
  6032. res = cli_.Put("/binary", binary.data(), binary.size(),
  6033. "application/octet-stream");
  6034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6035. ASSERT_EQ(StatusCode::OK_200, res->status);
  6036. ASSERT_EQ(4U, res->body.size());
  6037. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6038. "application/octet-stream");
  6039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6040. ASSERT_EQ(StatusCode::OK_200, res->status);
  6041. ASSERT_EQ(4U, res->body.size());
  6042. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6043. "application/octet-stream");
  6044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6045. ASSERT_EQ(StatusCode::OK_200, res->status);
  6046. ASSERT_EQ(4U, res->body.size());
  6047. }
  6048. TEST_F(ServerTest, BinaryString) {
  6049. auto binary = std::string("\x00\x01\x02\x03", 4);
  6050. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6052. ASSERT_EQ(StatusCode::OK_200, res->status);
  6053. ASSERT_EQ(4U, res->body.size());
  6054. res = cli_.Put("/binary", binary, "application/octet-stream");
  6055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6056. ASSERT_EQ(StatusCode::OK_200, res->status);
  6057. ASSERT_EQ(4U, res->body.size());
  6058. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6060. ASSERT_EQ(StatusCode::OK_200, res->status);
  6061. ASSERT_EQ(4U, res->body.size());
  6062. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6064. ASSERT_EQ(StatusCode::OK_200, res->status);
  6065. ASSERT_EQ(4U, res->body.size());
  6066. }
  6067. TEST_F(ServerTest, EmptyRequest) {
  6068. auto res = cli_.Get("");
  6069. ASSERT_TRUE(!res);
  6070. EXPECT_EQ(Error::Connection, res.error());
  6071. }
  6072. TEST_F(ServerTest, LongRequest) {
  6073. std::string request;
  6074. for (size_t i = 0; i < 545; i++) {
  6075. request += "/TooLongRequest";
  6076. }
  6077. request += "OK";
  6078. auto res = cli_.Get(request.c_str());
  6079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6080. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6081. }
  6082. TEST_F(ServerTest, TooLongRequest) {
  6083. std::string request;
  6084. for (size_t i = 0; i < 546; i++) {
  6085. request += "/TooLongRequest";
  6086. }
  6087. request += "_NG";
  6088. auto start = std::chrono::high_resolution_clock::now();
  6089. cli_.set_keep_alive(true);
  6090. auto res = cli_.Get(request.c_str());
  6091. auto end = std::chrono::high_resolution_clock::now();
  6092. auto elapsed =
  6093. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6094. .count();
  6095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6096. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6097. EXPECT_LE(elapsed, 1000);
  6098. EXPECT_EQ("close", res->get_header_value("Connection"));
  6099. EXPECT_FALSE(cli_.is_socket_open());
  6100. }
  6101. TEST_F(ServerTest, AlmostTooLongRequest) {
  6102. // test for #2046 - URI length check shouldn't include other content on req
  6103. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6104. // leading /, space, HTTP/1.1)
  6105. std::string request =
  6106. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6107. auto res = cli_.Get(request.c_str());
  6108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6109. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6110. }
  6111. TEST_F(ServerTest, LongHeader) {
  6112. Request req;
  6113. req.method = "GET";
  6114. req.path = "/hi";
  6115. std::string host_and_port;
  6116. host_and_port += HOST;
  6117. host_and_port += ":";
  6118. host_and_port += std::to_string(PORT);
  6119. req.headers.emplace("Host", host_and_port.c_str());
  6120. req.headers.emplace("Accept", "*/*");
  6121. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6122. req.headers.emplace(
  6123. "Header-Name",
  6124. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6125. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6126. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6127. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6128. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6129. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6130. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6131. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6132. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6133. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6134. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6135. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6136. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6137. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6138. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6139. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6140. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6141. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6142. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6143. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6144. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6145. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6146. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6147. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6148. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6149. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6150. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6151. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6152. "@@@@@@@@@@@@@@@@");
  6153. auto res = std::make_shared<Response>();
  6154. auto error = Error::Success;
  6155. auto ret = cli_.send(req, *res, error);
  6156. ASSERT_TRUE(ret);
  6157. EXPECT_EQ(StatusCode::OK_200, res->status);
  6158. }
  6159. TEST_F(ServerTest, LongQueryValue) {
  6160. auto start = std::chrono::high_resolution_clock::now();
  6161. cli_.set_keep_alive(true);
  6162. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6163. auto end = std::chrono::high_resolution_clock::now();
  6164. auto elapsed =
  6165. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6166. .count();
  6167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6168. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6169. EXPECT_LE(elapsed, 1000);
  6170. EXPECT_EQ("close", res->get_header_value("Connection"));
  6171. EXPECT_FALSE(cli_.is_socket_open());
  6172. }
  6173. TEST_F(ServerTest, TooLongQueryValue) {
  6174. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6175. ASSERT_FALSE(res);
  6176. EXPECT_EQ(Error::Read, res.error());
  6177. }
  6178. TEST_F(ServerTest, TooLongHeader) {
  6179. Request req;
  6180. req.method = "GET";
  6181. req.path = "/hi";
  6182. std::string host_and_port;
  6183. host_and_port += HOST;
  6184. host_and_port += ":";
  6185. host_and_port += std::to_string(PORT);
  6186. req.headers.emplace("Host", host_and_port.c_str());
  6187. req.headers.emplace("Accept", "*/*");
  6188. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6189. req.headers.emplace(
  6190. "Header-Name",
  6191. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6192. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6193. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6194. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6195. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6196. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6197. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6198. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6199. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6200. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6201. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6202. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6203. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6204. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6205. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6206. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6207. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6208. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6209. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6210. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6211. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6212. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6213. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6214. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6215. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6216. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6217. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6218. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6219. "@@@@@@@@@@@@@@@@@");
  6220. auto res = std::make_shared<Response>();
  6221. auto error = Error::Success;
  6222. auto ret = cli_.send(req, *res, error);
  6223. ASSERT_TRUE(ret);
  6224. EXPECT_EQ(StatusCode::OK_200, res->status);
  6225. }
  6226. TEST_F(ServerTest, HeaderCountAtLimit) {
  6227. // Test with headers just under the 100 limit
  6228. httplib::Headers headers;
  6229. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6230. // This should keep us just under the 100 header limit
  6231. for (int i = 0; i < 95; i++) {
  6232. std::string name = "X-Test-Header-" + std::to_string(i);
  6233. std::string value = "value" + std::to_string(i);
  6234. headers.emplace(name, value);
  6235. }
  6236. // This should work fine as we're under the limit
  6237. auto res = cli_.Get("/hi", headers);
  6238. EXPECT_TRUE(res);
  6239. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6240. }
  6241. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6242. // Test with many headers to exceed the 100 limit
  6243. httplib::Headers headers;
  6244. // Add 150 headers to definitely exceed the 100 limit
  6245. for (int i = 0; i < 150; i++) {
  6246. std::string name = "X-Test-Header-" + std::to_string(i);
  6247. std::string value = "value" + std::to_string(i);
  6248. headers.emplace(name, value);
  6249. }
  6250. // This should fail due to exceeding header count limit
  6251. cli_.set_keep_alive(true);
  6252. auto res = cli_.Get("/hi", headers);
  6253. // The server should respond with 400 Bad Request
  6254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6255. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6256. EXPECT_EQ("close", res->get_header_value("Connection"));
  6257. EXPECT_FALSE(cli_.is_socket_open());
  6258. }
  6259. TEST_F(ServerTest, PercentEncoding) {
  6260. auto res = cli_.Get("/e%6edwith%");
  6261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6262. EXPECT_EQ(StatusCode::OK_200, res->status);
  6263. }
  6264. TEST_F(ServerTest, PercentEncodingUnicode) {
  6265. auto res = cli_.Get("/e%u006edwith%");
  6266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6267. EXPECT_EQ(StatusCode::OK_200, res->status);
  6268. }
  6269. TEST_F(ServerTest, InvalidPercentEncoding) {
  6270. auto res = cli_.Get("/%endwith%");
  6271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6272. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6273. }
  6274. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6275. auto res = cli_.Get("/%uendwith%");
  6276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6277. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6278. }
  6279. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6280. auto res = cli_.Get("/hello?aaa=bbb%");
  6281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6282. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6283. }
  6284. TEST_F(ServerTest, PlusSignEncoding) {
  6285. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6287. EXPECT_EQ(StatusCode::OK_200, res->status);
  6288. EXPECT_EQ("a +b", res->body);
  6289. }
  6290. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6291. // This test simulates a potential DoS attack using many headers
  6292. // to verify our security fix prevents memory exhaustion
  6293. httplib::Headers attack_headers;
  6294. // Attempt to add many headers like an attacker would (200 headers to far
  6295. // exceed limit)
  6296. for (int i = 0; i < 200; i++) {
  6297. std::string name = "X-Attack-Header-" + std::to_string(i);
  6298. std::string value = "attack_payload_" + std::to_string(i);
  6299. attack_headers.emplace(name, value);
  6300. }
  6301. // Try to POST with excessive headers
  6302. cli_.set_keep_alive(true);
  6303. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6304. // Should either fail or return 400 Bad Request due to security limit
  6305. if (res) {
  6306. // If we get a response, it should be 400 Bad Request
  6307. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6308. EXPECT_EQ("close", res->get_header_value("Connection"));
  6309. }
  6310. EXPECT_FALSE(cli_.is_socket_open());
  6311. }
  6312. TEST_F(ServerTest, MultipartFormData) {
  6313. UploadFormDataItems items = {
  6314. {"text1", "text default", "", ""},
  6315. {"text2", "aωb", "", ""},
  6316. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6317. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6318. {"file3", "", "", "application/octet-stream"},
  6319. {"file4", "", "", " application/json tmp-string "}};
  6320. auto res = cli_.Post("/multipart", items);
  6321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6322. EXPECT_EQ(StatusCode::OK_200, res->status);
  6323. }
  6324. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6325. UploadFormDataItems items = {
  6326. {"text", "default text", "", ""},
  6327. {"multi_text1", "aaaaa", "", ""},
  6328. {"multi_text1", "bbbbb", "", ""},
  6329. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6330. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6331. "application/json"},
  6332. };
  6333. auto res = cli_.Post("/multipart/multi_file_values", items);
  6334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6335. EXPECT_EQ(StatusCode::OK_200, res->status);
  6336. }
  6337. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6338. auto res = cli_.Get("/hi");
  6339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6340. EXPECT_EQ(StatusCode::OK_200, res->status);
  6341. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6342. EXPECT_EQ("Hello World!", res->body);
  6343. }
  6344. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6345. Request req;
  6346. req.method = "POST";
  6347. req.path = "/chunked";
  6348. std::string host_and_port;
  6349. host_and_port += HOST;
  6350. host_and_port += ":";
  6351. host_and_port += std::to_string(PORT);
  6352. req.headers.emplace("Host", host_and_port.c_str());
  6353. req.headers.emplace("Accept", "*/*");
  6354. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6355. req.headers.emplace("Content-Type", "text/plain");
  6356. req.headers.emplace("Content-Length", "0");
  6357. req.headers.emplace(
  6358. "Transfer-Encoding",
  6359. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6360. // Client does not chunk, so make a chunked body manually.
  6361. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6362. auto res = std::make_shared<Response>();
  6363. auto error = Error::Success;
  6364. auto ret = cli_.send(req, *res, error);
  6365. ASSERT_TRUE(ret);
  6366. EXPECT_EQ(StatusCode::OK_200, res->status);
  6367. }
  6368. template <typename ClientT>
  6369. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6370. int expected_status) {
  6371. Request req;
  6372. req.method = "POST";
  6373. req.path = "/chunked";
  6374. std::string host_and_port;
  6375. host_and_port += HOST;
  6376. host_and_port += ":";
  6377. host_and_port += std::to_string(PORT);
  6378. req.headers.emplace("Host", host_and_port.c_str());
  6379. req.headers.emplace("Content-Length", "0");
  6380. req.headers.emplace("Transfer-Encoding", "chunked");
  6381. req.body = body;
  6382. auto res = std::make_shared<Response>();
  6383. auto error = Error::Success;
  6384. ASSERT_TRUE(cli.send(req, *res, error));
  6385. EXPECT_EQ(expected_status, res->status);
  6386. }
  6387. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6388. // rather than treat them as valid lengths.
  6389. template <typename ClientT>
  6390. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6391. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6392. }
  6393. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6394. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6395. }
  6396. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6397. expect_chunked_body_rejected(
  6398. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6399. }
  6400. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6401. // chunk-size line carries no CR, LF or other control character ahead of its
  6402. // terminator. Such a line must be refused rather than read as extension text.
  6403. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6404. expect_chunked_body_rejected(
  6405. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6406. }
  6407. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6408. expect_chunked_body_rejected(
  6409. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6410. }
  6411. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6412. expect_chunked_body_rejected(
  6413. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6414. }
  6415. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6416. // The literal stays split: a hex escape consumes every hex digit that
  6417. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6418. expect_chunked_body_rejected(
  6419. cli_, "4;a\x01"
  6420. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6421. }
  6422. TEST_F(ServerTest, AcceptsChunkExtension) {
  6423. expect_chunked_body_status(cli_,
  6424. "4;name=value\r\ndech\r\n"
  6425. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6426. "0;last\r\n\r\n",
  6427. StatusCode::OK_200);
  6428. }
  6429. TEST_F(ServerTest, GetStreamed2) {
  6430. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6432. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6433. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6434. EXPECT_EQ(true, res->has_header("Content-Range"));
  6435. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6436. EXPECT_EQ(std::string("ab"), res->body);
  6437. }
  6438. TEST_F(ServerTest, GetStreamed) {
  6439. auto res = cli_.Get("/streamed");
  6440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6441. EXPECT_EQ(StatusCode::OK_200, res->status);
  6442. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6443. EXPECT_EQ(std::string("aaabbb"), res->body);
  6444. }
  6445. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6446. auto res = cli_.Get("/streamed-without-length",
  6447. Headers{make_range_header({{0, -1}})});
  6448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6449. EXPECT_EQ(StatusCode::OK_200, res->status);
  6450. EXPECT_EQ(false, res->has_header("Content-Length"));
  6451. EXPECT_EQ(false, res->has_header("Content-Range"));
  6452. EXPECT_EQ(std::string("abcdefg"), res->body);
  6453. }
  6454. TEST_F(ServerTest, GetStreamedWithRange1) {
  6455. auto res =
  6456. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6458. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6459. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6460. EXPECT_EQ(true, res->has_header("Content-Range"));
  6461. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6462. EXPECT_EQ(std::string("def"), res->body);
  6463. }
  6464. TEST_F(ServerTest, GetStreamedWithRange2) {
  6465. auto res =
  6466. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6468. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6469. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6470. EXPECT_EQ(true, res->has_header("Content-Range"));
  6471. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6472. EXPECT_EQ(std::string("bcdefg"), res->body);
  6473. }
  6474. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6475. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6477. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6478. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6479. EXPECT_EQ(true, res->has_header("Content-Range"));
  6480. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6481. EXPECT_EQ(std::string("efg"), res->body);
  6482. }
  6483. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6484. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6485. // the entire representation.
  6486. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6487. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6489. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6490. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6491. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6492. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6493. }
  6494. }
  6495. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6496. auto res =
  6497. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6499. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6500. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6501. EXPECT_EQ(false, res->has_header("Content-Range"));
  6502. EXPECT_EQ(0U, res->body.size());
  6503. }
  6504. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6505. // Only a 206 is served as a partial representation. Under any other status
  6506. // `apply_ranges()` reported the full content length, so the body must match
  6507. // that header, and the content provider must never be asked for an offset
  6508. // outside the representation.
  6509. auto check = [&](int status, const char *range) {
  6510. auto path =
  6511. std::string("/streamed-with-range?status=") + std::to_string(status);
  6512. auto ctx = path + " Range: " + range;
  6513. auto res = cli_.Get(path, Headers{{"Range", range}});
  6514. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6515. EXPECT_EQ(status, res->status) << ctx;
  6516. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6517. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6518. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6519. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6520. };
  6521. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6522. check(403, "bytes=3-5");
  6523. // The offset is far past the representation.
  6524. check(403, "bytes=100000-100200");
  6525. // `first_pos` is still -1 here, and the bounds asserts in
  6526. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6527. check(403, "bytes=-3");
  6528. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6529. // multipart branch would have written one that is empty.
  6530. check(403, "bytes=1-2, 4-5");
  6531. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6532. // covers the whole representation.
  6533. check(200, "bytes=3-5");
  6534. check(200, "bytes=1-2, 4-5");
  6535. }
  6536. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6537. auto res =
  6538. cli_.Get("/streamed-with-range",
  6539. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6540. "92233720368547758079223372036854775807"}});
  6541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6542. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6543. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6544. EXPECT_EQ(false, res->has_header("Content-Range"));
  6545. EXPECT_EQ(0U, res->body.size());
  6546. }
  6547. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6548. auto res = cli_.Get(
  6549. "/with-range",
  6550. Headers{{"Range",
  6551. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6552. {"Accept-Encoding", ""}});
  6553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6554. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6555. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6556. EXPECT_EQ(true, res->has_header("Content-Range"));
  6557. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6558. EXPECT_EQ(std::string("abcdefg"), res->body);
  6559. }
  6560. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6561. auto res = cli_.Get("/with-range", Headers{
  6562. {"Range", "bytes=0-"},
  6563. {"Accept-Encoding", ""},
  6564. });
  6565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6566. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6567. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6568. EXPECT_EQ(true, res->has_header("Content-Range"));
  6569. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6570. EXPECT_EQ(std::string("abcdefg"), res->body);
  6571. }
  6572. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6573. auto res = cli_.Get("/streamed-with-range",
  6574. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6576. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6577. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6578. EXPECT_EQ(false, res->has_header("Content-Range"));
  6579. EXPECT_EQ(267U, res->body.size());
  6580. // Check that both range contents are present
  6581. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6582. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6583. // Check that Content-Range headers are present for both ranges
  6584. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6585. std::string::npos);
  6586. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6587. std::string::npos);
  6588. }
  6589. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6590. Ranges ranges;
  6591. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6592. ranges.emplace_back(0, -1);
  6593. }
  6594. auto res = cli_.Get("/streamed-with-range?error",
  6595. Headers{{make_range_header(ranges)}});
  6596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6597. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6598. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6599. EXPECT_EQ(false, res->has_header("Content-Range"));
  6600. EXPECT_EQ(0U, res->body.size());
  6601. }
  6602. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6603. auto res = cli_.Get("/streamed-with-range",
  6604. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6606. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6607. EXPECT_EQ(5U, res->body.size());
  6608. // Check that overlapping ranges are coalesced into a single range
  6609. EXPECT_EQ("bcdef", res->body);
  6610. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6611. // Should be single range, not multipart
  6612. EXPECT_TRUE(res->has_header("Content-Range"));
  6613. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6614. }
  6615. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6616. auto res = cli_.Get("/streamed-with-range",
  6617. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6619. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6620. EXPECT_EQ(268U, res->body.size());
  6621. // Check that both range contents are present
  6622. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6623. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6624. // Check that Content-Range headers are present for both ranges
  6625. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6626. std::string::npos);
  6627. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6628. std::string::npos);
  6629. }
  6630. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6631. auto res = cli_.Get("/streamed-with-range",
  6632. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6634. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6635. EXPECT_EQ(269U, res->body.size());
  6636. // Check that both duplicate range contents are present
  6637. size_t first_abc = res->body.find("abc\r\n");
  6638. EXPECT_TRUE(first_abc != std::string::npos);
  6639. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6640. EXPECT_TRUE(second_abc != std::string::npos);
  6641. // Check that Content-Range headers are present for both ranges
  6642. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6643. EXPECT_TRUE(first_range != std::string::npos);
  6644. size_t second_range =
  6645. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6646. EXPECT_TRUE(second_range != std::string::npos);
  6647. }
  6648. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6649. auto res =
  6650. cli_.Get("/streamed-with-range?error",
  6651. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6653. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6654. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6655. EXPECT_EQ(false, res->has_header("Content-Range"));
  6656. EXPECT_EQ(0U, res->body.size());
  6657. }
  6658. TEST_F(ServerTest, GetStreamedEndless) {
  6659. uint64_t offset = 0;
  6660. auto res = cli_.Get("/streamed-cancel",
  6661. [&](const char * /*data*/, uint64_t data_length) {
  6662. if (offset < 100) {
  6663. offset += data_length;
  6664. return true;
  6665. }
  6666. return false;
  6667. });
  6668. ASSERT_TRUE(!res);
  6669. EXPECT_EQ(Error::Canceled, res.error());
  6670. }
  6671. TEST_F(ServerTest, ClientStop) {
  6672. std::atomic_size_t count{4};
  6673. std::vector<std::thread> threads;
  6674. for (auto i = count.load(); i != 0; --i) {
  6675. threads.emplace_back([&]() {
  6676. auto res = cli_.Get("/streamed-cancel",
  6677. [&](const char *, uint64_t) { return true; });
  6678. --count;
  6679. ASSERT_TRUE(!res);
  6680. EXPECT_TRUE(res.error() == Error::Canceled ||
  6681. res.error() == Error::Read || res.error() == Error::Write);
  6682. });
  6683. }
  6684. std::this_thread::sleep_for(std::chrono::seconds(2));
  6685. while (count != 0) {
  6686. cli_.stop();
  6687. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6688. }
  6689. for (auto &t : threads) {
  6690. t.join();
  6691. }
  6692. }
  6693. TEST_F(ServerTest, GetWithRange1) {
  6694. auto res = cli_.Get("/with-range", Headers{
  6695. make_range_header({{3, 5}}),
  6696. {"Accept-Encoding", ""},
  6697. });
  6698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6699. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6700. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6701. EXPECT_EQ(true, res->has_header("Content-Range"));
  6702. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6703. EXPECT_EQ(std::string("def"), res->body);
  6704. }
  6705. TEST_F(ServerTest, GetWithRange2) {
  6706. auto res = cli_.Get("/with-range", Headers{
  6707. make_range_header({{1, -1}}),
  6708. {"Accept-Encoding", ""},
  6709. });
  6710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6711. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6712. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6713. EXPECT_EQ(true, res->has_header("Content-Range"));
  6714. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6715. EXPECT_EQ(std::string("bcdefg"), res->body);
  6716. }
  6717. TEST_F(ServerTest, GetWithRange3) {
  6718. auto res = cli_.Get("/with-range", Headers{
  6719. make_range_header({{0, 0}}),
  6720. {"Accept-Encoding", ""},
  6721. });
  6722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6723. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6724. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6725. EXPECT_EQ(true, res->has_header("Content-Range"));
  6726. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6727. EXPECT_EQ(std::string("a"), res->body);
  6728. }
  6729. TEST_F(ServerTest, GetWithRange4) {
  6730. auto res = cli_.Get("/with-range", Headers{
  6731. make_range_header({{-1, 2}}),
  6732. {"Accept-Encoding", ""},
  6733. });
  6734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6735. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6736. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6737. EXPECT_EQ(true, res->has_header("Content-Range"));
  6738. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6739. EXPECT_EQ(std::string("fg"), res->body);
  6740. }
  6741. TEST_F(ServerTest, GetWithRange5) {
  6742. auto res = cli_.Get("/with-range", Headers{
  6743. make_range_header({{0, 5}}),
  6744. {"Accept-Encoding", ""},
  6745. });
  6746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6747. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6748. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6749. EXPECT_EQ(true, res->has_header("Content-Range"));
  6750. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6751. EXPECT_EQ(std::string("abcdef"), res->body);
  6752. }
  6753. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6754. auto res =
  6755. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6757. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6758. }
  6759. TEST_F(ServerTest, GetWithRangeMultipart) {
  6760. auto res =
  6761. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6763. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6764. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6765. EXPECT_EQ(false, res->has_header("Content-Range"));
  6766. EXPECT_EQ(267U, res->body.size());
  6767. }
  6768. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6769. auto res = cli_.Get("/with-range",
  6770. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6772. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6773. }
  6774. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6775. auto res = cli_.Get("/with-range-customized-response",
  6776. Headers{{make_range_header({{1, 2}})}});
  6777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6778. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6779. EXPECT_EQ(true, res->has_header("Content-Length"));
  6780. EXPECT_EQ(false, res->has_header("Content-Range"));
  6781. EXPECT_EQ(JSON_DATA, res->body);
  6782. }
  6783. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6784. auto res = cli_.Get("/with-range-customized-response",
  6785. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6787. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6788. EXPECT_EQ(true, res->has_header("Content-Length"));
  6789. EXPECT_EQ(false, res->has_header("Content-Range"));
  6790. EXPECT_EQ(JSON_DATA, res->body);
  6791. }
  6792. TEST_F(ServerTest, Issue1772) {
  6793. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6795. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6796. }
  6797. TEST_F(ServerTest, Issue609) {
  6798. auto res = cli_.Delete("/issue609");
  6799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6800. EXPECT_EQ(StatusCode::OK_200, res->status);
  6801. EXPECT_EQ(std::string("ok"), res->body);
  6802. }
  6803. TEST_F(ServerTest, GetStreamedChunked) {
  6804. auto res = cli_.Get("/streamed-chunked");
  6805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6806. EXPECT_EQ(StatusCode::OK_200, res->status);
  6807. EXPECT_EQ(std::string("123456789"), res->body);
  6808. }
  6809. TEST_F(ServerTest, GetStreamedChunked2) {
  6810. auto res = cli_.Get("/streamed-chunked2");
  6811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6812. EXPECT_EQ(StatusCode::OK_200, res->status);
  6813. EXPECT_EQ(std::string("123456789"), res->body);
  6814. }
  6815. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6816. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6818. EXPECT_EQ(StatusCode::OK_200, res->status);
  6819. EXPECT_EQ(std::string("123456789"), res->body);
  6820. EXPECT_TRUE(res->has_header("Trailer"));
  6821. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6822. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6823. // Trailers are now stored separately from headers (security fix)
  6824. EXPECT_EQ(2U, res->trailers.size());
  6825. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6826. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6827. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6828. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6829. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6830. // Verify trailers are NOT in headers (security verification)
  6831. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6832. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6833. }
  6834. TEST_F(ServerTest, LargeChunkedPost) {
  6835. Request req;
  6836. req.method = "POST";
  6837. req.path = "/large-chunked";
  6838. std::string host_and_port;
  6839. host_and_port += HOST;
  6840. host_and_port += ":";
  6841. host_and_port += std::to_string(PORT);
  6842. req.headers.emplace("Host", host_and_port.c_str());
  6843. req.headers.emplace("Accept", "*/*");
  6844. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6845. req.headers.emplace("Content-Type", "text/plain");
  6846. req.headers.emplace("Content-Length", "0");
  6847. req.headers.emplace("Transfer-Encoding", "chunked");
  6848. std::string long_string(30 * 1024u, 'a');
  6849. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6850. // Attempt to make a large enough post to exceed OS buffers, to test that
  6851. // the server handles short reads if the full chunk data isn't available.
  6852. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6853. auto res = std::make_shared<Response>();
  6854. auto error = Error::Success;
  6855. auto ret = cli_.send(req, *res, error);
  6856. ASSERT_TRUE(ret);
  6857. EXPECT_EQ(StatusCode::OK_200, res->status);
  6858. }
  6859. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6860. auto res = cli_.Get("/remote_addr");
  6861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6862. EXPECT_EQ(StatusCode::OK_200, res->status);
  6863. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6864. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6865. }
  6866. TEST_F(ServerTest, GetMethodLocalAddr) {
  6867. auto res = cli_.Get("/local_addr");
  6868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6869. EXPECT_EQ(StatusCode::OK_200, res->status);
  6870. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6871. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6872. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6873. }
  6874. TEST_F(ServerTest, HTTPResponseSplitting) {
  6875. auto res = cli_.Get("/http_response_splitting");
  6876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6877. EXPECT_EQ(StatusCode::OK_200, res->status);
  6878. }
  6879. TEST_F(ServerTest, SlowRequest) {
  6880. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6881. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6882. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6883. }
  6884. #if 0
  6885. TEST_F(ServerTest, SlowPost) {
  6886. char buffer[64 * 1024];
  6887. memset(buffer, 0x42, sizeof(buffer));
  6888. auto res = cli_.Post(
  6889. "/slowpost", 64 * 1024 * 1024,
  6890. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6891. auto ret = sink.write(buffer, sizeof(buffer));
  6892. EXPECT_TRUE(ret);
  6893. return true;
  6894. },
  6895. "text/plain");
  6896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6897. EXPECT_EQ(StatusCode::OK_200, res->status);
  6898. }
  6899. TEST_F(ServerTest, SlowPostFail) {
  6900. char buffer[64 * 1024];
  6901. memset(buffer, 0x42, sizeof(buffer));
  6902. cli_.set_write_timeout(std::chrono::seconds(0));
  6903. auto res = cli_.Post(
  6904. "/slowpost", 64 * 1024 * 1024,
  6905. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6906. sink.write(buffer, sizeof(buffer));
  6907. return true;
  6908. },
  6909. "text/plain");
  6910. ASSERT_TRUE(!res);
  6911. EXPECT_EQ(Error::Write, res.error());
  6912. }
  6913. #endif
  6914. TEST_F(ServerTest, Put) {
  6915. auto res = cli_.Put("/put", "PUT", "text/plain");
  6916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6917. EXPECT_EQ(StatusCode::OK_200, res->status);
  6918. EXPECT_EQ("PUT", res->body);
  6919. }
  6920. TEST_F(ServerTest, PutWithContentProvider) {
  6921. auto res = cli_.Put(
  6922. "/put", 3,
  6923. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6924. sink.os << "PUT";
  6925. return true;
  6926. },
  6927. "text/plain");
  6928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6929. EXPECT_EQ(StatusCode::OK_200, res->status);
  6930. EXPECT_EQ("PUT", res->body);
  6931. }
  6932. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6933. auto res = cli_.Post(
  6934. "/post", 42,
  6935. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6936. return false;
  6937. },
  6938. "text/plain");
  6939. ASSERT_TRUE(!res);
  6940. EXPECT_EQ(Error::Canceled, res.error());
  6941. }
  6942. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6943. auto res = cli_.Put(
  6944. "/put",
  6945. [](size_t /*offset*/, DataSink &sink) {
  6946. sink.os << "PUT";
  6947. sink.done();
  6948. return true;
  6949. },
  6950. "text/plain");
  6951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6952. EXPECT_EQ(StatusCode::OK_200, res->status);
  6953. EXPECT_EQ("PUT", res->body);
  6954. }
  6955. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6956. auto res = cli_.Post(
  6957. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6958. "text/plain");
  6959. ASSERT_TRUE(!res);
  6960. EXPECT_EQ(Error::Canceled, res.error());
  6961. }
  6962. TEST_F(ServerTest, PostLoopBack) {
  6963. std::string body;
  6964. auto res = cli_.Post(
  6965. "/post-loopback", 9,
  6966. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6967. EXPECT_EQ(9u, length);
  6968. sink.write("123", 3);
  6969. sink.write("456", 3);
  6970. sink.write("789", 3);
  6971. return true;
  6972. },
  6973. "text/plain",
  6974. [&body](const char *data, size_t data_length) {
  6975. body.append(data, data_length);
  6976. return true;
  6977. });
  6978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6979. EXPECT_EQ(StatusCode::OK_200, res->status);
  6980. EXPECT_EQ("123456789", body);
  6981. }
  6982. TEST_F(ServerTest, PutLoopBack) {
  6983. std::string body;
  6984. auto res = cli_.Put(
  6985. "/put-loopback", 9,
  6986. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6987. EXPECT_EQ(9u, length);
  6988. sink.write("123", 3);
  6989. sink.write("456", 3);
  6990. sink.write("789", 3);
  6991. return true;
  6992. },
  6993. "text/plain",
  6994. [&body](const char *data, size_t data_length) {
  6995. body.append(data, data_length);
  6996. return true;
  6997. });
  6998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6999. EXPECT_EQ(StatusCode::OK_200, res->status);
  7000. EXPECT_EQ("123456789", body);
  7001. }
  7002. TEST_F(ServerTest, PatchLoopBack) {
  7003. std::string body;
  7004. auto res = cli_.Patch(
  7005. "/patch-loopback", 9,
  7006. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7007. EXPECT_EQ(9u, length);
  7008. sink.write("123", 3);
  7009. sink.write("456", 3);
  7010. sink.write("789", 3);
  7011. return true;
  7012. },
  7013. "text/plain",
  7014. [&body](const char *data, size_t data_length) {
  7015. body.append(data, data_length);
  7016. return true;
  7017. });
  7018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7019. EXPECT_EQ(StatusCode::OK_200, res->status);
  7020. EXPECT_EQ("123456789", body);
  7021. }
  7022. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7023. std::string body;
  7024. auto res = cli_.Post(
  7025. "/post-loopback",
  7026. [](size_t /*offset*/, DataSink &sink) {
  7027. sink.write("123", 3);
  7028. sink.write("456", 3);
  7029. sink.write("789", 3);
  7030. sink.done();
  7031. return true;
  7032. },
  7033. "text/plain",
  7034. [&body](const char *data, size_t data_length) {
  7035. body.append(data, data_length);
  7036. return true;
  7037. });
  7038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7039. EXPECT_EQ(StatusCode::OK_200, res->status);
  7040. EXPECT_EQ("123456789", body);
  7041. }
  7042. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7043. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7044. cli_.set_compress(true);
  7045. auto res = cli_.Put(
  7046. "/put", 3,
  7047. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7048. sink.os << "PUT";
  7049. return true;
  7050. },
  7051. "text/plain");
  7052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7053. EXPECT_EQ(StatusCode::OK_200, res->status);
  7054. EXPECT_EQ("PUT", res->body);
  7055. }
  7056. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7057. cli_.set_compress(true);
  7058. auto res = cli_.Post(
  7059. "/post", 42,
  7060. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7061. return false;
  7062. },
  7063. "text/plain");
  7064. ASSERT_TRUE(!res);
  7065. EXPECT_EQ(Error::Canceled, res.error());
  7066. }
  7067. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7068. cli_.set_compress(true);
  7069. auto res = cli_.Put(
  7070. "/put",
  7071. [](size_t /*offset*/, DataSink &sink) {
  7072. sink.os << "PUT";
  7073. sink.done();
  7074. return true;
  7075. },
  7076. "text/plain");
  7077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7078. EXPECT_EQ(StatusCode::OK_200, res->status);
  7079. EXPECT_EQ("PUT", res->body);
  7080. }
  7081. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7082. cli_.set_compress(true);
  7083. auto res = cli_.Post(
  7084. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7085. "text/plain");
  7086. ASSERT_TRUE(!res);
  7087. EXPECT_EQ(Error::Canceled, res.error());
  7088. }
  7089. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7090. cli_.set_compress(true);
  7091. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7093. EXPECT_EQ(StatusCode::OK_200, res->status);
  7094. EXPECT_EQ(LARGE_DATA, res->body);
  7095. }
  7096. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7097. #ifdef CPPHTTPLIB_SSL_ENABLED
  7098. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7099. Client cli(s.c_str());
  7100. cli.enable_server_certificate_verification(false);
  7101. #else
  7102. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7103. Client cli(s.c_str());
  7104. #endif
  7105. cli.set_compress(true);
  7106. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7108. EXPECT_EQ(StatusCode::OK_200, res->status);
  7109. EXPECT_EQ(LARGE_DATA, res->body);
  7110. // The compressed size should be less than a 10th of the original. May vary
  7111. // depending on the zlib library.
  7112. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7113. static_cast<uint64_t>(10 * 1024 * 1024));
  7114. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7115. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7116. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7117. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7118. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7119. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7120. #endif
  7121. }
  7122. TEST_F(ServerTest, PutContentWithDeflate) {
  7123. cli_.set_compress(false);
  7124. Headers headers;
  7125. headers.emplace("Content-Encoding", "deflate");
  7126. // PUT in deflate format:
  7127. auto res = cli_.Put("/put", headers,
  7128. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7130. EXPECT_EQ(StatusCode::OK_200, res->status);
  7131. EXPECT_EQ("PUT", res->body);
  7132. }
  7133. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7134. Headers headers;
  7135. headers.emplace("Accept-Encoding", "gzip, deflate");
  7136. auto res = cli_.Get("/streamed-chunked", headers);
  7137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7138. EXPECT_EQ(StatusCode::OK_200, res->status);
  7139. EXPECT_EQ(std::string("123456789"), res->body);
  7140. }
  7141. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7142. Headers headers;
  7143. headers.emplace("Accept-Encoding", "gzip, deflate");
  7144. auto res = cli_.Get("/streamed-chunked2", headers);
  7145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7146. EXPECT_EQ(StatusCode::OK_200, res->status);
  7147. EXPECT_EQ(std::string("123456789"), res->body);
  7148. }
  7149. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7150. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7152. EXPECT_EQ(StatusCode::OK_200, res->status);
  7153. }
  7154. TEST(GzipDecompressor, ChunkedDecompression) {
  7155. std::string data;
  7156. for (size_t i = 0; i < 32 * 1024; ++i) {
  7157. data.push_back(static_cast<char>('a' + i % 26));
  7158. }
  7159. std::string compressed_data;
  7160. {
  7161. httplib::detail::gzip_compressor compressor;
  7162. bool result = compressor.compress(
  7163. data.data(), data.size(),
  7164. /*last=*/true,
  7165. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7166. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7167. compressed_data_size);
  7168. return true;
  7169. });
  7170. ASSERT_TRUE(result);
  7171. }
  7172. std::string decompressed_data;
  7173. {
  7174. httplib::detail::gzip_decompressor decompressor;
  7175. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7176. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7177. size_t chunk_size = 130;
  7178. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7179. chunk_begin += chunk_size) {
  7180. size_t current_chunk_size =
  7181. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7182. bool result = decompressor.decompress(
  7183. compressed_data.data() + chunk_begin, current_chunk_size,
  7184. [&](const char *decompressed_data_chunk,
  7185. size_t decompressed_data_chunk_size) {
  7186. decompressed_data.insert(decompressed_data.size(),
  7187. decompressed_data_chunk,
  7188. decompressed_data_chunk_size);
  7189. return true;
  7190. });
  7191. ASSERT_TRUE(result);
  7192. }
  7193. }
  7194. ASSERT_EQ(data, decompressed_data);
  7195. }
  7196. TEST(GzipDecompressor, DeflateDecompression) {
  7197. std::string original_text = "Raw deflate without gzip";
  7198. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7199. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7200. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7201. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7202. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7203. std::string decompressed_data;
  7204. {
  7205. httplib::detail::gzip_decompressor decompressor;
  7206. bool result = decompressor.decompress(
  7207. compressed_data.data(), compressed_data.size(),
  7208. [&](const char *decompressed_data_chunk,
  7209. size_t decompressed_data_chunk_size) {
  7210. decompressed_data.insert(decompressed_data.size(),
  7211. decompressed_data_chunk,
  7212. decompressed_data_chunk_size);
  7213. return true;
  7214. });
  7215. ASSERT_TRUE(result);
  7216. }
  7217. ASSERT_EQ(original_text, decompressed_data);
  7218. }
  7219. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7220. std::string original_text = "Raw deflate without gzip";
  7221. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7222. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7223. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7224. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7225. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7226. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7227. std::string decompressed_data;
  7228. {
  7229. httplib::detail::gzip_decompressor decompressor;
  7230. bool result = decompressor.decompress(
  7231. compressed_data.data(), compressed_data.size(),
  7232. [&](const char *decompressed_data_chunk,
  7233. size_t decompressed_data_chunk_size) {
  7234. decompressed_data.insert(decompressed_data.size(),
  7235. decompressed_data_chunk,
  7236. decompressed_data_chunk_size);
  7237. return true;
  7238. });
  7239. ASSERT_TRUE(result);
  7240. }
  7241. ASSERT_EQ(original_text, decompressed_data);
  7242. }
  7243. #endif
  7244. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7245. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7246. Headers headers;
  7247. headers.emplace("Accept-Encoding", "br");
  7248. auto res = cli_.Get("/streamed-chunked", headers);
  7249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7250. EXPECT_EQ(StatusCode::OK_200, res->status);
  7251. EXPECT_EQ(std::string("123456789"), res->body);
  7252. }
  7253. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7254. Headers headers;
  7255. headers.emplace("Accept-Encoding", "br");
  7256. auto res = cli_.Get("/streamed-chunked2", headers);
  7257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7258. EXPECT_EQ(StatusCode::OK_200, res->status);
  7259. EXPECT_EQ(std::string("123456789"), res->body);
  7260. }
  7261. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7262. cli_.set_compress(true);
  7263. auto res = cli_.Put(
  7264. "/put", 3,
  7265. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7266. sink.os << "PUT";
  7267. return true;
  7268. },
  7269. "text/plain");
  7270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7271. EXPECT_EQ(StatusCode::OK_200, res->status);
  7272. EXPECT_EQ("PUT", res->body);
  7273. }
  7274. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7275. cli_.set_compress(true);
  7276. auto res = cli_.Put(
  7277. "/put",
  7278. [](size_t /*offset*/, DataSink &sink) {
  7279. sink.os << "PUT";
  7280. sink.done();
  7281. return true;
  7282. },
  7283. "text/plain");
  7284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7285. EXPECT_EQ(StatusCode::OK_200, res->status);
  7286. EXPECT_EQ("PUT", res->body);
  7287. }
  7288. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7289. cli_.set_compress(true);
  7290. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7292. EXPECT_EQ(StatusCode::OK_200, res->status);
  7293. EXPECT_EQ(LARGE_DATA, res->body);
  7294. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7295. }
  7296. #endif
  7297. TEST_F(ServerTest, Patch) {
  7298. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7300. EXPECT_EQ(StatusCode::OK_200, res->status);
  7301. EXPECT_EQ("PATCH", res->body);
  7302. }
  7303. TEST_F(ServerTest, Delete) {
  7304. auto res = cli_.Delete("/delete");
  7305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7306. EXPECT_EQ(StatusCode::OK_200, res->status);
  7307. EXPECT_EQ("DELETE", res->body);
  7308. }
  7309. TEST_F(ServerTest, DeleteContentReceiver) {
  7310. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7312. EXPECT_EQ(StatusCode::OK_200, res->status);
  7313. EXPECT_EQ("content", res->body);
  7314. }
  7315. TEST_F(ServerTest, Options) {
  7316. auto res = cli_.Options("*");
  7317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7318. EXPECT_EQ(StatusCode::OK_200, res->status);
  7319. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7320. EXPECT_TRUE(res->body.empty());
  7321. }
  7322. TEST_F(ServerTest, URL) {
  7323. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7325. EXPECT_EQ(StatusCode::OK_200, res->status);
  7326. }
  7327. TEST_F(ServerTest, ArrayParam) {
  7328. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7330. EXPECT_EQ(StatusCode::OK_200, res->status);
  7331. }
  7332. TEST_F(ServerTest, ArrayParamValues) {
  7333. auto res =
  7334. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7336. EXPECT_EQ(StatusCode::OK_200, res->status);
  7337. }
  7338. TEST_F(ServerTest, NoMultipleHeaders) {
  7339. Headers headers = {{"Content-Length", "5"}};
  7340. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7341. "text/plain");
  7342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7343. EXPECT_EQ(StatusCode::OK_200, res->status);
  7344. }
  7345. TEST_F(ServerTest, PostContentReceiver) {
  7346. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7348. ASSERT_EQ(StatusCode::OK_200, res->status);
  7349. ASSERT_EQ("content", res->body);
  7350. }
  7351. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7352. UploadFormDataItems items = {
  7353. {"text1", "text default", "", ""},
  7354. {"text2", "aωb", "", ""},
  7355. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7356. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7357. {"file3", "", "", "application/octet-stream"},
  7358. };
  7359. auto res = cli_.Post("/content_receiver", items);
  7360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7361. EXPECT_EQ(StatusCode::OK_200, res->status);
  7362. }
  7363. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7364. UploadFormDataItems items = {
  7365. {"text1", "text default", "", ""},
  7366. {"text2", "aωb", "", ""},
  7367. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7368. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7369. {"file3", "", "", "application/octet-stream"},
  7370. };
  7371. auto boundary = std::string("+++++");
  7372. std::string body;
  7373. for (const auto &item : items) {
  7374. body += "--" + boundary + "\r\n";
  7375. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7376. if (!item.filename.empty()) {
  7377. body += "; filename=\"" + item.filename + "\"";
  7378. }
  7379. body += "\r\n";
  7380. if (!item.content_type.empty()) {
  7381. body += "Content-Type: " + item.content_type + "\r\n";
  7382. }
  7383. body += "\r\n";
  7384. body += item.content + "\r\n";
  7385. }
  7386. body += "--" + boundary + "--\r\n";
  7387. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7388. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7390. EXPECT_EQ(StatusCode::OK_200, res->status);
  7391. }
  7392. TEST(MultipartFormDataTest, FieldEscaping) {
  7393. Server svr;
  7394. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7395. const ContentReader &content_reader) {
  7396. ASSERT_TRUE(req.is_multipart_form_data());
  7397. std::vector<FormData> received;
  7398. content_reader(
  7399. [&](const FormData &file) {
  7400. received.push_back(file);
  7401. return true;
  7402. },
  7403. [&](const char *data, size_t data_length) {
  7404. received.back().content.append(data, data_length);
  7405. return true;
  7406. });
  7407. // '"', CR and LF in names and filenames are escaped following the
  7408. // WHATWG HTML standard, so each part still parses as a single part
  7409. // with no injected headers. Content types get CR/LF escaped too,
  7410. // while '"' (legal there, e.g. quoted charset) is preserved.
  7411. ASSERT_EQ(4U, received.size());
  7412. EXPECT_EQ("na%22me", received[0].name);
  7413. EXPECT_EQ("quoted name", received[0].content);
  7414. EXPECT_EQ("file", received[1].name);
  7415. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7416. received[1].filename);
  7417. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7418. EXPECT_EQ("injected", received[1].content);
  7419. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7420. EXPECT_EQ("my%22file.txt", received[2].filename);
  7421. EXPECT_EQ("cr lf name", received[2].content);
  7422. EXPECT_EQ("typed", received[3].name);
  7423. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7424. received[3].content_type);
  7425. EXPECT_EQ("typed content", received[3].content);
  7426. });
  7427. auto port = svr.bind_to_any_port("localhost");
  7428. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7429. auto se = detail::scope_exit([&] {
  7430. svr.stop();
  7431. t.join();
  7432. ASSERT_FALSE(svr.is_running());
  7433. });
  7434. svr.wait_until_ready();
  7435. Client cli("localhost", port);
  7436. UploadFormDataItems items = {
  7437. {"na\"me", "quoted name", "", ""},
  7438. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7439. "application/octet-stream"},
  7440. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7441. {"typed", "typed content", "",
  7442. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7443. };
  7444. auto res = cli.Post("/post", items);
  7445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7446. EXPECT_EQ(StatusCode::OK_200, res->status);
  7447. }
  7448. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7449. const UploadFormDataItems items = {
  7450. {"name1", "Content 1", "", ""},
  7451. {"name2", "Content 2", "file2.txt", "text/plain"},
  7452. };
  7453. Server svr;
  7454. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7455. const ContentReader &content_reader) {
  7456. ASSERT_TRUE(req.is_multipart_form_data());
  7457. std::vector<FormData> received;
  7458. content_reader(
  7459. [&](const FormData &file) {
  7460. received.push_back(file);
  7461. return true;
  7462. },
  7463. [&](const char *data, size_t data_length) {
  7464. received.back().content.append(data, data_length);
  7465. return true;
  7466. });
  7467. ASSERT_EQ(2U, received.size());
  7468. EXPECT_EQ("name1", received[0].name);
  7469. EXPECT_EQ("Content 1", received[0].content);
  7470. EXPECT_EQ("name2", received[1].name);
  7471. EXPECT_EQ("Content 2", received[1].content);
  7472. EXPECT_EQ("file2.txt", received[1].filename);
  7473. EXPECT_EQ("text/plain", received[1].content_type);
  7474. });
  7475. auto port = svr.bind_to_any_port("localhost");
  7476. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7477. auto se = detail::scope_exit([&] {
  7478. svr.stop();
  7479. t.join();
  7480. ASSERT_FALSE(svr.is_running());
  7481. });
  7482. svr.wait_until_ready();
  7483. Client cli("localhost", port);
  7484. // Whole-body serialization with a generated boundary
  7485. {
  7486. MultipartFormDataWriter writer;
  7487. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7488. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7489. writer.content_type());
  7490. auto body = writer.serialize(items);
  7491. EXPECT_EQ(body.size(), writer.content_length(items));
  7492. auto res = cli.Post("/post", body, writer.content_type());
  7493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7494. EXPECT_EQ(StatusCode::OK_200, res->status);
  7495. }
  7496. // Per-part framing with a custom boundary via a content provider
  7497. {
  7498. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7499. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7500. MultipartFormDataWriter writer("custom-boundary_123");
  7501. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7502. std::string body;
  7503. for (const auto &item : items) {
  7504. body += writer.item_begin(item);
  7505. body += item.content;
  7506. body += MultipartFormDataWriter::item_end();
  7507. }
  7508. body += writer.finish();
  7509. EXPECT_EQ(body.size(), writer.content_length(items));
  7510. auto res = cli.Post(
  7511. "/post", body.size(),
  7512. [&](size_t offset, size_t length, DataSink &sink) {
  7513. sink.write(body.data() + offset, length);
  7514. return true;
  7515. },
  7516. writer.content_type());
  7517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7518. EXPECT_EQ(StatusCode::OK_200, res->status);
  7519. }
  7520. }
  7521. TEST_F(ServerTest, PostContentReceiverGzip) {
  7522. cli_.set_compress(true);
  7523. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7525. ASSERT_EQ(StatusCode::OK_200, res->status);
  7526. ASSERT_EQ("content", res->body);
  7527. }
  7528. TEST_F(ServerTest, PutContentReceiver) {
  7529. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7531. ASSERT_EQ(StatusCode::OK_200, res->status);
  7532. ASSERT_EQ("content", res->body);
  7533. }
  7534. TEST_F(ServerTest, PatchContentReceiver) {
  7535. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7537. ASSERT_EQ(StatusCode::OK_200, res->status);
  7538. ASSERT_EQ("content", res->body);
  7539. }
  7540. template <typename ClientType>
  7541. void TestWithHeadersAndContentReceiver(
  7542. ClientType &cli,
  7543. std::function<Result(ClientType &, const std::string &, const Headers &,
  7544. const std::string &, const std::string &,
  7545. ContentReceiver, DownloadProgress)>
  7546. request_func) {
  7547. Headers headers;
  7548. headers.emplace("X-Custom-Header", "test-value");
  7549. std::string received_body;
  7550. auto res = request_func(
  7551. cli, "/content_receiver", headers, "content", "application/json",
  7552. [&](const char *data, size_t data_length) {
  7553. received_body.append(data, data_length);
  7554. return true;
  7555. },
  7556. nullptr);
  7557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7558. EXPECT_EQ(StatusCode::OK_200, res->status);
  7559. EXPECT_EQ("content", received_body);
  7560. }
  7561. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7562. #ifdef CPPHTTPLIB_SSL_ENABLED
  7563. using ClientT = SSLClient;
  7564. #else
  7565. using ClientT = Client;
  7566. #endif
  7567. TestWithHeadersAndContentReceiver<ClientT>(
  7568. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7569. const std::string &body, const std::string &content_type,
  7570. ContentReceiver receiver, DownloadProgress progress) {
  7571. return cli.Post(path, headers, body, content_type, receiver, progress);
  7572. });
  7573. }
  7574. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7575. #ifdef CPPHTTPLIB_SSL_ENABLED
  7576. using ClientT = SSLClient;
  7577. #else
  7578. using ClientT = Client;
  7579. #endif
  7580. TestWithHeadersAndContentReceiver<ClientT>(
  7581. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7582. const std::string &body, const std::string &content_type,
  7583. ContentReceiver receiver, DownloadProgress progress) {
  7584. return cli.Put(path, headers, body, content_type, receiver, progress);
  7585. });
  7586. }
  7587. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7588. #ifdef CPPHTTPLIB_SSL_ENABLED
  7589. using ClientT = SSLClient;
  7590. #else
  7591. using ClientT = Client;
  7592. #endif
  7593. TestWithHeadersAndContentReceiver<ClientT>(
  7594. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7595. const std::string &body, const std::string &content_type,
  7596. ContentReceiver receiver, DownloadProgress progress) {
  7597. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7598. });
  7599. }
  7600. template <typename ClientType>
  7601. void TestWithHeadersAndContentReceiverWithProgress(
  7602. ClientType &cli,
  7603. std::function<Result(ClientType &, const std::string &, const Headers &,
  7604. const std::string &, const std::string &,
  7605. ContentReceiver, DownloadProgress)>
  7606. request_func) {
  7607. Headers headers;
  7608. headers.emplace("X-Test-Header", "progress-test");
  7609. std::string received_body;
  7610. auto progress_called = false;
  7611. auto res = request_func(
  7612. cli, "/content_receiver", headers, "content", "text/plain",
  7613. [&](const char *data, size_t data_length) {
  7614. received_body.append(data, data_length);
  7615. return true;
  7616. },
  7617. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7618. progress_called = true;
  7619. return true;
  7620. });
  7621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7622. EXPECT_EQ(StatusCode::OK_200, res->status);
  7623. EXPECT_EQ("content", received_body);
  7624. EXPECT_TRUE(progress_called);
  7625. }
  7626. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7627. #ifdef CPPHTTPLIB_SSL_ENABLED
  7628. using ClientT = SSLClient;
  7629. #else
  7630. using ClientT = Client;
  7631. #endif
  7632. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7633. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7634. const std::string &body, const std::string &content_type,
  7635. ContentReceiver receiver, DownloadProgress progress) {
  7636. return cli.Post(path, headers, body, content_type, receiver, progress);
  7637. });
  7638. }
  7639. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7640. #ifdef CPPHTTPLIB_SSL_ENABLED
  7641. using ClientT = SSLClient;
  7642. #else
  7643. using ClientT = Client;
  7644. #endif
  7645. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7646. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7647. const std::string &body, const std::string &content_type,
  7648. ContentReceiver receiver, DownloadProgress progress) {
  7649. return cli.Put(path, headers, body, content_type, receiver, progress);
  7650. });
  7651. }
  7652. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7653. #ifdef CPPHTTPLIB_SSL_ENABLED
  7654. using ClientT = SSLClient;
  7655. #else
  7656. using ClientT = Client;
  7657. #endif
  7658. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7659. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7660. const std::string &body, const std::string &content_type,
  7661. ContentReceiver receiver, DownloadProgress progress) {
  7662. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7663. });
  7664. }
  7665. template <typename ClientType>
  7666. void TestWithHeadersAndContentReceiverError(
  7667. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7668. const Headers &, const std::string &,
  7669. const std::string &, ContentReceiver)>
  7670. request_func) {
  7671. Headers headers;
  7672. headers.emplace("X-Error-Test", "true");
  7673. std::string received_body;
  7674. auto receiver_failed = false;
  7675. auto res =
  7676. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7677. [&](const char *data, size_t data_length) {
  7678. received_body.append(data, data_length);
  7679. receiver_failed = true;
  7680. return false;
  7681. });
  7682. ASSERT_FALSE(res);
  7683. EXPECT_TRUE(receiver_failed);
  7684. }
  7685. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7686. #ifdef CPPHTTPLIB_SSL_ENABLED
  7687. using ClientT = SSLClient;
  7688. #else
  7689. using ClientT = Client;
  7690. #endif
  7691. TestWithHeadersAndContentReceiverError<ClientT>(
  7692. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7693. const std::string &body, const std::string &content_type,
  7694. ContentReceiver receiver) {
  7695. return cli.Post(path, headers, body, content_type, receiver);
  7696. });
  7697. }
  7698. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7699. #ifdef CPPHTTPLIB_SSL_ENABLED
  7700. using ClientT = SSLClient;
  7701. #else
  7702. using ClientT = Client;
  7703. #endif
  7704. TestWithHeadersAndContentReceiverError<ClientT>(
  7705. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7706. const std::string &body, const std::string &content_type,
  7707. ContentReceiver receiver) {
  7708. return cli.Put(path, headers, body, content_type, receiver);
  7709. });
  7710. }
  7711. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7712. #ifdef CPPHTTPLIB_SSL_ENABLED
  7713. using ClientT = SSLClient;
  7714. #else
  7715. using ClientT = Client;
  7716. #endif
  7717. TestWithHeadersAndContentReceiverError<ClientT>(
  7718. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7719. const std::string &body, const std::string &content_type,
  7720. ContentReceiver receiver) {
  7721. return cli.Patch(path, headers, body, content_type, receiver);
  7722. });
  7723. }
  7724. TEST_F(ServerTest, PostQueryStringAndBody) {
  7725. auto res =
  7726. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7728. ASSERT_EQ(StatusCode::OK_200, res->status);
  7729. }
  7730. TEST_F(ServerTest, HTTP2Magic) {
  7731. Request req;
  7732. req.method = "PRI";
  7733. req.path = "*";
  7734. req.body = "SM";
  7735. auto res = std::make_shared<Response>();
  7736. auto error = Error::Success;
  7737. auto ret = cli_.send(req, *res, error);
  7738. ASSERT_TRUE(ret);
  7739. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7740. }
  7741. TEST_F(ServerTest, KeepAlive) {
  7742. auto res = cli_.Get("/hi");
  7743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7744. EXPECT_EQ(StatusCode::OK_200, res->status);
  7745. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7746. EXPECT_EQ("Hello World!", res->body);
  7747. res = cli_.Get("/hi");
  7748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7749. EXPECT_EQ(StatusCode::OK_200, res->status);
  7750. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7751. EXPECT_EQ("Hello World!", res->body);
  7752. res = cli_.Get("/hi");
  7753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7754. EXPECT_EQ(StatusCode::OK_200, res->status);
  7755. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7756. EXPECT_EQ("Hello World!", res->body);
  7757. res = cli_.Get("/not-exist");
  7758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7759. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7760. res = cli_.Post("/empty", "", "text/plain");
  7761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7762. EXPECT_EQ(StatusCode::OK_200, res->status);
  7763. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7764. EXPECT_EQ("empty", res->body);
  7765. EXPECT_EQ("close", res->get_header_value("Connection"));
  7766. res = cli_.Post(
  7767. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7768. "text/plain");
  7769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7770. EXPECT_EQ(StatusCode::OK_200, res->status);
  7771. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7772. EXPECT_EQ("empty", res->body);
  7773. cli_.set_keep_alive(false);
  7774. res = cli_.Get("/last-request");
  7775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7776. EXPECT_EQ(StatusCode::OK_200, res->status);
  7777. EXPECT_EQ("close", res->get_header_value("Connection"));
  7778. }
  7779. TEST_F(ServerTest, TooManyRedirect) {
  7780. cli_.set_follow_location(true);
  7781. auto res = cli_.Get("/redirect/0");
  7782. ASSERT_TRUE(!res);
  7783. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7784. }
  7785. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7786. Request req;
  7787. req.method = "FOOBAR";
  7788. req.path = "/hi";
  7789. cli_.set_keep_alive(true);
  7790. auto res = cli_.send(req);
  7791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7792. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7793. EXPECT_EQ("close", res->get_header_value("Connection"));
  7794. EXPECT_FALSE(cli_.is_socket_open());
  7795. }
  7796. TEST_F(ServerTest, CustomRouteReadsBody) {
  7797. const std::string xml =
  7798. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7799. Request req;
  7800. req.method = "PROPFIND";
  7801. req.path = "/dav/dir";
  7802. req.set_header("Depth", "1");
  7803. req.body = xml;
  7804. auto res = cli_.send(req);
  7805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7806. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7807. EXPECT_EQ(xml, res->body);
  7808. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7809. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7810. }
  7811. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7812. Request req;
  7813. req.method = "PROPFIND";
  7814. req.path = "/dav/42";
  7815. auto res = cli_.send(req);
  7816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7817. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7818. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7819. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7820. }
  7821. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7822. Request req;
  7823. req.method = "PROPFIND";
  7824. req.path = "/dav-re/123";
  7825. auto res = cli_.send(req);
  7826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7827. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7828. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7829. }
  7830. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7831. Request req;
  7832. req.method = "MKCOL";
  7833. req.path = "/dav-mkcol";
  7834. auto res = cli_.send(req);
  7835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7836. EXPECT_EQ(StatusCode::Created_201, res->status);
  7837. }
  7838. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7839. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7840. Request req;
  7841. req.method = "REPORT";
  7842. req.path = "/dav-report";
  7843. req.body = xml;
  7844. auto res = cli_.send(req);
  7845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7846. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7847. EXPECT_EQ(xml, res->body);
  7848. }
  7849. // A content reader route must fire even when the request carries no body,
  7850. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7851. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7852. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7853. Request req;
  7854. req.method = "REPORT";
  7855. req.path = "/dav-report";
  7856. auto res = cli_.send(req);
  7857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7858. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7859. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7860. }
  7861. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7862. Request req;
  7863. req.method = "PROPFIND";
  7864. req.path = "/not-dav";
  7865. auto res = cli_.send(req);
  7866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7867. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7868. }
  7869. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7870. Request req;
  7871. req.method = "UNLOCK";
  7872. req.path = "/dav/dir";
  7873. cli_.set_keep_alive(true);
  7874. auto res = cli_.send(req);
  7875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7876. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7877. EXPECT_EQ("close", res->get_header_value("Connection"));
  7878. EXPECT_FALSE(cli_.is_socket_open());
  7879. }
  7880. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7881. // The mount point serves this path, but only for GET and HEAD.
  7882. auto get_res = cli_.Get("/dir/index.html");
  7883. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7884. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7885. Request req;
  7886. req.method = "PROPFIND";
  7887. req.path = "/dir/index.html";
  7888. auto res = cli_.send(req);
  7889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7890. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7891. }
  7892. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7893. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7894. cli_.set_keep_alive(true);
  7895. for (auto i = 0; i < 2; i++) {
  7896. Request req;
  7897. req.method = "PROPFIND";
  7898. req.path = "/dav/dir";
  7899. req.body = xml;
  7900. auto res = cli_.send(req);
  7901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7902. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7903. EXPECT_EQ(xml, res->body);
  7904. EXPECT_TRUE(cli_.is_socket_open());
  7905. }
  7906. // A built-in method must still be served on the same connection.
  7907. cli_.set_keep_alive(false);
  7908. auto res = cli_.Get("/hi");
  7909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7910. EXPECT_EQ(StatusCode::OK_200, res->status);
  7911. EXPECT_EQ("close", res->get_header_value("Connection"));
  7912. }
  7913. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7914. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7915. Request req;
  7916. req.method = "PROPFIND";
  7917. req.path = "/dav/dir";
  7918. req.set_header("Expect", "100-continue");
  7919. req.body = xml;
  7920. auto res = cli_.send(req);
  7921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7922. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7923. EXPECT_EQ(xml, res->body);
  7924. }
  7925. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7926. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7927. TEST_F(ServerTest, Gzip) {
  7928. Headers headers;
  7929. headers.emplace("Accept-Encoding", "gzip, deflate");
  7930. auto res = cli_.Get("/compress", headers);
  7931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7932. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7933. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7934. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7935. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7936. "7890123456789012345678901234567890",
  7937. res->body);
  7938. EXPECT_EQ(StatusCode::OK_200, res->status);
  7939. }
  7940. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7941. Headers headers;
  7942. headers.emplace("Accept-Encoding", "gzip, deflate");
  7943. auto res = cli_.Get("/compress-with-charset", headers);
  7944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7945. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7946. EXPECT_EQ("application/json; charset=utf-8",
  7947. res->get_header_value("Content-Type"));
  7948. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7949. "7890123456789012345678901234567890",
  7950. res->body);
  7951. EXPECT_EQ(StatusCode::OK_200, res->status);
  7952. }
  7953. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7954. Headers headers;
  7955. headers.emplace("Accept-Encoding", "");
  7956. auto res = cli_.Get("/compress", headers);
  7957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7958. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7959. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7960. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7961. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7962. "7890123456789012345678901234567890",
  7963. res->body);
  7964. EXPECT_EQ(StatusCode::OK_200, res->status);
  7965. }
  7966. TEST_F(ServerTest, GzipWithContentReceiver) {
  7967. Headers headers;
  7968. headers.emplace("Accept-Encoding", "gzip, deflate");
  7969. std::string body;
  7970. auto res = cli_.Get("/compress", headers,
  7971. [&](const char *data, uint64_t data_length) {
  7972. EXPECT_EQ(100U, data_length);
  7973. body.append(data, data_length);
  7974. return true;
  7975. });
  7976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7977. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7978. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7979. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7980. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7981. "7890123456789012345678901234567890",
  7982. body);
  7983. EXPECT_EQ(StatusCode::OK_200, res->status);
  7984. }
  7985. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7986. Headers headers;
  7987. headers.emplace("Accept-Encoding", "gzip, deflate");
  7988. cli_.set_decompress(false);
  7989. auto res = cli_.Get("/compress", headers);
  7990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7991. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7992. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7993. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7994. EXPECT_EQ(33U, res->body.size());
  7995. EXPECT_EQ(StatusCode::OK_200, res->status);
  7996. }
  7997. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7998. Headers headers;
  7999. headers.emplace("Accept-Encoding", "");
  8000. std::string body;
  8001. auto res = cli_.Get("/compress", headers,
  8002. [&](const char *data, uint64_t data_length) {
  8003. EXPECT_EQ(100U, data_length);
  8004. body.append(data, data_length);
  8005. return true;
  8006. });
  8007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8008. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8009. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8010. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8011. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8012. "7890123456789012345678901234567890",
  8013. body);
  8014. EXPECT_EQ(StatusCode::OK_200, res->status);
  8015. }
  8016. TEST_F(ServerTest, NoGzip) {
  8017. Headers headers;
  8018. headers.emplace("Accept-Encoding", "gzip, deflate");
  8019. auto res = cli_.Get("/nocompress", headers);
  8020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8021. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8022. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8023. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8024. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8025. "7890123456789012345678901234567890",
  8026. res->body);
  8027. EXPECT_EQ(StatusCode::OK_200, res->status);
  8028. }
  8029. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8030. Headers headers;
  8031. headers.emplace("Accept-Encoding", "gzip, deflate");
  8032. std::string body;
  8033. auto res = cli_.Get("/nocompress", headers,
  8034. [&](const char *data, uint64_t data_length) {
  8035. EXPECT_EQ(100U, data_length);
  8036. body.append(data, data_length);
  8037. return true;
  8038. });
  8039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8040. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8041. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8042. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8043. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8044. "7890123456789012345678901234567890",
  8045. body);
  8046. EXPECT_EQ(StatusCode::OK_200, res->status);
  8047. }
  8048. TEST_F(ServerTest, MultipartFormDataGzip) {
  8049. UploadFormDataItems items = {
  8050. {"key1", "test", "", ""},
  8051. {"key2", "--abcdefg123", "", ""},
  8052. };
  8053. cli_.set_compress(true);
  8054. auto res = cli_.Post("/compress-multipart", items);
  8055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8056. EXPECT_EQ(StatusCode::OK_200, res->status);
  8057. }
  8058. #endif
  8059. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8060. // Static file compression is opt-in, so these run their own server rather than
  8061. // flipping it on for the shared ServerTest fixture, which would silently
  8062. // rewrite what every other static file test is asserting.
  8063. class StaticFileCompressionTest : public ::testing::Test {
  8064. protected:
  8065. void TearDown() override {
  8066. if (t_.joinable()) {
  8067. svr_.stop();
  8068. t_.join();
  8069. }
  8070. }
  8071. int start(const std::function<void(Server &)> &configure = nullptr) {
  8072. // Serves the same tree as a directory of build-time compressed assets
  8073. // would be served: the mount point names the coding the files are already
  8074. // stored in. Registered before "/" so it is the one that matches.
  8075. svr_.set_mount_point("/pre-encoded", "./www",
  8076. {{"Content-Encoding", "gzip"}});
  8077. svr_.set_mount_point("/", "./www");
  8078. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8079. res.set_file_content("./www/dir/index.html", "text/html");
  8080. });
  8081. svr_.Get("/pre-encoded-file-content",
  8082. [](const Request & /*req*/, Response &res) {
  8083. res.set_header("Content-Encoding", "gzip");
  8084. res.set_file_content("./www/dir/index.html", "text/html");
  8085. });
  8086. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8087. res.set_content_provider(
  8088. 6, "text/plain",
  8089. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8090. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8091. return true;
  8092. });
  8093. });
  8094. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8095. res.set_content_provider(
  8096. 1000, "text/plain",
  8097. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8098. if (offset < 100) {
  8099. std::string data(100, 'A');
  8100. sink.write(data.data(), data.size());
  8101. return true;
  8102. }
  8103. std::this_thread::sleep_for(std::chrono::seconds(2));
  8104. std::string data(900, 'B');
  8105. sink.write(data.data(), data.size());
  8106. return true;
  8107. });
  8108. });
  8109. if (configure) { configure(svr_); }
  8110. auto port = svr_.bind_to_any_port(HOST);
  8111. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8112. svr_.wait_until_ready();
  8113. return port;
  8114. }
  8115. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8116. // Every file under ./www except 1MB.txt is smaller than the default
  8117. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8118. // it out of the way.
  8119. static void enable_without_floor(Server &svr) {
  8120. svr.set_static_file_compression(true);
  8121. svr.set_static_file_compression_min_length(0);
  8122. }
  8123. Server svr_;
  8124. std::thread t_;
  8125. };
  8126. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8127. auto port = start();
  8128. Client cli(HOST, port);
  8129. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8131. EXPECT_EQ(StatusCode::OK_200, res->status);
  8132. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8133. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8134. EXPECT_EQ(1048576U, res->body.size());
  8135. }
  8136. TEST_F(StaticFileCompressionTest, MountPoint) {
  8137. auto port = start(enable);
  8138. Client cli(HOST, port);
  8139. cli.set_decompress(false);
  8140. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8142. EXPECT_EQ(StatusCode::OK_200, res->status);
  8143. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8144. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8145. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8146. // The response stays self-delimiting: a length, not a chunked body.
  8147. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8148. EXPECT_EQ(std::to_string(res->body.size()),
  8149. res->get_header_value("Content-Length"));
  8150. EXPECT_LT(res->body.size(), 1048576U);
  8151. EXPECT_FALSE(res->body.empty());
  8152. }
  8153. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8154. auto port = start(enable);
  8155. Client cli(HOST, port);
  8156. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8158. EXPECT_EQ(StatusCode::OK_200, res->status);
  8159. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8160. EXPECT_EQ(1048576U, res->body.size());
  8161. }
  8162. TEST_F(StaticFileCompressionTest, FileContent) {
  8163. auto port = start(enable_without_floor);
  8164. Client cli(HOST, port);
  8165. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8167. EXPECT_EQ(StatusCode::OK_200, res->status);
  8168. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8169. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8170. EXPECT_EQ(104U, res->body.size());
  8171. }
  8172. // A handler that serves an already-encoded file names the coding itself. The
  8173. // file-backed path decided its coding from Accept-Encoding and the content
  8174. // type alone, so it compressed the stored bytes a second time and appended a
  8175. // second Content-Encoding field line.
  8176. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8177. auto port = start(enable_without_floor);
  8178. Client cli(HOST, port);
  8179. cli.set_decompress(false);
  8180. auto res = cli.Get("/pre-encoded-file-content",
  8181. Headers{{"Accept-Encoding", "gzip"}});
  8182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8183. EXPECT_EQ(StatusCode::OK_200, res->status);
  8184. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8185. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8186. // Vary belongs to a coding the server chose, and it chose none here.
  8187. EXPECT_FALSE(res->has_header("Vary"));
  8188. // The file travels exactly as it is stored on disk.
  8189. EXPECT_EQ(104U, res->body.size());
  8190. }
  8191. // The 1MB file clears the default floor, so this one runs the configuration a
  8192. // deployment would actually have.
  8193. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8194. auto port = start(enable);
  8195. Client cli(HOST, port);
  8196. cli.set_decompress(false);
  8197. auto res =
  8198. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8200. EXPECT_EQ(StatusCode::OK_200, res->status);
  8201. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8202. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8203. EXPECT_FALSE(res->has_header("Vary"));
  8204. EXPECT_EQ(1048576U, res->body.size());
  8205. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8206. }
  8207. TEST_F(StaticFileCompressionTest, Head) {
  8208. auto port = start(enable);
  8209. Client cli(HOST, port);
  8210. cli.set_decompress(false);
  8211. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8212. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8213. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8215. EXPECT_EQ(StatusCode::OK_200, res->status);
  8216. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8217. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8218. // HEAD still reports the size a GET would return.
  8219. EXPECT_EQ(get->get_header_value("Content-Length"),
  8220. res->get_header_value("Content-Length"));
  8221. EXPECT_TRUE(res->body.empty());
  8222. }
  8223. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8224. auto port = start(enable);
  8225. Client cli(HOST, port);
  8226. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8227. {"Accept-Encoding", "gzip"}});
  8228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8229. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8230. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8231. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8232. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8233. EXPECT_EQ("cd", res->body);
  8234. }
  8235. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8236. auto port = start(enable);
  8237. Client cli(HOST, port);
  8238. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8240. EXPECT_EQ(StatusCode::OK_200, res->status);
  8241. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8242. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8243. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8244. }
  8245. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8246. auto port = start(enable);
  8247. Client cli(HOST, port);
  8248. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8250. EXPECT_EQ(StatusCode::OK_200, res->status);
  8251. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8252. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8253. EXPECT_TRUE(res->body.empty());
  8254. }
  8255. TEST_F(StaticFileCompressionTest, MinLength) {
  8256. auto port = start(enable);
  8257. Client cli(HOST, port);
  8258. // 104 bytes, well under the default floor. Compressing it would add the
  8259. // gzip header and trailer to a body that already fits in one packet.
  8260. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8262. EXPECT_EQ(StatusCode::OK_200, res->status);
  8263. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8264. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8265. }
  8266. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8267. auto port = start([](Server &svr) {
  8268. svr.set_static_file_compression(true);
  8269. svr.set_static_file_compression_min_length(1);
  8270. });
  8271. Client cli(HOST, port);
  8272. cli.set_decompress(false);
  8273. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8275. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8276. // A 9-byte file comes back larger than it went in, because gzip's header and
  8277. // trailer outweigh anything deflate can save. That is the end of the range
  8278. // the floor exists to keep out.
  8279. EXPECT_GT(res->body.size(), 9U);
  8280. }
  8281. TEST_F(StaticFileCompressionTest, MaxLength) {
  8282. auto port = start([](Server &svr) {
  8283. svr.set_static_file_compression(true);
  8284. svr.set_static_file_compression_min_length(0);
  8285. svr.set_static_file_compression_max_length(1024);
  8286. });
  8287. Client cli(HOST, port);
  8288. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8289. // defines `small` as a macro on Windows.
  8290. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8291. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8292. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8293. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8294. // Under it: compressed.
  8295. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8296. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8297. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8298. }
  8299. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8300. auto port = start(enable_without_floor);
  8301. Client cli(HOST, port);
  8302. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8303. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8304. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8305. auto identity_etag = identity->get_header_value("ETag");
  8306. ASSERT_FALSE(identity_etag.empty());
  8307. auto gzipped =
  8308. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8309. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8310. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8311. auto gzip_etag = gzipped->get_header_value("ETag");
  8312. ASSERT_FALSE(gzip_etag.empty());
  8313. // Two representations, two validators.
  8314. EXPECT_NE(identity_etag, gzip_etag);
  8315. // Each one revalidates against the request that would produce it...
  8316. auto fresh =
  8317. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8318. {"If-None-Match", gzip_etag}});
  8319. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8320. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8321. auto fresh_identity =
  8322. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8323. {"If-None-Match", identity_etag}});
  8324. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8325. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8326. // ...and not against the other representation.
  8327. auto crossed =
  8328. cli.Get("/dir/index.html",
  8329. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8330. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8331. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8332. }
  8333. // The opt-in covers responses the server reads off disk itself. A caller's own
  8334. // known-length provider keeps its Content-Length and, more importantly, keeps
  8335. // delivering incrementally: routing it through a compressor would hold every
  8336. // write back until zlib's window filled.
  8337. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8338. auto port = start(enable);
  8339. Client cli(HOST, port);
  8340. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8342. EXPECT_EQ(StatusCode::OK_200, res->status);
  8343. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8344. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8345. EXPECT_EQ("aaabbb", res->body);
  8346. }
  8347. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8348. auto port = start(enable);
  8349. Client cli(HOST, port);
  8350. cli.set_read_timeout(1, 0);
  8351. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8352. Headers{{"Accept-Encoding", "gzip"}});
  8353. ASSERT_TRUE(handle.is_valid());
  8354. // The provider writes 100 bytes and then stalls for longer than the read
  8355. // timeout. Those first bytes have to arrive anyway: run the response through
  8356. // a compressor and zlib holds them until its window fills, so the read would
  8357. // come back empty instead.
  8358. char buf[256];
  8359. auto n = handle.read(buf, sizeof(buf));
  8360. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8361. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8362. }
  8363. #endif
  8364. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8365. TEST_F(ServerTest, Brotli) {
  8366. Headers headers;
  8367. headers.emplace("Accept-Encoding", "br");
  8368. auto res = cli_.Get("/compress", headers);
  8369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8370. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8371. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8372. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8373. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8374. "7890123456789012345678901234567890",
  8375. res->body);
  8376. EXPECT_EQ(StatusCode::OK_200, res->status);
  8377. }
  8378. #endif
  8379. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8380. TEST_F(ServerTest, Zstd) {
  8381. Headers headers;
  8382. headers.emplace("Accept-Encoding", "zstd");
  8383. auto res = cli_.Get("/compress", headers);
  8384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8385. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8386. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8387. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8388. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8389. "7890123456789012345678901234567890",
  8390. res->body);
  8391. EXPECT_EQ(StatusCode::OK_200, res->status);
  8392. }
  8393. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8394. Headers headers;
  8395. headers.emplace("Accept-Encoding", "");
  8396. auto res = cli_.Get("/compress", headers);
  8397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8398. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8399. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8400. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8401. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8402. "7890123456789012345678901234567890",
  8403. res->body);
  8404. EXPECT_EQ(StatusCode::OK_200, res->status);
  8405. }
  8406. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8407. Headers headers;
  8408. headers.emplace("Accept-Encoding", "zstd");
  8409. std::string body;
  8410. auto res = cli_.Get("/compress", headers,
  8411. [&](const char *data, uint64_t data_length) {
  8412. EXPECT_EQ(100U, data_length);
  8413. body.append(data, data_length);
  8414. return true;
  8415. });
  8416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8417. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8418. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8419. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8420. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8421. "7890123456789012345678901234567890",
  8422. body);
  8423. EXPECT_EQ(StatusCode::OK_200, res->status);
  8424. }
  8425. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8426. Headers headers;
  8427. headers.emplace("Accept-Encoding", "zstd");
  8428. cli_.set_decompress(false);
  8429. auto res = cli_.Get("/compress", headers);
  8430. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8431. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8432. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8433. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8435. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8436. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8437. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8438. EXPECT_EQ(StatusCode::OK_200, res->status);
  8439. ASSERT_EQ(26U, res->body.size());
  8440. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8441. 0);
  8442. }
  8443. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8444. Headers headers;
  8445. headers.emplace("Accept-Encoding", "");
  8446. std::string body;
  8447. auto res = cli_.Get("/compress", headers,
  8448. [&](const char *data, uint64_t data_length) {
  8449. EXPECT_EQ(100U, data_length);
  8450. body.append(data, data_length);
  8451. return true;
  8452. });
  8453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8454. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8455. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8456. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8457. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8458. "7890123456789012345678901234567890",
  8459. body);
  8460. EXPECT_EQ(StatusCode::OK_200, res->status);
  8461. }
  8462. TEST_F(ServerTest, NoZstd) {
  8463. Headers headers;
  8464. headers.emplace("Accept-Encoding", "zstd");
  8465. auto res = cli_.Get("/nocompress", headers);
  8466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8467. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8468. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8469. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8470. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8471. "7890123456789012345678901234567890",
  8472. res->body);
  8473. EXPECT_EQ(StatusCode::OK_200, res->status);
  8474. }
  8475. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8476. Headers headers;
  8477. headers.emplace("Accept-Encoding", "zstd");
  8478. std::string body;
  8479. auto res = cli_.Get("/nocompress", headers,
  8480. [&](const char *data, uint64_t data_length) {
  8481. EXPECT_EQ(100U, data_length);
  8482. body.append(data, data_length);
  8483. return true;
  8484. });
  8485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8486. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8487. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8488. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8489. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8490. "7890123456789012345678901234567890",
  8491. body);
  8492. EXPECT_EQ(StatusCode::OK_200, res->status);
  8493. }
  8494. // TODO: How to enable zstd ??
  8495. TEST_F(ServerTest, MultipartFormDataZstd) {
  8496. UploadFormDataItems items = {
  8497. {"key1", "test", "", ""},
  8498. {"key2", "--abcdefg123", "", ""},
  8499. };
  8500. Headers headers;
  8501. headers.emplace("Accept-Encoding", "zstd");
  8502. cli_.set_compress(true);
  8503. auto res = cli_.Post("/compress-multipart", headers, items);
  8504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8505. EXPECT_EQ(StatusCode::OK_200, res->status);
  8506. }
  8507. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8508. Headers headers;
  8509. headers.emplace("Accept-Encoding", "zstd");
  8510. cli_.set_compress(true);
  8511. auto res = cli_.Put(
  8512. "/put", headers, 3,
  8513. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8514. sink.os << "PUT";
  8515. return true;
  8516. },
  8517. "text/plain");
  8518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8519. EXPECT_EQ(StatusCode::OK_200, res->status);
  8520. EXPECT_EQ("PUT", res->body);
  8521. }
  8522. // Pre-compression logging tests
  8523. TEST_F(ServerTest, PreCompressionLogging) {
  8524. // Test data for compression (matches the actual /compress endpoint content)
  8525. const std::string test_content =
  8526. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8527. "3456789012345678901234567890";
  8528. // Variables to capture logging data
  8529. std::string pre_compression_body;
  8530. std::string pre_compression_content_type;
  8531. std::string pre_compression_content_encoding;
  8532. std::string post_compression_body;
  8533. std::string post_compression_content_type;
  8534. std::string post_compression_content_encoding;
  8535. // Set up pre-compression logger
  8536. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8537. const Response &res) {
  8538. pre_compression_body = res.body;
  8539. pre_compression_content_type = res.get_header_value("Content-Type");
  8540. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8541. });
  8542. // Set up post-compression logger
  8543. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8544. post_compression_body = res.body;
  8545. post_compression_content_type = res.get_header_value("Content-Type");
  8546. post_compression_content_encoding =
  8547. res.get_header_value("Content-Encoding");
  8548. });
  8549. // Test with gzip compression
  8550. Headers headers;
  8551. headers.emplace("Accept-Encoding", "gzip");
  8552. auto res = cli_.Get("/compress", headers);
  8553. // Verify response was compressed
  8554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8555. EXPECT_EQ(StatusCode::OK_200, res->status);
  8556. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8557. // Verify pre-compression logger captured uncompressed content
  8558. EXPECT_EQ(test_content, pre_compression_body);
  8559. EXPECT_EQ("text/plain", pre_compression_content_type);
  8560. EXPECT_TRUE(pre_compression_content_encoding
  8561. .empty()); // No encoding header before compression
  8562. // Verify post-compression logger captured compressed content
  8563. EXPECT_NE(test_content,
  8564. post_compression_body); // Should be different after compression
  8565. EXPECT_EQ("text/plain", post_compression_content_type);
  8566. EXPECT_EQ("gzip", post_compression_content_encoding);
  8567. // Verify compressed content is smaller
  8568. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8569. }
  8570. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8571. const std::string test_content =
  8572. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8573. "3456789012345678901234567890";
  8574. std::string pre_compression_body;
  8575. std::string post_compression_body;
  8576. svr_.set_pre_compression_logger(
  8577. [&](const Request & /*req*/, const Response &res) {
  8578. pre_compression_body = res.body;
  8579. });
  8580. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8581. post_compression_body = res.body;
  8582. });
  8583. Headers headers;
  8584. headers.emplace("Accept-Encoding", "br");
  8585. auto res = cli_.Get("/compress", headers);
  8586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8587. EXPECT_EQ(StatusCode::OK_200, res->status);
  8588. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8589. // Verify pre-compression content is uncompressed
  8590. EXPECT_EQ(test_content, pre_compression_body);
  8591. // Verify post-compression content is compressed
  8592. EXPECT_NE(test_content, post_compression_body);
  8593. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8594. }
  8595. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8596. const std::string test_content =
  8597. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8598. "3456789012345678901234567890";
  8599. std::string pre_compression_body;
  8600. std::string post_compression_body;
  8601. svr_.set_pre_compression_logger(
  8602. [&](const Request & /*req*/, const Response &res) {
  8603. pre_compression_body = res.body;
  8604. });
  8605. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8606. post_compression_body = res.body;
  8607. });
  8608. // Request without compression (use /nocompress endpoint)
  8609. Headers headers;
  8610. auto res = cli_.Get("/nocompress", headers);
  8611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8612. EXPECT_EQ(StatusCode::OK_200, res->status);
  8613. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8614. // Pre-compression logger should not be called when no compression is applied
  8615. EXPECT_TRUE(
  8616. pre_compression_body.empty()); // Pre-compression logger not called
  8617. EXPECT_EQ(
  8618. test_content,
  8619. post_compression_body); // Post-compression logger captures final content
  8620. }
  8621. TEST_F(ServerTest, LoggerSeesContentLength) {
  8622. size_t logged_content_length = 0;
  8623. std::string logged_content_length_header;
  8624. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8625. logged_content_length = res.content_length_;
  8626. logged_content_length_header = res.get_header_value("Content-Length");
  8627. });
  8628. auto res = cli_.Get("/nocompress");
  8629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8630. EXPECT_EQ(StatusCode::OK_200, res->status);
  8631. EXPECT_EQ(res->body.size(), logged_content_length);
  8632. EXPECT_EQ(std::to_string(logged_content_length),
  8633. logged_content_length_header);
  8634. }
  8635. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8636. const std::string test_content =
  8637. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8638. "3456789012345678901234567890";
  8639. std::string pre_compression_body;
  8640. bool pre_logger_called = false;
  8641. // Set only pre-compression logger
  8642. svr_.set_pre_compression_logger(
  8643. [&](const Request & /*req*/, const Response &res) {
  8644. pre_compression_body = res.body;
  8645. pre_logger_called = true;
  8646. });
  8647. Headers headers;
  8648. headers.emplace("Accept-Encoding", "gzip");
  8649. auto res = cli_.Get("/compress", headers);
  8650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8651. EXPECT_EQ(StatusCode::OK_200, res->status);
  8652. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8653. // Verify pre-compression logger was called
  8654. EXPECT_TRUE(pre_logger_called);
  8655. EXPECT_EQ(test_content, pre_compression_body);
  8656. }
  8657. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8658. {
  8659. // Test with Expect: 100-continue header - success case
  8660. // Server returns 100 Continue, client sends body, server returns 200 OK
  8661. Request req;
  8662. req.method = "POST";
  8663. req.path = "/post-large";
  8664. req.set_header("Expect", "100-continue");
  8665. req.body = LARGE_DATA;
  8666. Response res;
  8667. auto error = Error::Success;
  8668. cli_.set_keep_alive(true);
  8669. auto ret = cli_.send(req, res, error);
  8670. EXPECT_TRUE(ret);
  8671. EXPECT_EQ(StatusCode::OK_200, res.status);
  8672. EXPECT_EQ(LARGE_DATA, res.body);
  8673. }
  8674. {
  8675. // Test with Expect: 100-continue header - error case
  8676. // Client should not send the body when server returns an error
  8677. Request req;
  8678. req.method = "POST";
  8679. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8680. req.set_header("Expect", "100-continue");
  8681. req.body = LARGE_DATA;
  8682. Response res;
  8683. auto error = Error::Success;
  8684. auto start = std::chrono::high_resolution_clock::now();
  8685. cli_.set_keep_alive(true);
  8686. auto ret = cli_.send(req, res, error);
  8687. auto end = std::chrono::high_resolution_clock::now();
  8688. auto elapsed =
  8689. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8690. .count();
  8691. // With Expect: 100-continue, request completes successfully but with error
  8692. EXPECT_TRUE(ret);
  8693. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8694. EXPECT_EQ("close", res.get_header_value("Connection"));
  8695. EXPECT_FALSE(cli_.is_socket_open());
  8696. EXPECT_LE(elapsed, 2000);
  8697. }
  8698. {
  8699. // Send an extra GET request to ensure error recovery without hanging
  8700. Request req;
  8701. req.method = "GET";
  8702. req.path = "/hi";
  8703. auto start = std::chrono::high_resolution_clock::now();
  8704. auto res = cli_.send(req);
  8705. auto end = std::chrono::high_resolution_clock::now();
  8706. auto elapsed =
  8707. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8708. .count();
  8709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8710. EXPECT_EQ(StatusCode::OK_200, res->status);
  8711. EXPECT_EQ("Hello World!", res->body);
  8712. EXPECT_LE(elapsed, 500);
  8713. }
  8714. }
  8715. TEST(ZstdDecompressor, ChunkedDecompression) {
  8716. std::string data;
  8717. for (size_t i = 0; i < 32 * 1024; ++i) {
  8718. data.push_back(static_cast<char>('a' + i % 26));
  8719. }
  8720. std::string compressed_data;
  8721. {
  8722. httplib::detail::zstd_compressor compressor;
  8723. bool result = compressor.compress(
  8724. data.data(), data.size(),
  8725. /*last=*/true,
  8726. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8727. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8728. compressed_data_size);
  8729. return true;
  8730. });
  8731. ASSERT_TRUE(result);
  8732. }
  8733. std::string decompressed_data;
  8734. {
  8735. httplib::detail::zstd_decompressor decompressor;
  8736. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8737. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8738. size_t chunk_size = 130;
  8739. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8740. chunk_begin += chunk_size) {
  8741. size_t current_chunk_size =
  8742. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8743. bool result = decompressor.decompress(
  8744. compressed_data.data() + chunk_begin, current_chunk_size,
  8745. [&](const char *decompressed_data_chunk,
  8746. size_t decompressed_data_chunk_size) {
  8747. decompressed_data.insert(decompressed_data.size(),
  8748. decompressed_data_chunk,
  8749. decompressed_data_chunk_size);
  8750. return true;
  8751. });
  8752. ASSERT_TRUE(result);
  8753. }
  8754. }
  8755. ASSERT_EQ(data, decompressed_data);
  8756. }
  8757. TEST(ZstdDecompressor, Decompress) {
  8758. std::string original_text = "Compressed with ZSTD";
  8759. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8760. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8761. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8762. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8763. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8764. std::string decompressed_data;
  8765. {
  8766. httplib::detail::zstd_decompressor decompressor;
  8767. bool result = decompressor.decompress(
  8768. compressed_data.data(), compressed_data.size(),
  8769. [&](const char *decompressed_data_chunk,
  8770. size_t decompressed_data_chunk_size) {
  8771. decompressed_data.insert(decompressed_data.size(),
  8772. decompressed_data_chunk,
  8773. decompressed_data_chunk_size);
  8774. return true;
  8775. });
  8776. ASSERT_TRUE(result);
  8777. }
  8778. ASSERT_EQ(original_text, decompressed_data);
  8779. }
  8780. #endif
  8781. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8782. // separate chunks so that the server sees each part in its own read(). Used to
  8783. // place a read boundary at a specific offset of a request body.
  8784. static bool send_request_in_parts(time_t read_timeout_sec,
  8785. const std::vector<std::string> &parts,
  8786. std::string *resp = nullptr,
  8787. int port = PORT) {
  8788. auto error = Error::Success;
  8789. auto client_sock = detail::create_client_socket(
  8790. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8791. /*connection_timeout_sec=*/5, 0,
  8792. /*read_timeout_sec=*/5, 0,
  8793. /*write_timeout_sec=*/5, 0, std::string(), error);
  8794. if (client_sock == INVALID_SOCKET) { return false; }
  8795. auto ret = detail::process_client_socket(
  8796. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8797. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8798. for (size_t i = 0; i < parts.size(); i++) {
  8799. const auto &part = parts[i];
  8800. if (part.size() !=
  8801. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8802. return false;
  8803. }
  8804. if (i + 1 < parts.size()) {
  8805. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8806. }
  8807. }
  8808. char buf[512];
  8809. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8810. while (line_reader.getline()) {
  8811. if (resp) { *resp += line_reader.ptr(); }
  8812. }
  8813. return true;
  8814. });
  8815. detail::close_socket(client_sock);
  8816. return ret;
  8817. }
  8818. // Sends a raw request to a server listening at HOST:PORT.
  8819. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8820. std::string *resp = nullptr, int port = PORT) {
  8821. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8822. }
  8823. #ifdef CPPHTTPLIB_SSL_ENABLED
  8824. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  8825. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8826. ASSERT_TRUE(svr.is_valid());
  8827. svr.set_read_timeout(1, 0);
  8828. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8829. auto se = detail::scope_exit([&] {
  8830. svr.stop();
  8831. t.join();
  8832. ASSERT_FALSE(svr.is_running());
  8833. });
  8834. svr.wait_until_ready();
  8835. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  8836. // keeps each wait well within the read timeout. The server gives up a
  8837. // second in, so the bytes sent after that fail.
  8838. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  8839. parts.resize(26, std::string(1, '\0'));
  8840. EXPECT_FALSE(send_request_in_parts(5, parts));
  8841. }
  8842. #endif
  8843. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8844. Server svr;
  8845. std::string header_value;
  8846. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8847. header_value = req.get_header_value("foo");
  8848. res.set_content("ok", "text/plain");
  8849. });
  8850. thread t = thread([&] { svr.listen(HOST, PORT); });
  8851. auto se = detail::scope_exit([&] {
  8852. svr.stop();
  8853. t.join();
  8854. ASSERT_FALSE(svr.is_running());
  8855. });
  8856. svr.wait_until_ready();
  8857. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8858. // like characters are not treated the same - use vertical tab and escape.
  8859. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8860. "foo: \t \v bar \x1B\t \r\n"
  8861. "Connection: close\r\n"
  8862. "\r\n";
  8863. std::string res;
  8864. ASSERT_TRUE(send_request(5, req, &res));
  8865. EXPECT_EQ(header_value, "");
  8866. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8867. }
  8868. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8869. Server svr;
  8870. std::string received;
  8871. svr.Get("/order", [&](const Request &req, Response &res) {
  8872. received = entries_to_string(req.headers);
  8873. res.set_content("ok", "text/plain");
  8874. });
  8875. auto port = svr.bind_to_any_port(HOST);
  8876. thread t = thread([&] { svr.listen_after_bind(); });
  8877. auto se = detail::scope_exit([&] {
  8878. svr.stop();
  8879. t.join();
  8880. ASSERT_FALSE(svr.is_running());
  8881. });
  8882. svr.wait_until_ready();
  8883. const std::string req = "GET /order HTTP/1.1\r\n"
  8884. "Host: localhost\r\n"
  8885. "X-First: 1\r\n"
  8886. "X-Dup: a\r\n"
  8887. "X-Second: 2\r\n"
  8888. "X-Dup: b\r\n"
  8889. "Connection: close\r\n"
  8890. "\r\n";
  8891. std::string res;
  8892. ASSERT_TRUE(send_request(5, req, &res, port));
  8893. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8894. EXPECT_EQ(
  8895. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  8896. received);
  8897. }
  8898. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8899. Server svr;
  8900. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8901. res.set_header("Set-Cookie", "first=1");
  8902. res.set_header("X-Between", "y");
  8903. res.set_header("Set-Cookie", "second=2");
  8904. res.set_content("ok", "text/plain");
  8905. });
  8906. auto port = svr.bind_to_any_port(HOST);
  8907. thread t = thread([&] { svr.listen_after_bind(); });
  8908. auto se = detail::scope_exit([&] {
  8909. svr.stop();
  8910. t.join();
  8911. ASSERT_FALSE(svr.is_running());
  8912. });
  8913. svr.wait_until_ready();
  8914. Client cli(HOST, port);
  8915. auto res = cli.Get("/cookies");
  8916. ASSERT_TRUE(res);
  8917. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8918. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8919. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8920. }
  8921. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8922. Server svr;
  8923. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8924. auto i = new int(0);
  8925. res.set_header("Trailer", "X-Safe, X-Reflected");
  8926. res.set_chunked_content_provider(
  8927. "text/plain",
  8928. [i](size_t /*offset*/, DataSink &sink) {
  8929. if (*i == 0) {
  8930. sink.os << "body";
  8931. } else {
  8932. Headers trailer;
  8933. // A valid trailer that must survive.
  8934. trailer.emplace("X-Safe", "safe");
  8935. // Attacker-controlled value carrying CR/LF (response splitting).
  8936. trailer.emplace("X-Reflected",
  8937. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8938. // Attacker-controlled name carrying CR/LF.
  8939. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8940. sink.done_with_trailer(trailer);
  8941. }
  8942. (*i)++;
  8943. return true;
  8944. },
  8945. [i](bool /*success*/) { delete i; });
  8946. });
  8947. thread t = thread([&] { svr.listen(HOST, PORT); });
  8948. auto se = detail::scope_exit([&] {
  8949. svr.stop();
  8950. t.join();
  8951. ASSERT_FALSE(svr.is_running());
  8952. });
  8953. svr.wait_until_ready();
  8954. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8955. "Host: " + HOST +
  8956. "\r\n"
  8957. "Connection: close\r\n"
  8958. "\r\n";
  8959. std::string res;
  8960. ASSERT_TRUE(send_request(5, req, &res));
  8961. // The injected fields must not appear anywhere in the raw response.
  8962. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8963. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8964. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8965. // Invalid trailers are dropped entirely, matching set_header().
  8966. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8967. // The valid trailer still passes through.
  8968. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8969. }
  8970. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8971. Server svr;
  8972. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8973. // res.headers is a public field an application can populate directly,
  8974. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8975. // A valid header that must survive.
  8976. res.headers.emplace("X-Safe", "safe");
  8977. // Attacker-controlled value carrying CR/LF (response splitting).
  8978. res.headers.emplace("X-Reflected",
  8979. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8980. // Attacker-controlled name carrying CR/LF.
  8981. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8982. res.set_content("body", "text/plain");
  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. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8992. "Host: " + HOST +
  8993. "\r\n"
  8994. "Connection: close\r\n"
  8995. "\r\n";
  8996. std::string res;
  8997. ASSERT_TRUE(send_request(5, req, &res));
  8998. // The injected fields must not appear anywhere in the raw response.
  8999. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9000. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9001. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9002. // Invalid headers are dropped entirely, matching set_header().
  9003. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9004. // The valid header still passes through.
  9005. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9006. }
  9007. // Forward declaration: in split builds split.py strips `inline` and moves the
  9008. // definition into httplib.cc, so detail::write_request_line is not visible from
  9009. // the public httplib.h. Re-declaring it here lets the tests link against the
  9010. // symbol in both header-only and split builds.
  9011. namespace httplib {
  9012. namespace detail {
  9013. ssize_t write_request_line(Stream &strm, const std::string &method,
  9014. const std::string &path);
  9015. } // namespace detail
  9016. } // namespace httplib
  9017. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9018. // A well-formed target is written verbatim.
  9019. {
  9020. detail::BufferStream strm;
  9021. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9022. EXPECT_GT(n, 0);
  9023. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9024. }
  9025. // A target carrying CR/LF, SP or other control octets must be rejected
  9026. // before anything reaches the wire, otherwise it splits the request line and
  9027. // injects a header or a whole request.
  9028. const std::string evil_targets[] = {
  9029. "/a\r\nInjected: pwned",
  9030. "/a\rInjected",
  9031. "/a\nInjected",
  9032. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9033. "/a b",
  9034. "/a\tb",
  9035. "/a\x7f",
  9036. };
  9037. for (const auto &evil : evil_targets) {
  9038. detail::BufferStream strm;
  9039. auto n = detail::write_request_line(strm, "GET", evil);
  9040. EXPECT_LT(n, 0);
  9041. EXPECT_TRUE(strm.get_buffer().empty());
  9042. }
  9043. }
  9044. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9045. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9046. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9047. // target reaches write_request. The client must fail cleanly with
  9048. // Error::Write instead of putting a request-line-less, header-injecting
  9049. // request on the wire.
  9050. Server svr;
  9051. svr.Get("/a", [](const Request &, Response &res) {
  9052. res.set_content("ok", "text/plain");
  9053. });
  9054. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9055. auto se = detail::scope_exit([&] {
  9056. svr.stop();
  9057. thread.join();
  9058. ASSERT_FALSE(svr.is_running());
  9059. });
  9060. svr.wait_until_ready();
  9061. {
  9062. Client cli(HOST, PORT);
  9063. cli.set_path_encode(false);
  9064. // The request is rejected before anything is written, so the connection
  9065. // stays silent and the subsequent response read would otherwise block for
  9066. // the full default read timeout. Shorten it -- the assertion is on the
  9067. // error, not the timeout.
  9068. cli.set_read_timeout(1, 0);
  9069. auto res = cli.Get("/a\r\nInjected: pwned");
  9070. EXPECT_FALSE(res);
  9071. EXPECT_EQ(Error::Write, res.error());
  9072. }
  9073. }
  9074. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9075. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9076. // including extension methods.
  9077. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9078. for (const auto &method : good_methods) {
  9079. detail::BufferStream strm;
  9080. auto n = detail::write_request_line(strm, method, "/");
  9081. EXPECT_GT(n, 0);
  9082. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9083. }
  9084. // A method carrying CR/LF would split the request line and smuggle a whole
  9085. // request ahead of the real one. A space or an empty method corrupts the
  9086. // request line. All must be rejected before anything reaches the wire.
  9087. const std::string evil_methods[] = {
  9088. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9089. "GET\r\nInjected: pwned",
  9090. "GET\r",
  9091. "GET\n",
  9092. "GE T",
  9093. "",
  9094. };
  9095. for (const auto &evil : evil_methods) {
  9096. detail::BufferStream strm;
  9097. auto n = detail::write_request_line(strm, evil, "/");
  9098. EXPECT_LT(n, 0);
  9099. EXPECT_TRUE(strm.get_buffer().empty());
  9100. }
  9101. }
  9102. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9103. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9104. // through Client::send must fail with Error::Write and no request, neither
  9105. // the smuggled one nor the real one, may reach the server.
  9106. Server svr;
  9107. std::atomic<int> request_count(0);
  9108. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9109. request_count++;
  9110. res.status = StatusCode::OK_200;
  9111. return Server::HandlerResponse::Handled;
  9112. });
  9113. auto port = svr.bind_to_any_port(HOST);
  9114. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9115. auto se = detail::scope_exit([&] {
  9116. svr.stop();
  9117. thread.join();
  9118. ASSERT_FALSE(svr.is_running());
  9119. });
  9120. svr.wait_until_ready();
  9121. {
  9122. Client cli(HOST, port);
  9123. const std::string evil_methods[] = {
  9124. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9125. "GE T",
  9126. "",
  9127. };
  9128. for (const auto &evil : evil_methods) {
  9129. Request req;
  9130. req.method = evil;
  9131. req.path = "/";
  9132. auto res = cli.send(req);
  9133. EXPECT_FALSE(res);
  9134. EXPECT_EQ(Error::Write, res.error());
  9135. }
  9136. auto handle =
  9137. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9138. EXPECT_FALSE(handle.is_valid());
  9139. EXPECT_EQ(Error::Write, handle.error);
  9140. // A valid request on the same client still goes through.
  9141. auto res = cli.Get("/");
  9142. ASSERT_TRUE(res);
  9143. EXPECT_EQ(StatusCode::OK_200, res->status);
  9144. }
  9145. EXPECT_EQ(1, request_count.load());
  9146. }
  9147. // Sends a raw request and verifies that there isn't a crash or exception.
  9148. static void test_raw_request(const std::string &req,
  9149. std::string *out = nullptr) {
  9150. Server svr;
  9151. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9152. res.set_content("ok", "text/plain");
  9153. });
  9154. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9155. res.set_content("ok", "text/plain");
  9156. });
  9157. svr.Get("/header_field_value_check",
  9158. [&](const Request & /*req*/, Response &res) {
  9159. res.set_content("ok", "text/plain");
  9160. });
  9161. svr.CustomRoute("PROPFIND", "/dav",
  9162. [&](const Request & /*req*/, Response &res) {
  9163. res.status = StatusCode::MultiStatus_207;
  9164. });
  9165. // Server read timeout must be longer than the client read timeout for the
  9166. // bug to reproduce, probably to force the server to process a request
  9167. // without a trailing blank line.
  9168. const time_t client_read_timeout_sec = 1;
  9169. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9170. bool listen_thread_ok = false;
  9171. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9172. auto se = detail::scope_exit([&] {
  9173. svr.stop();
  9174. t.join();
  9175. ASSERT_FALSE(svr.is_running());
  9176. EXPECT_TRUE(listen_thread_ok);
  9177. });
  9178. svr.wait_until_ready();
  9179. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9180. }
  9181. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9182. // A certain header line causes an exception if the header property is parsed
  9183. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9184. test_raw_request(
  9185. "GET /hi HTTP/1.1\r\n"
  9186. " : "
  9187. " "
  9188. " ");
  9189. }
  9190. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9191. // A certain header line causes an exception if the header property *name* is
  9192. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9193. // greedy matcher and requires backtracking when there are a lot of ":"
  9194. // characters.
  9195. // This occurs with libc++ but not libstdc++.
  9196. test_raw_request(
  9197. "GET /hi HTTP/1.1\r\n"
  9198. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9199. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9200. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9201. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9202. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9203. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9204. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9205. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9206. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9207. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9208. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9209. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9210. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9211. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9212. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9213. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9214. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9215. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9216. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9217. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9218. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9219. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9220. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9221. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9222. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9223. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9224. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9225. "&&&%%%");
  9226. }
  9227. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9228. // Make sure this doesn't crash the server.
  9229. // In a previous version of the header line regex, the "\r" rendered the line
  9230. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9231. // a new position where the leading white space ended and the field value
  9232. // began.
  9233. // The crash occurs with libc++ but not libstdc++.
  9234. test_raw_request("GET /hi HTTP/1.1\r\n"
  9235. "a:" +
  9236. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9237. "\r\n"
  9238. "\r\n");
  9239. }
  9240. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9241. const char *rejected[] = {
  9242. // RFC 9112 §3: one SP between the parts, and nothing else
  9243. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9244. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9245. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9246. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9247. // A request-target has no fragment
  9248. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9249. // An HTTP/1.1 request needs a Host
  9250. "GET /hi HTTP/1.1\r\n\r\n",
  9251. };
  9252. for (auto request : rejected) {
  9253. std::string out;
  9254. test_raw_request(request, &out);
  9255. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9256. }
  9257. std::string out;
  9258. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9259. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9260. }
  9261. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9262. // RFC 9112 §6.1
  9263. const char *requests[] = {
  9264. "PUT /put_hi HTTP/1.1\r\n"
  9265. "Host: localhost\r\n"
  9266. "Content-Length: 0\r\n"
  9267. "Transfer-Encoding: chunked\r\n"
  9268. "\r\n"
  9269. "0\r\n\r\n",
  9270. "PUT /put_hi HTTP/1.0\r\n"
  9271. "Connection: keep-alive\r\n"
  9272. "Transfer-Encoding: chunked\r\n"
  9273. "\r\n"
  9274. "0\r\n\r\n",
  9275. };
  9276. for (auto request : requests) {
  9277. std::string out;
  9278. test_raw_request(request, &out);
  9279. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9280. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9281. }
  9282. }
  9283. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9284. std::string out;
  9285. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9286. "Content-Type: text/plain\r\n"
  9287. "Transfer-Encoding: chunked\r\n"
  9288. "\r\n"
  9289. "nothex\r\n",
  9290. &out);
  9291. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9292. }
  9293. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9294. std::string out;
  9295. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9296. "Content-Type: text/plain\r\n"
  9297. "Transfer-Encoding: chunked\r\n"
  9298. "\r\n"
  9299. "3\r\n"
  9300. "xyz\r\n"
  9301. "NaN\r\n",
  9302. &out);
  9303. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9304. }
  9305. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9306. std::string out;
  9307. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9308. "Content-Type: text/plain\r\n"
  9309. "Transfer-Encoding: chunked\r\n"
  9310. "\r\n"
  9311. // Length is too large for 64 bits.
  9312. "1ffffffffffffffff\r\n"
  9313. "xyz\r\n",
  9314. &out);
  9315. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9316. }
  9317. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9318. test_raw_request("GET /hi HTTP/1.1\r\n"
  9319. "Content-Type: text/plain\r\n\r");
  9320. }
  9321. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9322. std::string out;
  9323. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9324. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9325. }
  9326. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9327. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9328. std::string out;
  9329. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9330. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9331. }
  9332. }
  9333. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9334. std::string out;
  9335. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9336. "Host: localhost\r\n"
  9337. "Connection: close\r\n\r\n",
  9338. &out);
  9339. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9340. }
  9341. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9342. Server svr;
  9343. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9344. EXPECT_TRUE(!req.remote_addr.empty());
  9345. });
  9346. thread t = thread([&] { svr.listen(HOST, PORT); });
  9347. auto se = detail::scope_exit([&] {
  9348. svr.stop();
  9349. t.join();
  9350. ASSERT_FALSE(svr.is_running());
  9351. });
  9352. svr.wait_until_ready();
  9353. // Send an invalid request line to trigger Bad Request
  9354. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9355. std::string out;
  9356. ASSERT_TRUE(send_request(5, bad_req, &out));
  9357. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9358. }
  9359. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9360. // answered right away rather than blocking on a read that waits for EOF.
  9361. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9362. std::string out;
  9363. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9364. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9365. }
  9366. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9367. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9368. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9369. for (const auto *method : methods) {
  9370. Server svr;
  9371. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9372. EXPECT_FALSE(svr.is_valid()) << method;
  9373. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9374. }
  9375. }
  9376. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9377. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9378. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9379. for (const auto *method : methods) {
  9380. Server svr;
  9381. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9382. EXPECT_FALSE(svr.is_valid()) << method;
  9383. }
  9384. }
  9385. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9386. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9387. "COPY", "MOVE", "LOCK",
  9388. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9389. Server svr;
  9390. for (const auto *method : methods) {
  9391. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9392. }
  9393. EXPECT_TRUE(svr.is_valid());
  9394. }
  9395. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9396. Server svr;
  9397. svr.CustomRoute("POST", "/x",
  9398. [](const Request &, Response &, const ContentReader &) {});
  9399. EXPECT_FALSE(svr.is_valid());
  9400. }
  9401. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9402. Server svr;
  9403. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9404. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9405. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9406. EXPECT_FALSE(svr.is_valid());
  9407. }
  9408. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9409. Server svr;
  9410. auto captured = Error::Success;
  9411. svr.set_error_logger(
  9412. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9413. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9414. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9415. }
  9416. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9417. std::string out;
  9418. std::string request(
  9419. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9420. test_raw_request(request, &out);
  9421. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9422. }
  9423. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9424. std::string out;
  9425. std::string request(
  9426. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9427. test_raw_request(request, &out);
  9428. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9429. }
  9430. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9431. std::string out;
  9432. std::string request(
  9433. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9434. test_raw_request(request, &out);
  9435. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9436. }
  9437. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9438. std::string out;
  9439. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9440. "Host: localhost\r\n"
  9441. "Test: \r\n\r\n",
  9442. &out);
  9443. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9444. }
  9445. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9446. Server svr;
  9447. std::string x_custom;
  9448. std::string cookie;
  9449. std::string xff;
  9450. std::string x_unicode;
  9451. std::string x_iis;
  9452. svr.Get("/check", [&](const Request &req, Response &res) {
  9453. x_custom = req.get_header_value("X-Custom");
  9454. cookie = req.get_header_value("Cookie");
  9455. xff = req.get_header_value("X-Forwarded-For");
  9456. x_unicode = req.get_header_value("X-Unicode");
  9457. x_iis = req.get_header_value("X-IIS");
  9458. res.set_content("ok", "text/plain");
  9459. });
  9460. thread t = thread([&] { svr.listen(HOST, PORT); });
  9461. auto se = detail::scope_exit([&] {
  9462. svr.stop();
  9463. t.join();
  9464. ASSERT_FALSE(svr.is_running());
  9465. });
  9466. svr.wait_until_ready();
  9467. const std::string req = "GET /check HTTP/1.1\r\n"
  9468. "Host: localhost\r\n"
  9469. "X-Custom: a%0D%0AInjected: b\r\n"
  9470. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9471. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9472. "X-Unicode: %E3%81%82\r\n"
  9473. "X-IIS: %u00E9\r\n"
  9474. "Connection: close\r\n"
  9475. "\r\n";
  9476. std::string res;
  9477. ASSERT_TRUE(send_request(5, req, &res));
  9478. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9479. // Every value must be returned verbatim (wire form), with no decoding.
  9480. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9481. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9482. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9483. EXPECT_EQ("%E3%81%82", x_unicode);
  9484. EXPECT_EQ("%u00E9", x_iis);
  9485. }
  9486. // Applications that previously relied on automatic percent-decoding can
  9487. // reproduce the old behavior by explicitly calling decode_path_component()
  9488. // or, for RFC 3986 conformance, decode_uri_component().
  9489. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9490. Server svr;
  9491. std::string decoded;
  9492. svr.Get("/check", [&](const Request &req, Response &res) {
  9493. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9494. res.set_content("ok", "text/plain");
  9495. });
  9496. thread t = thread([&] { svr.listen(HOST, PORT); });
  9497. auto se = detail::scope_exit([&] {
  9498. svr.stop();
  9499. t.join();
  9500. ASSERT_FALSE(svr.is_running());
  9501. });
  9502. svr.wait_until_ready();
  9503. const std::string req = "GET /check HTTP/1.1\r\n"
  9504. "Host: localhost\r\n"
  9505. "X-Custom: hello%20world\r\n"
  9506. "Connection: close\r\n"
  9507. "\r\n";
  9508. std::string res;
  9509. ASSERT_TRUE(send_request(5, req, &res));
  9510. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9511. EXPECT_EQ("hello world", decoded);
  9512. }
  9513. // Regression test for #2033. Browsers send Referer values that include
  9514. // percent-encoded characters such as %0A inside the URL. Decoding the
  9515. // header value would either trip the post-decode CR/LF/NUL guard (the
  9516. // original bug, returning 400) or, after that guard was relaxed, silently
  9517. // store a literal LF — both unacceptable. The wire form must round-trip.
  9518. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9519. Server svr;
  9520. std::string referer;
  9521. svr.Get("/check", [&](const Request &req, Response &res) {
  9522. referer = req.get_header_value("Referer");
  9523. res.set_content("ok", "text/plain");
  9524. });
  9525. thread t = thread([&] { svr.listen(HOST, PORT); });
  9526. auto se = detail::scope_exit([&] {
  9527. svr.stop();
  9528. t.join();
  9529. ASSERT_FALSE(svr.is_running());
  9530. });
  9531. svr.wait_until_ready();
  9532. const std::string req = "GET /check HTTP/1.1\r\n"
  9533. "Host: localhost\r\n"
  9534. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9535. "Connection: close\r\n"
  9536. "\r\n";
  9537. std::string res;
  9538. ASSERT_TRUE(send_request(5, req, &res));
  9539. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9540. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9541. }
  9542. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9543. Server svr;
  9544. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9545. res.set_header("Cache-Control", "no-cache");
  9546. res.set_chunked_content_provider(
  9547. "text/event-stream", [](size_t offset, DataSink &sink) {
  9548. std::string s = "data:";
  9549. s += std::to_string(offset);
  9550. s += "\n\n";
  9551. auto ret = sink.write(s.data(), s.size());
  9552. EXPECT_TRUE(ret);
  9553. std::this_thread::sleep_for(std::chrono::seconds(1));
  9554. return true;
  9555. });
  9556. });
  9557. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9558. svr.wait_until_ready();
  9559. Client client(HOST, PORT);
  9560. const Headers headers = {{"Accept", "text/event-stream"}};
  9561. auto get_thread = std::thread([&client, &headers]() {
  9562. auto res = client.Get(
  9563. "/events", headers,
  9564. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9565. });
  9566. auto se = detail::scope_exit([&] {
  9567. svr.stop();
  9568. get_thread.join();
  9569. listen_thread.join();
  9570. ASSERT_FALSE(svr.is_running());
  9571. });
  9572. // Give GET time to get a few messages.
  9573. std::this_thread::sleep_for(std::chrono::seconds(2));
  9574. }
  9575. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9576. httplib::Server svr;
  9577. svr.Post("/hi",
  9578. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9579. res.status = StatusCode::OK_200;
  9580. });
  9581. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9582. svr.wait_until_ready();
  9583. Client cli(HOST, PORT);
  9584. auto res = cli.Post("/hi", "data", "text/plain");
  9585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9586. EXPECT_EQ(StatusCode::OK_200, res->status);
  9587. svr.stop();
  9588. thread.join();
  9589. ASSERT_FALSE(svr.is_running());
  9590. res = cli.Post("/hi", "data", "text/plain");
  9591. ASSERT_FALSE(res);
  9592. }
  9593. TEST(ServerStopTest, ListenFailure) {
  9594. Server svr;
  9595. auto t = thread([&]() {
  9596. auto ret = svr.listen("????", PORT);
  9597. EXPECT_FALSE(ret);
  9598. });
  9599. svr.wait_until_ready();
  9600. svr.stop();
  9601. t.join();
  9602. }
  9603. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9604. TEST(ServerStopTest, Decommision) {
  9605. Server svr;
  9606. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9607. for (int i = 0; i < 4; i++) {
  9608. auto is_even = !(i % 2);
  9609. std::thread t{[&] {
  9610. try {
  9611. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9612. if (is_even) {
  9613. throw std::runtime_error("Some thing that happens to go wrong.");
  9614. }
  9615. svr.listen(HOST, PORT);
  9616. } catch (...) { svr.decommission(); }
  9617. }};
  9618. svr.wait_until_ready();
  9619. // Server is up
  9620. {
  9621. Client cli(HOST, PORT);
  9622. auto res = cli.Get("/hi");
  9623. if (is_even) {
  9624. EXPECT_FALSE(res);
  9625. } else {
  9626. EXPECT_TRUE(res);
  9627. EXPECT_EQ("hi...", res->body);
  9628. }
  9629. }
  9630. svr.stop();
  9631. t.join();
  9632. // Server is down...
  9633. {
  9634. Client cli(HOST, PORT);
  9635. auto res = cli.Get("/hi");
  9636. EXPECT_FALSE(res);
  9637. }
  9638. }
  9639. }
  9640. #endif
  9641. // Helper function for string body upload progress tests
  9642. template <typename SetupHandler, typename ClientCall>
  9643. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9644. ClientCall &&client_call,
  9645. const string &body) {
  9646. Server svr;
  9647. setup_handler(svr);
  9648. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9649. auto se = detail::scope_exit([&] {
  9650. svr.stop();
  9651. t.join();
  9652. });
  9653. svr.wait_until_ready();
  9654. Client cli(HOST, PORT);
  9655. vector<uint64_t> progress_values;
  9656. bool progress_called = false;
  9657. auto res =
  9658. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9659. progress_values.push_back(current);
  9660. progress_called = true;
  9661. return true;
  9662. });
  9663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9664. EXPECT_EQ(200, res->status);
  9665. EXPECT_TRUE(progress_called);
  9666. }
  9667. TEST(UploadProgressTest, PostStringBodyBasic) {
  9668. TestStringBodyUploadProgress(
  9669. [](Server &svr) {
  9670. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9671. res.set_content("received", "text/plain");
  9672. });
  9673. },
  9674. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9675. return cli.Post("/test", body, "text/plain", progress_callback);
  9676. },
  9677. "test data for upload progress");
  9678. }
  9679. TEST(UploadProgressTest, PutStringBodyBasic) {
  9680. TestStringBodyUploadProgress(
  9681. [](Server &svr) {
  9682. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9683. res.set_content("put received", "text/plain");
  9684. });
  9685. },
  9686. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9687. return cli.Put("/test", body, "text/plain", progress_callback);
  9688. },
  9689. "put test data for upload progress");
  9690. }
  9691. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9692. TestStringBodyUploadProgress(
  9693. [](Server &svr) {
  9694. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9695. res.set_content("patch received", "text/plain");
  9696. });
  9697. },
  9698. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9699. return cli.Patch("/test", body, "text/plain", progress_callback);
  9700. },
  9701. "patch test data for upload progress");
  9702. }
  9703. // Helper function for content provider upload progress tests
  9704. template <typename SetupHandler, typename ClientCall>
  9705. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9706. ClientCall &&client_call) {
  9707. Server svr;
  9708. setup_handler(svr);
  9709. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9710. auto se = detail::scope_exit([&] {
  9711. svr.stop();
  9712. t.join();
  9713. });
  9714. svr.wait_until_ready();
  9715. Client cli(HOST, PORT);
  9716. vector<uint64_t> progress_values;
  9717. auto res =
  9718. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9719. progress_values.push_back(current);
  9720. return true;
  9721. });
  9722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9723. EXPECT_EQ(200, res->status);
  9724. EXPECT_FALSE(progress_values.empty());
  9725. }
  9726. TEST(UploadProgressTest, PostContentProviderProgress) {
  9727. TestContentProviderUploadProgress(
  9728. [](Server &svr) {
  9729. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9730. res.set_content("provider received", "text/plain");
  9731. });
  9732. },
  9733. [](Client &cli, UploadProgress progress_callback) {
  9734. return cli.Post(
  9735. "/test", 10,
  9736. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9737. sink.os << "test data";
  9738. return true;
  9739. },
  9740. "text/plain", progress_callback);
  9741. });
  9742. }
  9743. // Helper function for multipart upload progress tests
  9744. template <typename SetupHandler, typename ClientCall>
  9745. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9746. ClientCall &&client_call,
  9747. const string &endpoint) {
  9748. Server svr;
  9749. setup_handler(svr);
  9750. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9751. auto se = detail::scope_exit([&] {
  9752. svr.stop();
  9753. t.join();
  9754. });
  9755. svr.wait_until_ready();
  9756. Client cli(HOST, PORT);
  9757. vector<uint64_t> progress_values;
  9758. UploadFormDataItems items = {
  9759. {"field1", "value1", "", ""},
  9760. {"field2", "longer value for progress tracking test", "", ""},
  9761. {"file1", "file content data for upload progress", "test.txt",
  9762. "text/plain"}};
  9763. auto res = client_call(cli, endpoint, items,
  9764. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9765. progress_values.push_back(current);
  9766. return true;
  9767. });
  9768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9769. EXPECT_EQ(200, res->status);
  9770. EXPECT_FALSE(progress_values.empty());
  9771. }
  9772. TEST(UploadProgressTest, PostMultipartProgress) {
  9773. TestMultipartUploadProgress(
  9774. [](Server &svr) {
  9775. svr.Post("/multipart", [](const Request &req, Response &res) {
  9776. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9777. res.set_content("multipart received", "text/plain");
  9778. });
  9779. },
  9780. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9781. UploadProgress progress_callback) {
  9782. return cli.Post(endpoint, items, progress_callback);
  9783. },
  9784. "/multipart");
  9785. }
  9786. // Helper function for basic download progress tests
  9787. template <typename SetupHandler, typename ClientCall>
  9788. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9789. ClientCall &&client_call, const string &endpoint,
  9790. size_t expected_content_size) {
  9791. Server svr;
  9792. setup_handler(svr);
  9793. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9794. auto se = detail::scope_exit([&] {
  9795. svr.stop();
  9796. t.join();
  9797. });
  9798. svr.wait_until_ready();
  9799. Client cli(HOST, PORT);
  9800. vector<uint64_t> progress_values;
  9801. auto res = client_call(cli, endpoint,
  9802. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9803. progress_values.push_back(current);
  9804. return true;
  9805. });
  9806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9807. EXPECT_EQ(200, res->status);
  9808. EXPECT_FALSE(progress_values.empty());
  9809. EXPECT_EQ(expected_content_size, res->body.size());
  9810. }
  9811. TEST(DownloadProgressTest, GetBasic) {
  9812. TestBasicDownloadProgress(
  9813. [](Server &svr) {
  9814. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9815. string content(1000, 'D');
  9816. res.set_content(content, "text/plain");
  9817. });
  9818. },
  9819. [](Client &cli, const string &endpoint,
  9820. DownloadProgress progress_callback) {
  9821. return cli.Get(endpoint, progress_callback);
  9822. },
  9823. "/download", 1000u);
  9824. }
  9825. // Helper function for content receiver download progress tests
  9826. template <typename SetupHandler, typename ClientCall>
  9827. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9828. ClientCall &&client_call,
  9829. const string &endpoint,
  9830. size_t expected_content_size) {
  9831. Server svr;
  9832. setup_handler(svr);
  9833. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9834. auto se = detail::scope_exit([&] {
  9835. svr.stop();
  9836. t.join();
  9837. });
  9838. svr.wait_until_ready();
  9839. Client cli(HOST, PORT);
  9840. vector<uint64_t> progress_values;
  9841. string received_body;
  9842. auto res = client_call(
  9843. cli, endpoint,
  9844. [&](const char *data, size_t data_length) -> bool {
  9845. received_body.append(data, data_length);
  9846. return true;
  9847. },
  9848. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9849. progress_values.push_back(current);
  9850. return true;
  9851. });
  9852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9853. EXPECT_EQ(200, res->status);
  9854. EXPECT_FALSE(progress_values.empty());
  9855. EXPECT_EQ(expected_content_size, received_body.size());
  9856. EXPECT_TRUE(res->body.empty());
  9857. }
  9858. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9859. TestContentReceiverDownloadProgress(
  9860. [](Server &svr) {
  9861. svr.Get("/download-receiver",
  9862. [](const Request & /*req*/, Response &res) {
  9863. string content(2000, 'R');
  9864. res.set_content(content, "text/plain");
  9865. });
  9866. },
  9867. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9868. DownloadProgress progress_callback) {
  9869. return cli.Get(endpoint, content_receiver, progress_callback);
  9870. },
  9871. "/download-receiver", 2000u);
  9872. }
  9873. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9874. // A provider reaching a pass with nothing to hand over - an empty buffer
  9875. // popped off a queue, say - must not be taken to mean the body is finished.
  9876. // It used to end the loop with the terminating chunk unwritten while the
  9877. // server still considered the response complete, so the peer waited for an
  9878. // end that never arrived.
  9879. Server svr;
  9880. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9881. auto step = std::make_shared<int>(0);
  9882. res.set_chunked_content_provider("text/plain",
  9883. [step](size_t /*offset*/, DataSink &sink) {
  9884. switch ((*step)++) {
  9885. case 0: sink.write("", 0); break;
  9886. case 1: sink.write("hello", 5); break;
  9887. default: sink.done(); break;
  9888. }
  9889. return true;
  9890. });
  9891. });
  9892. auto port = svr.bind_to_any_port(HOST);
  9893. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9894. auto listen_se = detail::scope_exit([&] {
  9895. svr.stop();
  9896. listen_thread.join();
  9897. ASSERT_FALSE(svr.is_running());
  9898. });
  9899. svr.wait_until_ready();
  9900. Client cli(HOST, port);
  9901. // Without the fix the body is never terminated, so bound the wait rather
  9902. // than letting the test hang on the default read timeout.
  9903. cli.set_read_timeout(5, 0);
  9904. auto res = cli.Get("/stream");
  9905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9906. EXPECT_EQ(StatusCode::OK_200, res->status);
  9907. EXPECT_EQ("hello", res->body);
  9908. }
  9909. TEST(StreamingTest, NoContentLengthStreaming) {
  9910. Server svr;
  9911. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9912. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9913. if (offset < 6) {
  9914. sink.os << (offset < 3 ? "a" : "b");
  9915. } else {
  9916. sink.done();
  9917. }
  9918. return true;
  9919. });
  9920. });
  9921. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9922. auto listen_se = detail::scope_exit([&] {
  9923. svr.stop();
  9924. listen_thread.join();
  9925. ASSERT_FALSE(svr.is_running());
  9926. });
  9927. svr.wait_until_ready();
  9928. Client client(HOST, PORT);
  9929. auto get_thread = std::thread([&client]() {
  9930. std::string s;
  9931. auto res =
  9932. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9933. s += std::string(data, len);
  9934. return true;
  9935. });
  9936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9937. EXPECT_EQ(StatusCode::OK_200, res->status);
  9938. EXPECT_EQ("aaabbb", s);
  9939. });
  9940. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9941. // Give GET time to get a few messages.
  9942. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9943. }
  9944. TEST(MountTest, Unmount) {
  9945. Server svr;
  9946. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9947. auto se = detail::scope_exit([&] {
  9948. svr.stop();
  9949. listen_thread.join();
  9950. ASSERT_FALSE(svr.is_running());
  9951. });
  9952. svr.wait_until_ready();
  9953. Client cli("localhost", PORT);
  9954. svr.set_mount_point("/mount2", "./www2");
  9955. auto res = cli.Get("/");
  9956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9957. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9958. res = cli.Get("/mount2/dir/test.html");
  9959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9960. EXPECT_EQ(StatusCode::OK_200, res->status);
  9961. svr.set_mount_point("/", "./www");
  9962. res = cli.Get("/dir/");
  9963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9964. EXPECT_EQ(StatusCode::OK_200, res->status);
  9965. svr.remove_mount_point("/");
  9966. res = cli.Get("/dir/");
  9967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9968. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9969. svr.remove_mount_point("/mount2");
  9970. res = cli.Get("/mount2/dir/test.html");
  9971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9972. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9973. }
  9974. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  9975. Server svr;
  9976. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  9977. svr.Get("/api/hello", [](const Request &, Response &res) {
  9978. res.set_content("api", "text/plain");
  9979. });
  9980. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9981. auto se = detail::scope_exit([&] {
  9982. svr.stop();
  9983. listen_thread.join();
  9984. ASSERT_FALSE(svr.is_running());
  9985. });
  9986. svr.wait_until_ready();
  9987. Client cli(HOST, PORT);
  9988. auto res = cli.Get("/dir/test.html");
  9989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9990. EXPECT_EQ(StatusCode::OK_200, res->status);
  9991. res = cli.Get("/api/hello");
  9992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9993. EXPECT_EQ(StatusCode::OK_200, res->status);
  9994. EXPECT_EQ("api", res->body);
  9995. }
  9996. TEST(MountTest, PathSegmentBoundary) {
  9997. Server svr;
  9998. svr.set_mount_point("/mount2", "./www2");
  9999. svr.set_mount_point("/", "./www");
  10000. auto port = svr.bind_to_any_port(HOST);
  10001. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10002. auto se = detail::scope_exit([&] {
  10003. svr.stop();
  10004. listen_thread.join();
  10005. ASSERT_FALSE(svr.is_running());
  10006. });
  10007. svr.wait_until_ready();
  10008. Client cli(HOST, port);
  10009. auto res = cli.Get("/mount2/dir/test.html");
  10010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10011. EXPECT_EQ(StatusCode::OK_200, res->status);
  10012. // "/mount2" must not match part-way through a path segment.
  10013. res = cli.Get("/mount2dir/test.html");
  10014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10015. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10016. // A mount point ending in '/' keeps matching every path below it.
  10017. res = cli.Get("/dir/test.html");
  10018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10019. EXPECT_EQ(StatusCode::OK_200, res->status);
  10020. }
  10021. TEST(MountTest, Redicect) {
  10022. Server svr;
  10023. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10024. auto se = detail::scope_exit([&] {
  10025. svr.stop();
  10026. listen_thread.join();
  10027. ASSERT_FALSE(svr.is_running());
  10028. });
  10029. svr.set_mount_point("/", "./www");
  10030. svr.wait_until_ready();
  10031. Client cli("localhost", PORT);
  10032. auto res = cli.Get("/dir/");
  10033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10034. EXPECT_EQ(StatusCode::OK_200, res->status);
  10035. res = cli.Get("/dir");
  10036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10037. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10038. res = cli.Get("/file");
  10039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10040. EXPECT_EQ(StatusCode::OK_200, res->status);
  10041. res = cli.Get("/file/");
  10042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10043. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10044. cli.set_follow_location(true);
  10045. res = cli.Get("/dir");
  10046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10047. EXPECT_EQ(StatusCode::OK_200, res->status);
  10048. }
  10049. TEST(MountTest, MultibytesPathName) {
  10050. Server svr;
  10051. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10052. auto se = detail::scope_exit([&] {
  10053. svr.stop();
  10054. listen_thread.join();
  10055. ASSERT_FALSE(svr.is_running());
  10056. });
  10057. svr.set_mount_point("/", "./www");
  10058. svr.wait_until_ready();
  10059. Client cli("localhost", PORT);
  10060. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10062. EXPECT_EQ(StatusCode::OK_200, res->status);
  10063. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10064. }
  10065. #ifdef _WIN32
  10066. // Issue #2435: mmap::open() must succeed even when another handle holds
  10067. // the file open for writing (e.g. an active log file).
  10068. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10069. const char *path = "mmap_concurrent_writer_test.txt";
  10070. const char *content = "hello";
  10071. {
  10072. std::ofstream f(path, std::ios::binary);
  10073. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10074. }
  10075. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10076. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10077. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10078. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10079. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10080. detail::mmap m(path);
  10081. ASSERT_TRUE(m.is_open());
  10082. EXPECT_EQ(strlen(content), m.size());
  10083. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  10084. }
  10085. #endif
  10086. #ifndef _WIN32
  10087. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  10088. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  10089. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  10090. TEST(MmapTest, FailedMappingIsNotOpen) {
  10091. const char *path = "./mmap_failed_mapping_test_dir";
  10092. ASSERT_EQ(0, ::mkdir(path, 0755));
  10093. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10094. detail::mmap m(path);
  10095. EXPECT_FALSE(m.is_open());
  10096. EXPECT_EQ(0U, m.size());
  10097. EXPECT_NE(static_cast<const void *>(m.data()),
  10098. static_cast<const void *>(MAP_FAILED));
  10099. }
  10100. #endif
  10101. TEST(KeepAliveTest, ReadTimeout) {
  10102. Server svr;
  10103. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10104. std::this_thread::sleep_for(std::chrono::seconds(2));
  10105. res.set_content("a", "text/plain");
  10106. });
  10107. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10108. res.set_content("b", "text/plain");
  10109. });
  10110. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10111. auto se = detail::scope_exit([&] {
  10112. svr.stop();
  10113. listen_thread.join();
  10114. ASSERT_FALSE(svr.is_running());
  10115. });
  10116. svr.wait_until_ready();
  10117. Client cli("localhost", PORT);
  10118. cli.set_keep_alive(true);
  10119. cli.set_read_timeout(std::chrono::seconds(1));
  10120. auto resa = cli.Get("/a");
  10121. ASSERT_FALSE(resa);
  10122. EXPECT_EQ(Error::Read, resa.error());
  10123. auto resb = cli.Get("/b");
  10124. ASSERT_TRUE(resb);
  10125. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10126. EXPECT_EQ("b", resb->body);
  10127. }
  10128. TEST(KeepAliveTest, MaxCount) {
  10129. size_t keep_alive_max_count = 3;
  10130. Server svr;
  10131. svr.set_keep_alive_max_count(keep_alive_max_count);
  10132. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10133. res.set_content("Hello World!", "text/plain");
  10134. });
  10135. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10136. auto se = detail::scope_exit([&] {
  10137. svr.stop();
  10138. listen_thread.join();
  10139. ASSERT_FALSE(svr.is_running());
  10140. });
  10141. svr.wait_until_ready();
  10142. Client cli(HOST, PORT);
  10143. cli.set_keep_alive(true);
  10144. for (size_t i = 0; i < 5; i++) {
  10145. auto result = cli.Get("/hi");
  10146. ASSERT_TRUE(result);
  10147. EXPECT_EQ(StatusCode::OK_200, result->status);
  10148. if (i == keep_alive_max_count - 1) {
  10149. EXPECT_EQ("close", result->get_header_value("Connection"));
  10150. } else {
  10151. EXPECT_FALSE(result->has_header("Connection"));
  10152. }
  10153. }
  10154. }
  10155. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10156. // can pull the next one into the server's buffer. The server must serve it
  10157. // without waiting for the socket to become readable again. The keep-alive
  10158. // timeout outlasts the client's read timeout, so a request left waiting for it
  10159. // shows up as a missing response.
  10160. static void serve_pipelining_routes(Server &svr,
  10161. const std::function<void(int)> &client) {
  10162. svr.set_keep_alive_timeout(5);
  10163. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10164. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10165. });
  10166. svr.Post("/echo", [](const Request &req, Response &res) {
  10167. res.set_content("echo " + req.body, "text/plain");
  10168. });
  10169. auto port = svr.bind_to_any_port(HOST);
  10170. thread t = thread([&] { svr.listen_after_bind(); });
  10171. auto se = detail::scope_exit([&] {
  10172. svr.stop();
  10173. t.join();
  10174. });
  10175. svr.wait_until_ready();
  10176. client(port);
  10177. }
  10178. static std::string
  10179. send_pipelined_requests(const std::vector<std::string> &parts) {
  10180. Server svr;
  10181. std::string res;
  10182. serve_pipelining_routes(svr, [&](int port) {
  10183. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10184. });
  10185. return res;
  10186. }
  10187. static void expect_in_order(const std::string &res,
  10188. const std::vector<std::string> &bodies) {
  10189. size_t pos = 0;
  10190. for (const auto &body : bodies) {
  10191. pos = res.find(body, pos);
  10192. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10193. pos += body.size();
  10194. }
  10195. }
  10196. TEST(KeepAliveTest, PipelinedRequests) {
  10197. auto res = send_pipelined_requests(
  10198. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10199. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10200. "Content-Length: 4\r\n\r\nbody"
  10201. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10202. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10203. }
  10204. // The second request starts in the server's buffer and ends on the socket.
  10205. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10206. auto res =
  10207. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10208. "GET /hi/2 HTTP/1.1\r\nHo",
  10209. "st: localhost\r\nConnection: close\r\n\r\n"});
  10210. expect_in_order(res, {"hi 1", "hi 2"});
  10211. }
  10212. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10213. // CRLF after a body does not turn into a 400 for the next request.
  10214. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10215. auto res = send_pipelined_requests(
  10216. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10217. "Content-Length: 4\r\n\r\nbody\r\n"
  10218. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10219. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10220. expect_in_order(res, {"echo body", "hi 2"});
  10221. }
  10222. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10223. // must not be served as the next request.
  10224. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10225. auto res = send_pipelined_requests(
  10226. {"INVALID REQUEST LINE\r\n\r\n"
  10227. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10228. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10229. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10230. }
  10231. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10232. // Over TLS, the next request is held by the TLS library as already decrypted
  10233. // data rather than on the socket.
  10234. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10235. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10236. std::string res;
  10237. serve_pipelining_routes(svr, [&](int port) {
  10238. auto error = Error::Success;
  10239. auto sock = detail::create_client_socket(
  10240. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  10241. /*connection_timeout_sec=*/5, 0,
  10242. /*read_timeout_sec=*/2, 0,
  10243. /*write_timeout_sec=*/5, 0, std::string(), error);
  10244. ASSERT_NE(INVALID_SOCKET, sock);
  10245. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  10246. auto ctx = SSL_CTX_new(TLS_client_method());
  10247. auto ssl = SSL_new(ctx);
  10248. auto ssl_se = detail::scope_exit([&] {
  10249. SSL_free(ssl);
  10250. SSL_CTX_free(ctx);
  10251. });
  10252. SSL_set_fd(ssl, static_cast<int>(sock));
  10253. ASSERT_EQ(1, SSL_connect(ssl));
  10254. // One write, so all three requests arrive in one TLS record
  10255. const std::string req =
  10256. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10257. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10258. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
  10259. ASSERT_EQ(static_cast<int>(req.size()),
  10260. SSL_write(ssl, req.data(), static_cast<int>(req.size())));
  10261. char buf[512];
  10262. int n;
  10263. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  10264. res.append(buf, static_cast<size_t>(n));
  10265. }
  10266. });
  10267. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10268. }
  10269. #endif
  10270. TEST(KeepAliveTest, Issue1041) {
  10271. Server svr;
  10272. svr.set_keep_alive_timeout(3);
  10273. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10274. res.set_content("Hello World!", "text/plain");
  10275. });
  10276. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10277. auto se = detail::scope_exit([&] {
  10278. svr.stop();
  10279. listen_thread.join();
  10280. ASSERT_FALSE(svr.is_running());
  10281. });
  10282. svr.wait_until_ready();
  10283. Client cli(HOST, PORT);
  10284. cli.set_keep_alive(true);
  10285. auto result = cli.Get("/hi");
  10286. ASSERT_TRUE(result);
  10287. EXPECT_EQ(StatusCode::OK_200, result->status);
  10288. std::this_thread::sleep_for(std::chrono::seconds(5));
  10289. result = cli.Get("/hi");
  10290. ASSERT_TRUE(result);
  10291. EXPECT_EQ(StatusCode::OK_200, result->status);
  10292. }
  10293. TEST(KeepAliveTest, Issue1959) {
  10294. Server svr;
  10295. svr.set_keep_alive_timeout(5);
  10296. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10297. res.set_content("a", "text/plain");
  10298. });
  10299. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10300. auto se = detail::scope_exit([&] {
  10301. if (!svr.is_running()) return;
  10302. svr.stop();
  10303. listen_thread.join();
  10304. ASSERT_FALSE(svr.is_running());
  10305. });
  10306. svr.wait_until_ready();
  10307. Client cli("localhost", PORT);
  10308. cli.set_keep_alive(true);
  10309. using namespace std::chrono;
  10310. auto start = steady_clock::now();
  10311. cli.Get("/a");
  10312. svr.stop();
  10313. listen_thread.join();
  10314. auto end = steady_clock::now();
  10315. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10316. EXPECT_LT(elapsed, 5000);
  10317. }
  10318. #ifdef CPPHTTPLIB_SSL_ENABLED
  10319. TEST(KeepAliveTest, SSLClientReconnection) {
  10320. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10321. ASSERT_TRUE(svr.is_valid());
  10322. svr.set_keep_alive_timeout(1);
  10323. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10324. res.set_content("Hello World!", "text/plain");
  10325. });
  10326. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10327. auto se = detail::scope_exit([&] {
  10328. svr.stop();
  10329. listen_thread.join();
  10330. ASSERT_FALSE(svr.is_running());
  10331. });
  10332. svr.wait_until_ready();
  10333. SSLClient cli(HOST, PORT);
  10334. cli.enable_server_certificate_verification(false);
  10335. cli.set_keep_alive(true);
  10336. auto result = cli.Get("/hi");
  10337. ASSERT_TRUE(result);
  10338. EXPECT_EQ(StatusCode::OK_200, result->status);
  10339. result = cli.Get("/hi");
  10340. ASSERT_TRUE(result);
  10341. EXPECT_EQ(StatusCode::OK_200, result->status);
  10342. std::this_thread::sleep_for(std::chrono::seconds(2));
  10343. // Recoonect
  10344. result = cli.Get("/hi");
  10345. ASSERT_TRUE(result);
  10346. EXPECT_EQ(StatusCode::OK_200, result->status);
  10347. result = cli.Get("/hi");
  10348. ASSERT_TRUE(result);
  10349. EXPECT_EQ(StatusCode::OK_200, result->status);
  10350. }
  10351. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10352. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10353. ASSERT_TRUE(svr.is_valid());
  10354. svr.set_keep_alive_timeout(1);
  10355. std::string content = "reconnect";
  10356. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10357. res.set_content("Hello World!", "text/plain");
  10358. });
  10359. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10360. auto se = detail::scope_exit([&] {
  10361. svr.stop();
  10362. listen_thread.join();
  10363. ASSERT_FALSE(svr.is_running());
  10364. });
  10365. svr.wait_until_ready();
  10366. SSLClient cli(HOST, PORT);
  10367. cli.enable_server_certificate_verification(false);
  10368. cli.set_keep_alive(true);
  10369. auto result = cli.Post(
  10370. "/hi", content.size(),
  10371. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10372. sink.write(content.c_str(), content.size());
  10373. return true;
  10374. },
  10375. "text/plain");
  10376. ASSERT_TRUE(result);
  10377. EXPECT_EQ(200, result->status);
  10378. std::this_thread::sleep_for(std::chrono::seconds(2));
  10379. // Recoonect
  10380. result = cli.Post(
  10381. "/hi", content.size(),
  10382. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10383. sink.write(content.c_str(), content.size());
  10384. return true;
  10385. },
  10386. "text/plain");
  10387. ASSERT_TRUE(result);
  10388. EXPECT_EQ(200, result->status);
  10389. result = cli.Post(
  10390. "/hi", content.size(),
  10391. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10392. sink.write(content.c_str(), content.size());
  10393. return true;
  10394. },
  10395. "text/plain");
  10396. ASSERT_TRUE(result);
  10397. EXPECT_EQ(200, result->status);
  10398. }
  10399. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10400. using namespace httplib::tls;
  10401. {
  10402. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10403. ASSERT_TRUE(svr.is_valid());
  10404. svr.Get("/sni", [&](const Request &req, Response &res) {
  10405. std::string expected = req.sni();
  10406. EXPECT_EQ(expected, req.get_param_value("expected"));
  10407. res.set_content("ok", "text/plain");
  10408. });
  10409. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10410. auto se = detail::scope_exit([&] {
  10411. svr.stop();
  10412. listen_thread.join();
  10413. ASSERT_FALSE(svr.is_running());
  10414. });
  10415. svr.wait_until_ready();
  10416. {
  10417. SSLClient cli("localhost", PORT);
  10418. cli.enable_server_certificate_verification(false);
  10419. auto res = cli.Get("/sni?expected=localhost");
  10420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10421. }
  10422. {
  10423. SSLClient cli("::1", PORT);
  10424. cli.enable_server_certificate_verification(false);
  10425. auto res = cli.Get("/sni?expected=");
  10426. // NOTE: This may fail if the server is listening on IPv4 only
  10427. // (e.g., when localhost resolves to 127.0.0.1 only)
  10428. if (res) {
  10429. EXPECT_EQ(StatusCode::OK_200, res->status);
  10430. } else {
  10431. EXPECT_EQ(Error::Connection, res.error());
  10432. }
  10433. }
  10434. }
  10435. }
  10436. #endif
  10437. TEST(ClientProblemDetectionTest, ContentProvider) {
  10438. Server svr;
  10439. size_t content_length = 1024 * 1024;
  10440. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10441. res.set_content_provider(
  10442. content_length, "text/plain",
  10443. [&](size_t offset, size_t length, DataSink &sink) {
  10444. auto out_len = std::min(length, static_cast<size_t>(1024));
  10445. std::string out(out_len, '@');
  10446. sink.write(out.data(), out_len);
  10447. return offset < 4096;
  10448. },
  10449. [](bool success) { ASSERT_FALSE(success); });
  10450. });
  10451. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10452. res.set_content_provider(
  10453. 0, "text/plain",
  10454. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10455. EXPECT_TRUE(false);
  10456. return true;
  10457. },
  10458. [](bool success) { ASSERT_FALSE(success); });
  10459. });
  10460. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10461. auto se = detail::scope_exit([&] {
  10462. svr.stop();
  10463. listen_thread.join();
  10464. ASSERT_FALSE(svr.is_running());
  10465. });
  10466. svr.wait_until_ready();
  10467. Client cli("localhost", PORT);
  10468. {
  10469. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10470. size_t /*data_length*/) { return false; });
  10471. ASSERT_FALSE(res);
  10472. }
  10473. {
  10474. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10475. size_t /*data_length*/) { return false; });
  10476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10477. }
  10478. }
  10479. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10480. // A provider that reports success without writing anything and without
  10481. // calling done() used to be handed the same offset and length again on every
  10482. // pass, so it spun for as long as the peer stayed connected.
  10483. Server svr;
  10484. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10485. res.set_content("ok", "text/plain");
  10486. });
  10487. auto port = svr.bind_to_any_port(HOST);
  10488. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10489. auto se = detail::scope_exit([&] {
  10490. svr.stop();
  10491. listen_thread.join();
  10492. ASSERT_FALSE(svr.is_running());
  10493. });
  10494. svr.wait_until_ready();
  10495. std::atomic<int> call_count{0};
  10496. Client cli(HOST, port);
  10497. auto res = cli.Post(
  10498. "/", 1024,
  10499. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10500. // Give up after enough passes to show the spin, so that losing the
  10501. // check below fails this test instead of hanging it.
  10502. return ++call_count < 100;
  10503. },
  10504. "text/plain");
  10505. ASSERT_FALSE(res);
  10506. EXPECT_EQ(Error::Write, res.error());
  10507. EXPECT_EQ(1, call_count.load());
  10508. }
  10509. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10510. // A writer only has to assign `write`. The other three used to be left as
  10511. // empty std::functions, so a provider calling one threw
  10512. // std::bad_function_call out of the thread running it and took the whole
  10513. // process down.
  10514. DataSink sink;
  10515. std::string written;
  10516. sink.write = [&](const char *data, size_t data_len) {
  10517. written.append(data, data_len);
  10518. return true;
  10519. };
  10520. EXPECT_TRUE(sink.is_writable());
  10521. sink.done();
  10522. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10523. EXPECT_TRUE(written.empty());
  10524. }
  10525. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10526. // A sink that cannot carry trailers still has to finish.
  10527. DataSink sink;
  10528. auto done_count = 0;
  10529. sink.done = [&]() { done_count++; };
  10530. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10531. EXPECT_EQ(1, done_count);
  10532. }
  10533. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10534. Server svr;
  10535. const std::string body(4096, 'x');
  10536. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10537. res.set_content_provider(body.size(), "text/plain",
  10538. [&](size_t offset, size_t length, DataSink &sink) {
  10539. sink.write(body.data() + offset, length);
  10540. sink.done();
  10541. return true;
  10542. });
  10543. });
  10544. auto port = svr.bind_to_any_port(HOST);
  10545. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10546. auto se = detail::scope_exit([&] {
  10547. svr.stop();
  10548. listen_thread.join();
  10549. ASSERT_FALSE(svr.is_running());
  10550. });
  10551. svr.wait_until_ready();
  10552. Client cli(HOST, port);
  10553. auto res = cli.Get("/");
  10554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10555. EXPECT_EQ(StatusCode::OK_200, res->status);
  10556. EXPECT_EQ(body, res->body);
  10557. }
  10558. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10559. Server svr;
  10560. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10561. res.set_content_provider(
  10562. 1024, "text/plain",
  10563. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10564. sink.write("hello", 5);
  10565. sink.done(); // short of the 1024 bytes the response promised
  10566. return true;
  10567. });
  10568. });
  10569. auto port = svr.bind_to_any_port(HOST);
  10570. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10571. auto se = detail::scope_exit([&] {
  10572. svr.stop();
  10573. listen_thread.join();
  10574. ASSERT_FALSE(svr.is_running());
  10575. });
  10576. svr.wait_until_ready();
  10577. Client cli(HOST, port);
  10578. cli.set_read_timeout(5, 0);
  10579. // The response is short of its Content-Length, so the client cannot read a
  10580. // complete body. What matters is that this returns at all: a no-op done()
  10581. // would leave the writer looping over a provider that never makes progress.
  10582. auto res = cli.Get("/");
  10583. EXPECT_FALSE(res);
  10584. }
  10585. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10586. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10587. // The compressed path builds the whole body before connecting, so this
  10588. // fails client-side and never reaches a server.
  10589. Client cli(HOST, PORT);
  10590. cli.set_compress(true);
  10591. auto res = cli.Post(
  10592. "/", 1024,
  10593. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10594. sink.write("hello", 5);
  10595. sink.done(); // short of the 1024 bytes the request announced
  10596. return true;
  10597. },
  10598. "text/plain");
  10599. ASSERT_FALSE(res);
  10600. EXPECT_EQ(Error::Write, res.error());
  10601. }
  10602. #endif
  10603. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  10604. Server svr;
  10605. svr.set_error_handler([](Request const &, Response &res) -> void {
  10606. res.set_chunked_content_provider(
  10607. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10608. sink.os << "hello";
  10609. sink.os << "world";
  10610. sink.done();
  10611. return true;
  10612. });
  10613. });
  10614. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10615. auto se = detail::scope_exit([&] {
  10616. svr.stop();
  10617. listen_thread.join();
  10618. ASSERT_FALSE(svr.is_running());
  10619. });
  10620. svr.wait_until_ready();
  10621. Client cli("localhost", PORT);
  10622. auto res = cli.Get("/");
  10623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10624. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10625. EXPECT_EQ("helloworld", res->body);
  10626. }
  10627. // A body set after a content provider must replace it, not be sent through it.
  10628. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  10629. Server svr;
  10630. svr.set_mount_point("/", "./www");
  10631. svr.set_file_request_handler([](const Request &req, Response &res) {
  10632. if (req.path == "/dir/test.html") {
  10633. res.status = StatusCode::Forbidden_403;
  10634. res.set_content(std::string(5000, 'D'), "text/plain");
  10635. } else if (req.path == "/file") {
  10636. res.status = StatusCode::Forbidden_403;
  10637. res.body = "Denied";
  10638. }
  10639. });
  10640. auto port = svr.bind_to_any_port(HOST);
  10641. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10642. auto se = detail::scope_exit([&] {
  10643. svr.stop();
  10644. t.join();
  10645. ASSERT_FALSE(svr.is_running());
  10646. });
  10647. svr.wait_until_ready();
  10648. Client cli(HOST, port);
  10649. {
  10650. auto res = cli.Get("/dir/test.html");
  10651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10652. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10653. EXPECT_EQ(std::string(5000, 'D'), res->body);
  10654. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  10655. }
  10656. {
  10657. auto res = cli.Get("/file");
  10658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10659. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10660. EXPECT_EQ("Denied", res->body);
  10661. }
  10662. {
  10663. auto res = cli.Get("/dir/index.html");
  10664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10665. EXPECT_EQ(StatusCode::OK_200, res->status);
  10666. EXPECT_EQ(0U, res->body.find("<html>"));
  10667. }
  10668. }
  10669. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  10670. Server svr;
  10671. std::vector<bool> released;
  10672. std::mutex released_mutex;
  10673. auto releaser = [&](bool success) {
  10674. std::lock_guard<std::mutex> guard(released_mutex);
  10675. released.push_back(success);
  10676. };
  10677. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  10678. return sink.write(&"hello"[offset], length);
  10679. };
  10680. svr.Get("/sized", [&](const Request &, Response &res) {
  10681. res.status = StatusCode::NotFound_404;
  10682. res.set_content_provider(5, "text/plain", provider, releaser);
  10683. });
  10684. svr.Get("/chunked", [&](const Request &, Response &res) {
  10685. res.status = StatusCode::ServiceUnavailable_503;
  10686. res.set_chunked_content_provider(
  10687. "text/plain",
  10688. [](size_t, DataSink &sink) {
  10689. sink.os << "chunk";
  10690. sink.done();
  10691. return true;
  10692. },
  10693. releaser);
  10694. });
  10695. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  10696. res.set_content_provider(5, "text/plain", provider, releaser);
  10697. throw std::runtime_error("after the provider");
  10698. });
  10699. svr.set_error_handler([](const Request &req, Response &res) {
  10700. // Leave the exception handler's content to it.
  10701. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  10702. res.set_content(std::string(1000, 'E'), "text/html");
  10703. return Server::HandlerResponse::Handled;
  10704. });
  10705. svr.set_exception_handler(
  10706. [](const Request &, Response &res, std::exception_ptr) {
  10707. res.status = StatusCode::InternalServerError_500;
  10708. res.set_content(std::string(1000, 'X'), "text/html");
  10709. });
  10710. auto port = svr.bind_to_any_port(HOST);
  10711. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10712. auto se = detail::scope_exit([&] {
  10713. svr.stop();
  10714. t.join();
  10715. ASSERT_FALSE(svr.is_running());
  10716. });
  10717. svr.wait_until_ready();
  10718. Client cli(HOST, port);
  10719. {
  10720. auto res = cli.Get("/sized");
  10721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10722. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10723. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10724. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  10725. }
  10726. {
  10727. auto res = cli.Get("/chunked");
  10728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10729. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  10730. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10731. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  10732. }
  10733. {
  10734. auto res = cli.Get("/throw");
  10735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10736. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  10737. EXPECT_EQ(std::string(1000, 'X'), res->body);
  10738. }
  10739. std::lock_guard<std::mutex> guard(released_mutex);
  10740. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  10741. }
  10742. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  10743. Server svr;
  10744. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  10745. return sink.write(&"abc"[offset], length);
  10746. };
  10747. svr.Get("/file-then-body", [](const Request &, Response &res) {
  10748. res.set_file_content("./www/dir/test.html");
  10749. res.set_content("body", "text/plain");
  10750. });
  10751. svr.Get("/body-then-file", [](const Request &, Response &res) {
  10752. res.set_content(std::string(100, 'B'), "text/plain");
  10753. res.set_file_content("./www/dir/test.html");
  10754. });
  10755. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  10756. res.set_content(std::string(100, 'B'), "text/plain");
  10757. res.set_content_provider(3, "text/plain", abc);
  10758. });
  10759. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  10760. res.set_content_provider(3, "text/plain", abc);
  10761. res.set_content(std::string(100, 'B'), "text/plain");
  10762. });
  10763. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  10764. res.set_content_provider(3, "text/plain", abc);
  10765. res.body = "direct";
  10766. });
  10767. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  10768. res.set_file_content("./www/dir/test.html");
  10769. res.body = "direct";
  10770. });
  10771. auto port = svr.bind_to_any_port(HOST);
  10772. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10773. auto se = detail::scope_exit([&] {
  10774. svr.stop();
  10775. t.join();
  10776. ASSERT_FALSE(svr.is_running());
  10777. });
  10778. svr.wait_until_ready();
  10779. Client cli(HOST, port);
  10780. auto expect_body = [&](const char *path, const std::string &body) {
  10781. // Uncompressed, so Content-Length can be compared with the body.
  10782. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  10783. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  10784. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10785. EXPECT_EQ(body, res->body) << path;
  10786. EXPECT_EQ(std::to_string(body.size()),
  10787. res->get_header_value("Content-Length"))
  10788. << path;
  10789. };
  10790. expect_body("/file-then-body", "body");
  10791. expect_body("/body-then-file", "test.html");
  10792. expect_body("/body-then-provider", "abc");
  10793. expect_body("/provider-then-body", std::string(100, 'B'));
  10794. expect_body("/provider-then-direct-body", "direct");
  10795. expect_body("/file-then-direct-body", "direct");
  10796. // Ranges are checked against the body, not the dropped provider.
  10797. {
  10798. auto res = cli.Get("/provider-then-direct-body",
  10799. Headers{{make_range_header({{1, 2}})}});
  10800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10801. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10802. EXPECT_EQ("ir", res->body);
  10803. }
  10804. {
  10805. auto res = cli.Get("/file-then-direct-body",
  10806. Headers{{make_range_header({{7, 8}})}});
  10807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10808. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  10809. }
  10810. }
  10811. // Forward declaration (see the base64_encode note).
  10812. namespace httplib {
  10813. namespace detail {
  10814. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  10815. const std::string &content_type,
  10816. EncodingType encoding);
  10817. } // namespace detail
  10818. } // namespace httplib
  10819. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  10820. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  10821. ASSERT_TRUE(mm->is_open());
  10822. Response res;
  10823. detail::set_file_content_provider(res, mm, "text/html",
  10824. detail::EncodingType::None);
  10825. std::string out;
  10826. DataSink sink;
  10827. sink.write = [&](const char *d, size_t l) {
  10828. out.append(d, l);
  10829. return true;
  10830. };
  10831. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  10832. EXPECT_EQ("test.html", out);
  10833. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  10834. EXPECT_EQ("test.html", out);
  10835. }
  10836. TEST(LongPollingTest, ClientCloseDetection) {
  10837. Server svr;
  10838. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10839. res.set_chunked_content_provider(
  10840. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10841. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10842. sink.os << "hello";
  10843. auto count = 10;
  10844. while (count > 0 && sink.is_writable()) {
  10845. this_thread::sleep_for(chrono::milliseconds(10));
  10846. count--;
  10847. }
  10848. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  10849. return true;
  10850. });
  10851. });
  10852. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10853. auto se = detail::scope_exit([&] {
  10854. svr.stop();
  10855. listen_thread.join();
  10856. ASSERT_FALSE(svr.is_running());
  10857. });
  10858. svr.wait_until_ready();
  10859. Client cli("localhost", PORT);
  10860. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10861. EXPECT_EQ("hello", string(data, data_length));
  10862. return false; // close the socket immediately.
  10863. });
  10864. ASSERT_FALSE(res);
  10865. }
  10866. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  10867. Server svr;
  10868. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10869. res.set_chunked_content_provider(
  10870. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10871. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10872. sink.os << "hello";
  10873. EXPECT_TRUE(sink.os.good());
  10874. // Wait for the client to close the connection
  10875. auto count = 10;
  10876. while (count > 0 && sink.is_writable()) {
  10877. this_thread::sleep_for(chrono::milliseconds(10));
  10878. count--;
  10879. }
  10880. // After client disconnect, write repeatedly until the socket
  10881. // write actually fails (small writes may be absorbed by the
  10882. // kernel buffer)
  10883. std::string chunk(1024, 'x');
  10884. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  10885. sink.os << chunk;
  10886. }
  10887. EXPECT_TRUE(sink.os.fail());
  10888. return true;
  10889. });
  10890. });
  10891. auto port = svr.bind_to_any_port("localhost");
  10892. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10893. auto se = detail::scope_exit([&] {
  10894. svr.stop();
  10895. listen_thread.join();
  10896. ASSERT_FALSE(svr.is_running());
  10897. });
  10898. svr.wait_until_ready();
  10899. Client cli("localhost", port);
  10900. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10901. EXPECT_EQ("hello", string(data, data_length));
  10902. return false; // close the socket immediately.
  10903. });
  10904. ASSERT_FALSE(res);
  10905. }
  10906. TEST(GetWithParametersTest, GetWithParameters) {
  10907. Server svr;
  10908. svr.Get("/", [&](const Request &req, Response &) {
  10909. EXPECT_EQ("world", req.get_param_value("hello"));
  10910. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10911. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10912. });
  10913. svr.Get("/params", [&](const Request &req, Response &) {
  10914. EXPECT_EQ("world", req.get_param_value("hello"));
  10915. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10916. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10917. });
  10918. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10919. EXPECT_EQ("resource-id", req.matches[1]);
  10920. EXPECT_EQ("foo", req.get_param_value("param1"));
  10921. EXPECT_EQ("bar", req.get_param_value("param2"));
  10922. });
  10923. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10924. EXPECT_EQ("user-id", req.path_params.at("id"));
  10925. EXPECT_EQ("foo", req.get_param_value("param1"));
  10926. EXPECT_EQ("bar", req.get_param_value("param2"));
  10927. });
  10928. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10929. auto se = detail::scope_exit([&] {
  10930. svr.stop();
  10931. listen_thread.join();
  10932. ASSERT_FALSE(svr.is_running());
  10933. });
  10934. svr.wait_until_ready();
  10935. {
  10936. Client cli(HOST, PORT);
  10937. Params params;
  10938. params.emplace("hello", "world");
  10939. params.emplace("hello2", "world2");
  10940. params.emplace("hello3", "world3");
  10941. auto res = cli.Get("/", params, Headers{});
  10942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10943. EXPECT_EQ(StatusCode::OK_200, res->status);
  10944. }
  10945. {
  10946. Client cli(HOST, PORT);
  10947. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10949. EXPECT_EQ(StatusCode::OK_200, res->status);
  10950. }
  10951. {
  10952. Client cli(HOST, PORT);
  10953. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  10954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10955. EXPECT_EQ(StatusCode::OK_200, res->status);
  10956. }
  10957. {
  10958. Client cli(HOST, PORT);
  10959. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  10960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10961. EXPECT_EQ(StatusCode::OK_200, res->status);
  10962. }
  10963. }
  10964. TEST(GetWithParametersTest, GetWithParameters2) {
  10965. Server svr;
  10966. svr.Get("/", [&](const Request &req, Response &res) {
  10967. auto text = req.get_param_value("hello");
  10968. res.set_content(text, "text/plain");
  10969. });
  10970. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10971. auto se = detail::scope_exit([&] {
  10972. svr.stop();
  10973. listen_thread.join();
  10974. ASSERT_FALSE(svr.is_running());
  10975. });
  10976. svr.wait_until_ready();
  10977. Client cli("localhost", PORT);
  10978. Params params;
  10979. params.emplace("hello", "world");
  10980. std::string body;
  10981. auto res = cli.Get("/", params, Headers{},
  10982. [&](const char *data, size_t data_length) {
  10983. body.append(data, data_length);
  10984. return true;
  10985. });
  10986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10987. EXPECT_EQ(StatusCode::OK_200, res->status);
  10988. EXPECT_EQ("world", body);
  10989. }
  10990. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  10991. Server svr;
  10992. svr.Get("/search", [&](const Request &req, Response &res) {
  10993. auto q = req.get_param_value("q");
  10994. res.set_content(q, "text/plain");
  10995. });
  10996. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10997. auto se = detail::scope_exit([&] {
  10998. svr.stop();
  10999. listen_thread.join();
  11000. ASSERT_FALSE(svr.is_running());
  11001. });
  11002. svr.wait_until_ready();
  11003. Client cli("localhost", PORT);
  11004. // Verify that Get(path, params) works without requiring Headers argument
  11005. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11007. EXPECT_EQ(StatusCode::OK_200, res->status);
  11008. EXPECT_EQ("cpp-httplib", res->body);
  11009. }
  11010. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11011. auto host = "httpbingo.org";
  11012. auto path = std::string{"/range/32"};
  11013. #ifdef CPPHTTPLIB_SSL_ENABLED
  11014. SSLClient cli(host);
  11015. #else
  11016. Client cli(host);
  11017. #endif
  11018. cli.set_default_headers({make_range_header({{1, 10}})});
  11019. cli.set_connection_timeout(5);
  11020. {
  11021. auto res = cli.Get(path);
  11022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11023. EXPECT_EQ("bcdefghijk", res->body);
  11024. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11025. }
  11026. {
  11027. auto res = cli.Get(path);
  11028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11029. EXPECT_EQ("bcdefghijk", res->body);
  11030. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11031. }
  11032. }
  11033. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11034. Server svr;
  11035. svr.set_default_headers({{"Hello", "World"}});
  11036. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11037. res.set_content("ok", "text/plain");
  11038. });
  11039. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11040. auto se = detail::scope_exit([&] {
  11041. svr.stop();
  11042. listen_thread.join();
  11043. ASSERT_FALSE(svr.is_running());
  11044. });
  11045. svr.wait_until_ready();
  11046. Client cli("localhost", PORT);
  11047. auto res = cli.Get("/");
  11048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11049. EXPECT_EQ(StatusCode::OK_200, res->status);
  11050. EXPECT_EQ("ok", res->body);
  11051. EXPECT_EQ("World", res->get_header_value("Hello"));
  11052. }
  11053. #ifdef CPPHTTPLIB_SSL_ENABLED
  11054. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11055. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11056. ASSERT_TRUE(svr.is_valid());
  11057. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11058. std::this_thread::sleep_for(std::chrono::seconds(2));
  11059. res.set_content("a", "text/plain");
  11060. });
  11061. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11062. res.set_content("b", "text/plain");
  11063. });
  11064. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11065. auto se = detail::scope_exit([&] {
  11066. svr.stop();
  11067. listen_thread.join();
  11068. ASSERT_FALSE(svr.is_running());
  11069. });
  11070. svr.wait_until_ready();
  11071. SSLClient cli("localhost", PORT);
  11072. cli.enable_server_certificate_verification(false);
  11073. cli.set_keep_alive(true);
  11074. cli.set_read_timeout(std::chrono::seconds(1));
  11075. auto resa = cli.Get("/a");
  11076. ASSERT_TRUE(!resa);
  11077. EXPECT_EQ(Error::Read, resa.error());
  11078. auto resb = cli.Get("/b");
  11079. ASSERT_TRUE(resb);
  11080. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11081. EXPECT_EQ("b", resb->body);
  11082. }
  11083. // Closing an idle keep-alive connection sends close_notify and returns. The
  11084. // server must not wait for the client's close_notify: an idle client never
  11085. // sends one, so the worker would be held until the read timeout expires, and
  11086. // stop() would wait for it.
  11087. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11088. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11089. ASSERT_TRUE(svr.is_valid());
  11090. svr.set_keep_alive_timeout(1);
  11091. svr.set_read_timeout(10, 0);
  11092. svr.Get("/", [](const Request &, Response &res) {
  11093. res.set_content("ok", "text/plain");
  11094. });
  11095. auto port = svr.bind_to_any_port(HOST);
  11096. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11097. auto se = detail::scope_exit([&] {
  11098. if (listen_thread.joinable()) {
  11099. svr.stop();
  11100. listen_thread.join();
  11101. }
  11102. });
  11103. svr.wait_until_ready();
  11104. SSLClient cli(HOST, port);
  11105. cli.enable_server_certificate_verification(false);
  11106. cli.set_keep_alive(true);
  11107. auto res = cli.Get("/");
  11108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11109. EXPECT_EQ(StatusCode::OK_200, res->status);
  11110. // Stay idle past the keep-alive timeout so the server closes the connection.
  11111. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11112. auto start = std::chrono::steady_clock::now();
  11113. svr.stop();
  11114. listen_thread.join();
  11115. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11116. std::chrono::steady_clock::now() - start)
  11117. .count();
  11118. EXPECT_LT(elapsed, 3000);
  11119. }
  11120. #endif
  11121. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11122. protected:
  11123. ServerTestWithAI_PASSIVE()
  11124. : cli_(HOST, PORT)
  11125. #ifdef CPPHTTPLIB_SSL_ENABLED
  11126. ,
  11127. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11128. #endif
  11129. {
  11130. #ifdef CPPHTTPLIB_SSL_ENABLED
  11131. cli_.enable_server_certificate_verification(false);
  11132. #endif
  11133. }
  11134. virtual void SetUp() {
  11135. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11136. res.set_content("Hello World!", "text/plain");
  11137. });
  11138. t_ = thread(
  11139. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11140. svr_.wait_until_ready();
  11141. }
  11142. virtual void TearDown() {
  11143. svr_.stop();
  11144. t_.join();
  11145. }
  11146. #ifdef CPPHTTPLIB_SSL_ENABLED
  11147. SSLClient cli_;
  11148. SSLServer svr_;
  11149. #else
  11150. Client cli_;
  11151. Server svr_;
  11152. #endif
  11153. thread t_;
  11154. };
  11155. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11156. auto res = cli_.Get("/hi");
  11157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11158. EXPECT_EQ(StatusCode::OK_200, res->status);
  11159. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11160. EXPECT_EQ("Hello World!", res->body);
  11161. }
  11162. class ServerUpDownTest : public ::testing::Test {
  11163. protected:
  11164. ServerUpDownTest() : cli_(HOST, PORT) {}
  11165. virtual void SetUp() {
  11166. t_ = thread([&]() {
  11167. svr_.bind_to_any_port(HOST);
  11168. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11169. ASSERT_TRUE(svr_.listen_after_bind());
  11170. });
  11171. svr_.wait_until_ready();
  11172. }
  11173. virtual void TearDown() {
  11174. svr_.stop();
  11175. t_.join();
  11176. }
  11177. Client cli_;
  11178. Server svr_;
  11179. thread t_;
  11180. };
  11181. TEST_F(ServerUpDownTest, QuickStartStop) {
  11182. // Should not crash, especially when run with
  11183. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11184. }
  11185. class PayloadMaxLengthTest : public ::testing::Test {
  11186. protected:
  11187. PayloadMaxLengthTest()
  11188. : cli_(HOST, PORT)
  11189. #ifdef CPPHTTPLIB_SSL_ENABLED
  11190. ,
  11191. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11192. #endif
  11193. {
  11194. #ifdef CPPHTTPLIB_SSL_ENABLED
  11195. cli_.enable_server_certificate_verification(false);
  11196. #endif
  11197. }
  11198. virtual void SetUp() {
  11199. svr_.set_payload_max_length(8);
  11200. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11201. res.set_content("test", "text/plain");
  11202. });
  11203. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11204. svr_.wait_until_ready();
  11205. }
  11206. virtual void TearDown() {
  11207. svr_.stop();
  11208. t_.join();
  11209. }
  11210. #ifdef CPPHTTPLIB_SSL_ENABLED
  11211. SSLClient cli_;
  11212. SSLServer svr_;
  11213. #else
  11214. Client cli_;
  11215. Server svr_;
  11216. #endif
  11217. thread t_;
  11218. };
  11219. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11220. auto res = cli_.Post("/test", "123456789", "text/plain");
  11221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11222. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11223. res = cli_.Post("/test", "12345678", "text/plain");
  11224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11225. EXPECT_EQ(StatusCode::OK_200, res->status);
  11226. }
  11227. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11228. // Test chunked encoding with payload exceeding the 8-byte limit
  11229. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11230. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11232. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11233. }
  11234. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11235. // Test chunked encoding with payload within the 8-byte limit
  11236. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11237. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11239. EXPECT_EQ(StatusCode::OK_200, res->status);
  11240. }
  11241. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11242. // Test using send_request to send chunked data exceeding payload limit
  11243. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11244. "Host: " +
  11245. std::string(HOST) + ":" + std::to_string(PORT) +
  11246. "\r\n"
  11247. "Transfer-Encoding: chunked\r\n"
  11248. "Connection: close\r\n"
  11249. "\r\n"
  11250. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  11251. "0123456789\r\n"
  11252. "0\r\n" // End chunk
  11253. "\r\n";
  11254. std::string response;
  11255. bool result = send_request(1, chunked_request, &response);
  11256. if (!result) {
  11257. // If send_request fails, it might be because the server closed the
  11258. // connection due to payload limit enforcement, which is acceptable
  11259. SUCCEED()
  11260. << "Server rejected oversized chunked request (connection closed)";
  11261. } else {
  11262. // If we got a response, check if it's an error response or connection was
  11263. // closed early Short response length indicates connection was closed due to
  11264. // payload limit
  11265. if (response.length() <= 10) {
  11266. SUCCEED() << "Server closed connection for oversized chunked request";
  11267. } else {
  11268. // Check for error status codes
  11269. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11270. response.find("Payload Too Large") != std::string::npos ||
  11271. response.find("400") != std::string::npos);
  11272. }
  11273. }
  11274. }
  11275. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  11276. // Test request without Content-Length header exceeding payload limit
  11277. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11278. "Host: " +
  11279. std::string(HOST) + ":" +
  11280. std::to_string(PORT) +
  11281. "\r\n"
  11282. "Connection: close\r\n"
  11283. "\r\n";
  11284. // Add payload exceeding the 8-byte limit
  11285. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  11286. request_without_content_length += large_payload;
  11287. std::string response;
  11288. bool result = send_request(1, request_without_content_length, &response);
  11289. if (!result) {
  11290. // If send_request fails, server likely closed connection due to payload
  11291. // limit
  11292. SUCCEED() << "Server rejected oversized request without Content-Length "
  11293. "(connection closed)";
  11294. } else {
  11295. // Check if server responded with error or closed connection early
  11296. if (response.length() <= 10) {
  11297. SUCCEED() << "Server closed connection for oversized request without "
  11298. "Content-Length";
  11299. } else {
  11300. // Check for error status codes
  11301. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11302. response.find("Payload Too Large") != std::string::npos ||
  11303. response.find("400") != std::string::npos);
  11304. }
  11305. }
  11306. }
  11307. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  11308. // Test request without Content-Length header within payload limit
  11309. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11310. "Host: " +
  11311. std::string(HOST) + ":" +
  11312. std::to_string(PORT) +
  11313. "\r\n"
  11314. "Connection: close\r\n"
  11315. "\r\n";
  11316. // Add payload within the 8-byte limit
  11317. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  11318. request_without_content_length += small_payload;
  11319. std::string response;
  11320. bool result = send_request(1, request_without_content_length, &response);
  11321. // For requests without Content-Length, the server may have different behavior
  11322. // The key is that it should not reject due to payload limit for small
  11323. // payloads
  11324. if (result) {
  11325. // Check for any HTTP response (success or error, but not connection closed)
  11326. if (response.length() > 10) {
  11327. SUCCEED()
  11328. << "Server processed request without Content-Length within limit";
  11329. } else {
  11330. // Short response might indicate connection closed, which is acceptable
  11331. SUCCEED() << "Server closed connection for request without "
  11332. "Content-Length (acceptable behavior)";
  11333. }
  11334. } else {
  11335. // Connection failure might be due to protocol requirements
  11336. SUCCEED() << "Connection issue with request without Content-Length "
  11337. "(environment-specific)";
  11338. }
  11339. }
  11340. class LargePayloadMaxLengthTest : public ::testing::Test {
  11341. protected:
  11342. LargePayloadMaxLengthTest()
  11343. : cli_(HOST, PORT)
  11344. #ifdef CPPHTTPLIB_SSL_ENABLED
  11345. ,
  11346. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11347. #endif
  11348. {
  11349. #ifdef CPPHTTPLIB_SSL_ENABLED
  11350. cli_.enable_server_certificate_verification(false);
  11351. #endif
  11352. }
  11353. virtual void SetUp() {
  11354. // Set 10MB payload limit
  11355. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  11356. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  11357. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11358. res.set_content("Large payload test", "text/plain");
  11359. });
  11360. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11361. svr_.wait_until_ready();
  11362. }
  11363. virtual void TearDown() {
  11364. svr_.stop();
  11365. t_.join();
  11366. }
  11367. #ifdef CPPHTTPLIB_SSL_ENABLED
  11368. SSLClient cli_;
  11369. SSLServer svr_;
  11370. #else
  11371. Client cli_;
  11372. Server svr_;
  11373. #endif
  11374. thread t_;
  11375. };
  11376. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  11377. // Test chunked encoding with payload within 10MB limit
  11378. std::string medium_payload(5 * 1024 * 1024,
  11379. 'A'); // 5MB payload, within 10MB limit
  11380. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  11381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11382. EXPECT_EQ(StatusCode::OK_200, res->status);
  11383. }
  11384. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  11385. // Test chunked encoding with payload exceeding 10MB limit
  11386. std::string large_payload(12 * 1024 * 1024,
  11387. 'B'); // 12MB payload, exceeds 10MB limit
  11388. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  11389. // Server may either return 413 or close the connection
  11390. if (res) {
  11391. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11392. } else {
  11393. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  11394. }
  11395. }
  11396. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  11397. // Test request without Content-Length header within 10MB limit
  11398. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11399. "Host: " +
  11400. std::string(HOST) + ":" +
  11401. std::to_string(PORT) +
  11402. "\r\n"
  11403. "Connection: close\r\n"
  11404. "\r\n";
  11405. // Add 1MB payload (within 10MB limit)
  11406. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  11407. request_without_content_length += medium_payload;
  11408. std::string response;
  11409. bool result = send_request(5, request_without_content_length, &response);
  11410. if (result) {
  11411. // Should get a proper HTTP response for payloads within limit
  11412. if (response.length() > 10) {
  11413. SUCCEED() << "Server processed 1MB request without Content-Length within "
  11414. "10MB limit";
  11415. } else {
  11416. SUCCEED() << "Server closed connection (acceptable behavior for no "
  11417. "Content-Length)";
  11418. }
  11419. } else {
  11420. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  11421. }
  11422. }
  11423. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  11424. // Test request without Content-Length header exceeding 10MB limit
  11425. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11426. "Host: " +
  11427. std::string(HOST) + ":" +
  11428. std::to_string(PORT) +
  11429. "\r\n"
  11430. "Connection: close\r\n"
  11431. "\r\n";
  11432. // Add 12MB payload (exceeds 10MB limit)
  11433. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  11434. request_without_content_length += large_payload;
  11435. std::string response;
  11436. bool result = send_request(10, request_without_content_length, &response);
  11437. if (!result) {
  11438. // Server should close connection due to payload limit
  11439. SUCCEED() << "Server rejected 12MB request without Content-Length "
  11440. "(connection closed)";
  11441. } else {
  11442. // Check for error response
  11443. if (response.length() <= 10) {
  11444. SUCCEED()
  11445. << "Server closed connection for 12MB request exceeding 10MB limit";
  11446. } else {
  11447. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11448. response.find("Payload Too Large") != std::string::npos ||
  11449. response.find("400") != std::string::npos);
  11450. }
  11451. }
  11452. }
  11453. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  11454. Server svr;
  11455. svr.Get("/", [](const Request &, Response &res) {
  11456. // Claims far more than it sends, then drops the connection.
  11457. res.set_content_provider(size_t(1) << 41, "text/plain",
  11458. [](size_t, size_t, DataSink &sink) {
  11459. sink.write("abc", 3);
  11460. return false;
  11461. });
  11462. });
  11463. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11464. auto se = detail::scope_exit([&] {
  11465. svr.stop();
  11466. thread.join();
  11467. ASSERT_FALSE(svr.is_running());
  11468. });
  11469. svr.wait_until_ready();
  11470. Client cli(HOST, PORT);
  11471. cli.set_payload_max_length(0);
  11472. EXPECT_FALSE(cli.Get("/"));
  11473. }
  11474. // Accepts one connection on 127.0.0.1:port, reads the request head and sends
  11475. // back the given bytes, which httplib::Server could not be made to send.
  11476. static void serve_raw_once(int port, const std::string &response) {
  11477. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11478. default_socket_options(srv);
  11479. sockaddr_in addr{};
  11480. addr.sin_family = AF_INET;
  11481. addr.sin_port = htons(static_cast<uint16_t>(port));
  11482. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11483. int opt = 1;
  11484. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11485. #ifdef _WIN32
  11486. reinterpret_cast<const char *>(&opt),
  11487. #else
  11488. &opt,
  11489. #endif
  11490. sizeof(opt));
  11491. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11492. ::listen(srv, 1);
  11493. auto cli = ::accept(srv, nullptr, nullptr);
  11494. if (cli != INVALID_SOCKET) {
  11495. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  11496. std::string head;
  11497. char c;
  11498. while (head.find("\r\n\r\n") == std::string::npos &&
  11499. ::recv(cli, &c, 1, 0) == 1) {
  11500. head += c;
  11501. }
  11502. ::send(cli, response.data(), static_cast<int>(response.size()), 0);
  11503. detail::close_socket(cli);
  11504. }
  11505. detail::close_socket(srv);
  11506. }
  11507. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  11508. const char *responses[] = {
  11509. "HTTP/1.1 103 Early Hints\r\n"
  11510. "Link: </style.css>; rel=preload\r\n"
  11511. "\r\n"
  11512. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  11513. "HTTP/1.1 100 Continue\r\n"
  11514. "X-Note: interim\r\n"
  11515. "\r\n"
  11516. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  11517. };
  11518. for (auto response : responses) {
  11519. std::thread t([&]() { serve_raw_once(PORT, response); });
  11520. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  11521. Client cli("127.0.0.1", PORT);
  11522. auto res = cli.Get("/");
  11523. t.join();
  11524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11525. EXPECT_EQ(StatusCode::OK_200, res->status);
  11526. EXPECT_EQ("ok", res->body);
  11527. }
  11528. }
  11529. #ifdef CPPHTTPLIB_SSL_ENABLED
  11530. TEST(ProxyConnectTest, OnlyARefusalIsPassedOn) {
  11531. // Anything but 200 or a refusal would read as the origin's own response.
  11532. {
  11533. std::thread t([] {
  11534. serve_raw_once(PORT, "HTTP/1.1 201 Created\r\n"
  11535. "Set-Cookie: session=from-proxy\r\n"
  11536. "Content-Length: 0\r\n\r\n");
  11537. });
  11538. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  11539. SSLClient cli("example.com", 443);
  11540. cli.set_proxy("127.0.0.1", PORT);
  11541. auto res = cli.Get("/");
  11542. t.join();
  11543. EXPECT_FALSE(res);
  11544. EXPECT_EQ(Error::ProxyConnection, res.error());
  11545. }
  11546. {
  11547. std::thread t([] {
  11548. serve_raw_once(PORT, "HTTP/1.1 407 Proxy Authentication Required\r\n"
  11549. "Content-Length: 0\r\n\r\n");
  11550. });
  11551. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  11552. SSLClient cli("example.com", 443);
  11553. cli.set_proxy("127.0.0.1", PORT);
  11554. auto res = cli.Get("/");
  11555. t.join();
  11556. ASSERT_TRUE(res);
  11557. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  11558. }
  11559. }
  11560. #endif
  11561. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  11562. std::atomic<bool> closed_by_client{false};
  11563. auto server_thread = std::thread([&] {
  11564. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11565. default_socket_options(srv);
  11566. sockaddr_in addr{};
  11567. addr.sin_family = AF_INET;
  11568. addr.sin_port = htons(static_cast<uint16_t>(PORT));
  11569. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11570. int opt = 1;
  11571. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11572. #ifdef _WIN32
  11573. reinterpret_cast<const char *>(&opt),
  11574. #else
  11575. &opt,
  11576. #endif
  11577. sizeof(opt));
  11578. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11579. ::listen(srv, 1);
  11580. auto cli = ::accept(srv, nullptr, nullptr);
  11581. if (cli != INVALID_SOCKET) {
  11582. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  11583. // Answer the head without asking for the body, and keep the connection.
  11584. std::string head;
  11585. char c;
  11586. while (head.find("\r\n\r\n") == std::string::npos &&
  11587. ::recv(cli, &c, 1, 0) == 1) {
  11588. head += c;
  11589. }
  11590. std::string res =
  11591. "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n";
  11592. ::send(cli, res.data(), static_cast<int>(res.size()), 0);
  11593. // Bytes here would be read as the body the first request declared.
  11594. char buf[256];
  11595. closed_by_client = ::recv(cli, buf, sizeof(buf), 0) == 0;
  11596. detail::close_socket(cli);
  11597. }
  11598. detail::close_socket(srv);
  11599. });
  11600. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  11601. Client cli("127.0.0.1", PORT);
  11602. cli.set_keep_alive(true);
  11603. cli.set_read_timeout(1, 0);
  11604. // Long enough for the client to send Expect: 100-continue.
  11605. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  11606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11607. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  11608. cli.Get("/second");
  11609. server_thread.join();
  11610. EXPECT_TRUE(closed_by_client);
  11611. }
  11612. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11613. // `payload_max_length` is not enforced on decompressed body in ContentReader
  11614. // path.
  11615. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  11616. Server svr;
  11617. const size_t LIMIT = 64 * 1024; // 64KB
  11618. svr.set_payload_max_length(LIMIT);
  11619. size_t total = 0;
  11620. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11621. const ContentReader &content_reader) {
  11622. content_reader([&](const char * /*data*/, size_t len) {
  11623. total += len;
  11624. return true;
  11625. });
  11626. res.status = 200;
  11627. res.set_content("stream_ok", "text/plain");
  11628. });
  11629. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11630. auto se = detail::scope_exit([&] {
  11631. svr.stop();
  11632. thread.join();
  11633. ASSERT_FALSE(svr.is_running());
  11634. });
  11635. svr.wait_until_ready();
  11636. // Prepare 256KB raw data and gzip-compress it
  11637. std::string raw(256 * 1024, 'A');
  11638. std::string gz;
  11639. {
  11640. z_stream zs{};
  11641. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  11642. Z_DEFAULT_STRATEGY);
  11643. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  11644. zs.avail_in = static_cast<uInt>(raw.size());
  11645. char outbuf[4096];
  11646. int ret;
  11647. do {
  11648. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  11649. zs.avail_out = sizeof(outbuf);
  11650. ret = deflate(&zs, Z_FINISH);
  11651. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  11652. } while (ret != Z_STREAM_END);
  11653. deflateEnd(&zs);
  11654. }
  11655. Client cli(HOST, PORT);
  11656. cli.set_connection_timeout(std::chrono::seconds(5));
  11657. Headers headers = {{"Content-Encoding", "gzip"}};
  11658. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  11659. "application/octet-stream");
  11660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11661. // Server must reject oversized decompressed payloads with 413.
  11662. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11663. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11664. EXPECT_LE(total, LIMIT);
  11665. }
  11666. #ifndef CPPHTTPLIB_SSL_ENABLED
  11667. // For a request with neither Content-Length nor Transfer-Encoding, the
  11668. // non-SSL raw-socket fallback in read_content_core() used to hand the
  11669. // compressed wire bytes straight to the ContentReader without ever routing
  11670. // them through the decompressor, so payload_max_length_ only bounded the
  11671. // compressed size on the wire, not the decompressed size.
  11672. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  11673. Server svr;
  11674. const size_t LIMIT = 64 * 1024; // 64KB
  11675. svr.set_payload_max_length(LIMIT);
  11676. size_t total = 0;
  11677. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11678. const ContentReader &content_reader) {
  11679. content_reader([&](const char * /*data*/, size_t len) {
  11680. total += len;
  11681. return true;
  11682. });
  11683. res.status = 200;
  11684. res.set_content("stream_ok", "text/plain");
  11685. });
  11686. auto port = svr.bind_to_any_port(HOST);
  11687. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11688. auto se = detail::scope_exit([&] {
  11689. svr.stop();
  11690. thread.join();
  11691. ASSERT_FALSE(svr.is_running());
  11692. });
  11693. svr.wait_until_ready();
  11694. // Prepare 256KB raw data and gzip-compress it, same payload as the
  11695. // StreamingGzipDecompression test above.
  11696. std::string raw(256 * 1024, 'A');
  11697. std::string gz;
  11698. {
  11699. httplib::detail::gzip_compressor compressor;
  11700. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  11701. [&](const char *chunk, size_t len) {
  11702. gz.append(chunk, len);
  11703. return true;
  11704. });
  11705. ASSERT_TRUE(result);
  11706. }
  11707. // Send the gzip body over raw TCP with neither Content-Length nor
  11708. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  11709. // kicks in.
  11710. std::string req = "POST /stream HTTP/1.1\r\n"
  11711. "Host: " +
  11712. std::string(HOST) + ":" + std::to_string(port) +
  11713. "\r\n"
  11714. "Content-Encoding: gzip\r\n"
  11715. "Connection: close\r\n"
  11716. "\r\n" +
  11717. gz;
  11718. std::string response;
  11719. ASSERT_TRUE(send_request(5, req, &response, port));
  11720. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11721. EXPECT_LE(total, LIMIT);
  11722. }
  11723. #endif
  11724. #endif
  11725. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  11726. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  11727. // the payload must be passed through untouched instead of being rejected.
  11728. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  11729. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11730. Server svr;
  11731. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  11732. res.set_content(body, "image/jpeg");
  11733. res.set_header("Content-Encoding", "UTF-8");
  11734. });
  11735. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  11736. res.set_content(body, "image/jpeg");
  11737. res.set_header("Content-Encoding", "identity");
  11738. });
  11739. svr.Post("/echo", [](const Request &req, Response &res) {
  11740. res.set_content(req.body, "image/jpeg");
  11741. });
  11742. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11743. auto se = detail::scope_exit([&] {
  11744. svr.stop();
  11745. t.join();
  11746. ASSERT_FALSE(svr.is_running());
  11747. });
  11748. svr.wait_until_ready();
  11749. Client cli(HOST, PORT);
  11750. {
  11751. auto res = cli.Get("/image");
  11752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11753. EXPECT_EQ(StatusCode::OK_200, res->status);
  11754. EXPECT_EQ(body, res->body);
  11755. }
  11756. {
  11757. auto res = cli.Get("/identity");
  11758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11759. EXPECT_EQ(StatusCode::OK_200, res->status);
  11760. EXPECT_EQ(body, res->body);
  11761. }
  11762. {
  11763. // The same applies to a request body reaching the server.
  11764. Headers headers = {{"Content-Encoding", "UTF-8"}};
  11765. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  11766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11767. EXPECT_EQ(StatusCode::OK_200, res->status);
  11768. EXPECT_EQ(body, res->body);
  11769. }
  11770. }
  11771. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  11772. // gzip-encoded response even when the build has no zlib support.
  11773. static const char GZIPPED_HELLO_WORLD[] = {
  11774. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  11775. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  11776. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  11777. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  11778. // A content coding is a whole token, not something the field value merely
  11779. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  11780. // as "fibre" look like Brotli, and turned a multi-coding value like
  11781. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  11782. // it was never meant to see.
  11783. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  11784. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11785. Server svr;
  11786. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  11787. res.set_content(body, "image/jpeg");
  11788. res.set_header("Content-Encoding", "fibre");
  11789. });
  11790. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  11791. res.set_content(body, "image/jpeg");
  11792. res.set_header("Content-Encoding", "gzip, br");
  11793. });
  11794. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  11795. res.set_content(body, "image/jpeg");
  11796. res.set_header("Content-Encoding", "x-zstd-ish");
  11797. });
  11798. auto port = svr.bind_to_any_port(HOST);
  11799. thread t = thread([&]() { svr.listen_after_bind(); });
  11800. auto se = detail::scope_exit([&] {
  11801. svr.stop();
  11802. t.join();
  11803. ASSERT_FALSE(svr.is_running());
  11804. });
  11805. svr.wait_until_ready();
  11806. Client cli(HOST, port);
  11807. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  11808. auto res = cli.Get(path);
  11809. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11810. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11811. // Not a coding we recognize, so the payload comes back untouched
  11812. EXPECT_EQ(body, res->body) << path;
  11813. }
  11814. }
  11815. // A content coding cpp-httplib recognizes but was not built with must be
  11816. // reported as such. Handing the still-compressed payload back to the caller
  11817. // would silently corrupt it.
  11818. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  11819. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11820. Server svr;
  11821. // "image/jpeg" keeps the server from applying a content coding of its own,
  11822. // so the hand-crafted Content-Encoding below survives.
  11823. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  11824. res.set_content(gzipped, "image/jpeg");
  11825. res.set_header("Content-Encoding", "gzip");
  11826. });
  11827. // Content codings are case-insensitive (RFC 9110 8.4.1).
  11828. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  11829. res.set_content(gzipped, "image/jpeg");
  11830. res.set_header("Content-Encoding", "GZIP");
  11831. });
  11832. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11833. auto se = detail::scope_exit([&] {
  11834. svr.stop();
  11835. t.join();
  11836. ASSERT_FALSE(svr.is_running());
  11837. });
  11838. svr.wait_until_ready();
  11839. Client cli(HOST, PORT);
  11840. {
  11841. auto res = cli.Get("/gzipped");
  11842. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11844. EXPECT_EQ("Hello World!", res->body);
  11845. #else
  11846. ASSERT_FALSE(res);
  11847. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11848. #endif
  11849. }
  11850. {
  11851. // open_stream() must behave the same way.
  11852. auto handle = cli.open_stream("GET", "/gzipped");
  11853. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11854. ASSERT_TRUE(handle.is_valid());
  11855. std::string received;
  11856. char buf[256];
  11857. ssize_t n;
  11858. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11859. received.append(buf, static_cast<size_t>(n));
  11860. }
  11861. EXPECT_EQ("Hello World!", received);
  11862. #else
  11863. EXPECT_FALSE(handle.is_valid());
  11864. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  11865. #endif
  11866. }
  11867. {
  11868. // A differently-cased coding must not be mistaken for an unknown one, or
  11869. // the body would be handed back still compressed.
  11870. auto res = cli.Get("/gzipped-uppercase");
  11871. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11873. EXPECT_EQ("Hello World!", res->body);
  11874. #else
  11875. ASSERT_FALSE(res);
  11876. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11877. #endif
  11878. }
  11879. }
  11880. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11881. // A handler serving pre-compressed content (e.g. build-time gzipped static
  11882. // assets) sets Content-Encoding itself. The server used to pick a coding from
  11883. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  11884. // body a second time and appending a second Content-Encoding field line, so
  11885. // clients that decode one coding per listed value handed back raw gzip bytes.
  11886. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  11887. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11888. Server svr;
  11889. // text/plain is a compressible type, so only the pre-set Content-Encoding
  11890. // keeps the server from applying a coding of its own.
  11891. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11892. res.set_content(gzipped, "text/plain");
  11893. res.set_header("Content-Encoding", "gzip");
  11894. });
  11895. auto port = svr.bind_to_any_port(HOST);
  11896. thread t = thread([&]() { svr.listen_after_bind(); });
  11897. auto se = detail::scope_exit([&] {
  11898. svr.stop();
  11899. t.join();
  11900. ASSERT_FALSE(svr.is_running());
  11901. });
  11902. svr.wait_until_ready();
  11903. Client cli(HOST, port);
  11904. Headers headers = {{"Accept-Encoding", "gzip"}};
  11905. auto res = cli.Get("/pre-gzipped", headers);
  11906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11907. EXPECT_EQ(StatusCode::OK_200, res->status);
  11908. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11909. EXPECT_EQ("Hello World!", res->body);
  11910. }
  11911. // A chunked provider settles its coding where the headers are written and
  11912. // reuses it at write time. Both ends of that have to hold: a handler's own
  11913. // Content-Encoding suppresses the coding, and a response without one is still
  11914. // compressed as it always was.
  11915. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  11916. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11917. const std::string plain = "Hello World! Hello World! Hello World!";
  11918. Server svr;
  11919. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11920. res.set_header("Content-Encoding", "gzip");
  11921. res.set_chunked_content_provider(
  11922. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  11923. sink.write(gzipped.data(), gzipped.size());
  11924. sink.done();
  11925. return true;
  11926. });
  11927. });
  11928. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  11929. res.set_chunked_content_provider(
  11930. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  11931. sink.write(plain.data(), plain.size());
  11932. sink.done();
  11933. return true;
  11934. });
  11935. });
  11936. auto port = svr.bind_to_any_port(HOST);
  11937. thread t = thread([&]() { svr.listen_after_bind(); });
  11938. auto se = detail::scope_exit([&] {
  11939. svr.stop();
  11940. t.join();
  11941. ASSERT_FALSE(svr.is_running());
  11942. });
  11943. svr.wait_until_ready();
  11944. Client cli(HOST, port);
  11945. Headers headers = {{"Accept-Encoding", "gzip"}};
  11946. {
  11947. auto res = cli.Get("/pre-gzipped", headers);
  11948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11949. EXPECT_EQ(StatusCode::OK_200, res->status);
  11950. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11951. EXPECT_EQ("Hello World!", res->body);
  11952. }
  11953. {
  11954. auto res = cli.Get("/negotiated", headers);
  11955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11956. EXPECT_EQ(StatusCode::OK_200, res->status);
  11957. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  11958. EXPECT_EQ(plain, res->body);
  11959. }
  11960. }
  11961. #endif
  11962. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  11963. // the same message as the comma-joined one, so both have to be read the same
  11964. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  11965. // single gzip coding, and a body the sender says was encoded twice was handed
  11966. // back after one pass, still compressed but presented as decoded.
  11967. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  11968. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11969. Server svr;
  11970. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  11971. res.set_content(body, "image/jpeg");
  11972. res.headers.emplace("Content-Encoding", "gzip");
  11973. res.headers.emplace("Content-Encoding", "gzip");
  11974. });
  11975. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  11976. res.set_content(body, "image/jpeg");
  11977. res.set_header("Content-Encoding", "gzip, gzip");
  11978. });
  11979. auto port = svr.bind_to_any_port(HOST);
  11980. thread t = thread([&]() { svr.listen_after_bind(); });
  11981. auto se = detail::scope_exit([&] {
  11982. svr.stop();
  11983. t.join();
  11984. ASSERT_FALSE(svr.is_running());
  11985. });
  11986. svr.wait_until_ready();
  11987. Client cli(HOST, port);
  11988. // Two codings is not something cpp-httplib decodes, so both representations
  11989. // take the pass-through path rather than one of them being gunzipped once.
  11990. for (const char *path : {"/split", "/joined"}) {
  11991. auto res = cli.Get(path);
  11992. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11993. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11994. EXPECT_EQ(body, res->body) << path;
  11995. }
  11996. }
  11997. // Regression test for DoS vulnerability: a malicious server sending a response
  11998. // without Content-Length header must not cause unbounded memory consumption on
  11999. // the client side. The client should stop reading after a reasonable limit,
  12000. // similar to the server-side set_payload_max_length protection.
  12001. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12002. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12003. #ifndef _WIN32
  12004. signal(SIGPIPE, SIG_IGN);
  12005. #endif
  12006. auto server_thread = std::thread([] {
  12007. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12008. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12009. default_socket_options(srv);
  12010. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12011. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12012. sockaddr_in addr{};
  12013. addr.sin_family = AF_INET;
  12014. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12015. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12016. int opt = 1;
  12017. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12018. #ifdef _WIN32
  12019. reinterpret_cast<const char *>(&opt),
  12020. #else
  12021. &opt,
  12022. #endif
  12023. sizeof(opt));
  12024. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12025. ::listen(srv, 1);
  12026. sockaddr_in cli_addr{};
  12027. socklen_t cli_len = sizeof(cli_addr);
  12028. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12029. if (cli != INVALID_SOCKET) {
  12030. char buf[4096];
  12031. ::recv(cli, buf, sizeof(buf), 0);
  12032. // Malicious response: no Content-Length, no chunked encoding
  12033. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12034. "Connection: close\r\n"
  12035. "\r\n";
  12036. ::send(cli,
  12037. #ifdef _WIN32
  12038. static_cast<const char *>(response_header.c_str()),
  12039. static_cast<int>(response_header.size()),
  12040. #else
  12041. response_header.c_str(), response_header.size(),
  12042. #endif
  12043. 0);
  12044. // Send 10MB of data
  12045. std::string chunk(64 * 1024, 'A');
  12046. size_t total_sent = 0;
  12047. while (total_sent < MALICIOUS_DATA_SIZE) {
  12048. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12049. auto sent = ::send(cli,
  12050. #ifdef _WIN32
  12051. static_cast<const char *>(chunk.c_str()),
  12052. static_cast<int>(to_send),
  12053. #else
  12054. chunk.c_str(), to_send,
  12055. #endif
  12056. 0);
  12057. if (sent <= 0) break;
  12058. total_sent += static_cast<size_t>(sent);
  12059. }
  12060. detail::close_socket(cli);
  12061. }
  12062. detail::close_socket(srv);
  12063. });
  12064. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12065. size_t total_read = 0;
  12066. {
  12067. Client cli("127.0.0.1", PORT + 2);
  12068. cli.set_read_timeout(5, 0);
  12069. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12070. auto stream = cli.open_stream("GET", "/malicious");
  12071. ASSERT_TRUE(stream.is_valid());
  12072. char buffer[64 * 1024];
  12073. ssize_t n;
  12074. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12075. total_read += static_cast<size_t>(n);
  12076. }
  12077. } // StreamHandle and Client destroyed here, closing the socket
  12078. server_thread.join();
  12079. // With set_payload_max_length, the client must stop reading before consuming
  12080. // all 10MB. The read loop should be cut off at or near the configured limit.
  12081. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12082. << "Client read " << total_read << " bytes, exceeding the configured "
  12083. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12084. }
  12085. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12086. // the entire response body without truncation.
  12087. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12088. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12089. #ifndef _WIN32
  12090. signal(SIGPIPE, SIG_IGN);
  12091. #endif
  12092. auto server_thread = std::thread([] {
  12093. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12094. default_socket_options(srv);
  12095. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12096. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12097. sockaddr_in addr{};
  12098. addr.sin_family = AF_INET;
  12099. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12100. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12101. int opt = 1;
  12102. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12103. #ifdef _WIN32
  12104. reinterpret_cast<const char *>(&opt),
  12105. #else
  12106. &opt,
  12107. #endif
  12108. sizeof(opt));
  12109. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12110. ::listen(srv, 1);
  12111. sockaddr_in cli_addr{};
  12112. socklen_t cli_len = sizeof(cli_addr);
  12113. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12114. if (cli != INVALID_SOCKET) {
  12115. char buf[4096];
  12116. ::recv(cli, buf, sizeof(buf), 0);
  12117. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12118. "Connection: close\r\n"
  12119. "\r\n";
  12120. ::send(cli,
  12121. #ifdef _WIN32
  12122. static_cast<const char *>(response_header.c_str()),
  12123. static_cast<int>(response_header.size()),
  12124. #else
  12125. response_header.c_str(), response_header.size(),
  12126. #endif
  12127. 0);
  12128. std::string chunk(64 * 1024, 'A');
  12129. size_t total_sent = 0;
  12130. while (total_sent < DATA_SIZE) {
  12131. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12132. auto sent = ::send(cli,
  12133. #ifdef _WIN32
  12134. static_cast<const char *>(chunk.c_str()),
  12135. static_cast<int>(to_send),
  12136. #else
  12137. chunk.c_str(), to_send,
  12138. #endif
  12139. 0);
  12140. if (sent <= 0) break;
  12141. total_sent += static_cast<size_t>(sent);
  12142. }
  12143. #ifdef _WIN32
  12144. ::shutdown(cli, SD_SEND);
  12145. #else
  12146. ::shutdown(cli, SHUT_WR);
  12147. #endif
  12148. // Drain until the client closes its end, ensuring all data is delivered
  12149. char drain[1024];
  12150. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12151. detail::close_socket(cli);
  12152. }
  12153. detail::close_socket(srv);
  12154. });
  12155. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12156. size_t total_read = 0;
  12157. {
  12158. Client cli("127.0.0.1", PORT + 2);
  12159. cli.set_read_timeout(5, 0);
  12160. cli.set_payload_max_length(0); // 0 means no limit
  12161. auto stream = cli.open_stream("GET", "/data");
  12162. ASSERT_TRUE(stream.is_valid());
  12163. char buffer[64 * 1024];
  12164. ssize_t n;
  12165. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12166. total_read += static_cast<size_t>(n);
  12167. }
  12168. }
  12169. server_thread.join();
  12170. EXPECT_EQ(total_read, DATA_SIZE)
  12171. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12172. << " bytes without truncation, but only read " << total_read << " bytes.";
  12173. }
  12174. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12175. // enormous Content-Length must not cause the client to pre-allocate a huge
  12176. // response body buffer. The reservation is capped at payload_max_length_, and
  12177. // the read itself fails when the body exceeds the limit.
  12178. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12179. #ifndef _WIN32
  12180. signal(SIGPIPE, SIG_IGN);
  12181. #endif
  12182. auto server_thread = std::thread([] {
  12183. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12184. default_socket_options(srv);
  12185. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12186. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12187. sockaddr_in addr{};
  12188. addr.sin_family = AF_INET;
  12189. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12190. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12191. int opt = 1;
  12192. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12193. #ifdef _WIN32
  12194. reinterpret_cast<const char *>(&opt),
  12195. #else
  12196. &opt,
  12197. #endif
  12198. sizeof(opt));
  12199. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12200. ::listen(srv, 1);
  12201. sockaddr_in cli_addr{};
  12202. socklen_t cli_len = sizeof(cli_addr);
  12203. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12204. if (cli != INVALID_SOCKET) {
  12205. char buf[4096];
  12206. ::recv(cli, buf, sizeof(buf), 0);
  12207. // Malicious response: claim a 20GB body but send only a tiny payload.
  12208. std::string response = "HTTP/1.1 200 OK\r\n"
  12209. "Content-Length: 20000000000\r\n"
  12210. "\r\n"
  12211. "abc";
  12212. ::send(cli,
  12213. #ifdef _WIN32
  12214. static_cast<const char *>(response.c_str()),
  12215. static_cast<int>(response.size()),
  12216. #else
  12217. response.c_str(), response.size(),
  12218. #endif
  12219. 0);
  12220. detail::close_socket(cli);
  12221. }
  12222. detail::close_socket(srv);
  12223. });
  12224. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12225. {
  12226. Client cli("127.0.0.1", PORT + 2);
  12227. cli.set_read_timeout(5, 0);
  12228. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12229. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12230. // (server claims more bytes than payload_max_length permits), but it must
  12231. // not exhaust memory before getting there.
  12232. auto res = cli.Get("/malicious");
  12233. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12234. }
  12235. server_thread.join();
  12236. }
  12237. // Verify that content_receiver bypasses the default payload_max_length,
  12238. // allowing streaming downloads larger than 100MB without requiring an explicit
  12239. // set_payload_max_length call.
  12240. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12241. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12242. #ifndef _WIN32
  12243. signal(SIGPIPE, SIG_IGN);
  12244. #endif
  12245. auto server_thread = std::thread([] {
  12246. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12247. default_socket_options(srv);
  12248. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12249. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12250. sockaddr_in addr{};
  12251. addr.sin_family = AF_INET;
  12252. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12253. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12254. int opt = 1;
  12255. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12256. #ifdef _WIN32
  12257. reinterpret_cast<const char *>(&opt),
  12258. #else
  12259. &opt,
  12260. #endif
  12261. sizeof(opt));
  12262. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12263. ::listen(srv, 1);
  12264. sockaddr_in cli_addr{};
  12265. socklen_t cli_len = sizeof(cli_addr);
  12266. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12267. if (cli != INVALID_SOCKET) {
  12268. char buf[4096];
  12269. ::recv(cli, buf, sizeof(buf), 0);
  12270. // Response with Content-Length larger than default 100MB limit
  12271. auto content_length = std::to_string(DATA_SIZE);
  12272. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12273. "Content-Length: " +
  12274. content_length +
  12275. "\r\n"
  12276. "Connection: close\r\n"
  12277. "\r\n";
  12278. ::send(cli,
  12279. #ifdef _WIN32
  12280. static_cast<const char *>(response_header.c_str()),
  12281. static_cast<int>(response_header.size()),
  12282. #else
  12283. response_header.c_str(), response_header.size(),
  12284. #endif
  12285. 0);
  12286. std::string chunk(64 * 1024, 'A');
  12287. size_t total_sent = 0;
  12288. while (total_sent < DATA_SIZE) {
  12289. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12290. auto sent = ::send(cli,
  12291. #ifdef _WIN32
  12292. static_cast<const char *>(chunk.c_str()),
  12293. static_cast<int>(to_send),
  12294. #else
  12295. chunk.c_str(), to_send,
  12296. #endif
  12297. 0);
  12298. if (sent <= 0) break;
  12299. total_sent += static_cast<size_t>(sent);
  12300. }
  12301. detail::close_socket(cli);
  12302. }
  12303. detail::close_socket(srv);
  12304. });
  12305. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12306. size_t total_received = 0;
  12307. {
  12308. Client cli("127.0.0.1", PORT + 2);
  12309. cli.set_read_timeout(10, 0);
  12310. // Do NOT call set_payload_max_length — use the default 100MB limit
  12311. auto res =
  12312. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12313. total_received += data_length;
  12314. return true;
  12315. });
  12316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12317. EXPECT_EQ(StatusCode::OK_200, res->status);
  12318. }
  12319. server_thread.join();
  12320. EXPECT_EQ(total_received, DATA_SIZE)
  12321. << "With content_receiver, the client should read all " << DATA_SIZE
  12322. << " bytes despite the default 100MB payload_max_length, but only read "
  12323. << total_received << " bytes.";
  12324. }
  12325. // Verify that an explicit set_payload_max_length smaller than the response is
  12326. // enforced even when a content_receiver is used.
  12327. TEST(ClientVulnerabilityTest,
  12328. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12329. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12330. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12331. #ifndef _WIN32
  12332. signal(SIGPIPE, SIG_IGN);
  12333. #endif
  12334. auto server_thread = std::thread([] {
  12335. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12336. default_socket_options(srv);
  12337. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12338. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12339. sockaddr_in addr{};
  12340. addr.sin_family = AF_INET;
  12341. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12342. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12343. int opt = 1;
  12344. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12345. #ifdef _WIN32
  12346. reinterpret_cast<const char *>(&opt),
  12347. #else
  12348. &opt,
  12349. #endif
  12350. sizeof(opt));
  12351. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12352. ::listen(srv, 1);
  12353. sockaddr_in cli_addr{};
  12354. socklen_t cli_len = sizeof(cli_addr);
  12355. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12356. if (cli != INVALID_SOCKET) {
  12357. char buf[4096];
  12358. ::recv(cli, buf, sizeof(buf), 0);
  12359. auto content_length = std::to_string(DATA_SIZE);
  12360. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12361. "Content-Length: " +
  12362. content_length +
  12363. "\r\n"
  12364. "Connection: close\r\n"
  12365. "\r\n";
  12366. ::send(cli,
  12367. #ifdef _WIN32
  12368. static_cast<const char *>(response_header.c_str()),
  12369. static_cast<int>(response_header.size()),
  12370. #else
  12371. response_header.c_str(), response_header.size(),
  12372. #endif
  12373. 0);
  12374. std::string chunk(64 * 1024, 'A');
  12375. size_t total_sent = 0;
  12376. while (total_sent < DATA_SIZE) {
  12377. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12378. auto sent = ::send(cli,
  12379. #ifdef _WIN32
  12380. static_cast<const char *>(chunk.c_str()),
  12381. static_cast<int>(to_send),
  12382. #else
  12383. chunk.c_str(), to_send,
  12384. #endif
  12385. 0);
  12386. if (sent <= 0) break;
  12387. total_sent += static_cast<size_t>(sent);
  12388. }
  12389. detail::close_socket(cli);
  12390. }
  12391. detail::close_socket(srv);
  12392. });
  12393. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12394. size_t total_received = 0;
  12395. {
  12396. Client cli("127.0.0.1", PORT + 2);
  12397. cli.set_read_timeout(10, 0);
  12398. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  12399. auto res =
  12400. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12401. total_received += data_length;
  12402. return true;
  12403. });
  12404. // Should fail because 200MB exceeds the explicit 150MB limit
  12405. EXPECT_FALSE(res);
  12406. }
  12407. server_thread.join();
  12408. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12409. << "Client with content_receiver should respect the explicit "
  12410. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12411. << total_received << " bytes.";
  12412. }
  12413. // Verify that an explicit set_payload_max_length larger than the response
  12414. // allows the content_receiver to read all data successfully.
  12415. TEST(ClientVulnerabilityTest,
  12416. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  12417. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12418. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  12419. #ifndef _WIN32
  12420. signal(SIGPIPE, SIG_IGN);
  12421. #endif
  12422. auto server_thread = std::thread([] {
  12423. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12424. default_socket_options(srv);
  12425. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12426. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12427. sockaddr_in addr{};
  12428. addr.sin_family = AF_INET;
  12429. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12430. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12431. int opt = 1;
  12432. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12433. #ifdef _WIN32
  12434. reinterpret_cast<const char *>(&opt),
  12435. #else
  12436. &opt,
  12437. #endif
  12438. sizeof(opt));
  12439. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12440. ::listen(srv, 1);
  12441. sockaddr_in cli_addr{};
  12442. socklen_t cli_len = sizeof(cli_addr);
  12443. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12444. if (cli != INVALID_SOCKET) {
  12445. char buf[4096];
  12446. ::recv(cli, buf, sizeof(buf), 0);
  12447. auto content_length = std::to_string(DATA_SIZE);
  12448. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12449. "Content-Length: " +
  12450. content_length +
  12451. "\r\n"
  12452. "Connection: close\r\n"
  12453. "\r\n";
  12454. ::send(cli,
  12455. #ifdef _WIN32
  12456. static_cast<const char *>(response_header.c_str()),
  12457. static_cast<int>(response_header.size()),
  12458. #else
  12459. response_header.c_str(), response_header.size(),
  12460. #endif
  12461. 0);
  12462. std::string chunk(64 * 1024, 'A');
  12463. size_t total_sent = 0;
  12464. while (total_sent < DATA_SIZE) {
  12465. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12466. auto sent = ::send(cli,
  12467. #ifdef _WIN32
  12468. static_cast<const char *>(chunk.c_str()),
  12469. static_cast<int>(to_send),
  12470. #else
  12471. chunk.c_str(), to_send,
  12472. #endif
  12473. 0);
  12474. if (sent <= 0) break;
  12475. total_sent += static_cast<size_t>(sent);
  12476. }
  12477. #ifdef _WIN32
  12478. ::shutdown(cli, SD_SEND);
  12479. #else
  12480. ::shutdown(cli, SHUT_WR);
  12481. #endif
  12482. char drain[1024];
  12483. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12484. detail::close_socket(cli);
  12485. }
  12486. detail::close_socket(srv);
  12487. });
  12488. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12489. size_t total_received = 0;
  12490. {
  12491. Client cli("127.0.0.1", PORT + 2);
  12492. cli.set_read_timeout(10, 0);
  12493. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  12494. auto res =
  12495. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12496. total_received += data_length;
  12497. return true;
  12498. });
  12499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12500. EXPECT_EQ(StatusCode::OK_200, res->status);
  12501. }
  12502. server_thread.join();
  12503. EXPECT_EQ(total_received, DATA_SIZE)
  12504. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  12505. << " bytes (larger than " << DATA_SIZE
  12506. << " bytes response), content_receiver should read all data, but only "
  12507. "read "
  12508. << total_received << " bytes.";
  12509. }
  12510. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  12511. // Regression test for "zip bomb" attack on the client side: a malicious server
  12512. // sends a small gzip-compressed response that decompresses to a huge payload.
  12513. // The client must enforce payload_max_length on the decompressed size.
  12514. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  12515. constexpr size_t DECOMPRESSED_SIZE =
  12516. 10 * 1024 * 1024; // 10MB after decompression
  12517. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12518. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  12519. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  12520. std::string compressed;
  12521. {
  12522. httplib::detail::gzip_compressor compressor;
  12523. bool ok =
  12524. compressor.compress(uncompressed.data(), uncompressed.size(),
  12525. /*last=*/true, [&](const char *buf, size_t len) {
  12526. compressed.append(buf, len);
  12527. return true;
  12528. });
  12529. ASSERT_TRUE(ok);
  12530. }
  12531. // Sanity: compressed data should be much smaller than the decompressed size
  12532. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  12533. #ifndef _WIN32
  12534. signal(SIGPIPE, SIG_IGN);
  12535. #endif
  12536. // Set up the listening socket in the main thread so the server is guaranteed
  12537. // to be ready before the client connects (eliminates race condition).
  12538. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12539. default_socket_options(srv);
  12540. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12541. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12542. sockaddr_in addr{};
  12543. addr.sin_family = AF_INET;
  12544. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  12545. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12546. int opt = 1;
  12547. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12548. #ifdef _WIN32
  12549. reinterpret_cast<const char *>(&opt),
  12550. #else
  12551. &opt,
  12552. #endif
  12553. sizeof(opt));
  12554. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12555. ASSERT_EQ(0, ::listen(srv, 1));
  12556. auto server_thread = std::thread([&compressed, srv] {
  12557. sockaddr_in cli_addr{};
  12558. socklen_t cli_len = sizeof(cli_addr);
  12559. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12560. if (cli != INVALID_SOCKET) {
  12561. // Read the full HTTP request (until \r\n\r\n)
  12562. char buf[4096];
  12563. size_t total = 0;
  12564. while (total < sizeof(buf)) {
  12565. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  12566. if (n <= 0) break;
  12567. total += static_cast<size_t>(n);
  12568. // Check for end of headers
  12569. if (total >= 4) {
  12570. std::string req(buf, total);
  12571. if (req.find("\r\n\r\n") != std::string::npos) break;
  12572. }
  12573. }
  12574. // Malicious response: gzip-compressed body, no Content-Length
  12575. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12576. "Content-Encoding: gzip\r\n"
  12577. "Connection: close\r\n"
  12578. "\r\n";
  12579. ::send(cli,
  12580. #ifdef _WIN32
  12581. static_cast<const char *>(response_header.c_str()),
  12582. static_cast<int>(response_header.size()),
  12583. #else
  12584. response_header.c_str(), response_header.size(),
  12585. #endif
  12586. 0);
  12587. // Send the compressed payload (small on the wire, huge when decompressed)
  12588. size_t total_sent = 0;
  12589. while (total_sent < compressed.size()) {
  12590. auto to_send = std::min(compressed.size() - total_sent,
  12591. static_cast<size_t>(64 * 1024));
  12592. auto sent =
  12593. ::send(cli,
  12594. #ifdef _WIN32
  12595. static_cast<const char *>(compressed.c_str() + total_sent),
  12596. static_cast<int>(to_send),
  12597. #else
  12598. compressed.c_str() + total_sent, to_send,
  12599. #endif
  12600. 0);
  12601. if (sent <= 0) break;
  12602. total_sent += static_cast<size_t>(sent);
  12603. }
  12604. detail::close_socket(cli);
  12605. }
  12606. });
  12607. auto se = detail::scope_exit([&] {
  12608. detail::close_socket(srv);
  12609. server_thread.join();
  12610. });
  12611. size_t total_decompressed = 0;
  12612. {
  12613. Client cli("127.0.0.1", PORT + 3);
  12614. cli.set_read_timeout(5, 0);
  12615. cli.set_decompress(true);
  12616. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12617. auto stream = cli.open_stream("GET", "/zipbomb");
  12618. ASSERT_TRUE(stream.is_valid());
  12619. char buffer[64 * 1024];
  12620. ssize_t n;
  12621. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12622. total_decompressed += static_cast<size_t>(n);
  12623. }
  12624. }
  12625. // The decompressed size must be capped by payload_max_length. Without
  12626. // protection, the client would decompress the full 10MB from a tiny
  12627. // compressed payload, enabling a zip bomb DoS attack.
  12628. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  12629. << "Client decompressed " << total_decompressed
  12630. << " bytes from a gzip response. The decompressed size should be "
  12631. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  12632. }
  12633. #endif
  12634. TEST(HostAndPortPropertiesTest, NoSSL) {
  12635. httplib::Client cli("www.google.com", 1234);
  12636. ASSERT_EQ("www.google.com", cli.host());
  12637. ASSERT_EQ(1234, cli.port());
  12638. }
  12639. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  12640. httplib::Client cli("www.google.com:1234");
  12641. ASSERT_EQ("www.google.com", cli.host());
  12642. ASSERT_EQ(1234, cli.port());
  12643. }
  12644. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  12645. // Port number that overflows int — should not crash, client becomes invalid
  12646. httplib::Client cli("http://www.google.com:99999999999999999999");
  12647. ASSERT_FALSE(cli.is_valid());
  12648. }
  12649. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  12650. // Port 99999 exceeds valid range (1-65535) — should not crash
  12651. httplib::Client cli("http://www.google.com:99999");
  12652. ASSERT_FALSE(cli.is_valid());
  12653. auto res = cli.Get("/");
  12654. EXPECT_FALSE(res);
  12655. EXPECT_EQ(Error::Connection, res.error());
  12656. }
  12657. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  12658. httplib::Client cli("http://www.google.com:80abc");
  12659. ASSERT_FALSE(cli.is_valid());
  12660. }
  12661. #ifdef CPPHTTPLIB_SSL_ENABLED
  12662. TEST(HostAndPortPropertiesTest, SSL) {
  12663. httplib::SSLClient cli("www.google.com");
  12664. ASSERT_EQ("www.google.com", cli.host());
  12665. ASSERT_EQ(443, cli.port());
  12666. }
  12667. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  12668. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  12669. std::string cert;
  12670. read_file(CA_CERT_FILE, cert);
  12671. httplib::SSLClient httplib_client("www.google.com");
  12672. // Load CA store first time
  12673. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12674. // Load CA store second time (update)
  12675. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12676. // Verify client is still valid and can make connections
  12677. httplib_client.enable_server_certificate_verification(true);
  12678. auto res = httplib_client.Get("/");
  12679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12680. // Google may return 200 or 301 depending on various factors
  12681. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  12682. res->status == StatusCode::MovedPermanently_301);
  12683. }
  12684. TEST(SSLClientTest, ServerNameIndication_Online) {
  12685. auto host = "httpbingo.org";
  12686. auto path = std::string{"/get"};
  12687. SSLClient cli(host, 443);
  12688. auto res = cli.Get(path);
  12689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12690. ASSERT_EQ(StatusCode::OK_200, res->status);
  12691. }
  12692. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  12693. // Use a site that will cause SSL verification failure due to self-signed cert
  12694. SSLClient cli("self-signed.badssl.com", 443);
  12695. cli.enable_server_certificate_verification(true);
  12696. auto res = cli.Get("/");
  12697. ASSERT_TRUE(!res);
  12698. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12699. // Verify backend error is captured for SSLServerVerification
  12700. // This occurs when certificate verification fails
  12701. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  12702. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  12703. EXPECT_NE(0UL, res.ssl_backend_error());
  12704. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12705. // For OpenSSL, ssl_error is 0 for verification errors
  12706. EXPECT_EQ(0, res.ssl_error());
  12707. #if !defined(_WIN32) || \
  12708. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12709. // On non-Windows or when Windows Schannel is disabled, the error comes
  12710. // from OpenSSL's verification
  12711. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  12712. res.ssl_backend_error());
  12713. #endif
  12714. #endif
  12715. }
  12716. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  12717. // Use a site where hostname doesn't match the certificate
  12718. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  12719. SSLClient cli("wrong.host.badssl.com", 443);
  12720. cli.enable_server_certificate_verification(true);
  12721. cli.enable_server_hostname_verification(true);
  12722. auto res = cli.Get("/");
  12723. ASSERT_TRUE(!res);
  12724. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  12725. // Verify backend error is captured for hostname verification failure
  12726. EXPECT_NE(0UL, res.ssl_backend_error());
  12727. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12728. // For OpenSSL, ssl_error is 0 for verification errors
  12729. EXPECT_EQ(0, res.ssl_error());
  12730. #if !defined(_WIN32) || \
  12731. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12732. // On non-Windows or when Windows Schannel is disabled, the error comes
  12733. // from OpenSSL's hostname verification
  12734. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  12735. res.ssl_backend_error());
  12736. #endif
  12737. #endif
  12738. }
  12739. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  12740. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12741. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  12742. SSLClient cli("www.google.com", 443);
  12743. cli.enable_server_certificate_verification(true);
  12744. auto res = cli.Get("/");
  12745. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12746. }
  12747. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  12748. SSLClient cli("www.google.com", 443);
  12749. cli.enable_server_certificate_verification(true);
  12750. cli.enable_windows_certificate_verification(false);
  12751. auto res = cli.Get("/");
  12752. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12753. }
  12754. // The server sends an intermediate cross-signed by a root Windows trusts,
  12755. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  12756. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  12757. SSLClient cli("accounts.spotify.com", 443);
  12758. auto res = cli.Get("/");
  12759. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  12760. << " ssl_backend_error=" << res.ssl_backend_error();
  12761. }
  12762. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  12763. // policy status, which no backend reports for a self-signed certificate.
  12764. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  12765. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12766. ASSERT_TRUE(svr.is_valid());
  12767. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12768. auto se = detail::scope_exit([&] {
  12769. svr.stop();
  12770. t.join();
  12771. ASSERT_FALSE(svr.is_running());
  12772. });
  12773. svr.wait_until_ready();
  12774. SSLClient cli("127.0.0.1", PORT);
  12775. cli.set_connection_timeout(30);
  12776. auto res = cli.Get("/");
  12777. ASSERT_FALSE(res);
  12778. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12779. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  12780. }
  12781. #endif
  12782. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  12783. Client cli("https://google.com");
  12784. auto res = cli.Get("/");
  12785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12786. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12787. }
  12788. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  12789. SSLClient cli("google.com");
  12790. cli.set_ca_cert_path(CA_CERT_FILE);
  12791. auto res = cli.Get("/");
  12792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12793. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12794. }
  12795. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  12796. SSLClient cli("google.com");
  12797. cli.enable_server_certificate_verification(true);
  12798. cli.set_ca_cert_path("hello");
  12799. auto res = cli.Get("/");
  12800. ASSERT_TRUE(!res);
  12801. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  12802. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  12803. // should be set
  12804. EXPECT_EQ(0, res.ssl_error());
  12805. // Verify backend error is captured for SSLLoadingCerts
  12806. // This error occurs when loading CA certificates fails
  12807. EXPECT_NE(0UL, res.ssl_backend_error());
  12808. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12809. // OpenSSL specific error codes:
  12810. // > openssl errstr 0x80000002
  12811. // error:80000002:system library::No such file or directory
  12812. // > openssl errstr 0xA000126
  12813. // error:0A000126:SSL routines::unexpected eof while reading
  12814. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  12815. res.ssl_backend_error() == 0xA000126);
  12816. #endif
  12817. }
  12818. TEST(SSLClientTest, ServerCertificateVerification4) {
  12819. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12820. ASSERT_TRUE(svr.is_valid());
  12821. svr.Get("/test", [&](const Request &, Response &res) {
  12822. res.set_content("test", "text/plain");
  12823. svr.stop();
  12824. ASSERT_TRUE(true);
  12825. });
  12826. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12827. auto se = detail::scope_exit([&] {
  12828. t.join();
  12829. ASSERT_FALSE(svr.is_running());
  12830. });
  12831. svr.wait_until_ready();
  12832. SSLClient cli("127.0.0.1", PORT);
  12833. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12834. cli.enable_server_certificate_verification(true);
  12835. cli.set_connection_timeout(30);
  12836. auto res = cli.Get("/test");
  12837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12838. ASSERT_EQ(StatusCode::OK_200, res->status);
  12839. }
  12840. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  12841. std::string cert;
  12842. read_file(CA_CERT_FILE, cert);
  12843. SSLClient cli("google.com");
  12844. cli.load_ca_cert_store(cert.data(), cert.size());
  12845. const auto res = cli.Get("/");
  12846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12847. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12848. }
  12849. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  12850. // clang-format off
  12851. static constexpr char cert[] =
  12852. "GlobalSign Root CA\n"
  12853. "==================\n"
  12854. "-----BEGIN CERTIFICATE-----\n"
  12855. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  12856. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  12857. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  12858. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  12859. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  12860. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  12861. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  12862. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  12863. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  12864. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  12865. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  12866. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  12867. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  12868. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  12869. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  12870. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  12871. "-----END CERTIFICATE-----\n";
  12872. // clang-format on
  12873. SSLClient cli("google.com");
  12874. cli.load_ca_cert_store(cert, sizeof(cert));
  12875. const auto res = cli.Get("/");
  12876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12877. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12878. }
  12879. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  12880. SSLClient cli("www.youtube.com");
  12881. cli.set_ca_cert_path(CA_CERT_FILE);
  12882. cli.enable_server_certificate_verification(true);
  12883. cli.set_follow_location(true);
  12884. auto res = cli.Get("/");
  12885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12886. ASSERT_EQ(StatusCode::OK_200, res->status);
  12887. }
  12888. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  12889. SSLClient cli("wWw.YouTube.Com");
  12890. cli.set_ca_cert_path(CA_CERT_FILE);
  12891. cli.enable_server_certificate_verification(true);
  12892. cli.enable_server_hostname_verification(true);
  12893. cli.set_follow_location(true);
  12894. auto res = cli.Get("/");
  12895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12896. ASSERT_EQ(StatusCode::OK_200, res->status);
  12897. }
  12898. TEST(SSLClientTest, HostNameMatchCase_Online) {
  12899. SSLClient cli("gOoGlE.COm");
  12900. cli.enable_server_certificate_verification(true);
  12901. cli.enable_server_hostname_verification(true);
  12902. cli.set_follow_location(true);
  12903. auto res = cli.Get("/");
  12904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12905. ASSERT_EQ(StatusCode::OK_200, res->status);
  12906. }
  12907. TEST(SSLClientTest, Issue2004_Online) {
  12908. Client client("https://google.com");
  12909. client.set_follow_location(true);
  12910. auto res = client.Get("/");
  12911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12912. ASSERT_EQ(StatusCode::OK_200, res->status);
  12913. auto body = res->body;
  12914. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  12915. }
  12916. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  12917. // Create SSLClient with invalid cert/key to make is_valid() return false
  12918. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  12919. "nonexistent_key.pem");
  12920. // is_valid() should be false due to cert loading failure
  12921. ASSERT_FALSE(cli.is_valid());
  12922. auto res = cli.Get("/");
  12923. ASSERT_FALSE(res);
  12924. EXPECT_EQ(Error::SSLConnection, res.error());
  12925. }
  12926. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  12927. // Test for Issue #2251: SSL error not properly reported when client cert
  12928. // and key paths are swapped or mismatched
  12929. // This simulates the scenario where user accidentally swaps the cert and key
  12930. // files
  12931. // Using client cert file as private key and vice versa (completely wrong)
  12932. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  12933. // Should fail validation due to cert/key mismatch
  12934. ASSERT_FALSE(cli.is_valid());
  12935. // Attempt to make a request should fail with proper error
  12936. auto res = cli.Get("/");
  12937. ASSERT_FALSE(res);
  12938. EXPECT_EQ(Error::SSLConnection, res.error());
  12939. // SSL error should be recorded in the Result object (this is the key fix for
  12940. // Issue #2251)
  12941. auto backend_error = res.ssl_backend_error();
  12942. EXPECT_NE(0u, backend_error);
  12943. }
  12944. // Tests cert/key mismatch detection at the TLS context level
  12945. TEST(TlsApiTest, ClientCertKeyMismatch) {
  12946. // Test that using mismatched cert/key causes connection failure.
  12947. // We verify this at the SSLClient level rather than through internal
  12948. // TLS API functions.
  12949. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  12950. cli.enable_server_certificate_verification(false);
  12951. cli.set_connection_timeout(2);
  12952. // The mismatch should cause a connection or handshake error
  12953. auto res = cli.Get("/test");
  12954. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  12955. // Either way, the request should fail
  12956. EXPECT_FALSE(res);
  12957. }
  12958. #endif
  12959. #if 0
  12960. TEST(SSLClientTest, SetInterfaceWithINET6) {
  12961. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  12962. ASSERT_TRUE(cli != nullptr);
  12963. cli->set_address_family(AF_INET6);
  12964. cli->set_interface("en0");
  12965. auto res = cli->Get("/get");
  12966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12967. ASSERT_EQ(StatusCode::OK_200, res->status);
  12968. }
  12969. #endif
  12970. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  12971. #ifdef CPPHTTPLIB_SSL_ENABLED
  12972. void ClientCertPresent(
  12973. const std::string &client_cert_file,
  12974. const std::string &client_private_key_file,
  12975. const std::string &client_encrypted_private_key_pass = std::string()) {
  12976. using namespace httplib::tls;
  12977. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12978. CLIENT_CA_CERT_DIR);
  12979. ASSERT_TRUE(svr.is_valid());
  12980. svr.Get("/test", [&](const Request &req, Response &res) {
  12981. res.set_content("test", "text/plain");
  12982. auto cert = req.peer_cert();
  12983. ASSERT_TRUE(static_cast<bool>(cert));
  12984. std::string common_name = cert.subject_cn();
  12985. EXPECT_EQ("Common Name", common_name);
  12986. });
  12987. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12988. auto se = detail::scope_exit([&] {
  12989. svr.stop();
  12990. t.join();
  12991. ASSERT_FALSE(svr.is_running());
  12992. });
  12993. svr.wait_until_ready();
  12994. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  12995. client_encrypted_private_key_pass);
  12996. cli.enable_server_certificate_verification(false);
  12997. cli.set_connection_timeout(30);
  12998. auto res = cli.Get("/test");
  12999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13000. ASSERT_EQ(StatusCode::OK_200, res->status);
  13001. }
  13002. TEST(SSLClientServerTest, ClientCertPresent) {
  13003. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13004. }
  13005. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13006. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13007. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13008. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13009. }
  13010. // PEM memory-based constructor tests (works with all TLS backends)
  13011. void PemMemoryClientCertPresent(
  13012. const std::string &client_cert_file,
  13013. const std::string &client_private_key_file,
  13014. const std::string &client_encrypted_private_key_pass = std::string()) {
  13015. // Read PEM files into memory
  13016. std::string server_cert_pem, server_key_pem;
  13017. std::string client_ca_pem;
  13018. std::string client_cert_pem, client_key_pem;
  13019. read_file(SERVER_CERT_FILE, server_cert_pem);
  13020. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13021. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13022. read_file(client_cert_file, client_cert_pem);
  13023. read_file(client_private_key_file, client_key_pem);
  13024. // Create server with PEM memory
  13025. SSLServer::PemMemory server_pem = {
  13026. server_cert_pem.c_str(),
  13027. server_cert_pem.size(),
  13028. server_key_pem.c_str(),
  13029. server_key_pem.size(),
  13030. client_ca_pem.c_str(),
  13031. client_ca_pem.size(),
  13032. nullptr // no password for server key
  13033. };
  13034. SSLServer svr(server_pem);
  13035. ASSERT_TRUE(svr.is_valid());
  13036. svr.Get("/test", [&](const Request &, Response &res) {
  13037. res.set_content("test", "text/plain");
  13038. });
  13039. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13040. auto se = detail::scope_exit([&] {
  13041. svr.stop();
  13042. t.join();
  13043. ASSERT_FALSE(svr.is_running());
  13044. });
  13045. svr.wait_until_ready();
  13046. // Create client with PEM memory
  13047. const char *password = client_encrypted_private_key_pass.empty()
  13048. ? nullptr
  13049. : client_encrypted_private_key_pass.c_str();
  13050. SSLClient::PemMemory client_pem = {
  13051. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  13052. client_key_pem.size(), password};
  13053. SSLClient cli(HOST, PORT, client_pem);
  13054. cli.enable_server_certificate_verification(false);
  13055. cli.set_connection_timeout(30);
  13056. auto res = cli.Get("/test");
  13057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13058. ASSERT_EQ(StatusCode::OK_200, res->status);
  13059. }
  13060. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13061. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13062. }
  13063. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13064. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13065. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13066. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13067. }
  13068. TEST(SSLClientServerTest, ClientCertMissing) {
  13069. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13070. CLIENT_CA_CERT_DIR);
  13071. ASSERT_TRUE(svr.is_valid());
  13072. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  13073. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13074. auto se = detail::scope_exit([&] {
  13075. svr.stop();
  13076. t.join();
  13077. ASSERT_FALSE(svr.is_running());
  13078. });
  13079. svr.wait_until_ready();
  13080. SSLClient cli(HOST, PORT);
  13081. cli.set_connection_timeout(30);
  13082. // cert.pem does not match HOST. Skip the hostname check, which runs before
  13083. // the chain check on Windows, so the result does not depend on the order.
  13084. cli.enable_server_hostname_verification(false);
  13085. auto res = cli.Get("/test");
  13086. ASSERT_TRUE(!res);
  13087. // When client cert is missing and server requires it, connection fails
  13088. // Error type depends on backend implementation
  13089. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13090. res.error() == Error::SSLConnection);
  13091. // Verify backend error is captured
  13092. // Note: This test may have different error codes depending on the exact
  13093. // verification failure
  13094. EXPECT_NE(0UL, res.ssl_backend_error());
  13095. }
  13096. TEST(SSLClientServerTest, TrustDirOptional) {
  13097. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13098. ASSERT_TRUE(svr.is_valid());
  13099. svr.Get("/test", [&](const Request &, Response &res) {
  13100. res.set_content("test", "text/plain");
  13101. });
  13102. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13103. auto se = detail::scope_exit([&] {
  13104. svr.stop();
  13105. t.join();
  13106. ASSERT_FALSE(svr.is_running());
  13107. });
  13108. svr.wait_until_ready();
  13109. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13110. cli.enable_server_certificate_verification(false);
  13111. cli.set_connection_timeout(30);
  13112. auto res = cli.Get("/test");
  13113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13114. ASSERT_EQ(StatusCode::OK_200, res->status);
  13115. }
  13116. TEST(SSLClientServerTest, SSLConnectTimeout) {
  13117. class NoListenSSLServer : public SSLServer {
  13118. public:
  13119. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  13120. const char *client_ca_cert_file_path,
  13121. const char *client_ca_cert_dir_path = nullptr)
  13122. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  13123. client_ca_cert_dir_path),
  13124. stop_(false) {}
  13125. std::atomic_bool stop_;
  13126. private:
  13127. bool process_and_close_socket(socket_t /*sock*/) override {
  13128. // Don't create SSL context
  13129. while (!stop_.load()) {
  13130. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  13131. }
  13132. return true;
  13133. }
  13134. };
  13135. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13136. CLIENT_CA_CERT_FILE);
  13137. ASSERT_TRUE(svr.is_valid());
  13138. svr.Get("/test", [&](const Request &, Response &res) {
  13139. res.set_content("test", "text/plain");
  13140. });
  13141. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13142. auto se = detail::scope_exit([&] {
  13143. svr.stop_ = true;
  13144. svr.stop();
  13145. t.join();
  13146. ASSERT_FALSE(svr.is_running());
  13147. });
  13148. svr.wait_until_ready();
  13149. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13150. cli.enable_server_certificate_verification(false);
  13151. cli.set_connection_timeout(1);
  13152. auto res = cli.Get("/test");
  13153. ASSERT_TRUE(!res);
  13154. EXPECT_EQ(Error::SSLConnection, res.error());
  13155. // Timeout results in WantRead error code (maps to backend-specific value)
  13156. EXPECT_NE(0, res.ssl_error());
  13157. }
  13158. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  13159. // Test SSLServer with client certificate verification using the standard
  13160. // constructor (ContextSetupCallback is tested by backend-specific tests)
  13161. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13162. CLIENT_CA_CERT_DIR);
  13163. ASSERT_TRUE(svr.is_valid());
  13164. svr.Get("/test", [&](const Request &req, Response &res) {
  13165. res.set_content("test", "text/plain");
  13166. auto cert = req.peer_cert();
  13167. ASSERT_TRUE(static_cast<bool>(cert));
  13168. auto common_name = cert.subject_cn();
  13169. EXPECT_EQ("Common Name", common_name);
  13170. });
  13171. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13172. auto se = detail::scope_exit([&] {
  13173. svr.stop();
  13174. t.join();
  13175. ASSERT_FALSE(svr.is_running());
  13176. });
  13177. svr.wait_until_ready();
  13178. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13179. cli.enable_server_certificate_verification(false);
  13180. cli.set_connection_timeout(30);
  13181. auto res = cli.Get("/test");
  13182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13183. ASSERT_EQ(StatusCode::OK_200, res->status);
  13184. }
  13185. // Test verify_hostname for both OpenSSL and MbedTLS backends
  13186. // Verifies that wildcard matching and exact matching work consistently
  13187. TEST(SSLClientServerTest, TlsVerifyHostname) {
  13188. using namespace httplib::tls;
  13189. // We need a running server to test against
  13190. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13191. ASSERT_TRUE(svr.is_valid());
  13192. svr.Get("/test", [](const Request &, Response &res) {
  13193. res.set_content("ok", "text/plain");
  13194. });
  13195. thread t([&]() { svr.listen(HOST, PORT); });
  13196. auto se = detail::scope_exit([&] {
  13197. svr.stop();
  13198. t.join();
  13199. });
  13200. svr.wait_until_ready();
  13201. bool verify_callback_called = false;
  13202. bool verify_result_wrong = false;
  13203. SSLClient cli(HOST, PORT);
  13204. cli.enable_server_certificate_verification(true);
  13205. cli.set_ca_cert_path(CA_CERT_FILE);
  13206. cli.set_connection_timeout(5);
  13207. // Note: Test certificate has CN="Common Name", not "localhost"
  13208. bool verify_result_cn = false;
  13209. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13210. verify_callback_called = true;
  13211. if (!ctx.cert) return false;
  13212. // Test 1: "Common Name" should match (our test server cert CN)
  13213. verify_result_cn = ctx.check_hostname("Common Name");
  13214. // Test 2: wrong hostname should not match
  13215. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  13216. return true; // Accept for the purpose of this test
  13217. });
  13218. auto res = cli.Get("/test");
  13219. // The request may succeed or fail depending on cert configuration
  13220. // but the callback should have been called
  13221. ASSERT_TRUE(verify_callback_called)
  13222. << "Verify callback should have been called";
  13223. // CN="Common Name" should match our test certificate
  13224. //
  13225. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  13226. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  13227. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  13228. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  13229. // <openssl/base.h>, which is included transitively when
  13230. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  13231. #if defined(OPENSSL_IS_BORINGSSL)
  13232. EXPECT_FALSE(verify_result_cn)
  13233. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  13234. #else
  13235. EXPECT_TRUE(verify_result_cn)
  13236. << "verify_hostname should match 'Common Name' (certificate CN)";
  13237. #endif
  13238. // Wrong hostname should not match
  13239. EXPECT_FALSE(verify_result_wrong)
  13240. << "verify_hostname should not match 'wronghost.example.com'";
  13241. }
  13242. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  13243. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  13244. // X509_check_ip behavior and must hold for every backend.
  13245. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  13246. using namespace httplib::tls;
  13247. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  13248. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  13249. ASSERT_TRUE(svr.is_valid());
  13250. svr.Get("/test", [](const Request &, Response &res) {
  13251. res.set_content("ok", "text/plain");
  13252. });
  13253. thread t([&]() { svr.listen(HOST, PORT); });
  13254. auto se = detail::scope_exit([&] {
  13255. svr.stop();
  13256. t.join();
  13257. });
  13258. svr.wait_until_ready();
  13259. bool verify_callback_called = false;
  13260. bool ip_matched_via_cn = true;
  13261. SSLClient cli(HOST, PORT);
  13262. cli.enable_server_certificate_verification(true);
  13263. cli.set_ca_cert_path(CA_CERT_FILE);
  13264. cli.set_connection_timeout(5);
  13265. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13266. verify_callback_called = true;
  13267. if (!ctx.cert) return false;
  13268. // The IP appears only in the CN, so it must NOT be accepted.
  13269. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  13270. return true; // Accept for the purpose of this test
  13271. });
  13272. cli.Get("/test");
  13273. ASSERT_TRUE(verify_callback_called)
  13274. << "Verify callback should have been called";
  13275. EXPECT_FALSE(ip_matched_via_cn)
  13276. << "An IP host must not be authenticated via the certificate CN";
  13277. }
  13278. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  13279. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  13280. using namespace httplib::tls;
  13281. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  13282. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  13283. ASSERT_TRUE(svr.is_valid());
  13284. svr.Get("/test", [](const Request &, Response &res) {
  13285. res.set_content("ok", "text/plain");
  13286. });
  13287. thread t([&]() { svr.listen(HOST, PORT); });
  13288. auto se = detail::scope_exit([&] {
  13289. svr.stop();
  13290. t.join();
  13291. });
  13292. svr.wait_until_ready();
  13293. bool verify_callback_called = false;
  13294. bool san_matched = false;
  13295. bool wrong_ipv6_matched = true;
  13296. bool cn_ipv6_matched = true;
  13297. SSLClient cli(HOST, PORT);
  13298. cli.enable_server_certificate_verification(true);
  13299. cli.set_ca_cert_path(CA_CERT_FILE);
  13300. cli.set_connection_timeout(5);
  13301. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13302. verify_callback_called = true;
  13303. if (!ctx.cert) return false;
  13304. // Matches the IPv6 iPAddress SAN.
  13305. san_matched = ctx.check_hostname("2001:db8::1");
  13306. // A different IPv6 address must not match.
  13307. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  13308. // "::1" lives only in the CN, so it must not be accepted.
  13309. cn_ipv6_matched = ctx.check_hostname("::1");
  13310. return true; // Accept for the purpose of this test
  13311. });
  13312. cli.Get("/test");
  13313. ASSERT_TRUE(verify_callback_called)
  13314. << "Verify callback should have been called";
  13315. EXPECT_TRUE(san_matched)
  13316. << "verify_hostname should match an IPv6 iPAddress SAN";
  13317. EXPECT_FALSE(wrong_ipv6_matched)
  13318. << "verify_hostname should not match a non-matching IPv6 address";
  13319. EXPECT_FALSE(cn_ipv6_matched)
  13320. << "An IPv6 host must not be authenticated via the certificate CN";
  13321. }
  13322. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  13323. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  13324. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  13325. using namespace httplib::tls;
  13326. // SANs: DNS:a.zz, IP:42.46.122.122
  13327. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13328. ASSERT_TRUE(svr.is_valid());
  13329. svr.Get("/test", [](const Request &, Response &res) {
  13330. res.set_content("ok", "text/plain");
  13331. });
  13332. auto port = svr.bind_to_any_port(HOST);
  13333. thread t([&]() { svr.listen_after_bind(); });
  13334. auto se = detail::scope_exit([&] {
  13335. svr.stop();
  13336. t.join();
  13337. });
  13338. svr.wait_until_ready();
  13339. bool verify_callback_called = false;
  13340. bool dns_san_matched = false;
  13341. bool ip_san_matched = false;
  13342. bool ip_matched_via_dns_san = true;
  13343. bool dns_matched_via_ip_san = true;
  13344. SSLClient cli(HOST, port);
  13345. cli.enable_server_certificate_verification(true);
  13346. cli.set_ca_cert_path(CA_CERT_FILE);
  13347. cli.set_connection_timeout(5);
  13348. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13349. verify_callback_called = true;
  13350. if (!ctx.cert) return false;
  13351. dns_san_matched = ctx.check_hostname("a.zz");
  13352. ip_san_matched = ctx.check_hostname("42.46.122.122");
  13353. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  13354. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  13355. return true; // Accept for the purpose of this test
  13356. });
  13357. cli.Get("/test");
  13358. ASSERT_TRUE(verify_callback_called)
  13359. << "Verify callback should have been called";
  13360. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  13361. EXPECT_TRUE(ip_san_matched)
  13362. << "verify_hostname should match an iPAddress SAN";
  13363. EXPECT_FALSE(ip_matched_via_dns_san)
  13364. << "An IP host must not be authenticated via a dNSName SAN";
  13365. EXPECT_FALSE(dns_matched_via_ip_san)
  13366. << "A DNS host must not be authenticated via an iPAddress SAN";
  13367. }
  13368. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  13369. // "www.*.example.test" names one host and not every host under example.test.
  13370. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  13371. using namespace httplib::tls;
  13372. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  13373. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  13374. ASSERT_TRUE(svr.is_valid());
  13375. svr.Get("/test", [](const Request &, Response &res) {
  13376. res.set_content("ok", "text/plain");
  13377. });
  13378. auto port = svr.bind_to_any_port(HOST);
  13379. thread t([&]() { svr.listen_after_bind(); });
  13380. auto se = detail::scope_exit([&] {
  13381. svr.stop();
  13382. t.join();
  13383. });
  13384. svr.wait_until_ready();
  13385. bool verify_callback_called = false;
  13386. bool leftmost_wildcard_matched = false;
  13387. bool wildcard_spanned_labels = true;
  13388. bool inner_wildcard_matched = true;
  13389. SSLClient cli(HOST, port);
  13390. cli.enable_server_certificate_verification(true);
  13391. cli.set_ca_cert_path(CA_CERT_FILE);
  13392. cli.set_connection_timeout(5);
  13393. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13394. verify_callback_called = true;
  13395. if (!ctx.cert) return false;
  13396. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  13397. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  13398. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  13399. return true; // Accept for the purpose of this test
  13400. });
  13401. cli.Get("/test");
  13402. ASSERT_TRUE(verify_callback_called)
  13403. << "Verify callback should have been called";
  13404. EXPECT_TRUE(leftmost_wildcard_matched)
  13405. << "A leftmost wildcard should match a single label";
  13406. EXPECT_FALSE(wildcard_spanned_labels)
  13407. << "A wildcard label must not match more than one label";
  13408. EXPECT_FALSE(inner_wildcard_matched)
  13409. << "A wildcard outside the leftmost label must not be honoured";
  13410. }
  13411. // sans() must report each SAN entry under its own type.
  13412. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  13413. using namespace httplib::tls;
  13414. // SANs: DNS:a.zz, IP:42.46.122.122
  13415. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13416. ASSERT_TRUE(svr.is_valid());
  13417. svr.Get("/test", [](const Request &, Response &res) {
  13418. res.set_content("ok", "text/plain");
  13419. });
  13420. auto port = svr.bind_to_any_port(HOST);
  13421. thread t([&]() { svr.listen_after_bind(); });
  13422. auto se = detail::scope_exit([&] {
  13423. svr.stop();
  13424. t.join();
  13425. });
  13426. svr.wait_until_ready();
  13427. bool verify_callback_called = false;
  13428. std::vector<SanEntry> sans;
  13429. SSLClient cli(HOST, port);
  13430. cli.enable_server_certificate_verification(true);
  13431. cli.set_ca_cert_path(CA_CERT_FILE);
  13432. cli.set_connection_timeout(5);
  13433. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13434. verify_callback_called = true;
  13435. if (!ctx.cert) return false;
  13436. sans = ctx.sans();
  13437. return true; // Accept for the purpose of this test
  13438. });
  13439. cli.Get("/test");
  13440. ASSERT_TRUE(verify_callback_called)
  13441. << "Verify callback should have been called";
  13442. auto has_san = [&](SanType type, const std::string &value) {
  13443. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  13444. return san.type == type && san.value == value;
  13445. });
  13446. };
  13447. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  13448. << "sans() should report the dNSName SAN";
  13449. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  13450. << "sans() should report the iPAddress SAN";
  13451. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  13452. << "sans() must not report the dNSName SAN as an address";
  13453. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  13454. << "sans() must not report the iPAddress SAN as a DNS name";
  13455. }
  13456. #endif
  13457. // mbedTLS-specific callback constructor test
  13458. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  13459. #ifdef CPPHTTPLIB_SSL_ENABLED
  13460. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  13461. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13462. ASSERT_TRUE(svr.is_valid());
  13463. // Set up a handler to verify client certificate is present
  13464. bool client_cert_verified = false;
  13465. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13466. // Verify that client certificate was provided
  13467. client_cert_verified = true;
  13468. res.set_content("success", "text/plain");
  13469. });
  13470. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13471. auto se = detail::scope_exit([&] {
  13472. svr.stop();
  13473. t.join();
  13474. ASSERT_FALSE(svr.is_running());
  13475. });
  13476. svr.wait_until_ready();
  13477. // Client with certificate
  13478. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13479. cli.enable_server_certificate_verification(false);
  13480. cli.set_connection_timeout(30);
  13481. auto res = cli.Get("/test");
  13482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13483. ASSERT_EQ(StatusCode::OK_200, res->status);
  13484. ASSERT_TRUE(client_cert_verified);
  13485. EXPECT_EQ("success", res->body);
  13486. }
  13487. #endif
  13488. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  13489. // backends
  13490. #ifdef CPPHTTPLIB_SSL_ENABLED
  13491. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  13492. using namespace httplib::tls;
  13493. // Test that when client CA cert file is provided,
  13494. // the server properly requests and validates client certificates
  13495. // Create a server with client authentication
  13496. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13497. ASSERT_TRUE(svr.is_valid());
  13498. bool handler_called = false;
  13499. svr.Get("/test", [&](const Request &req, Response &res) {
  13500. handler_called = true;
  13501. // Verify that a client certificate was provided
  13502. auto cert = req.peer_cert();
  13503. ASSERT_TRUE(static_cast<bool>(cert));
  13504. // Get the issuer name
  13505. std::string issuer_str = cert.issuer_name();
  13506. ASSERT_FALSE(issuer_str.empty());
  13507. // The client certificate should be issued by our test CA
  13508. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  13509. res.set_content("authenticated", "text/plain");
  13510. });
  13511. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13512. auto se = detail::scope_exit([&] {
  13513. svr.stop();
  13514. t.join();
  13515. ASSERT_FALSE(svr.is_running());
  13516. });
  13517. svr.wait_until_ready();
  13518. // Connect with a client certificate issued by the CA
  13519. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13520. cli.enable_server_certificate_verification(false);
  13521. cli.set_connection_timeout(30);
  13522. auto res = cli.Get("/test");
  13523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13524. ASSERT_EQ(StatusCode::OK_200, res->status);
  13525. ASSERT_TRUE(handler_called);
  13526. EXPECT_EQ("authenticated", res->body);
  13527. }
  13528. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  13529. using namespace httplib::tls;
  13530. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13531. ASSERT_TRUE(svr.is_valid());
  13532. svr.Get("/test", [](const Request &, Response &res) {
  13533. res.set_content("ok", "text/plain");
  13534. });
  13535. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13536. auto se = detail::scope_exit([&] {
  13537. svr.stop();
  13538. t.join();
  13539. });
  13540. svr.wait_until_ready();
  13541. SSLClient cli(HOST, PORT);
  13542. cli.enable_server_certificate_verification(false);
  13543. cli.set_connection_timeout(30);
  13544. bool cert_checked = false;
  13545. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13546. if (ctx.cert) {
  13547. auto sans = ctx.sans();
  13548. // Test certificate may or may not have SANs - just verify the API
  13549. // works If SANs exist, verify the types are valid
  13550. for (const auto &san : sans) {
  13551. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  13552. san.type == SanType::EMAIL || san.type == SanType::URI ||
  13553. san.type == SanType::OTHER);
  13554. EXPECT_FALSE(san.value.empty());
  13555. }
  13556. cert_checked = true;
  13557. }
  13558. return true;
  13559. });
  13560. auto res = cli.Get("/test");
  13561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13562. EXPECT_TRUE(cert_checked);
  13563. }
  13564. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  13565. using namespace httplib::tls;
  13566. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13567. ASSERT_TRUE(svr.is_valid());
  13568. svr.Get("/test", [](const Request &, Response &res) {
  13569. res.set_content("ok", "text/plain");
  13570. });
  13571. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13572. auto se = detail::scope_exit([&] {
  13573. svr.stop();
  13574. t.join();
  13575. });
  13576. svr.wait_until_ready();
  13577. SSLClient cli(HOST, PORT);
  13578. cli.enable_server_certificate_verification(false);
  13579. cli.set_connection_timeout(30);
  13580. bool validity_checked = false;
  13581. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13582. if (ctx.cert) {
  13583. time_t not_before = 0, not_after = 0;
  13584. bool result = ctx.validity(not_before, not_after);
  13585. EXPECT_TRUE(result);
  13586. // Verify that not_before < now < not_after for a valid cert
  13587. time_t now = time(nullptr);
  13588. EXPECT_LT(not_before, now);
  13589. EXPECT_GT(not_after, now);
  13590. validity_checked = true;
  13591. }
  13592. return true;
  13593. });
  13594. auto res = cli.Get("/test");
  13595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13596. EXPECT_TRUE(validity_checked);
  13597. }
  13598. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  13599. using namespace httplib::tls;
  13600. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13601. ASSERT_TRUE(svr.is_valid());
  13602. svr.Get("/test", [](const Request &, Response &res) {
  13603. res.set_content("ok", "text/plain");
  13604. });
  13605. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13606. auto se = detail::scope_exit([&] {
  13607. svr.stop();
  13608. t.join();
  13609. });
  13610. svr.wait_until_ready();
  13611. SSLClient cli(HOST, PORT);
  13612. cli.enable_server_certificate_verification(false);
  13613. cli.set_connection_timeout(30);
  13614. bool serial_checked = false;
  13615. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13616. if (ctx.cert) {
  13617. std::string serial = ctx.serial();
  13618. EXPECT_FALSE(serial.empty());
  13619. // Serial should be a hex string
  13620. for (char c : serial) {
  13621. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  13622. (c >= 'a' && c <= 'f'));
  13623. }
  13624. serial_checked = true;
  13625. }
  13626. return true;
  13627. });
  13628. auto res = cli.Get("/test");
  13629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13630. EXPECT_TRUE(serial_checked);
  13631. }
  13632. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  13633. // Test 1: Valid CA file - no error should be recorded
  13634. {
  13635. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13636. CLIENT_CA_CERT_FILE);
  13637. ASSERT_TRUE(svr.is_valid());
  13638. // With valid setup, last_ssl_error should be 0
  13639. EXPECT_EQ(0, svr.ssl_last_error());
  13640. }
  13641. // Test 2: Invalid CA file content
  13642. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  13643. {
  13644. // Create a temporary file with completely invalid content
  13645. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  13646. {
  13647. std::ofstream ofs(temp_invalid_ca);
  13648. ofs << "This is not a certificate file at all\n";
  13649. ofs << "Just plain text content\n";
  13650. }
  13651. // Create server with invalid CA file
  13652. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  13653. // Clean up temporary file
  13654. std::remove(temp_invalid_ca);
  13655. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  13656. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  13657. // Note: SSL_CTX_load_verify_locations typically fails first,
  13658. // but our error handling code path is still exercised
  13659. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  13660. }
  13661. }
  13662. TEST(VerifyCallbackTest, VerifyContextFields) {
  13663. using namespace httplib::tls;
  13664. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13665. ASSERT_TRUE(svr.is_valid());
  13666. svr.Get("/test", [](const Request &, Response &res) {
  13667. res.set_content("ok", "text/plain");
  13668. });
  13669. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13670. auto se = detail::scope_exit([&] {
  13671. svr.stop();
  13672. t.join();
  13673. });
  13674. svr.wait_until_ready();
  13675. SSLClient cli(HOST, PORT);
  13676. cli.enable_server_certificate_verification(false);
  13677. cli.set_connection_timeout(30);
  13678. int callback_count = 0;
  13679. bool saw_leaf_cert = false;
  13680. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13681. if (ctx.cert) {
  13682. callback_count++;
  13683. // We should see at least one certificate (the leaf)
  13684. std::string cn = ctx.subject_cn();
  13685. if (!cn.empty()) { saw_leaf_cert = true; }
  13686. // Verify context fields are populated
  13687. EXPECT_NE(ctx.session, nullptr);
  13688. EXPECT_GE(ctx.depth, 0);
  13689. }
  13690. return true;
  13691. });
  13692. auto res = cli.Get("/test");
  13693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13694. EXPECT_GT(callback_count, 0);
  13695. EXPECT_TRUE(saw_leaf_cert);
  13696. }
  13697. // A verifier belongs to the client that set it, not to the thread that set it.
  13698. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  13699. using namespace httplib::tls;
  13700. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13701. ASSERT_TRUE(svr.is_valid());
  13702. svr.Get("/test", [](const Request &, Response &res) {
  13703. res.set_content("ok", "text/plain");
  13704. });
  13705. auto port = svr.bind_to_any_port(HOST);
  13706. thread t([&]() { svr.listen_after_bind(); });
  13707. auto se = detail::scope_exit([&] {
  13708. svr.stop();
  13709. t.join();
  13710. });
  13711. svr.wait_until_ready();
  13712. auto rejecting_calls = 0;
  13713. SSLClient rejecting(HOST, port);
  13714. rejecting.enable_server_certificate_verification(false);
  13715. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  13716. rejecting_calls++;
  13717. return false;
  13718. });
  13719. auto accepting_calls = 0;
  13720. SSLClient accepting(HOST, port);
  13721. accepting.enable_server_certificate_verification(false);
  13722. // Set on another thread than the requests below.
  13723. thread([&]() {
  13724. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  13725. accepting_calls++;
  13726. return true;
  13727. });
  13728. }).join();
  13729. // Requested on another thread than the verifier was set on.
  13730. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  13731. EXPECT_GT(rejecting_calls, 0);
  13732. auto res = accepting.Get("/test");
  13733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13734. EXPECT_GT(accepting_calls, 0);
  13735. }
  13736. // VerifyContext::session is the same handle the other tls:: functions take.
  13737. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  13738. using namespace httplib::tls;
  13739. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13740. ASSERT_TRUE(svr.is_valid());
  13741. svr.Get("/test", [](const Request &, Response &res) {
  13742. res.set_content("ok", "text/plain");
  13743. });
  13744. auto port = svr.bind_to_any_port(HOST);
  13745. thread t([&]() { svr.listen_after_bind(); });
  13746. auto se = detail::scope_exit([&] {
  13747. svr.stop();
  13748. t.join();
  13749. });
  13750. svr.wait_until_ready();
  13751. SSLClient cli(HOST, port);
  13752. cli.enable_server_certificate_verification(false);
  13753. session_t verifier_session = nullptr;
  13754. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  13755. verifier_session = ctx.session;
  13756. return true;
  13757. });
  13758. session_t session_verifier_session = nullptr;
  13759. cli.set_session_verifier([&](session_t session) {
  13760. session_verifier_session = session;
  13761. return SSLVerifierResponse::NoDecisionMade;
  13762. });
  13763. auto res = cli.Get("/test");
  13764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13765. EXPECT_NE(nullptr, verifier_session);
  13766. EXPECT_EQ(session_verifier_session, verifier_session);
  13767. }
  13768. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  13769. using httplib::tls::TlsError;
  13770. // Test that verify_error_to_string returns empty for success
  13771. std::string success_str = TlsError::verify_error_to_string(0);
  13772. EXPECT_TRUE(success_str.empty());
  13773. // Test that verify_error_to_string returns non-empty for error codes
  13774. // Using a common error code (certificate expired)
  13775. std::string error_str =
  13776. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  13777. EXPECT_FALSE(error_str.empty());
  13778. }
  13779. TEST(SessionVerifierTest, CertificateAccepted) {
  13780. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13781. ASSERT_TRUE(svr.is_valid());
  13782. svr.Get("/test", [](const Request &, Response &res) {
  13783. res.set_content("ok", "text/plain");
  13784. });
  13785. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13786. auto se = detail::scope_exit([&] {
  13787. svr.stop();
  13788. t.join();
  13789. });
  13790. svr.wait_until_ready();
  13791. SSLClient cli(HOST, PORT);
  13792. cli.enable_server_certificate_verification(false);
  13793. cli.set_connection_timeout(30);
  13794. bool callback_called = false;
  13795. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13796. EXPECT_NE(session, nullptr);
  13797. callback_called = true;
  13798. return SSLVerifierResponse::CertificateAccepted;
  13799. });
  13800. auto res = cli.Get("/test");
  13801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13802. EXPECT_EQ(200, res->status);
  13803. EXPECT_TRUE(callback_called);
  13804. }
  13805. TEST(SessionVerifierTest, CertificateRejected) {
  13806. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13807. ASSERT_TRUE(svr.is_valid());
  13808. svr.Get("/test", [](const Request &, Response &res) {
  13809. res.set_content("ok", "text/plain");
  13810. });
  13811. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13812. auto se = detail::scope_exit([&] {
  13813. svr.stop();
  13814. t.join();
  13815. });
  13816. svr.wait_until_ready();
  13817. SSLClient cli(HOST, PORT);
  13818. cli.enable_server_certificate_verification(false);
  13819. cli.set_connection_timeout(30);
  13820. bool callback_called = false;
  13821. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13822. EXPECT_NE(session, nullptr);
  13823. callback_called = true;
  13824. return SSLVerifierResponse::CertificateRejected;
  13825. });
  13826. auto res = cli.Get("/test");
  13827. EXPECT_FALSE(res);
  13828. EXPECT_TRUE(callback_called);
  13829. }
  13830. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  13831. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13832. ASSERT_TRUE(svr.is_valid());
  13833. svr.Get("/test", [](const Request &, Response &res) {
  13834. res.set_content("ok", "text/plain");
  13835. });
  13836. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13837. auto se = detail::scope_exit([&] {
  13838. svr.stop();
  13839. t.join();
  13840. });
  13841. svr.wait_until_ready();
  13842. // NoDecisionMade with verification disabled should succeed (no default check)
  13843. SSLClient cli(HOST, PORT);
  13844. cli.enable_server_certificate_verification(false);
  13845. cli.set_connection_timeout(30);
  13846. bool callback_called = false;
  13847. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13848. EXPECT_NE(session, nullptr);
  13849. callback_called = true;
  13850. return SSLVerifierResponse::NoDecisionMade;
  13851. });
  13852. auto res = cli.Get("/test");
  13853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13854. EXPECT_EQ(200, res->status);
  13855. EXPECT_TRUE(callback_called);
  13856. }
  13857. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  13858. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13859. ASSERT_TRUE(svr.is_valid());
  13860. svr.Get("/test", [](const Request &, Response &res) {
  13861. res.set_content("ok", "text/plain");
  13862. });
  13863. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13864. auto se = detail::scope_exit([&] {
  13865. svr.stop();
  13866. t.join();
  13867. });
  13868. svr.wait_until_ready();
  13869. // NoDecisionMade with verification enabled should fail (self-signed cert).
  13870. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  13871. // so we only check that the request fails, not whether the callback was
  13872. // called.
  13873. SSLClient cli(HOST, PORT);
  13874. cli.enable_server_certificate_verification(true);
  13875. cli.set_connection_timeout(30);
  13876. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13877. EXPECT_NE(session, nullptr);
  13878. return SSLVerifierResponse::NoDecisionMade;
  13879. });
  13880. auto res = cli.Get("/test");
  13881. EXPECT_FALSE(res);
  13882. }
  13883. TEST(SSLClientServerTest, ClientCAListFromPem) {
  13884. // Test SSL server using PemMemory constructor with client CA certificates
  13885. // Read PEM files
  13886. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13887. read_file(SERVER_CERT_FILE, server_cert_pem);
  13888. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13889. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13890. // Create SSLServer with PemMemory constructor including client CA
  13891. SSLServer::PemMemory server_pem = {
  13892. server_cert_pem.c_str(),
  13893. server_cert_pem.size(),
  13894. server_key_pem.c_str(),
  13895. server_key_pem.size(),
  13896. client_ca_pem.c_str(),
  13897. client_ca_pem.size(),
  13898. nullptr // no password for server key
  13899. };
  13900. SSLServer svr(server_pem);
  13901. ASSERT_TRUE(svr.is_valid());
  13902. // No SSL error should be recorded for valid setup
  13903. EXPECT_EQ(0, svr.ssl_last_error());
  13904. // Set up server endpoints
  13905. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  13906. res.set_content("ok", "text/plain");
  13907. });
  13908. // Start server in a thread
  13909. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  13910. svr.wait_until_ready();
  13911. // Connect with client certificate (using constructor with paths)
  13912. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13913. cli.enable_server_certificate_verification(false);
  13914. auto res = cli.Get("/test-pem-ca");
  13915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13916. EXPECT_EQ(200, res->status);
  13917. EXPECT_EQ("ok", res->body);
  13918. svr.stop();
  13919. server_thread.join();
  13920. }
  13921. #endif
  13922. #ifdef _WIN32
  13923. TEST(CleanupTest, WSACleanup) {
  13924. int ret = WSACleanup();
  13925. ASSERT_EQ(0, ret);
  13926. }
  13927. #endif
  13928. #ifndef CPPHTTPLIB_SSL_ENABLED
  13929. TEST(NoSSLSupport, SimpleInterface) {
  13930. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  13931. }
  13932. #endif
  13933. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  13934. TEST(InvalidScheme, SimpleInterface) {
  13935. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  13936. }
  13937. #endif
  13938. TEST(NoScheme, SimpleInterface) {
  13939. Client cli("yahoo.com:80");
  13940. ASSERT_TRUE(cli.is_valid());
  13941. }
  13942. TEST(SendAPI, SimpleInterface_Online) {
  13943. Client cli("http://yahoo.com");
  13944. Request req;
  13945. req.method = "GET";
  13946. req.path = "/";
  13947. auto res = cli.send(req);
  13948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13949. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13950. }
  13951. TEST(SendAPI, WithParamsInRequest) {
  13952. Server svr;
  13953. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  13954. EXPECT_TRUE(req.has_param("test"));
  13955. EXPECT_EQ("test_value", req.get_param_value("test"));
  13956. });
  13957. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13958. auto se = detail::scope_exit([&] {
  13959. svr.stop();
  13960. t.join();
  13961. ASSERT_FALSE(svr.is_running());
  13962. });
  13963. svr.wait_until_ready();
  13964. Client cli(HOST, PORT);
  13965. {
  13966. Request req;
  13967. req.method = "GET";
  13968. req.path = "/";
  13969. req.params.emplace("test", "test_value");
  13970. auto res = cli.send(req);
  13971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13972. }
  13973. {
  13974. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  13975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13976. }
  13977. }
  13978. TEST(ClientImplMethods, GetSocketTest) {
  13979. httplib::Server svr;
  13980. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  13981. res.status = StatusCode::OK_200;
  13982. });
  13983. auto port = svr.bind_to_any_port("127.0.0.1");
  13984. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13985. auto se = detail::scope_exit([&] {
  13986. svr.stop();
  13987. thread.join();
  13988. ASSERT_FALSE(svr.is_running());
  13989. });
  13990. svr.wait_until_ready();
  13991. {
  13992. httplib::Client cli("127.0.0.1", port);
  13993. cli.set_keep_alive(true);
  13994. // Use the behavior of cpp-httplib of opening the connection
  13995. // only when the first request happens. If that changes,
  13996. // this test would be obsolete.
  13997. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  13998. // This also implicitly tests the server. But other tests would fail much
  13999. // earlier than this one to be considered.
  14000. auto res = cli.Get("/");
  14001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14002. EXPECT_EQ(StatusCode::OK_200, res->status);
  14003. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14004. }
  14005. }
  14006. #ifdef CPPHTTPLIB_SSL_ENABLED
  14007. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  14008. Client cli("http://yahoo.com");
  14009. auto res = cli.Get("/");
  14010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14011. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14012. cli.set_follow_location(true);
  14013. res = cli.Get("/");
  14014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14015. EXPECT_EQ(StatusCode::OK_200, res->status);
  14016. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14017. }
  14018. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  14019. Client cli("https://yahoo.com");
  14020. auto res = cli.Get("/");
  14021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14022. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14023. cli.set_follow_location(true);
  14024. res = cli.Get("/");
  14025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14026. EXPECT_EQ(StatusCode::OK_200, res->status);
  14027. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14028. }
  14029. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  14030. Client cli("https://yahoo.com");
  14031. auto res = cli.Get("/");
  14032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14033. ASSERT_FALSE(!res);
  14034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14035. ASSERT_FALSE(res == nullptr);
  14036. ASSERT_TRUE(res != nullptr);
  14037. EXPECT_EQ(Error::Success, res.error());
  14038. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  14039. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  14040. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14041. cli.set_follow_location(true);
  14042. res = cli.Get("/");
  14043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14044. EXPECT_EQ(Error::Success, res.error());
  14045. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  14046. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  14047. EXPECT_EQ(StatusCode::OK_200, res->status);
  14048. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14049. }
  14050. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14051. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  14052. Client cli("https://cdnjs.cloudflare.com");
  14053. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  14054. Headers{{"Accept-Encoding", "br"}});
  14055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14056. EXPECT_EQ(StatusCode::OK_200, res->status);
  14057. EXPECT_EQ(287630U, res->body.size());
  14058. EXPECT_EQ("application/javascript; charset=utf-8",
  14059. res->get_header_value("Content-Type"));
  14060. }
  14061. #endif
  14062. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  14063. #undef REDIR_HOST // Silence compiler warning
  14064. #define REDIR_HOST "https://httpbingo.org"
  14065. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  14066. Client cli(REDIR_HOST);
  14067. cli.set_follow_location(true);
  14068. auto res =
  14069. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  14070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14071. EXPECT_EQ(StatusCode::OK_200, res->status);
  14072. }
  14073. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  14074. Client cli(REDIR_HOST);
  14075. cli.set_follow_location(true);
  14076. Params params;
  14077. params.emplace("url", "http://example.com");
  14078. params.emplace("status_code", "302");
  14079. auto res = cli.Get(REDIR_PATH, params, Headers{});
  14080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14081. EXPECT_EQ(StatusCode::OK_200, res->status);
  14082. }
  14083. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  14084. Client cli(REDIR_HOST);
  14085. cli.set_follow_location(true);
  14086. Params params;
  14087. params.emplace("url", "http://example.com");
  14088. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  14089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14090. EXPECT_EQ(StatusCode::OK_200, res->status);
  14091. }
  14092. TEST(HttpToHttpsRedirectTest, CertFile) {
  14093. auto ssl_port = PORT + 1;
  14094. Server svr;
  14095. ASSERT_TRUE(svr.is_valid());
  14096. svr.Get("/index", [&](const Request &, Response &res) {
  14097. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14098. "/index");
  14099. svr.stop();
  14100. });
  14101. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14102. ASSERT_TRUE(ssl_svr.is_valid());
  14103. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  14104. res.set_content("test", "text/plain");
  14105. ssl_svr.stop();
  14106. });
  14107. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14108. thread t2 =
  14109. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  14110. auto se = detail::scope_exit([&] {
  14111. t2.join();
  14112. t.join();
  14113. ASSERT_FALSE(svr.is_running());
  14114. });
  14115. svr.wait_until_ready();
  14116. ssl_svr.wait_until_ready();
  14117. Client cli("127.0.0.1", PORT);
  14118. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14119. cli.enable_server_certificate_verification(true);
  14120. cli.set_follow_location(true);
  14121. cli.set_connection_timeout(30);
  14122. auto res = cli.Get("/index");
  14123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14124. ASSERT_EQ(StatusCode::OK_200, res->status);
  14125. }
  14126. TEST(SSLClientRedirectTest, CertFile) {
  14127. auto ssl_port = PORT + 1;
  14128. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14129. ASSERT_TRUE(ssl_svr1.is_valid());
  14130. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14131. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14132. "/index");
  14133. ssl_svr1.stop();
  14134. });
  14135. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14136. ASSERT_TRUE(ssl_svr2.is_valid());
  14137. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14138. res.set_content("test", "text/plain");
  14139. ssl_svr2.stop();
  14140. });
  14141. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14142. thread t2 =
  14143. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14144. auto se = detail::scope_exit([&] {
  14145. t2.join();
  14146. t.join();
  14147. ASSERT_FALSE(ssl_svr1.is_running());
  14148. });
  14149. ssl_svr1.wait_until_ready();
  14150. ssl_svr2.wait_until_ready();
  14151. SSLClient cli("127.0.0.1", PORT);
  14152. std::string cert;
  14153. read_file(SERVER_CERT2_FILE, cert);
  14154. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14155. cli.enable_server_certificate_verification(true);
  14156. cli.set_follow_location(true);
  14157. cli.set_connection_timeout(30);
  14158. auto res = cli.Get("/index");
  14159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14160. ASSERT_EQ(StatusCode::OK_200, res->status);
  14161. }
  14162. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  14163. // another port, so the client follows it with a new client.
  14164. static Result GetThroughTlsRedirectToDifferentPort(
  14165. const std::function<void(SSLClient &)> &setup,
  14166. const char *target_cert = SERVER_CERT2_FILE) {
  14167. auto ssl_port = PORT + 1;
  14168. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14169. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14170. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14171. "/index");
  14172. });
  14173. SSLServer ssl_svr2(target_cert, SERVER_PRIVATE_KEY_FILE);
  14174. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14175. res.set_content("test", "text/plain");
  14176. });
  14177. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  14178. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  14179. auto se = detail::scope_exit([&] {
  14180. ssl_svr2.stop();
  14181. ssl_svr1.stop();
  14182. t2.join();
  14183. t.join();
  14184. });
  14185. ssl_svr1.wait_until_ready();
  14186. ssl_svr2.wait_until_ready();
  14187. SSLClient cli("127.0.0.1", PORT);
  14188. cli.set_follow_location(true);
  14189. cli.set_connection_timeout(30);
  14190. setup(cli);
  14191. return cli.Get("/index");
  14192. }
  14193. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  14194. auto calls = 0;
  14195. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  14196. cli.enable_server_certificate_verification(false);
  14197. // Accept the first server only.
  14198. cli.set_session_verifier([&](tls::session_t) {
  14199. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  14200. : SSLVerifierResponse::CertificateRejected;
  14201. });
  14202. });
  14203. EXPECT_FALSE(res);
  14204. EXPECT_EQ(2, calls);
  14205. }
  14206. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  14207. std::string pinned;
  14208. auto res = GetThroughTlsRedirectToDifferentPort(
  14209. [&](SSLClient &cli) {
  14210. cli.enable_server_certificate_verification(false);
  14211. // Pin the first certificate seen.
  14212. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  14213. if (pinned.empty()) { pinned = ctx.serial(); }
  14214. return ctx.serial() == pinned;
  14215. });
  14216. },
  14217. // A certificate other than the first server's.
  14218. SERVER_CERT_FILE);
  14219. EXPECT_FALSE(res);
  14220. EXPECT_FALSE(pinned.empty());
  14221. }
  14222. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  14223. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  14224. std::string cert;
  14225. read_file(SERVER_CERT2_FILE, cert);
  14226. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14227. });
  14228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14229. EXPECT_EQ(StatusCode::OK_200, res->status);
  14230. }
  14231. #endif
  14232. #ifdef CPPHTTPLIB_SSL_ENABLED
  14233. // Test that set_ca_cert_store() skips system certs (consistent with
  14234. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  14235. // should be trusted - system certs should NOT be loaded.
  14236. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  14237. // Load a specific cert that is NOT a system CA cert
  14238. std::string cert;
  14239. read_file(SERVER_CERT2_FILE, cert);
  14240. SSLClient cli("google.com");
  14241. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14242. cli.enable_server_certificate_verification(true);
  14243. // This should FAIL because:
  14244. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  14245. // 2. System certs should NOT be loaded when custom store is set
  14246. // If system certs WERE loaded, this would succeed
  14247. auto res = cli.Get("/");
  14248. ASSERT_FALSE(res);
  14249. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14250. }
  14251. // Same as above, but through the native store handle path. Regression test:
  14252. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  14253. // merged system certs into the user-provided store.
  14254. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  14255. std::string cert;
  14256. read_file(SERVER_CERT2_FILE, cert);
  14257. SSLClient cli("google.com");
  14258. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14259. cli.enable_server_certificate_verification(true);
  14260. auto res = cli.Get("/");
  14261. ASSERT_FALSE(res);
  14262. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14263. }
  14264. // A custom store set via the native handle must still verify a server whose
  14265. // cert it does contain.
  14266. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  14267. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14268. ASSERT_TRUE(svr.is_valid());
  14269. svr.Get("/test", [&](const Request &, Response &res) {
  14270. res.set_content("test", "text/plain");
  14271. });
  14272. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14273. auto se = detail::scope_exit([&] {
  14274. svr.stop();
  14275. t.join();
  14276. ASSERT_FALSE(svr.is_running());
  14277. });
  14278. svr.wait_until_ready();
  14279. SSLClient cli("127.0.0.1", PORT);
  14280. std::string cert;
  14281. read_file(SERVER_CERT2_FILE, cert);
  14282. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14283. cli.enable_server_certificate_verification(true);
  14284. cli.set_connection_timeout(30);
  14285. auto res = cli.Get("/test");
  14286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14287. ASSERT_EQ(StatusCode::OK_200, res->status);
  14288. }
  14289. // CA certs loaded through the universal Client must be transferred to the
  14290. // client created internally for following an HTTPS redirect. Regression test:
  14291. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  14292. // the CA data for redirect transfer.
  14293. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  14294. auto ssl_port = PORT + 1;
  14295. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14296. ASSERT_TRUE(ssl_svr1.is_valid());
  14297. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14298. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14299. "/index");
  14300. });
  14301. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14302. ASSERT_TRUE(ssl_svr2.is_valid());
  14303. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14304. res.set_content("test", "text/plain");
  14305. });
  14306. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14307. thread t2 =
  14308. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14309. auto se = detail::scope_exit([&] {
  14310. ssl_svr2.stop();
  14311. ssl_svr1.stop();
  14312. t2.join();
  14313. t.join();
  14314. ASSERT_FALSE(ssl_svr1.is_running());
  14315. });
  14316. ssl_svr1.wait_until_ready();
  14317. ssl_svr2.wait_until_ready();
  14318. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14319. std::string cert;
  14320. read_file(SERVER_CERT2_FILE, cert);
  14321. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14322. cli.enable_server_certificate_verification(true);
  14323. cli.set_follow_location(true);
  14324. cli.set_connection_timeout(30);
  14325. auto res = cli.Get("/index");
  14326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14327. ASSERT_EQ(StatusCode::OK_200, res->status);
  14328. }
  14329. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  14330. // so a host signed by a system CA verifies even though a custom CA is set
  14331. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  14332. std::string cert;
  14333. read_file(SERVER_CERT2_FILE, cert);
  14334. SSLClient cli("google.com");
  14335. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14336. cli.enable_system_ca(true);
  14337. cli.enable_server_certificate_verification(true);
  14338. auto res = cli.Get("/");
  14339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14340. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14341. }
  14342. // The custom CA remains effective when combined with the system CA
  14343. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  14344. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14345. ASSERT_TRUE(svr.is_valid());
  14346. svr.Get("/test", [&](const Request &, Response &res) {
  14347. res.set_content("test", "text/plain");
  14348. });
  14349. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14350. auto se = detail::scope_exit([&] {
  14351. svr.stop();
  14352. t.join();
  14353. ASSERT_FALSE(svr.is_running());
  14354. });
  14355. svr.wait_until_ready();
  14356. SSLClient cli("127.0.0.1", PORT);
  14357. std::string cert;
  14358. read_file(SERVER_CERT2_FILE, cert);
  14359. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14360. cli.enable_system_ca(true);
  14361. cli.enable_server_certificate_verification(true);
  14362. cli.set_connection_timeout(30);
  14363. auto res = cli.Get("/test");
  14364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14365. ASSERT_EQ(StatusCode::OK_200, res->status);
  14366. }
  14367. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  14368. // skip chain verification entirely (only the certificate identity was
  14369. // checked), so a server presenting an untrusted certificate with a matching
  14370. // IP SAN was accepted. The chain must be validated for IP hosts too.
  14371. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  14372. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14373. ASSERT_TRUE(svr.is_valid());
  14374. svr.Get("/test", [&](const Request &, Response &res) {
  14375. res.set_content("test", "text/plain");
  14376. });
  14377. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14378. auto se = detail::scope_exit([&] {
  14379. svr.stop();
  14380. t.join();
  14381. ASSERT_FALSE(svr.is_running());
  14382. });
  14383. svr.wait_until_ready();
  14384. SSLClient cli("127.0.0.1", PORT);
  14385. std::string cert;
  14386. // A trusted CA that did not sign the server certificate. The server cert
  14387. // (cert2) carries the matching IP SAN, so only chain validation can reject
  14388. // this connection.
  14389. read_file(CLIENT_CA_CERT_FILE, cert);
  14390. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14391. cli.enable_server_certificate_verification(true);
  14392. cli.set_connection_timeout(30);
  14393. auto res = cli.Get("/test");
  14394. ASSERT_FALSE(res);
  14395. }
  14396. // enable_system_ca(false) prevents system CA loading entirely
  14397. TEST(SSLClientTest, DisableSystemCa_Online) {
  14398. SSLClient cli("google.com");
  14399. cli.enable_system_ca(false);
  14400. cli.enable_server_certificate_verification(true);
  14401. auto res = cli.Get("/");
  14402. ASSERT_FALSE(res);
  14403. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  14404. // itself when the CA chain is empty
  14405. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  14406. res.error() == Error::SSLConnection);
  14407. }
  14408. // The universal Client forwards enable_system_ca()
  14409. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  14410. std::string cert;
  14411. read_file(SERVER_CERT2_FILE, cert);
  14412. Client cli("https://google.com");
  14413. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14414. cli.enable_system_ca(true);
  14415. cli.enable_server_certificate_verification(true);
  14416. auto res = cli.Get("/");
  14417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14418. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14419. }
  14420. // The system CA policy must carry over to the client created internally for
  14421. // following a cross-host HTTPS redirect
  14422. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  14423. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14424. ASSERT_TRUE(svr.is_valid());
  14425. svr.Get("/index", [&](const Request &, Response &res) {
  14426. res.set_redirect("https://www.google.com/");
  14427. });
  14428. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14429. auto se = detail::scope_exit([&] {
  14430. svr.stop();
  14431. t.join();
  14432. ASSERT_FALSE(svr.is_running());
  14433. });
  14434. svr.wait_until_ready();
  14435. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14436. std::string cert;
  14437. read_file(SERVER_CERT2_FILE, cert);
  14438. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14439. cli.enable_system_ca(true);
  14440. cli.enable_server_certificate_verification(true);
  14441. cli.set_follow_location(true);
  14442. cli.set_connection_timeout(30);
  14443. // Receiving any response proves the redirect client completed the TLS
  14444. // handshake with a system-CA-signed host
  14445. auto res = cli.Get("/index");
  14446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14447. }
  14448. TEST(MultipartFormDataTest, LargeData) {
  14449. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14450. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  14451. const ContentReader &content_reader) {
  14452. if (req.is_multipart_form_data()) {
  14453. std::vector<FormData> items;
  14454. content_reader(
  14455. [&](const FormData &file) {
  14456. items.push_back(file);
  14457. return true;
  14458. },
  14459. [&](const char *data, size_t data_length) {
  14460. items.back().content.append(data, data_length);
  14461. return true;
  14462. });
  14463. EXPECT_TRUE(std::string(items[0].name) == "document");
  14464. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14465. EXPECT_TRUE(items[0].filename == "2MB_data");
  14466. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14467. EXPECT_TRUE(items[1].name == "hello");
  14468. EXPECT_TRUE(items[1].content == "world");
  14469. EXPECT_TRUE(items[1].filename == "");
  14470. EXPECT_TRUE(items[1].content_type == "");
  14471. } else {
  14472. std::string body;
  14473. content_reader([&](const char *data, size_t data_length) {
  14474. body.append(data, data_length);
  14475. return true;
  14476. });
  14477. }
  14478. });
  14479. auto port = svr.bind_to_any_port(HOST);
  14480. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14481. auto se = detail::scope_exit([&] {
  14482. svr.stop();
  14483. t.join();
  14484. ASSERT_FALSE(svr.is_running());
  14485. });
  14486. svr.wait_until_ready();
  14487. {
  14488. std::string data(1024 * 1024 * 2, '.');
  14489. std::stringstream buffer;
  14490. buffer << data;
  14491. SSLClient cli(HOST, port);
  14492. cli.enable_server_certificate_verification(false);
  14493. UploadFormDataItems items{
  14494. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14495. {"hello", "world", "", ""},
  14496. };
  14497. auto res = cli.Post("/post", items);
  14498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14499. ASSERT_EQ(StatusCode::OK_200, res->status);
  14500. }
  14501. }
  14502. TEST(MultipartFormDataTest, DataProviderItems) {
  14503. std::random_device seed_gen;
  14504. std::mt19937 random(seed_gen());
  14505. std::string rand1;
  14506. rand1.resize(1000);
  14507. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  14508. std::string rand2;
  14509. rand2.resize(3000);
  14510. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  14511. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14512. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  14513. const ContentReader &content_reader) {
  14514. ASSERT_FALSE(req.is_multipart_form_data());
  14515. std::string body;
  14516. content_reader([&](const char *data, size_t data_length) {
  14517. body.append(data, data_length);
  14518. return true;
  14519. });
  14520. EXPECT_EQ(body, "");
  14521. });
  14522. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  14523. const ContentReader &content_reader) {
  14524. ASSERT_TRUE(req.is_multipart_form_data());
  14525. std::vector<FormData> items;
  14526. content_reader(
  14527. [&](const FormData &file) {
  14528. items.push_back(file);
  14529. return true;
  14530. },
  14531. [&](const char *data, size_t data_length) {
  14532. items.back().content.append(data, data_length);
  14533. return true;
  14534. });
  14535. ASSERT_TRUE(items.size() == 2);
  14536. EXPECT_EQ(std::string(items[0].name), "name1");
  14537. EXPECT_EQ(items[0].content, "Testing123");
  14538. EXPECT_EQ(items[0].filename, "filename1");
  14539. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14540. EXPECT_EQ(items[1].name, "name2");
  14541. EXPECT_EQ(items[1].content, "Testing456");
  14542. EXPECT_EQ(items[1].filename, "");
  14543. EXPECT_EQ(items[1].content_type, "");
  14544. });
  14545. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  14546. const ContentReader &content_reader) {
  14547. ASSERT_TRUE(req.is_multipart_form_data());
  14548. std::vector<FormData> items;
  14549. content_reader(
  14550. [&](const FormData &file) {
  14551. items.push_back(file);
  14552. return true;
  14553. },
  14554. [&](const char *data, size_t data_length) {
  14555. items.back().content.append(data, data_length);
  14556. return true;
  14557. });
  14558. ASSERT_TRUE(items.size() == 2);
  14559. EXPECT_EQ(items[0].name, "name3");
  14560. EXPECT_EQ(items[0].content, rand1);
  14561. EXPECT_EQ(items[0].filename, "filename3");
  14562. EXPECT_EQ(items[0].content_type, "");
  14563. EXPECT_EQ(items[1].name, "name4");
  14564. EXPECT_EQ(items[1].content, rand2);
  14565. EXPECT_EQ(items[1].filename, "filename4");
  14566. EXPECT_EQ(items[1].content_type, "");
  14567. });
  14568. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  14569. const ContentReader &content_reader) {
  14570. ASSERT_TRUE(req.is_multipart_form_data());
  14571. std::vector<FormData> items;
  14572. content_reader(
  14573. [&](const FormData &file) {
  14574. items.push_back(file);
  14575. return true;
  14576. },
  14577. [&](const char *data, size_t data_length) {
  14578. items.back().content.append(data, data_length);
  14579. return true;
  14580. });
  14581. ASSERT_TRUE(items.size() == 4);
  14582. EXPECT_EQ(std::string(items[0].name), "name1");
  14583. EXPECT_EQ(items[0].content, "Testing123");
  14584. EXPECT_EQ(items[0].filename, "filename1");
  14585. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14586. EXPECT_EQ(items[1].name, "name2");
  14587. EXPECT_EQ(items[1].content, "Testing456");
  14588. EXPECT_EQ(items[1].filename, "");
  14589. EXPECT_EQ(items[1].content_type, "");
  14590. EXPECT_EQ(items[2].name, "name3");
  14591. EXPECT_EQ(items[2].content, rand1);
  14592. EXPECT_EQ(items[2].filename, "filename3");
  14593. EXPECT_EQ(items[2].content_type, "");
  14594. EXPECT_EQ(items[3].name, "name4");
  14595. EXPECT_EQ(items[3].content, rand2);
  14596. EXPECT_EQ(items[3].filename, "filename4");
  14597. EXPECT_EQ(items[3].content_type, "");
  14598. });
  14599. auto port = svr.bind_to_any_port("localhost");
  14600. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14601. auto se = detail::scope_exit([&] {
  14602. svr.stop();
  14603. t.join();
  14604. ASSERT_FALSE(svr.is_running());
  14605. });
  14606. svr.wait_until_ready();
  14607. {
  14608. SSLClient cli("localhost", port);
  14609. cli.enable_server_certificate_verification(false);
  14610. UploadFormDataItems items{
  14611. {"name1", "Testing123", "filename1", "application/octet-stream"},
  14612. {"name2", "Testing456", "", ""}, // not a file
  14613. };
  14614. {
  14615. auto res = cli.Post("/post-none", {}, {}, {});
  14616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14617. ASSERT_EQ(StatusCode::OK_200, res->status);
  14618. }
  14619. FormDataProviderItems providers;
  14620. {
  14621. auto res =
  14622. cli.Post("/post-items", {}, items, providers); // empty providers
  14623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14624. ASSERT_EQ(StatusCode::OK_200, res->status);
  14625. }
  14626. providers.push_back({"name3",
  14627. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14628. // test the offset is given correctly at each step
  14629. if (!offset)
  14630. sink.os.write(rand1.data(), 30);
  14631. else if (offset == 30)
  14632. sink.os.write(rand1.data() + 30, 300);
  14633. else if (offset == 330)
  14634. sink.os.write(rand1.data() + 330, 670);
  14635. else if (offset == rand1.size())
  14636. sink.done();
  14637. return true;
  14638. },
  14639. "filename3",
  14640. {}});
  14641. providers.push_back({"name4",
  14642. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14643. // test the offset is given correctly at each step
  14644. if (!offset)
  14645. sink.os.write(rand2.data(), 2000);
  14646. else if (offset == 2000)
  14647. sink.os.write(rand2.data() + 2000, 1);
  14648. else if (offset == 2001)
  14649. sink.os.write(rand2.data() + 2001, 999);
  14650. else if (offset == rand2.size())
  14651. sink.done();
  14652. return true;
  14653. },
  14654. "filename4",
  14655. {}});
  14656. {
  14657. auto res = cli.Post("/post-providers", {}, {}, providers);
  14658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14659. ASSERT_EQ(StatusCode::OK_200, res->status);
  14660. }
  14661. {
  14662. auto res = cli.Post("/post-both", {}, items, providers);
  14663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14664. ASSERT_EQ(StatusCode::OK_200, res->status);
  14665. }
  14666. }
  14667. }
  14668. TEST(MultipartFormDataTest, BadHeader) {
  14669. Server svr;
  14670. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14671. res.set_content("ok", "text/plain");
  14672. });
  14673. thread t = thread([&] { svr.listen(HOST, PORT); });
  14674. auto se = detail::scope_exit([&] {
  14675. svr.stop();
  14676. t.join();
  14677. ASSERT_FALSE(svr.is_running());
  14678. });
  14679. svr.wait_until_ready();
  14680. const std::string body =
  14681. "This is the preamble. It is to be ignored, though it\r\n"
  14682. "is a handy place for composition agents to include an\r\n"
  14683. "explanatory note to non-MIME conformant readers.\r\n"
  14684. "\r\n"
  14685. "\r\n"
  14686. "--simple boundary\r\n"
  14687. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14688. ": BAD...\r\n"
  14689. "\r\n"
  14690. "value1\r\n"
  14691. "--simple boundary\r\n"
  14692. "Content-Disposition: form-data; name=\"field2\"; "
  14693. "filename=\"example.txt\"\r\n"
  14694. "\r\n"
  14695. "value2\r\n"
  14696. "--simple boundary--\r\n"
  14697. "This is the epilogue. It is also to be ignored.\r\n";
  14698. std::string content_type =
  14699. R"(multipart/form-data; boundary="simple boundary")";
  14700. Client cli(HOST, PORT);
  14701. auto res = cli.Post("/post", body, content_type.c_str());
  14702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14703. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14704. }
  14705. TEST(MultipartFormDataTest, WithPreamble) {
  14706. Server svr;
  14707. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14708. res.set_content("ok", "text/plain");
  14709. });
  14710. thread t = thread([&] { svr.listen(HOST, PORT); });
  14711. auto se = detail::scope_exit([&] {
  14712. svr.stop();
  14713. t.join();
  14714. ASSERT_FALSE(svr.is_running());
  14715. });
  14716. svr.wait_until_ready();
  14717. const std::string body =
  14718. "This is the preamble. It is to be ignored, though it\r\n"
  14719. "is a handy place for composition agents to include an\r\n"
  14720. "explanatory note to non-MIME conformant readers.\r\n"
  14721. "\r\n"
  14722. "\r\n"
  14723. "--simple boundary\r\n"
  14724. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14725. "\r\n"
  14726. "value1\r\n"
  14727. "--simple boundary\r\n"
  14728. "Content-Disposition: form-data; name=\"field2\"; "
  14729. "filename=\"example.txt\"\r\n"
  14730. "\r\n"
  14731. "value2\r\n"
  14732. "--simple boundary--\r\n"
  14733. "This is the epilogue. It is also to be ignored.\r\n";
  14734. std::string content_type =
  14735. R"(multipart/form-data; boundary="simple boundary")";
  14736. Client cli(HOST, PORT);
  14737. auto res = cli.Post("/post", body, content_type.c_str());
  14738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14739. EXPECT_EQ(StatusCode::OK_200, res->status);
  14740. }
  14741. TEST(MultipartFormDataTest, PostCustomBoundary) {
  14742. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14743. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  14744. const ContentReader &content_reader) {
  14745. if (req.is_multipart_form_data()) {
  14746. std::vector<FormData> items;
  14747. content_reader(
  14748. [&](const FormData &file) {
  14749. items.push_back(file);
  14750. return true;
  14751. },
  14752. [&](const char *data, size_t data_length) {
  14753. items.back().content.append(data, data_length);
  14754. return true;
  14755. });
  14756. EXPECT_TRUE(std::string(items[0].name) == "document");
  14757. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14758. EXPECT_TRUE(items[0].filename == "2MB_data");
  14759. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14760. EXPECT_TRUE(items[1].name == "hello");
  14761. EXPECT_TRUE(items[1].content == "world");
  14762. EXPECT_TRUE(items[1].filename == "");
  14763. EXPECT_TRUE(items[1].content_type == "");
  14764. } else {
  14765. std::string body;
  14766. content_reader([&](const char *data, size_t data_length) {
  14767. body.append(data, data_length);
  14768. return true;
  14769. });
  14770. }
  14771. });
  14772. auto port = svr.bind_to_any_port("localhost");
  14773. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14774. auto se = detail::scope_exit([&] {
  14775. svr.stop();
  14776. t.join();
  14777. ASSERT_FALSE(svr.is_running());
  14778. });
  14779. svr.wait_until_ready();
  14780. {
  14781. std::string data(1024 * 1024 * 2, '.');
  14782. std::stringstream buffer;
  14783. buffer << data;
  14784. SSLClient cli("localhost", port);
  14785. cli.enable_server_certificate_verification(false);
  14786. UploadFormDataItems items{
  14787. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14788. {"hello", "world", "", ""},
  14789. };
  14790. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  14791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14792. ASSERT_EQ(StatusCode::OK_200, res->status);
  14793. }
  14794. }
  14795. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  14796. std::string data(1024 * 1024 * 2, '&');
  14797. std::stringstream buffer;
  14798. buffer << data;
  14799. Client cli("https://localhost:8080");
  14800. UploadFormDataItems items{
  14801. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14802. {"hello", "world", "", ""},
  14803. };
  14804. for (const char &c : " \t\r\n") {
  14805. auto res =
  14806. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  14807. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14808. ASSERT_FALSE(res);
  14809. }
  14810. }
  14811. TEST(MultipartFormDataTest, PutFormData) {
  14812. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14813. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  14814. const ContentReader &content_reader) {
  14815. if (req.is_multipart_form_data()) {
  14816. std::vector<FormData> items;
  14817. content_reader(
  14818. [&](const FormData &file) {
  14819. items.push_back(file);
  14820. return true;
  14821. },
  14822. [&](const char *data, size_t data_length) {
  14823. items.back().content.append(data, data_length);
  14824. return true;
  14825. });
  14826. EXPECT_TRUE(std::string(items[0].name) == "document");
  14827. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14828. EXPECT_TRUE(items[0].filename == "2MB_data");
  14829. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14830. EXPECT_TRUE(items[1].name == "hello");
  14831. EXPECT_TRUE(items[1].content == "world");
  14832. EXPECT_TRUE(items[1].filename == "");
  14833. EXPECT_TRUE(items[1].content_type == "");
  14834. } else {
  14835. std::string body;
  14836. content_reader([&](const char *data, size_t data_length) {
  14837. body.append(data, data_length);
  14838. return true;
  14839. });
  14840. }
  14841. });
  14842. auto port = svr.bind_to_any_port("localhost");
  14843. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14844. auto se = detail::scope_exit([&] {
  14845. svr.stop();
  14846. t.join();
  14847. ASSERT_FALSE(svr.is_running());
  14848. });
  14849. svr.wait_until_ready();
  14850. {
  14851. std::string data(1024 * 1024 * 2, '&');
  14852. std::stringstream buffer;
  14853. buffer << data;
  14854. SSLClient cli("localhost", port);
  14855. cli.enable_server_certificate_verification(false);
  14856. UploadFormDataItems items{
  14857. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14858. {"hello", "world", "", ""},
  14859. };
  14860. auto res = cli.Put("/put", items);
  14861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14862. ASSERT_EQ(StatusCode::OK_200, res->status);
  14863. }
  14864. }
  14865. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  14866. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14867. svr.Put("/put_customboundary",
  14868. [&](const Request &req, const Response & /*res*/,
  14869. const ContentReader &content_reader) {
  14870. if (req.is_multipart_form_data()) {
  14871. std::vector<FormData> items;
  14872. content_reader(
  14873. [&](const FormData &file) {
  14874. items.push_back(file);
  14875. return true;
  14876. },
  14877. [&](const char *data, size_t data_length) {
  14878. items.back().content.append(data, data_length);
  14879. return true;
  14880. });
  14881. EXPECT_TRUE(std::string(items[0].name) == "document");
  14882. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14883. EXPECT_TRUE(items[0].filename == "2MB_data");
  14884. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14885. EXPECT_TRUE(items[1].name == "hello");
  14886. EXPECT_TRUE(items[1].content == "world");
  14887. EXPECT_TRUE(items[1].filename == "");
  14888. EXPECT_TRUE(items[1].content_type == "");
  14889. } else {
  14890. std::string body;
  14891. content_reader([&](const char *data, size_t data_length) {
  14892. body.append(data, data_length);
  14893. return true;
  14894. });
  14895. }
  14896. });
  14897. auto port = svr.bind_to_any_port("localhost");
  14898. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14899. auto se = detail::scope_exit([&] {
  14900. svr.stop();
  14901. t.join();
  14902. ASSERT_FALSE(svr.is_running());
  14903. });
  14904. svr.wait_until_ready();
  14905. {
  14906. std::string data(1024 * 1024 * 2, '&');
  14907. std::stringstream buffer;
  14908. buffer << data;
  14909. SSLClient cli("localhost", port);
  14910. cli.enable_server_certificate_verification(false);
  14911. UploadFormDataItems items{
  14912. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14913. {"hello", "world", "", ""},
  14914. };
  14915. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  14916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14917. ASSERT_EQ(StatusCode::OK_200, res->status);
  14918. }
  14919. }
  14920. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  14921. std::string data(1024 * 1024 * 2, '&');
  14922. std::stringstream buffer;
  14923. buffer << data;
  14924. Client cli("https://localhost:8080");
  14925. cli.enable_server_certificate_verification(false);
  14926. UploadFormDataItems items{
  14927. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14928. {"hello", "world", "", ""},
  14929. };
  14930. for (const char &c : " \t\r\n") {
  14931. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  14932. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14933. ASSERT_FALSE(res);
  14934. }
  14935. }
  14936. TEST(MultipartFormDataTest, AlternateFilename) {
  14937. auto handled = false;
  14938. Server svr;
  14939. svr.Post("/test", [&](const Request &req, Response &res) {
  14940. ASSERT_EQ(2u, req.form.files.size());
  14941. ASSERT_EQ(1u, req.form.fields.size());
  14942. // Test files
  14943. const auto &file1 = req.form.get_file("file1");
  14944. ASSERT_EQ("file1", file1.name);
  14945. ASSERT_EQ("A.txt", file1.filename);
  14946. ASSERT_EQ("text/plain", file1.content_type);
  14947. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  14948. const auto &file2 = req.form.get_file("file2");
  14949. ASSERT_EQ("file2", file2.name);
  14950. ASSERT_EQ("a.html", file2.filename);
  14951. ASSERT_EQ("text/html", file2.content_type);
  14952. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  14953. file2.content);
  14954. // Test text field
  14955. const auto &text = req.form.get_field("text");
  14956. ASSERT_EQ("text default", text);
  14957. res.set_content("ok", "text/plain");
  14958. handled = true;
  14959. });
  14960. thread t = thread([&] { svr.listen(HOST, PORT); });
  14961. auto se = detail::scope_exit([&] {
  14962. svr.stop();
  14963. t.join();
  14964. ASSERT_FALSE(svr.is_running());
  14965. ASSERT_TRUE(handled);
  14966. });
  14967. svr.wait_until_ready();
  14968. auto req = "POST /test HTTP/1.1\r\n"
  14969. "Host: localhost\r\n"
  14970. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14971. "Content-Length: 399\r\n"
  14972. "\r\n"
  14973. "----------\r\n"
  14974. "Content-Disposition: form-data; name=\"text\"\r\n"
  14975. "\r\n"
  14976. "text default\r\n"
  14977. "----------\r\n"
  14978. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  14979. "filename=\"a.txt\"; name=\"file1\"\r\n"
  14980. "Content-Type: text/plain\r\n"
  14981. "\r\n"
  14982. "Content of a.txt.\r\n"
  14983. "\r\n"
  14984. "----------\r\n"
  14985. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  14986. "\"a.html\"\r\n"
  14987. "Content-Type: text/html\r\n"
  14988. "\r\n"
  14989. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  14990. "\r\n"
  14991. "------------\r\n";
  14992. ASSERT_TRUE(send_request(1, req));
  14993. }
  14994. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  14995. auto handled = false;
  14996. Server svr;
  14997. svr.Post("/test", [&](const Request &req, Response &res) {
  14998. // Case-insensitive "utf-8''" prefix with a long value
  14999. const auto &file = req.form.get_file("file1");
  15000. ASSERT_EQ("file1", file.name);
  15001. // 8000 chars exercises both the Content-Disposition parser and the
  15002. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  15003. // Prior to the fix, std::regex_match on this header would cause O(N)
  15004. // stack recursion in libstdc++, leading to SIGSEGV.
  15005. std::string expected_filename(8000, 'A');
  15006. ASSERT_EQ(expected_filename, file.filename);
  15007. res.set_content("ok", "text/plain");
  15008. handled = true;
  15009. });
  15010. thread t = thread([&] { svr.listen(HOST, PORT); });
  15011. auto se = detail::scope_exit([&] {
  15012. svr.stop();
  15013. t.join();
  15014. ASSERT_FALSE(svr.is_running());
  15015. ASSERT_TRUE(handled);
  15016. });
  15017. svr.wait_until_ready();
  15018. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  15019. // Regression test for GHSA-qq6v-r583-3h69
  15020. std::string long_filename(8000, 'A');
  15021. std::string body = "----------\r\n"
  15022. "Content-Disposition: form-data; name=\"file1\"; "
  15023. "filename*=\"Utf-8''" +
  15024. long_filename +
  15025. "\"\r\n"
  15026. "\r\n"
  15027. "hello\r\n"
  15028. "------------\r\n";
  15029. auto req = "POST /test HTTP/1.1\r\n"
  15030. "Host: localhost\r\n"
  15031. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15032. "Content-Length: " +
  15033. std::to_string(body.size()) + "\r\n\r\n" + body;
  15034. ASSERT_TRUE(send_request(1, req));
  15035. }
  15036. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  15037. auto handled = false;
  15038. Server svr;
  15039. svr.Post("/test", [&](const Request &req, Response &) {
  15040. ASSERT_EQ(2u, req.form.fields.size());
  15041. const auto &text1 = req.form.get_field("text1");
  15042. ASSERT_EQ("text1", text1);
  15043. const auto &text2 = req.form.get_field("text2");
  15044. ASSERT_EQ("text2", text2);
  15045. handled = true;
  15046. });
  15047. thread t = thread([&] { svr.listen(HOST, PORT); });
  15048. auto se = detail::scope_exit([&] {
  15049. svr.stop();
  15050. t.join();
  15051. ASSERT_FALSE(svr.is_running());
  15052. ASSERT_TRUE(handled);
  15053. });
  15054. svr.wait_until_ready();
  15055. auto req = "POST /test HTTP/1.1\r\n"
  15056. "Host: localhost\r\n"
  15057. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15058. "Content-Length: 146\r\n"
  15059. "\r\n----------\r\n"
  15060. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15061. "\r\n"
  15062. "text1"
  15063. "\r\n----------\r\n"
  15064. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15065. "\r\n"
  15066. "text2"
  15067. "\r\n------------";
  15068. std::string response;
  15069. ASSERT_TRUE(send_request(1, req, &response));
  15070. ASSERT_EQ("200", response.substr(9, 3));
  15071. }
  15072. TEST(MultipartFormDataTest, ContentLength) {
  15073. auto handled = false;
  15074. Server svr;
  15075. svr.Post("/test", [&](const Request &req, Response &) {
  15076. ASSERT_EQ(2u, req.form.fields.size());
  15077. const auto &text1 = req.form.get_field("text1");
  15078. ASSERT_EQ("text1", text1);
  15079. const auto &text2 = req.form.get_field("text2");
  15080. ASSERT_EQ("text2", text2);
  15081. handled = true;
  15082. });
  15083. thread t = thread([&] { svr.listen(HOST, PORT); });
  15084. auto se = detail::scope_exit([&] {
  15085. svr.stop();
  15086. t.join();
  15087. ASSERT_FALSE(svr.is_running());
  15088. ASSERT_TRUE(handled);
  15089. });
  15090. svr.wait_until_ready();
  15091. auto req = "POST /test HTTP/1.1\r\n"
  15092. "Host: localhost\r\n"
  15093. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15094. "Content-Length: 167\r\n"
  15095. "\r\n----------\r\n"
  15096. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15097. "Content-Length: 5\r\n"
  15098. "\r\n"
  15099. "text1"
  15100. "\r\n----------\r\n"
  15101. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15102. "\r\n"
  15103. "text2"
  15104. "\r\n------------\r\n";
  15105. std::string response;
  15106. ASSERT_TRUE(send_request(1, req, &response));
  15107. ASSERT_EQ("200", response.substr(9, 3));
  15108. }
  15109. TEST(MultipartFormDataTest, AccessPartHeaders) {
  15110. auto handled = false;
  15111. Server svr;
  15112. svr.Post("/test", [&](const Request &req, Response &) {
  15113. ASSERT_EQ(2u, req.form.fields.size());
  15114. const auto &text1 = req.form.get_field("text1");
  15115. ASSERT_EQ("text1", text1);
  15116. // TODO: Add header access for text fields if needed
  15117. const auto &text2 = req.form.get_field("text2");
  15118. ASSERT_EQ("text2", text2);
  15119. // TODO: Header access for text fields needs to be implemented
  15120. // auto &headers = it->second.headers;
  15121. // ASSERT_EQ(3U, headers.size());
  15122. // auto custom_header = headers.find("x-whatever");
  15123. // ASSERT_TRUE(custom_header != headers.end());
  15124. // ASSERT_NE("customvalue", custom_header->second);
  15125. // ASSERT_EQ("CustomValue", custom_header->second);
  15126. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  15127. handled = true;
  15128. });
  15129. thread t = thread([&] { svr.listen(HOST, PORT); });
  15130. auto se = detail::scope_exit([&] {
  15131. svr.stop();
  15132. t.join();
  15133. ASSERT_FALSE(svr.is_running());
  15134. ASSERT_TRUE(handled);
  15135. });
  15136. svr.wait_until_ready();
  15137. auto req = "POST /test HTTP/1.1\r\n"
  15138. "Host: localhost\r\n"
  15139. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15140. "Content-Length: 232\r\n"
  15141. "\r\n----------\r\n"
  15142. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15143. "Content-Length: 5\r\n"
  15144. "X-Test: 1\r\n"
  15145. "\r\n"
  15146. "text1"
  15147. "\r\n----------\r\n"
  15148. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15149. "Content-Type: text/plain\r\n"
  15150. "X-Whatever: CustomValue\r\n"
  15151. "\r\n"
  15152. "text2"
  15153. "\r\n------------\r\n"
  15154. "That should be disregarded. Not even read";
  15155. std::string response;
  15156. ASSERT_TRUE(send_request(1, req, &response));
  15157. ASSERT_EQ("200", response.substr(9, 3));
  15158. }
  15159. TEST(MultipartFormDataTest, LargeHeader) {
  15160. auto handled = false;
  15161. Server svr;
  15162. svr.Post("/test", [&](const Request &req, Response &) {
  15163. ASSERT_EQ(1u, req.form.fields.size());
  15164. const auto &text = req.form.get_field("name1");
  15165. ASSERT_EQ("text1", text);
  15166. handled = true;
  15167. });
  15168. thread t = thread([&] { svr.listen(HOST, PORT); });
  15169. auto se = detail::scope_exit([&] {
  15170. svr.stop();
  15171. t.join();
  15172. ASSERT_FALSE(svr.is_running());
  15173. ASSERT_TRUE(handled);
  15174. });
  15175. svr.wait_until_ready();
  15176. auto boundary = std::string("cpp-httplib-multipart-data");
  15177. std::string content = "--" + boundary +
  15178. "\r\n"
  15179. "Content-Disposition: form-data; name=\"name1\"\r\n"
  15180. "\r\n"
  15181. "text1\r\n"
  15182. "--" +
  15183. boundary + "--\r\n";
  15184. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  15185. "Host: localhost\r\n"
  15186. "Content-Type: multipart/form-data;boundary=" +
  15187. boundary +
  15188. "\r\n"
  15189. "Content-Length: " +
  15190. std::to_string(content.size()) +
  15191. "\r\n"
  15192. "Dummy-Header: ";
  15193. std::string header_suffix = "\r\n"
  15194. "\r\n";
  15195. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  15196. size_t header_dummy_size =
  15197. read_buff_size -
  15198. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  15199. auto header_dummy = std::string(header_dummy_size, '@');
  15200. auto req = header_prefix + header_dummy + header_suffix + content;
  15201. std::string response;
  15202. ASSERT_TRUE(send_request(1, req, &response));
  15203. ASSERT_EQ("200", response.substr(9, 3));
  15204. }
  15205. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  15206. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  15207. // (not chunked Transfer-Encoding) after the streaming refactor.
  15208. auto handled = false;
  15209. Server svr;
  15210. svr.Post("/upload", [&](const Request &req, Response &res) {
  15211. auto cl_it = req.headers.find("Content-Length");
  15212. EXPECT_TRUE(cl_it != req.headers.end());
  15213. auto te_it = req.headers.find("Transfer-Encoding");
  15214. EXPECT_TRUE(te_it == req.headers.end());
  15215. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  15216. res.set_content("ok", "text/plain");
  15217. handled = true;
  15218. });
  15219. auto port = svr.bind_to_any_port(HOST);
  15220. auto t = thread([&] { svr.listen_after_bind(); });
  15221. auto se = detail::scope_exit([&] {
  15222. svr.stop();
  15223. t.join();
  15224. ASSERT_FALSE(svr.is_running());
  15225. ASSERT_TRUE(handled);
  15226. });
  15227. svr.wait_until_ready();
  15228. UploadFormDataItems items = {
  15229. {"field1", "hello", "", "text/plain"},
  15230. {"file1", "world", "test.txt", "application/octet-stream"},
  15231. };
  15232. Client cli(HOST, port);
  15233. auto res = cli.Post("/upload", {}, items);
  15234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15235. EXPECT_EQ(StatusCode::OK_200, res->status);
  15236. }
  15237. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  15238. // Verify that make_multipart_content_provider coalesces many small segments
  15239. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  15240. constexpr size_t kItemCount = 1000;
  15241. UploadFormDataItems items;
  15242. items.reserve(kItemCount);
  15243. for (size_t i = 0; i < kItemCount; i++) {
  15244. items.push_back(
  15245. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15246. }
  15247. const std::string boundary = "----test-boundary";
  15248. auto content_length = detail::get_multipart_content_length(items, boundary);
  15249. auto provider = detail::make_multipart_content_provider(items, boundary);
  15250. // Drive the provider the same way write_content_with_progress does
  15251. size_t write_count = 0;
  15252. size_t total_bytes = 0;
  15253. DataSink sink;
  15254. size_t offset = 0;
  15255. sink.write = [&](const char *d, size_t l) -> bool {
  15256. (void)d;
  15257. write_count++;
  15258. total_bytes += l;
  15259. offset += l;
  15260. return true;
  15261. };
  15262. sink.is_writable = []() -> bool { return true; };
  15263. while (offset < content_length) {
  15264. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  15265. }
  15266. EXPECT_EQ(content_length, total_bytes);
  15267. // The total number of segments is 3 * kItemCount + 1 = 3001.
  15268. // With buffering into 64KB blocks, write_count should be much smaller.
  15269. auto segment_count = 3 * kItemCount + 1;
  15270. EXPECT_LT(write_count, segment_count / 10);
  15271. }
  15272. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  15273. // Integration test: send many UploadFormDataItems and verify the server
  15274. // receives all of them correctly (#2410).
  15275. constexpr size_t kItemCount = 500;
  15276. auto handled = false;
  15277. Server svr;
  15278. svr.Post("/upload", [&](const Request &req, Response &res) {
  15279. EXPECT_EQ(kItemCount, req.form.fields.size());
  15280. for (size_t i = 0; i < kItemCount; i++) {
  15281. auto key = "field" + std::to_string(i);
  15282. auto val = "value" + std::to_string(i);
  15283. auto it = req.form.fields.find(key);
  15284. if (it != req.form.fields.end()) {
  15285. EXPECT_EQ(val, it->second.content);
  15286. } else {
  15287. ADD_FAILURE() << "Missing field: " << key;
  15288. }
  15289. }
  15290. res.set_content("ok", "text/plain");
  15291. handled = true;
  15292. });
  15293. auto port = svr.bind_to_any_port(HOST);
  15294. auto t = thread([&] { svr.listen_after_bind(); });
  15295. auto se = detail::scope_exit([&] {
  15296. svr.stop();
  15297. t.join();
  15298. ASSERT_FALSE(svr.is_running());
  15299. ASSERT_TRUE(handled);
  15300. });
  15301. svr.wait_until_ready();
  15302. UploadFormDataItems items;
  15303. items.reserve(kItemCount);
  15304. for (size_t i = 0; i < kItemCount; i++) {
  15305. items.push_back(
  15306. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15307. }
  15308. Client cli(HOST, port);
  15309. auto res = cli.Post("/upload", items);
  15310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15311. EXPECT_EQ(StatusCode::OK_200, res->status);
  15312. }
  15313. TEST(MultipartFormDataTest, MakeFileProvider) {
  15314. // Verify make_file_provider sends a file's contents correctly.
  15315. const std::string file_content(4096, 'Z');
  15316. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  15317. {
  15318. std::ofstream ofs(tmp_path, std::ios::binary);
  15319. ofs.write(file_content.data(),
  15320. static_cast<std::streamsize>(file_content.size()));
  15321. }
  15322. auto handled = false;
  15323. Server svr;
  15324. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  15325. const ContentReader &content_reader) {
  15326. ASSERT_TRUE(req.is_multipart_form_data());
  15327. std::vector<FormData> items;
  15328. content_reader(
  15329. [&](const FormData &file) {
  15330. items.push_back(file);
  15331. return true;
  15332. },
  15333. [&](const char *data, size_t data_length) {
  15334. items.back().content.append(data, data_length);
  15335. return true;
  15336. });
  15337. ASSERT_EQ(1u, items.size());
  15338. EXPECT_EQ("myfile", items[0].name);
  15339. EXPECT_EQ("data.bin", items[0].filename);
  15340. EXPECT_EQ("application/octet-stream", items[0].content_type);
  15341. EXPECT_EQ(file_content, items[0].content);
  15342. handled = true;
  15343. });
  15344. auto port = svr.bind_to_any_port(HOST);
  15345. auto t = thread([&] { svr.listen_after_bind(); });
  15346. auto se = detail::scope_exit([&] {
  15347. svr.stop();
  15348. t.join();
  15349. ASSERT_FALSE(svr.is_running());
  15350. ASSERT_TRUE(handled);
  15351. std::remove(tmp_path.c_str());
  15352. });
  15353. svr.wait_until_ready();
  15354. FormDataProviderItems providers;
  15355. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  15356. "application/octet-stream"));
  15357. Client cli(HOST, port);
  15358. auto res = cli.Post("/upload", {}, {}, providers);
  15359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15360. EXPECT_EQ(StatusCode::OK_200, res->status);
  15361. }
  15362. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  15363. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  15364. // (100) headers is rejected with a 400 Bad Request response.
  15365. Server svr;
  15366. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15367. res.set_content("ok", "text/plain");
  15368. });
  15369. thread t = thread([&] { svr.listen(HOST, PORT); });
  15370. auto se = detail::scope_exit([&] {
  15371. svr.stop();
  15372. t.join();
  15373. ASSERT_FALSE(svr.is_running());
  15374. });
  15375. svr.wait_until_ready();
  15376. // Build a multipart part with 101 custom headers (exceeding
  15377. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  15378. std::stringstream body;
  15379. body << "--simpleboundary\r\n"
  15380. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  15381. for (int i = 0; i < 101; i++) {
  15382. body << "X-Custom-Header-" << i << ": value\r\n";
  15383. }
  15384. body << "\r\n"
  15385. << "value1\r\n"
  15386. << "--simpleboundary--\r\n";
  15387. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  15388. Client cli(HOST, PORT);
  15389. auto res = cli.Post("/post", body.str(), content_type.c_str());
  15390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15391. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15392. }
  15393. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  15394. // A body that never contains the declared boundary must not be accumulated
  15395. // while the parser waits for it. Buffering it would also make every read
  15396. // rescan everything seen so far, which is quadratic in the body size.
  15397. Server svr;
  15398. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15399. res.set_content("ok", "text/plain");
  15400. });
  15401. auto port = svr.bind_to_any_port(HOST);
  15402. thread t = thread([&] { svr.listen_after_bind(); });
  15403. auto se = detail::scope_exit([&] {
  15404. svr.stop();
  15405. t.join();
  15406. ASSERT_FALSE(svr.is_running());
  15407. });
  15408. svr.wait_until_ready();
  15409. Client cli(HOST, port);
  15410. cli.set_read_timeout(60, 0);
  15411. cli.set_write_timeout(60, 0);
  15412. // '-' is the worst case: it matches the first character of the boundary, so
  15413. // every position has to be checked against it.
  15414. auto post_dashes = [&](size_t size) {
  15415. const std::string body(size, '-');
  15416. auto start = std::chrono::steady_clock::now();
  15417. auto res =
  15418. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  15419. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  15420. std::chrono::steady_clock::now() - start)
  15421. .count();
  15422. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15423. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  15424. return ms;
  15425. };
  15426. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  15427. // Windows.
  15428. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  15429. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  15430. // Comparing the two sizes rather than checking an absolute duration keeps
  15431. // this meaningful across build types and CI load, both of which move the
  15432. // absolute numbers by more than an order of magnitude. Four times the bytes
  15433. // costs about four times the time when parsing is linear, and about sixteen
  15434. // times when the body is buffered and rescanned.
  15435. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  15436. EXPECT_LT(ms_16mb, ms_4mb * 10)
  15437. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  15438. << "ms, which suggests the body is being buffered and rescanned";
  15439. }
  15440. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  15441. // A boundary can only be followed by CRLF or by "--", so anything else is
  15442. // malformed no matter what comes next. The parser must say so right away
  15443. // instead of buffering the rest of the declared body.
  15444. Server svr;
  15445. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15446. res.set_content("ok", "text/plain");
  15447. });
  15448. auto port = svr.bind_to_any_port(HOST);
  15449. thread t = thread([&] { svr.listen_after_bind(); });
  15450. auto se = detail::scope_exit([&] {
  15451. svr.stop();
  15452. t.join();
  15453. ASSERT_FALSE(svr.is_running());
  15454. });
  15455. svr.wait_until_ready();
  15456. // Announce a 1 MB body but send only the malformed prefix. A parser that
  15457. // buffers instead of failing would still be waiting for the remaining bytes.
  15458. const std::string body = "--zzzz\r\n"
  15459. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15460. "\r\n"
  15461. "text1"
  15462. "\r\n--zzzzXX";
  15463. const std::string req = "POST /post HTTP/1.1\r\n"
  15464. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15465. "Content-Length: 1048576\r\n"
  15466. "\r\n" +
  15467. body;
  15468. std::string response;
  15469. ASSERT_TRUE(send_request(3, req, &response, port));
  15470. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  15471. EXPECT_EQ("400", response.substr(9, 3));
  15472. }
  15473. // Posts a multipart body split into two writes, so that the server sees the
  15474. // split at whatever offset the caller chose, and expects the single "text1"
  15475. // field to come through.
  15476. static void expect_split_multipart_ok(const std::string &body1,
  15477. const std::string &body2) {
  15478. auto handled = false;
  15479. Server svr;
  15480. svr.Post("/post", [&](const Request &req, Response &) {
  15481. EXPECT_EQ(1u, req.form.fields.size());
  15482. EXPECT_EQ("text1", req.form.get_field("text1"));
  15483. handled = true;
  15484. });
  15485. auto port = svr.bind_to_any_port(HOST);
  15486. thread t = thread([&] { svr.listen_after_bind(); });
  15487. auto se = detail::scope_exit([&] {
  15488. svr.stop();
  15489. t.join();
  15490. ASSERT_FALSE(svr.is_running());
  15491. ASSERT_TRUE(handled);
  15492. });
  15493. svr.wait_until_ready();
  15494. // "Connection: close" makes the server close once it has answered, so the
  15495. // response drain ends immediately instead of idling until the read timeout.
  15496. const std::string head =
  15497. "POST /post HTTP/1.1\r\n"
  15498. "Host: localhost\r\n"
  15499. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15500. "Connection: close\r\n"
  15501. "Content-Length: " +
  15502. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  15503. std::string response;
  15504. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  15505. ASSERT_GE(response.size(), 12u) << "no response";
  15506. EXPECT_EQ("200", response.substr(9, 3));
  15507. }
  15508. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  15509. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  15510. // ignored, including when it does not arrive in the same read as the
  15511. // close-delimiter itself.
  15512. expect_split_multipart_ok("--zzzz\r\n"
  15513. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15514. "\r\n"
  15515. "text1"
  15516. "\r\n--zzzz--",
  15517. "\r\nthis epilogue must be ignored\r\n");
  15518. }
  15519. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  15520. // The initial boundary may be preceded by a preamble of any length and may
  15521. // straddle a read boundary. Discarding data while waiting for it must not
  15522. // throw away a partial boundary sitting at the end of the buffer.
  15523. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  15524. "zz\r\n"
  15525. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15526. "\r\n"
  15527. "text1"
  15528. "\r\n--zzzz--\r\n");
  15529. }
  15530. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  15531. // The received boundary was only checked for being non-empty, so it could be
  15532. // as long as a header is allowed to be. The parser scans the body for
  15533. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  15534. // costs a nearly full comparison at nearly every position, making the
  15535. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  15536. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  15537. Server svr;
  15538. svr.Post("/post", [](const Request &req, Response &res) {
  15539. EXPECT_EQ(1u, req.form.fields.size());
  15540. EXPECT_EQ("text1", req.form.get_field("text1"));
  15541. res.set_content("ok", "text/plain");
  15542. });
  15543. auto port = svr.bind_to_any_port(HOST);
  15544. thread t = thread([&] { svr.listen_after_bind(); });
  15545. auto se = detail::scope_exit([&] {
  15546. svr.stop();
  15547. t.join();
  15548. ASSERT_FALSE(svr.is_running());
  15549. });
  15550. svr.wait_until_ready();
  15551. Client cli(HOST, port);
  15552. auto post_with_boundary_of_length = [&](size_t len) {
  15553. const std::string boundary(len, 'a');
  15554. const std::string body =
  15555. "--" + boundary +
  15556. "\r\n"
  15557. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15558. "\r\n"
  15559. "text1"
  15560. "\r\n--" +
  15561. boundary + "--\r\n";
  15562. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  15563. };
  15564. auto res = post_with_boundary_of_length(70);
  15565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15566. EXPECT_EQ(StatusCode::OK_200, res->status);
  15567. res = post_with_boundary_of_length(71);
  15568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15569. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15570. }
  15571. TEST(MakeFileBodyTest, Basic) {
  15572. const std::string file_content(4096, 'Z');
  15573. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  15574. {
  15575. std::ofstream ofs(tmp_path, std::ios::binary);
  15576. ofs.write(file_content.data(),
  15577. static_cast<std::streamsize>(file_content.size()));
  15578. }
  15579. auto handled = false;
  15580. Server svr;
  15581. svr.Post("/upload", [&](const Request &req, Response &res) {
  15582. EXPECT_EQ(file_content, req.body);
  15583. handled = true;
  15584. res.status = StatusCode::OK_200;
  15585. });
  15586. auto port = svr.bind_to_any_port(HOST);
  15587. auto t = thread([&] { svr.listen_after_bind(); });
  15588. auto se = detail::scope_exit([&] {
  15589. svr.stop();
  15590. t.join();
  15591. ASSERT_FALSE(svr.is_running());
  15592. ASSERT_TRUE(handled);
  15593. std::remove(tmp_path.c_str());
  15594. });
  15595. svr.wait_until_ready();
  15596. auto fb = make_file_body(tmp_path);
  15597. ASSERT_GT(fb.first, 0u);
  15598. Client cli(HOST, port);
  15599. auto res =
  15600. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  15601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15602. EXPECT_EQ(StatusCode::OK_200, res->status);
  15603. }
  15604. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  15605. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  15606. {
  15607. std::ofstream ofs(path, std::ios::binary);
  15608. const std::string content(100, 'A');
  15609. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15610. }
  15611. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15612. auto body = make_file_body(path);
  15613. ASSERT_EQ(100u, body.first);
  15614. ASSERT_TRUE(static_cast<bool>(body.second));
  15615. // Rewritten shorter after its length was measured - and, on a server, after
  15616. // that length has already gone out as Content-Length.
  15617. {
  15618. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  15619. const std::string content(10, 'A');
  15620. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15621. }
  15622. std::string written;
  15623. DataSink sink;
  15624. sink.write = [&](const char *d, size_t l) {
  15625. written.append(d, l);
  15626. return true;
  15627. };
  15628. // The provider has to report failure. write_content_with_progress() advances
  15629. // its offset only by what was written, so a provider that returns true
  15630. // without completing the length it promised is called again straight away,
  15631. // and again.
  15632. EXPECT_FALSE(body.second(0, body.first, sink));
  15633. EXPECT_EQ(std::string(10, 'A'), written);
  15634. }
  15635. TEST(MakeFileBodyTest, WholeFileIsSent) {
  15636. const std::string path = "./httplib_test_make_file_body_whole.bin";
  15637. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  15638. {
  15639. std::ofstream ofs(path, std::ios::binary);
  15640. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15641. }
  15642. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15643. auto body = make_file_body(path);
  15644. ASSERT_EQ(content.size(), body.first);
  15645. ASSERT_TRUE(static_cast<bool>(body.second));
  15646. std::string written;
  15647. DataSink sink;
  15648. sink.write = [&](const char *d, size_t l) {
  15649. written.append(d, l);
  15650. return true;
  15651. };
  15652. EXPECT_TRUE(body.second(0, body.first, sink));
  15653. EXPECT_EQ(content, written);
  15654. }
  15655. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  15656. static constexpr unsigned int number_of_tasks{1000000};
  15657. std::atomic_uint count{0};
  15658. std::unique_ptr<TaskQueue> task_queue{
  15659. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  15660. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15661. auto queued = task_queue->enqueue(
  15662. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  15663. EXPECT_TRUE(queued);
  15664. }
  15665. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15666. task_queue->shutdown();
  15667. #else
  15668. EXPECT_NO_THROW(task_queue->shutdown());
  15669. #endif
  15670. EXPECT_EQ(number_of_tasks, count.load());
  15671. }
  15672. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  15673. static constexpr unsigned int number_of_tasks{1000000};
  15674. static constexpr unsigned int qlimit{2};
  15675. unsigned int queued_count{0};
  15676. std::atomic_uint count{0};
  15677. std::unique_ptr<TaskQueue> task_queue{
  15678. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  15679. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15680. if (task_queue->enqueue(
  15681. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  15682. queued_count++;
  15683. }
  15684. }
  15685. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15686. task_queue->shutdown();
  15687. #else
  15688. EXPECT_NO_THROW(task_queue->shutdown());
  15689. #endif
  15690. EXPECT_EQ(queued_count, count.load());
  15691. EXPECT_TRUE(queued_count <= number_of_tasks);
  15692. EXPECT_TRUE(queued_count >= qlimit);
  15693. }
  15694. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  15695. // Use a short idle timeout so a dynamic thread spawns, times out and
  15696. // exits during the test, and the pool keeps working afterwards.
  15697. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  15698. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  15699. /*idle_timeout_sec=*/1}};
  15700. std::atomic_uint count{0};
  15701. std::condition_variable cv;
  15702. std::mutex mtx;
  15703. bool release = false;
  15704. // Block the base thread so the second task spawns a dynamic thread.
  15705. EXPECT_TRUE(task_queue->enqueue([&] {
  15706. std::unique_lock<std::mutex> lock(mtx);
  15707. while (!release) {
  15708. cv.wait(lock);
  15709. }
  15710. count++;
  15711. }));
  15712. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15713. // Let the dynamic thread finish its task and exceed the idle timeout.
  15714. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  15715. {
  15716. std::unique_lock<std::mutex> lock(mtx);
  15717. release = true;
  15718. }
  15719. cv.notify_all();
  15720. // The pool must still accept and run tasks after the dynamic thread exited.
  15721. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15722. task_queue->shutdown();
  15723. EXPECT_EQ(3u, count.load());
  15724. }
  15725. TEST(TaskQueueTest, MaxQueuedRequests) {
  15726. static constexpr unsigned int qlimit{3};
  15727. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  15728. std::condition_variable sem_cv;
  15729. std::mutex sem_mtx;
  15730. int credits = 0;
  15731. bool queued;
  15732. /* Fill up the queue with tasks that will block until we give them credits to
  15733. * complete. */
  15734. for (unsigned int n = 0; n <= qlimit;) {
  15735. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  15736. std::unique_lock<std::mutex> lock(sem_mtx);
  15737. while (credits <= 0) {
  15738. sem_cv.wait(lock);
  15739. }
  15740. /* Consume the credit and signal the test code if they are all gone. */
  15741. if (--credits == 0) { sem_cv.notify_one(); }
  15742. });
  15743. if (n < qlimit) {
  15744. /* The first qlimit enqueues must succeed. */
  15745. EXPECT_TRUE(queued);
  15746. } else {
  15747. /* The last one will succeed only when the worker thread
  15748. * starts and dequeues the first blocking task. Although
  15749. * not necessary for the correctness of this test, we sleep for
  15750. * a short while to avoid busy waiting. */
  15751. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15752. }
  15753. if (queued) { n++; }
  15754. }
  15755. /* Further enqueues must fail since the queue is full. */
  15756. for (auto i = 0; i < 4; i++) {
  15757. queued = task_queue->enqueue([] {});
  15758. EXPECT_FALSE(queued);
  15759. }
  15760. /* Give the credits to allow the previous tasks to complete. */
  15761. {
  15762. std::unique_lock<std::mutex> lock(sem_mtx);
  15763. credits += qlimit + 1;
  15764. }
  15765. sem_cv.notify_all();
  15766. /* Wait for all the credits to be consumed. */
  15767. {
  15768. std::unique_lock<std::mutex> lock(sem_mtx);
  15769. while (credits > 0) {
  15770. sem_cv.wait(lock);
  15771. }
  15772. }
  15773. /* Check that we are able again to enqueue at least qlimit tasks. */
  15774. for (unsigned int i = 0; i < qlimit; i++) {
  15775. queued = task_queue->enqueue([] {});
  15776. EXPECT_TRUE(queued);
  15777. }
  15778. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15779. task_queue->shutdown();
  15780. #else
  15781. EXPECT_NO_THROW(task_queue->shutdown());
  15782. #endif
  15783. }
  15784. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  15785. Server svr;
  15786. std::string method;
  15787. std::string body;
  15788. auto has_content_length = false;
  15789. auto has_transfer_encoding = false;
  15790. std::atomic<int> bad_requests{0};
  15791. // Leftover body bytes get parsed as a malformed request and answered with
  15792. // 400
  15793. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  15794. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  15795. });
  15796. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  15797. res.set_redirect("/down", StatusCode::SeeOther_303);
  15798. });
  15799. svr.Get("/down", [&](const Request &req, Response &res) {
  15800. method = req.method;
  15801. body = req.body;
  15802. has_content_length = req.has_header("Content-Length");
  15803. has_transfer_encoding = req.has_header("Transfer-Encoding");
  15804. res.set_content("ok", "text/plain");
  15805. });
  15806. auto port = svr.bind_to_any_port(HOST);
  15807. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15808. auto se = detail::scope_exit([&] {
  15809. svr.stop();
  15810. thread.join();
  15811. ASSERT_FALSE(svr.is_running());
  15812. });
  15813. svr.wait_until_ready();
  15814. const std::string payload = "SECRET-BODY";
  15815. auto check = [&](Client &cli, const Result &res) {
  15816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15817. EXPECT_EQ(StatusCode::OK_200, res->status);
  15818. EXPECT_EQ("ok", res->body);
  15819. EXPECT_EQ("GET", method);
  15820. EXPECT_TRUE(body.empty());
  15821. EXPECT_FALSE(has_content_length);
  15822. EXPECT_FALSE(has_transfer_encoding);
  15823. // Nothing of the original body may be left on the connection
  15824. auto res2 = cli.Get("/down");
  15825. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  15826. EXPECT_EQ(StatusCode::OK_200, res2->status);
  15827. EXPECT_EQ("ok", res2->body);
  15828. EXPECT_EQ(0, bad_requests);
  15829. };
  15830. // With content length
  15831. {
  15832. Client cli(HOST, port);
  15833. cli.set_keep_alive(true);
  15834. cli.set_follow_location(true);
  15835. auto res = cli.Post(
  15836. "/up", payload.size(),
  15837. [&](size_t offset, size_t length, DataSink &sink) {
  15838. return sink.write(payload.data() + offset, length);
  15839. },
  15840. "text/plain");
  15841. check(cli, res);
  15842. }
  15843. // Without content length (chunked)
  15844. {
  15845. Client cli(HOST, port);
  15846. cli.set_keep_alive(true);
  15847. cli.set_follow_location(true);
  15848. auto res = cli.Post(
  15849. "/up",
  15850. [&](size_t /*offset*/, DataSink &sink) {
  15851. sink.write(payload.data(), payload.size());
  15852. sink.done();
  15853. return true;
  15854. },
  15855. "text/plain");
  15856. check(cli, res);
  15857. }
  15858. }
  15859. TEST(RedirectTest, LocationPathIsNotDecoded) {
  15860. Server svr;
  15861. std::string target;
  15862. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  15863. // Echo the still-encoded name back in the Location
  15864. const std::string prefix = "/start/";
  15865. res.status = StatusCode::Found_302;
  15866. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  15867. });
  15868. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  15869. target = req.target;
  15870. res.set_content("ok", "text/plain");
  15871. });
  15872. auto port = svr.bind_to_any_port(HOST);
  15873. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15874. auto se = detail::scope_exit([&] {
  15875. svr.stop();
  15876. thread.join();
  15877. ASSERT_FALSE(svr.is_running());
  15878. });
  15879. svr.wait_until_ready();
  15880. // Decoding the Location path would turn the first four into a path
  15881. // separator, a query delimiter, a fragment delimiter and a different
  15882. // percent-encoded octet. The rest must keep reaching the server as they are.
  15883. const std::vector<std::string> names = {
  15884. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  15885. };
  15886. for (auto path_encode : {true, false}) {
  15887. Client cli(HOST, port);
  15888. cli.set_follow_location(true);
  15889. cli.set_path_encode(path_encode);
  15890. for (const auto &name : names) {
  15891. target.clear();
  15892. auto res = cli.Get("/start/" + name);
  15893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15894. EXPECT_EQ(StatusCode::OK_200, res->status);
  15895. EXPECT_EQ("/dest/" + name, target);
  15896. }
  15897. }
  15898. }
  15899. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  15900. Server svr;
  15901. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15902. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  15903. });
  15904. svr.Get("/hello", [](const Request &req, Response &res) {
  15905. res.set_content(req.get_param_value("key"), "text/plain");
  15906. });
  15907. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15908. auto se = detail::scope_exit([&] {
  15909. svr.stop();
  15910. thread.join();
  15911. ASSERT_FALSE(svr.is_running());
  15912. });
  15913. svr.wait_until_ready();
  15914. {
  15915. Client cli(HOST, PORT);
  15916. cli.set_follow_location(true);
  15917. auto res = cli.Get("/");
  15918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15919. EXPECT_EQ(StatusCode::OK_200, res->status);
  15920. EXPECT_EQ("val&key2=val2", res->body);
  15921. }
  15922. }
  15923. #endif
  15924. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  15925. Server svr;
  15926. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15927. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  15928. });
  15929. svr.Get("/hello", [](const Request &req, Response &res) {
  15930. res.set_content(req.get_param_value("key"), "text/plain");
  15931. });
  15932. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15933. auto se = detail::scope_exit([&] {
  15934. svr.stop();
  15935. thread.join();
  15936. ASSERT_FALSE(svr.is_running());
  15937. });
  15938. svr.wait_until_ready();
  15939. {
  15940. Client cli(HOST, PORT);
  15941. cli.set_follow_location(true);
  15942. auto res = cli.Get("/");
  15943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15944. EXPECT_EQ(StatusCode::OK_200, res->status);
  15945. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  15946. }
  15947. }
  15948. TEST(RedirectTest, RedirectWithPlusInPath) {
  15949. Server svr;
  15950. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15951. res.set_redirect("/a+b");
  15952. });
  15953. // Route pattern uses regex; escape + as \\+
  15954. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  15955. res.set_content(req.path, "text/plain");
  15956. });
  15957. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15958. auto se = detail::scope_exit([&] {
  15959. svr.stop();
  15960. thread.join();
  15961. ASSERT_FALSE(svr.is_running());
  15962. });
  15963. svr.wait_until_ready();
  15964. {
  15965. Client cli(HOST, PORT);
  15966. cli.set_follow_location(true);
  15967. auto res = cli.Get("/");
  15968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15969. EXPECT_EQ(StatusCode::OK_200, res->status);
  15970. EXPECT_EQ("/a+b", res->body);
  15971. }
  15972. }
  15973. TEST(RedirectTest, ResolveRelativeLocation) {
  15974. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  15975. const std::vector<std::pair<std::string, std::string>> cases = {
  15976. {"g", "/b/c/g"},
  15977. {"./g", "/b/c/g"},
  15978. {"g/", "/b/c/g/"},
  15979. {"?y", "/b/c/d;p?y"},
  15980. {"g?y", "/b/c/g?y"},
  15981. {"#s", "/b/c/d;p?q#s"},
  15982. {"g#s", "/b/c/g#s"},
  15983. {"g?y#s", "/b/c/g?y#s"},
  15984. {";x", "/b/c/;x"},
  15985. {"g;x", "/b/c/g;x"},
  15986. {".", "/b/c/"},
  15987. {"./", "/b/c/"},
  15988. {"..", "/b/"},
  15989. {"../", "/b/"},
  15990. {"../g", "/b/g"},
  15991. {"../..", "/"},
  15992. {"../../", "/"},
  15993. {"../../g", "/g"},
  15994. {"../../../g", "/g"},
  15995. {"g.", "/b/c/g."},
  15996. {".g", "/b/c/.g"},
  15997. {"g..", "/b/c/g.."},
  15998. {"..g", "/b/c/..g"},
  15999. {"./../g", "/b/g"},
  16000. {"./g/.", "/b/c/g/"},
  16001. {"g/./h", "/b/c/g/h"},
  16002. {"g/../h", "/b/c/h"},
  16003. {"g;x=1/./y", "/b/c/g;x=1/y"},
  16004. {"g;x=1/../y", "/b/c/y"},
  16005. {"g?y/./x", "/b/c/g?y/./x"},
  16006. {"g#s/../x", "/b/c/g#s/../x"},
  16007. // Not relative-path references, so left for parse_url.
  16008. {"/g", "/g"},
  16009. {"//g", "//g"},
  16010. {"http://g/x", "http://g/x"},
  16011. {"g:h", "g:h"},
  16012. };
  16013. for (const auto &c : cases) {
  16014. EXPECT_EQ(c.second,
  16015. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  16016. << c.first;
  16017. }
  16018. }
  16019. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  16020. Server svr;
  16021. svr.Get("/dir/page", [](const Request &req, Response &res) {
  16022. res.set_redirect(req.get_param_value("to"));
  16023. });
  16024. svr.Get("/dir/next", [](const Request &req, Response &res) {
  16025. res.set_content(req.target, "text/plain");
  16026. });
  16027. svr.Get("/other", [](const Request &req, Response &res) {
  16028. res.set_content(req.target, "text/plain");
  16029. });
  16030. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16031. auto se = detail::scope_exit([&] {
  16032. svr.stop();
  16033. thread.join();
  16034. ASSERT_FALSE(svr.is_running());
  16035. });
  16036. svr.wait_until_ready();
  16037. const std::vector<std::pair<std::string, std::string>> cases = {
  16038. {"next", "/dir/next"},
  16039. {"./next?x=1", "/dir/next?x=1"},
  16040. {"../other", "/other"},
  16041. };
  16042. for (const auto &c : cases) {
  16043. Client cli(HOST, PORT);
  16044. cli.set_follow_location(true);
  16045. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  16046. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  16047. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  16048. EXPECT_EQ(c.second, res->body) << c.first;
  16049. }
  16050. }
  16051. #ifdef CPPHTTPLIB_SSL_ENABLED
  16052. TEST(RedirectTest, Issue2185_Online) {
  16053. SSLClient client("github.com");
  16054. client.set_follow_location(true);
  16055. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  16056. "Coollab-Windows.zip");
  16057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16058. EXPECT_EQ(StatusCode::OK_200, res->status);
  16059. EXPECT_EQ(9920427U, res->body.size());
  16060. }
  16061. #endif
  16062. TEST(VulnerabilityTest, CRLFInjection) {
  16063. Server svr;
  16064. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  16065. res.set_content("Hello 1", "text/plain");
  16066. });
  16067. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  16068. res.set_content("Hello 2", "text/plain");
  16069. });
  16070. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  16071. res.set_content("Hello 3", "text/plain");
  16072. });
  16073. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  16074. res.set_content("Hello 4", "text/plain");
  16075. });
  16076. svr.set_logger([](const Request &req, const Response & /*res*/) {
  16077. for (const auto &x : req.headers) {
  16078. auto key = x.first;
  16079. EXPECT_STRNE("evil", key.c_str());
  16080. }
  16081. });
  16082. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16083. auto se = detail::scope_exit([&] {
  16084. svr.stop();
  16085. thread.join();
  16086. ASSERT_FALSE(svr.is_running());
  16087. });
  16088. svr.wait_until_ready();
  16089. {
  16090. Client cli(HOST, PORT);
  16091. cli.Post("/test1", "A=B",
  16092. "application/x-www-form-urlencoded\r\nevil: hello1");
  16093. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  16094. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  16095. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  16096. }
  16097. }
  16098. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  16099. auto server_thread = std::thread([] {
  16100. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16101. default_socket_options(srv);
  16102. sockaddr_in addr{};
  16103. addr.sin_family = AF_INET;
  16104. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16105. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16106. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  16107. ::listen(srv, 1);
  16108. sockaddr_in cli_addr{};
  16109. socklen_t cli_len = sizeof(cli_addr);
  16110. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16111. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  16112. std::string buf_all;
  16113. char buf[2048];
  16114. ssize_t n;
  16115. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  16116. buf_all.append(buf, static_cast<size_t>(n));
  16117. size_t pos;
  16118. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  16119. auto request_block = buf_all.substr(0, pos + 4); // include separator
  16120. auto e = request_block.find("\r\n");
  16121. if (e != std::string::npos) {
  16122. auto request_line = request_block.substr(0, e);
  16123. std::string msg =
  16124. "CRLF injection detected in request line: '" + request_line + "'";
  16125. EXPECT_FALSE(true) << msg;
  16126. }
  16127. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  16128. ::send(cli,
  16129. #ifdef _WIN32
  16130. static_cast<const char *>(resp.c_str()),
  16131. static_cast<int>(resp.size()),
  16132. #else
  16133. resp.c_str(), resp.size(),
  16134. #endif
  16135. 0);
  16136. buf_all.erase(0, pos + 4);
  16137. }
  16138. }
  16139. detail::close_socket(cli);
  16140. detail::close_socket(srv);
  16141. });
  16142. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16143. auto cli = Client("127.0.0.1", PORT + 1);
  16144. auto headers = Headers{
  16145. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  16146. {"Connection", "keep-alive"}};
  16147. auto res = cli.Get("/hi", headers);
  16148. EXPECT_FALSE(res);
  16149. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16150. server_thread.join();
  16151. }
  16152. // A request rejected before any byte reaches the socket must fail right away
  16153. // instead of waiting for a response the server will never send.
  16154. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  16155. // The kernel completes the TCP handshake from the listen backlog, so the
  16156. // client connects, but nothing ever reads, responds or closes.
  16157. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16158. default_socket_options(srv);
  16159. sockaddr_in addr{};
  16160. addr.sin_family = AF_INET;
  16161. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16162. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16163. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16164. ASSERT_EQ(0, ::listen(srv, 8));
  16165. auto cli = Client("127.0.0.1", PORT + 1);
  16166. cli.set_read_timeout(10, 0);
  16167. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  16168. return std::chrono::duration_cast<std::chrono::milliseconds>(
  16169. std::chrono::steady_clock::now() - start)
  16170. .count();
  16171. };
  16172. {
  16173. Request req;
  16174. req.method = "GE T";
  16175. req.path = "/";
  16176. auto start = std::chrono::steady_clock::now();
  16177. auto res = cli.send(req);
  16178. EXPECT_FALSE(res);
  16179. EXPECT_EQ(Error::Write, res.error());
  16180. EXPECT_LT(elapsed_ms(start), 1000);
  16181. }
  16182. {
  16183. auto start = std::chrono::steady_clock::now();
  16184. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  16185. EXPECT_FALSE(res);
  16186. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16187. EXPECT_LT(elapsed_ms(start), 1000);
  16188. }
  16189. EXPECT_FALSE(cli.is_socket_open());
  16190. detail::close_socket(srv);
  16191. }
  16192. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  16193. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16194. default_socket_options(srv);
  16195. sockaddr_in addr{};
  16196. addr.sin_family = AF_INET;
  16197. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16198. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16199. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16200. ASSERT_EQ(0, ::listen(srv, 1));
  16201. std::string received;
  16202. auto server_thread = std::thread([&] {
  16203. auto sock = ::accept(srv, nullptr, nullptr);
  16204. if (sock == INVALID_SOCKET) { return; }
  16205. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  16206. char buf[2048];
  16207. ssize_t n;
  16208. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  16209. received.append(buf, static_cast<size_t>(n));
  16210. }
  16211. detail::close_socket(sock);
  16212. });
  16213. {
  16214. auto cli = Client("127.0.0.1", PORT + 1);
  16215. // "Z" sorts after the default headers, so writing straight to the socket
  16216. // would have sent the request line and those headers before the rejection.
  16217. auto handle =
  16218. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  16219. EXPECT_FALSE(handle.is_valid());
  16220. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  16221. }
  16222. server_thread.join();
  16223. detail::close_socket(srv);
  16224. EXPECT_TRUE(received.empty()) << received;
  16225. }
  16226. TEST(PathParamsTest, StaticMatch) {
  16227. const auto pattern = "/users/all";
  16228. detail::PathParamsMatcher matcher(pattern);
  16229. Request request;
  16230. request.path = "/users/all";
  16231. ASSERT_TRUE(matcher.match(request));
  16232. std::unordered_map<std::string, std::string> expected_params = {};
  16233. EXPECT_EQ(request.path_params, expected_params);
  16234. }
  16235. TEST(PathParamsTest, StaticMismatch) {
  16236. const auto pattern = "/users/all";
  16237. detail::PathParamsMatcher matcher(pattern);
  16238. Request request;
  16239. request.path = "/users/1";
  16240. ASSERT_FALSE(matcher.match(request));
  16241. }
  16242. TEST(PathParamsTest, SingleParamInTheMiddle) {
  16243. const auto pattern = "/users/:id/subscriptions";
  16244. detail::PathParamsMatcher matcher(pattern);
  16245. Request request;
  16246. request.path = "/users/42/subscriptions";
  16247. ASSERT_TRUE(matcher.match(request));
  16248. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16249. EXPECT_EQ(request.path_params, expected_params);
  16250. }
  16251. TEST(PathParamsTest, SingleParamInTheEnd) {
  16252. const auto pattern = "/users/:id";
  16253. detail::PathParamsMatcher matcher(pattern);
  16254. Request request;
  16255. request.path = "/users/24";
  16256. ASSERT_TRUE(matcher.match(request));
  16257. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  16258. EXPECT_EQ(request.path_params, expected_params);
  16259. }
  16260. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  16261. const auto pattern = "/users/:id/";
  16262. detail::PathParamsMatcher matcher(pattern);
  16263. Request request;
  16264. request.path = "/users/42/";
  16265. ASSERT_TRUE(matcher.match(request));
  16266. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16267. EXPECT_EQ(request.path_params, expected_params);
  16268. }
  16269. TEST(PathParamsTest, EmptyParam) {
  16270. const auto pattern = "/users/:id/";
  16271. detail::PathParamsMatcher matcher(pattern);
  16272. Request request;
  16273. request.path = "/users//";
  16274. ASSERT_TRUE(matcher.match(request));
  16275. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  16276. EXPECT_EQ(request.path_params, expected_params);
  16277. }
  16278. TEST(PathParamsTest, FragmentMismatch) {
  16279. const auto pattern = "/users/:id/";
  16280. detail::PathParamsMatcher matcher(pattern);
  16281. Request request;
  16282. request.path = "/admins/24/";
  16283. ASSERT_FALSE(matcher.match(request));
  16284. }
  16285. TEST(PathParamsTest, ExtraFragments) {
  16286. const auto pattern = "/users/:id";
  16287. detail::PathParamsMatcher matcher(pattern);
  16288. Request request;
  16289. request.path = "/users/42/subscriptions";
  16290. ASSERT_FALSE(matcher.match(request));
  16291. }
  16292. TEST(PathParamsTest, MissingTrailingParam) {
  16293. const auto pattern = "/users/:id";
  16294. detail::PathParamsMatcher matcher(pattern);
  16295. Request request;
  16296. request.path = "/users";
  16297. ASSERT_FALSE(matcher.match(request));
  16298. }
  16299. TEST(PathParamsTest, MissingParamInTheMiddle) {
  16300. const auto pattern = "/users/:id/subscriptions";
  16301. detail::PathParamsMatcher matcher(pattern);
  16302. Request request;
  16303. request.path = "/users/subscriptions";
  16304. ASSERT_FALSE(matcher.match(request));
  16305. }
  16306. TEST(PathParamsTest, MultipleParams) {
  16307. const auto pattern = "/users/:userid/subscriptions/:subid";
  16308. detail::PathParamsMatcher matcher(pattern);
  16309. Request request;
  16310. request.path = "/users/42/subscriptions/2";
  16311. ASSERT_TRUE(matcher.match(request));
  16312. std::unordered_map<std::string, std::string> expected_params = {
  16313. {"userid", "42"}, {"subid", "2"}};
  16314. EXPECT_EQ(request.path_params, expected_params);
  16315. }
  16316. TEST(PathParamsTest, SequenceOfParams) {
  16317. const auto pattern = "/values/:x/:y/:z";
  16318. detail::PathParamsMatcher matcher(pattern);
  16319. Request request;
  16320. request.path = "/values/1/2/3";
  16321. ASSERT_TRUE(matcher.match(request));
  16322. std::unordered_map<std::string, std::string> expected_params = {
  16323. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  16324. EXPECT_EQ(request.path_params, expected_params);
  16325. }
  16326. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  16327. const auto pattern = "/prefix:suffix";
  16328. detail::PathParamsMatcher matcher(pattern);
  16329. Request request;
  16330. request.path = "/prefix:suffix";
  16331. ASSERT_TRUE(matcher.match(request));
  16332. const std::unordered_map<std::string, std::string> expected_params = {};
  16333. EXPECT_EQ(request.path_params, expected_params);
  16334. }
  16335. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  16336. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  16337. // calling thread's stack on a long enough path for a quantified pattern;
  16338. // RegexMatcher must refuse to run regex matching on paths beyond
  16339. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  16340. detail::RegexMatcher matcher("/files/(.*)");
  16341. Request within_limit;
  16342. within_limit.path = "/files/" + std::string(10, 'A');
  16343. EXPECT_TRUE(matcher.match(within_limit));
  16344. Request over_limit;
  16345. over_limit.path =
  16346. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  16347. EXPECT_FALSE(matcher.match(over_limit));
  16348. }
  16349. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  16350. Server svr;
  16351. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  16352. res.set_content("ok", "text/plain");
  16353. });
  16354. auto port = svr.bind_to_any_port(HOST);
  16355. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16356. auto se = detail::scope_exit([&] {
  16357. svr.stop();
  16358. thread.join();
  16359. ASSERT_FALSE(svr.is_running());
  16360. });
  16361. svr.wait_until_ready();
  16362. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  16363. // request URI limit; this used to be able to crash the process.
  16364. std::string path =
  16365. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  16366. std::string req = "GET " + path +
  16367. " HTTP/1.1\r\n"
  16368. "Host: " +
  16369. std::string(HOST) + ":" + std::to_string(port) +
  16370. "\r\n"
  16371. "Connection: close\r\n"
  16372. "\r\n";
  16373. std::string response;
  16374. ASSERT_TRUE(send_request(5, req, &response, port));
  16375. EXPECT_NE(std::string::npos, response.find("404"));
  16376. }
  16377. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  16378. Server svr;
  16379. auto handler = [](const Request & /*req*/, Response &res) {
  16380. res.set_content("hit", "text/plain");
  16381. };
  16382. // No regex metacharacter, so this one is compared literally
  16383. svr.Get("/literal/route", handler);
  16384. // '.' is a regex metacharacter, so this one must keep regex semantics
  16385. svr.Get("/a.c", handler);
  16386. auto port = svr.bind_to_any_port(HOST);
  16387. std::thread t([&]() { svr.listen_after_bind(); });
  16388. auto se = detail::scope_exit([&] {
  16389. svr.stop();
  16390. t.join();
  16391. ASSERT_FALSE(svr.is_running());
  16392. });
  16393. svr.wait_until_ready();
  16394. Client cli(HOST, port);
  16395. struct {
  16396. const char *path;
  16397. int status;
  16398. } cases[] = {
  16399. {"/literal/route", StatusCode::OK_200},
  16400. {"/literal/routes", StatusCode::NotFound_404},
  16401. {"/literal/rout", StatusCode::NotFound_404},
  16402. {"/abc", StatusCode::OK_200},
  16403. {"/a.c", StatusCode::OK_200},
  16404. };
  16405. for (const auto &x : cases) {
  16406. auto res = cli.Get(x.path);
  16407. ASSERT_TRUE(res) << x.path;
  16408. EXPECT_EQ(x.status, res->status) << x.path;
  16409. }
  16410. }
  16411. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  16412. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  16413. // from exhausting the stack, so it must only constrain routes that actually
  16414. // run a regular expression. A literal route is matched by comparison and
  16415. // stays usable at any length.
  16416. Server svr;
  16417. const std::string pattern =
  16418. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  16419. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  16420. res.set_content("hit", "text/plain");
  16421. });
  16422. auto port = svr.bind_to_any_port(HOST);
  16423. std::thread t([&]() { svr.listen_after_bind(); });
  16424. auto se = detail::scope_exit([&] {
  16425. svr.stop();
  16426. t.join();
  16427. ASSERT_FALSE(svr.is_running());
  16428. });
  16429. svr.wait_until_ready();
  16430. Client cli(HOST, port);
  16431. auto res = cli.Get(pattern);
  16432. ASSERT_TRUE(res);
  16433. EXPECT_EQ(StatusCode::OK_200, res->status);
  16434. }
  16435. TEST(ParseUrlTest, VariousPatterns) {
  16436. {
  16437. detail::UrlComponents uc;
  16438. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  16439. EXPECT_EQ("http", uc.scheme);
  16440. EXPECT_EQ("example.com", uc.host);
  16441. EXPECT_EQ("8080", uc.port);
  16442. EXPECT_EQ("/path", uc.path);
  16443. EXPECT_EQ("?q=1", uc.query);
  16444. }
  16445. {
  16446. detail::UrlComponents uc;
  16447. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  16448. EXPECT_EQ("https", uc.scheme);
  16449. EXPECT_EQ("example.com", uc.host);
  16450. EXPECT_TRUE(uc.port.empty());
  16451. EXPECT_EQ("/path", uc.path);
  16452. }
  16453. {
  16454. detail::UrlComponents uc;
  16455. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  16456. EXPECT_EQ("::1", uc.host);
  16457. EXPECT_EQ("8080", uc.port);
  16458. EXPECT_EQ("/path", uc.path);
  16459. }
  16460. {
  16461. detail::UrlComponents uc;
  16462. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  16463. }
  16464. {
  16465. // Bytes after the IPv6 literal must be a delimiter, not folded into
  16466. // the path while the connection still targets the bracketed host.
  16467. detail::UrlComponents uc;
  16468. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  16469. }
  16470. {
  16471. detail::UrlComponents uc;
  16472. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  16473. }
  16474. {
  16475. detail::UrlComponents uc;
  16476. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  16477. EXPECT_EQ("::1", uc.host);
  16478. EXPECT_TRUE(uc.port.empty());
  16479. EXPECT_EQ("/path", uc.path);
  16480. }
  16481. {
  16482. detail::UrlComponents uc;
  16483. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  16484. EXPECT_TRUE(uc.scheme.empty());
  16485. EXPECT_EQ("example.com", uc.host);
  16486. EXPECT_EQ("/path", uc.path);
  16487. EXPECT_EQ("?q=1", uc.query);
  16488. }
  16489. {
  16490. detail::UrlComponents uc;
  16491. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  16492. EXPECT_TRUE(uc.host.empty());
  16493. EXPECT_EQ("/path", uc.path);
  16494. EXPECT_EQ("?q=1", uc.query);
  16495. }
  16496. {
  16497. detail::UrlComponents uc;
  16498. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  16499. EXPECT_EQ("example.com", uc.host);
  16500. EXPECT_EQ("8080", uc.port);
  16501. }
  16502. {
  16503. // Unix socket path — must not be parsed as host
  16504. detail::UrlComponents uc;
  16505. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  16506. EXPECT_TRUE(uc.host.empty());
  16507. }
  16508. {
  16509. detail::UrlComponents uc;
  16510. ASSERT_TRUE(detail::parse_url("", uc));
  16511. EXPECT_TRUE(uc.host.empty());
  16512. EXPECT_TRUE(uc.path.empty());
  16513. }
  16514. {
  16515. detail::UrlComponents uc;
  16516. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  16517. }
  16518. {
  16519. detail::UrlComponents uc;
  16520. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  16521. }
  16522. {
  16523. // Accepted by parse_url; callers restrict to http/https
  16524. detail::UrlComponents uc;
  16525. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  16526. EXPECT_EQ("ftp", uc.scheme);
  16527. }
  16528. {
  16529. detail::UrlComponents uc;
  16530. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  16531. }
  16532. {
  16533. detail::UrlComponents uc;
  16534. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  16535. }
  16536. }
  16537. TEST(ParseUrlTest, FragmentHandling) {
  16538. {
  16539. detail::UrlComponents uc;
  16540. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  16541. EXPECT_EQ("/path", uc.path);
  16542. EXPECT_TRUE(uc.query.empty());
  16543. }
  16544. {
  16545. detail::UrlComponents uc;
  16546. ASSERT_TRUE(detail::parse_url("#frag", uc));
  16547. EXPECT_TRUE(uc.path.empty());
  16548. EXPECT_TRUE(uc.query.empty());
  16549. }
  16550. }
  16551. TEST(ParseUrlTest, UserinfoHandling) {
  16552. // userinfo is not supported. Parsers that honour it, or take a backslash for
  16553. // '/', would see evil.com where the host used to be the whole authority.
  16554. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  16555. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  16556. for (auto url : urls) {
  16557. detail::UrlComponents uc;
  16558. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  16559. }
  16560. }
  16561. TEST(ParseUrlTest, IPv6EdgeCases) {
  16562. {
  16563. detail::UrlComponents uc;
  16564. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  16565. EXPECT_TRUE(uc.scheme.empty());
  16566. EXPECT_EQ("::1", uc.host);
  16567. EXPECT_EQ("8080", uc.port);
  16568. }
  16569. {
  16570. // Zone ID '%25' is not in [a-fA-F0-9:]
  16571. detail::UrlComponents uc;
  16572. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  16573. }
  16574. }
  16575. TEST(ParseUrlTest, SchemeEdgeCases) {
  16576. {
  16577. detail::UrlComponents uc;
  16578. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  16579. }
  16580. {
  16581. detail::UrlComponents uc;
  16582. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  16583. }
  16584. {
  16585. detail::UrlComponents uc;
  16586. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  16587. }
  16588. }
  16589. TEST(ParseUrlTest, PortEdgeCases) {
  16590. {
  16591. detail::UrlComponents uc;
  16592. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  16593. EXPECT_TRUE(uc.port.empty());
  16594. EXPECT_EQ("/path", uc.path);
  16595. }
  16596. {
  16597. // parse_url accepts any port string; validation is done by parse_port
  16598. detail::UrlComponents uc;
  16599. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  16600. EXPECT_EQ("abc", uc.port);
  16601. }
  16602. }
  16603. TEST(ParseUrlTest, WebSocketPatterns) {
  16604. {
  16605. detail::UrlComponents uc;
  16606. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  16607. EXPECT_EQ("ws", uc.scheme);
  16608. EXPECT_EQ("echo.example.com", uc.host);
  16609. EXPECT_EQ("8080", uc.port);
  16610. EXPECT_EQ("/ws", uc.path);
  16611. }
  16612. {
  16613. detail::UrlComponents uc;
  16614. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  16615. EXPECT_EQ("wss", uc.scheme);
  16616. EXPECT_EQ("echo.example.com", uc.host);
  16617. EXPECT_TRUE(uc.port.empty());
  16618. EXPECT_EQ("/ws", uc.path);
  16619. }
  16620. }
  16621. TEST(ParseUrlTest, QueryOnly) {
  16622. detail::UrlComponents uc;
  16623. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  16624. EXPECT_TRUE(uc.host.empty());
  16625. EXPECT_TRUE(uc.path.empty());
  16626. EXPECT_EQ("?q=1&r=2", uc.query);
  16627. }
  16628. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  16629. detail::UrlComponents uc;
  16630. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  16631. EXPECT_TRUE(uc.scheme.empty());
  16632. EXPECT_EQ("example.com", uc.host);
  16633. EXPECT_EQ("443", uc.port);
  16634. EXPECT_EQ("/path", uc.path);
  16635. }
  16636. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  16637. // If ipv6 regex working, regex match codepath is taken.
  16638. // else port will default to 80 in Client impl
  16639. int clientImplMagicPort = 80;
  16640. int port = 4321;
  16641. // above ports must be different to avoid false negative
  16642. EXPECT_NE(clientImplMagicPort, port);
  16643. std::string ipV6TestURL = "http://[ff06::c3]";
  16644. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  16645. CLIENT_PRIVATE_KEY_FILE);
  16646. EXPECT_EQ(cli.port(), port);
  16647. }
  16648. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  16649. auto file_path = "./www/dir/index.html";
  16650. auto dir_path = "./www/dir";
  16651. detail::FileStat stat_file(file_path);
  16652. EXPECT_TRUE(stat_file.is_file());
  16653. EXPECT_FALSE(stat_file.is_dir());
  16654. detail::FileStat stat_dir(dir_path);
  16655. EXPECT_FALSE(stat_dir.is_file());
  16656. EXPECT_TRUE(stat_dir.is_dir());
  16657. }
  16658. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  16659. // IPv4 with default HTTP port (80)
  16660. EXPECT_EQ("example.com",
  16661. detail::make_host_and_port_string("example.com", 80, false));
  16662. // IPv4 with default HTTPS port (443)
  16663. EXPECT_EQ("example.com",
  16664. detail::make_host_and_port_string("example.com", 443, true));
  16665. // IPv4 with non-default HTTP port
  16666. EXPECT_EQ("example.com:8080",
  16667. detail::make_host_and_port_string("example.com", 8080, false));
  16668. // IPv4 with non-default HTTPS port
  16669. EXPECT_EQ("example.com:8443",
  16670. detail::make_host_and_port_string("example.com", 8443, true));
  16671. // IPv6 with default HTTP port (80)
  16672. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  16673. // IPv6 with default HTTPS port (443)
  16674. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  16675. // IPv6 with non-default HTTP port
  16676. EXPECT_EQ("[::1]:8080",
  16677. detail::make_host_and_port_string("::1", 8080, false));
  16678. // IPv6 with non-default HTTPS port
  16679. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  16680. // IPv6 full address with default port
  16681. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  16682. detail::make_host_and_port_string(
  16683. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  16684. // IPv6 full address with non-default port
  16685. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  16686. detail::make_host_and_port_string(
  16687. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  16688. // IPv6 localhost with non-default port
  16689. EXPECT_EQ("[::1]:3000",
  16690. detail::make_host_and_port_string("::1", 3000, false));
  16691. // IPv6 with zone ID (link-local address) with default port
  16692. EXPECT_EQ("[fe80::1%eth0]",
  16693. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  16694. // IPv6 with zone ID (link-local address) with non-default port
  16695. EXPECT_EQ("[fe80::1%eth0]:8080",
  16696. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  16697. // Edge case: Port 443 with is_ssl=false (should add port)
  16698. EXPECT_EQ("example.com:443",
  16699. detail::make_host_and_port_string("example.com", 443, false));
  16700. // Edge case: Port 80 with is_ssl=true (should add port)
  16701. EXPECT_EQ("example.com:80",
  16702. detail::make_host_and_port_string("example.com", 80, true));
  16703. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  16704. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  16705. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  16706. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  16707. // Security fix: Already bracketed IPv6 should not get double brackets
  16708. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  16709. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  16710. EXPECT_EQ("[::1]:8080",
  16711. detail::make_host_and_port_string("[::1]", 8080, false));
  16712. EXPECT_EQ("[2001:db8::1]:8080",
  16713. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  16714. EXPECT_EQ("[fe80::1%eth0]",
  16715. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  16716. EXPECT_EQ("[fe80::1%eth0]:8080",
  16717. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  16718. // Edge case: Empty host (should return as-is)
  16719. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  16720. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  16721. // This is a known limitation but shouldn't crash
  16722. EXPECT_EQ("[host:name]",
  16723. detail::make_host_and_port_string("host:name", 80, false));
  16724. // Port number edge cases (no validation, but should not crash)
  16725. EXPECT_EQ("example.com:0",
  16726. detail::make_host_and_port_string("example.com", 0, false));
  16727. EXPECT_EQ("example.com:-1",
  16728. detail::make_host_and_port_string("example.com", -1, false));
  16729. EXPECT_EQ("example.com:65535",
  16730. detail::make_host_and_port_string("example.com", 65535, false));
  16731. EXPECT_EQ("example.com:65536",
  16732. detail::make_host_and_port_string("example.com", 65536, false));
  16733. }
  16734. #ifdef CPPHTTPLIB_SSL_ENABLED
  16735. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  16736. httplib::SSLClient cli("roblox.com", 443);
  16737. cli.set_follow_location(true);
  16738. auto res = cli.Get("/");
  16739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16740. EXPECT_EQ(StatusCode::OK_200, res->status);
  16741. }
  16742. #endif
  16743. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  16744. Server svr;
  16745. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16746. EXPECT_EQ(res.status, 400);
  16747. });
  16748. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16749. auto se = detail::scope_exit([&] {
  16750. svr.stop();
  16751. thread.join();
  16752. ASSERT_FALSE(svr.is_running());
  16753. });
  16754. svr.wait_until_ready();
  16755. Client cli(HOST, PORT);
  16756. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  16757. }
  16758. TEST(InvalidHeaderCharsTest, is_field_name) {
  16759. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  16760. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  16761. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  16762. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  16763. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  16764. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  16765. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  16766. EXPECT_FALSE(detail::fields::is_field_name(""));
  16767. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  16768. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  16769. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  16770. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  16771. }
  16772. TEST(InvalidHeaderCharsTest, is_field_value) {
  16773. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  16774. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  16775. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  16776. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  16777. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  16778. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  16779. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  16780. EXPECT_TRUE(detail::fields::is_field_value(""));
  16781. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  16782. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  16783. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  16784. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  16785. EXPECT_TRUE(detail::fields::is_field_value("0"));
  16786. }
  16787. TEST(InvalidHeaderCharsTest, OnServer) {
  16788. Server svr;
  16789. svr.Get("/test_name", [&](const Request &req, Response &res) {
  16790. std::string header = "Not Set";
  16791. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16792. res.set_header(header, "value");
  16793. res.set_content("Page Content Page Content", "text/plain");
  16794. });
  16795. svr.Get("/test_value", [&](const Request &req, Response &res) {
  16796. std::string header = "Not Set";
  16797. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16798. res.set_header("X-Test", header);
  16799. res.set_content("Page Content Page Content", "text/plain");
  16800. });
  16801. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16802. auto se = detail::scope_exit([&] {
  16803. svr.stop();
  16804. thread.join();
  16805. ASSERT_FALSE(svr.is_running());
  16806. });
  16807. svr.wait_until_ready();
  16808. Client cli(HOST, PORT);
  16809. {
  16810. auto res = cli.Get(
  16811. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16813. EXPECT_EQ("Page Content Page Content", res->body);
  16814. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16815. }
  16816. {
  16817. auto res = cli.Get(
  16818. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16820. EXPECT_EQ("Page Content Page Content", res->body);
  16821. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16822. }
  16823. }
  16824. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  16825. auto handled = false;
  16826. Server svr;
  16827. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16828. thread t = thread([&] { svr.listen(HOST, PORT); });
  16829. auto se = detail::scope_exit([&] {
  16830. svr.stop();
  16831. t.join();
  16832. ASSERT_FALSE(svr.is_running());
  16833. ASSERT_FALSE(handled);
  16834. });
  16835. svr.wait_until_ready();
  16836. auto req = "POST /test HTTP/1.1\r\n"
  16837. "Content-Length: x\r\n"
  16838. "\r\n";
  16839. std::string response;
  16840. ASSERT_TRUE(send_request(1, req, &response));
  16841. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16842. response.substr(0, response.find("\r\n")));
  16843. }
  16844. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  16845. // case-insensitive, and a server that receives a 100-continue expectation in
  16846. // an HTTP/1.0 request MUST ignore it.
  16847. static void probe_expect(int port, const std::string &req, bool *got_100) {
  16848. std::string response;
  16849. ASSERT_TRUE(send_request(1, req, &response, port));
  16850. *got_100 = response.find("100 Continue") != std::string::npos;
  16851. }
  16852. class ExpectTokenTest : public ::testing::Test {
  16853. protected:
  16854. void SetUp() override {
  16855. svr_.Post("/p", [](const Request &, Response &res) {
  16856. res.set_content("ok", "text/plain");
  16857. });
  16858. port_ = svr_.bind_to_any_port(HOST);
  16859. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16860. svr_.wait_until_ready();
  16861. }
  16862. void TearDown() override {
  16863. svr_.stop();
  16864. if (thread_.joinable()) { thread_.join(); }
  16865. }
  16866. std::string request(const char *version, const char *expect_value) const {
  16867. return std::string("POST /p ") + version +
  16868. "\r\n"
  16869. "Host: localhost\r\n"
  16870. "Content-Length: 2\r\n"
  16871. "Connection: close\r\n"
  16872. "Expect: " +
  16873. expect_value +
  16874. "\r\n"
  16875. "\r\n"
  16876. "hi";
  16877. }
  16878. Server svr_;
  16879. int port_ = 0;
  16880. thread thread_;
  16881. };
  16882. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  16883. bool got_100 = false;
  16884. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  16885. EXPECT_TRUE(got_100);
  16886. }
  16887. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  16888. bool got_100 = true;
  16889. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  16890. EXPECT_FALSE(got_100);
  16891. }
  16892. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  16893. bool got_100 = false;
  16894. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  16895. EXPECT_TRUE(got_100);
  16896. }
  16897. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  16898. bool got_100 = false;
  16899. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  16900. EXPECT_TRUE(got_100);
  16901. }
  16902. // `100 Continue` is sent only when the server starts reading the body, so a
  16903. // request rejected before that never invites the client to send it. The
  16904. // requests below carry the expectation but withhold the body, as a client
  16905. // waiting for `100 Continue` would.
  16906. // A POST that expects `100 Continue` and withholds its two-byte body.
  16907. static std::string expect_headers_only(const std::string &path) {
  16908. return "POST " + path +
  16909. " HTTP/1.1\r\n"
  16910. "Host: localhost\r\n"
  16911. "Content-Length: 2\r\n"
  16912. "Expect: 100-continue\r\n"
  16913. "\r\n";
  16914. }
  16915. class ExpectLazyContinueTest : public ::testing::Test {
  16916. protected:
  16917. void SetUp() override {
  16918. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  16919. if (req.path == "/pre-routing") {
  16920. res.status = StatusCode::Unauthorized_401;
  16921. return Server::HandlerResponse::Handled;
  16922. }
  16923. return Server::HandlerResponse::Unhandled;
  16924. });
  16925. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  16926. if (req.matched_route == "/pre-request") {
  16927. res.status = StatusCode::Forbidden_403;
  16928. return Server::HandlerResponse::Handled;
  16929. }
  16930. return Server::HandlerResponse::Unhandled;
  16931. });
  16932. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  16933. res.set_content("ok", "text/plain");
  16934. });
  16935. svr_.Post("/pre-request", [](const Request &, Response &res) {
  16936. res.set_content("ok", "text/plain");
  16937. });
  16938. svr_.Post("/reader-used", [](const Request &, Response &res,
  16939. const ContentReader &content_reader) {
  16940. std::string body;
  16941. content_reader([&](const char *data, size_t len) {
  16942. body.append(data, len);
  16943. return true;
  16944. });
  16945. res.set_content(body, "text/plain");
  16946. });
  16947. svr_.Post("/reader-unused",
  16948. [](const Request &, Response &res, const ContentReader &) {
  16949. res.set_content("ignored", "text/plain");
  16950. });
  16951. port_ = svr_.bind_to_any_port(HOST);
  16952. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16953. svr_.wait_until_ready();
  16954. }
  16955. void TearDown() override {
  16956. svr_.stop();
  16957. if (thread_.joinable()) { thread_.join(); }
  16958. }
  16959. // Sends `req` and reads until the server closes the connection. Returns
  16960. // false if the read had to wait for the client-side timeout instead.
  16961. bool send_until_closed(const std::string &req, std::string *resp) const {
  16962. auto start = std::chrono::steady_clock::now();
  16963. if (!send_request(3, req, resp, port_)) { return false; }
  16964. auto elapsed = std::chrono::steady_clock::now() - start;
  16965. return elapsed < std::chrono::seconds(2);
  16966. }
  16967. // The final response comes without `100 Continue`, and the server closes
  16968. // the connection since the body may or may not follow.
  16969. void expect_final_without_interim(const std::string &path,
  16970. const char *status_line) const {
  16971. std::string resp;
  16972. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  16973. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  16974. EXPECT_EQ(0u, resp.find(status_line));
  16975. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16976. }
  16977. Server svr_;
  16978. int port_ = 0;
  16979. thread thread_;
  16980. };
  16981. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  16982. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  16983. }
  16984. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  16985. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  16986. }
  16987. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  16988. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  16989. }
  16990. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  16991. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  16992. }
  16993. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  16994. // The body follows once `100 Continue` has had time to arrive.
  16995. auto req = expect_headers_only("/reader-used");
  16996. req.insert(req.size() - 2, "Connection: close\r\n");
  16997. std::string resp;
  16998. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  16999. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  17000. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  17001. EXPECT_NE(std::string::npos, resp.find("hi"));
  17002. }
  17003. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  17004. // Large enough for the client to add `Expect: 100-continue` itself.
  17005. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  17006. std::atomic<bool> body_sent{false};
  17007. Client cli(HOST, port_);
  17008. auto res = cli.Post(
  17009. "/pre-request", length,
  17010. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  17011. body_sent = true;
  17012. std::string chunk(len, 'x');
  17013. sink.write(chunk.data(), chunk.size());
  17014. return true;
  17015. },
  17016. "application/octet-stream");
  17017. ASSERT_TRUE(res);
  17018. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  17019. EXPECT_FALSE(body_sent);
  17020. }
  17021. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  17022. Server svr;
  17023. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  17024. return StatusCode::ExpectationFailed_417;
  17025. });
  17026. svr.Post("/p", [](const Request &, Response &res) {
  17027. res.set_content("ok", "text/plain");
  17028. });
  17029. auto port = svr.bind_to_any_port(HOST);
  17030. thread t = thread([&] { svr.listen_after_bind(); });
  17031. auto se = detail::scope_exit([&] {
  17032. svr.stop();
  17033. t.join();
  17034. });
  17035. svr.wait_until_ready();
  17036. std::string resp;
  17037. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  17038. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  17039. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17040. // Exactly one response: the route handler must not run after the 417.
  17041. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  17042. }
  17043. #ifndef _WIN32
  17044. TEST(Expect100ContinueTest, ServerClosesConnection) {
  17045. static constexpr char reject[] = "Unauthorized";
  17046. static constexpr char accept[] = "Upload accepted";
  17047. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  17048. Server svr;
  17049. svr.set_expect_100_continue_handler(
  17050. [](const Request & /*req*/, Response &res) {
  17051. res.status = StatusCode::Unauthorized_401;
  17052. res.set_content(reject, "text/plain");
  17053. return res.status;
  17054. });
  17055. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  17056. res.set_content(accept, "text/plain");
  17057. });
  17058. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17059. auto se = detail::scope_exit([&] {
  17060. svr.stop();
  17061. thread.join();
  17062. ASSERT_FALSE(svr.is_running());
  17063. });
  17064. svr.wait_until_ready();
  17065. {
  17066. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  17067. curl_easy_init(), &curl_easy_cleanup};
  17068. ASSERT_NE(curl, nullptr);
  17069. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  17070. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  17071. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  17072. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  17073. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  17074. &curl_slist_free_all};
  17075. ASSERT_NE(list, nullptr);
  17076. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  17077. struct read_data {
  17078. size_t read_size;
  17079. size_t total_size;
  17080. } data = {0, total_size};
  17081. using read_callback_t =
  17082. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17083. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  17084. void *userdata) -> size_t {
  17085. read_data *d = (read_data *)userdata;
  17086. if (!userdata || d->read_size >= d->total_size) { return 0; }
  17087. std::fill_n(ptr, size * nmemb, 'A');
  17088. d->read_size += size * nmemb;
  17089. return size * nmemb;
  17090. };
  17091. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  17092. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  17093. std::vector<char> buffer;
  17094. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  17095. using write_callback_t =
  17096. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17097. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  17098. void *userdata) -> size_t {
  17099. std::vector<char> *buf = (std::vector<char> *)userdata;
  17100. buf->reserve(buf->size() + size * nmemb + 1);
  17101. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  17102. return size * nmemb;
  17103. };
  17104. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  17105. {
  17106. const auto res = curl_easy_perform(curl.get());
  17107. ASSERT_EQ(res, CURLE_OK);
  17108. }
  17109. {
  17110. auto response_code = long{};
  17111. const auto res =
  17112. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  17113. ASSERT_EQ(res, CURLE_OK);
  17114. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  17115. }
  17116. {
  17117. auto dl = curl_off_t{};
  17118. const auto res =
  17119. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  17120. ASSERT_EQ(res, CURLE_OK);
  17121. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  17122. }
  17123. {
  17124. buffer.push_back('\0');
  17125. ASSERT_STRCASEEQ(buffer.data(), reject);
  17126. }
  17127. }
  17128. }
  17129. #endif
  17130. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  17131. // Regression test for #2458.
  17132. //
  17133. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  17134. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  17135. // ticket can make the client socket spuriously readable during the
  17136. // 100-continue wait. If the readiness is mistaken for an incoming response,
  17137. // the client withholds the body and then blocks reading a response that never
  17138. // comes, failing with `Failed to read connection`.
  17139. //
  17140. // A correct client (like curl) sends the body once no `100 Continue` arrives
  17141. // within the timeout. This raw OpenSSL server deliberately never sends
  17142. // `100 Continue`; the client must still deliver the body and receive 200.
  17143. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  17144. signal(SIGPIPE, SIG_IGN);
  17145. const auto port = PORT + 4;
  17146. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17147. ASSERT_NE(srv, INVALID_SOCKET);
  17148. int opt = 1;
  17149. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  17150. sockaddr_in addr{};
  17151. addr.sin_family = AF_INET;
  17152. addr.sin_port = htons(static_cast<uint16_t>(port));
  17153. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17154. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17155. ASSERT_EQ(0, ::listen(srv, 1));
  17156. std::atomic<size_t> server_body_bytes{0};
  17157. auto server_thread = std::thread([&] {
  17158. sockaddr_in cli_addr{};
  17159. socklen_t cli_len = sizeof(cli_addr);
  17160. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17161. if (cli == INVALID_SOCKET) { return; }
  17162. // Bound the lifetime of the server side so a buggy client (which never
  17163. // sends the body) cannot make this thread block forever on join.
  17164. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  17165. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  17166. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  17167. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  17168. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  17169. SSL *ssl = SSL_new(ctx);
  17170. SSL_set_fd(ssl, static_cast<int>(cli));
  17171. if (SSL_accept(ssl) > 0) {
  17172. // Read the request headers. Reading here also flushes the TLS 1.3
  17173. // session tickets to the client. Deliberately do NOT send
  17174. // `100 Continue`.
  17175. std::string buf;
  17176. char tmp[1024];
  17177. while (buf.find("\r\n\r\n") == std::string::npos) {
  17178. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17179. if (n <= 0) { break; }
  17180. buf.append(tmp, static_cast<size_t>(n));
  17181. }
  17182. // A correct client sends the body now; count what arrives.
  17183. auto pos = buf.find("\r\n\r\n");
  17184. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  17185. while (body < 4096) {
  17186. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17187. if (n <= 0) { break; }
  17188. body += static_cast<size_t>(n);
  17189. }
  17190. server_body_bytes = body;
  17191. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  17192. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  17193. SSL_shutdown(ssl);
  17194. }
  17195. SSL_free(ssl);
  17196. detail::close_socket(cli);
  17197. SSL_CTX_free(ctx);
  17198. });
  17199. auto se = detail::scope_exit([&] {
  17200. server_thread.join();
  17201. detail::close_socket(srv);
  17202. });
  17203. SSLClient cli("127.0.0.1", port);
  17204. cli.enable_server_certificate_verification(false);
  17205. cli.set_connection_timeout(5, 0);
  17206. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  17207. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  17208. std::string body(4096, 'A');
  17209. auto res = cli.Put("/api/test", body, "application/json");
  17210. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  17211. EXPECT_EQ(StatusCode::OK_200, res->status);
  17212. EXPECT_EQ(body.size(), server_body_bytes.load());
  17213. }
  17214. #endif
  17215. template <typename S, typename C>
  17216. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  17217. svr.Get("/stream", [&](const Request &, Response &res) {
  17218. auto data = new std::string("01234567890123456789");
  17219. res.set_content_provider(
  17220. data->size(), "text/plain",
  17221. [&, data](size_t offset, size_t length, DataSink &sink) {
  17222. const size_t DATA_CHUNK_SIZE = 4;
  17223. const auto &d = *data;
  17224. std::this_thread::sleep_for(std::chrono::seconds(1));
  17225. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  17226. return true;
  17227. },
  17228. [data](bool success) {
  17229. EXPECT_FALSE(success);
  17230. delete data;
  17231. });
  17232. });
  17233. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  17234. auto i = new size_t(0);
  17235. res.set_content_provider(
  17236. "text/plain",
  17237. [i](size_t, DataSink &sink) {
  17238. if (*i < 5) {
  17239. std::this_thread::sleep_for(std::chrono::seconds(1));
  17240. sink.write("abcd", 4);
  17241. (*i)++;
  17242. } else {
  17243. sink.done();
  17244. }
  17245. return true;
  17246. },
  17247. [i](bool success) {
  17248. EXPECT_FALSE(success);
  17249. delete i;
  17250. });
  17251. });
  17252. svr.Get("/chunked", [&](const Request &, Response &res) {
  17253. auto i = new size_t(0);
  17254. res.set_chunked_content_provider(
  17255. "text/plain",
  17256. [i](size_t, DataSink &sink) {
  17257. if (*i < 5) {
  17258. std::this_thread::sleep_for(std::chrono::seconds(1));
  17259. sink.os << "abcd";
  17260. (*i)++;
  17261. } else {
  17262. sink.done();
  17263. }
  17264. return true;
  17265. },
  17266. [i](bool success) {
  17267. EXPECT_FALSE(success);
  17268. delete i;
  17269. });
  17270. });
  17271. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  17272. auto se = detail::scope_exit([&] {
  17273. svr.stop();
  17274. listen_thread.join();
  17275. ASSERT_FALSE(svr.is_running());
  17276. });
  17277. svr.wait_until_ready();
  17278. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  17279. {
  17280. auto start = std::chrono::steady_clock::now();
  17281. auto res = cli.Get("/stream");
  17282. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17283. std::chrono::steady_clock::now() - start)
  17284. .count();
  17285. ASSERT_FALSE(res);
  17286. EXPECT_EQ(Error::Read, res.error());
  17287. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17288. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17289. }
  17290. {
  17291. auto start = std::chrono::steady_clock::now();
  17292. auto res = cli.Get("/stream_without_length");
  17293. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17294. std::chrono::steady_clock::now() - start)
  17295. .count();
  17296. ASSERT_FALSE(res);
  17297. EXPECT_EQ(Error::Read, res.error());
  17298. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17299. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17300. }
  17301. {
  17302. auto start = std::chrono::steady_clock::now();
  17303. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  17304. EXPECT_EQ("abcd", string(data, data_length));
  17305. return true;
  17306. });
  17307. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17308. std::chrono::steady_clock::now() - start)
  17309. .count();
  17310. ASSERT_FALSE(res);
  17311. EXPECT_EQ(Error::Read, res.error());
  17312. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17313. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17314. }
  17315. }
  17316. TEST(MaxTimeoutTest, ContentStream) {
  17317. time_t timeout = 2000;
  17318. time_t threshold = 200;
  17319. Server svr;
  17320. Client cli("localhost", PORT);
  17321. max_timeout_test(svr, cli, timeout, threshold);
  17322. }
  17323. #ifdef CPPHTTPLIB_SSL_ENABLED
  17324. TEST(MaxTimeoutTest, ContentStreamSSL) {
  17325. time_t timeout = 2000;
  17326. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  17327. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17328. SSLClient cli("localhost", PORT);
  17329. cli.enable_server_certificate_verification(false);
  17330. max_timeout_test(svr, cli, timeout, threshold);
  17331. }
  17332. #endif
  17333. class EventDispatcher {
  17334. public:
  17335. EventDispatcher() {}
  17336. bool wait_event(DataSink *sink) {
  17337. unique_lock<mutex> lk(m_);
  17338. int id = id_;
  17339. // Wait with timeout to prevent hanging if client disconnects
  17340. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  17341. [&] { return cid_ == id; })) {
  17342. return false; // Timeout occurred
  17343. }
  17344. sink->write(message_.data(), message_.size());
  17345. return true;
  17346. }
  17347. void send_event(const string &message) {
  17348. lock_guard<mutex> lk(m_);
  17349. cid_ = id_++;
  17350. message_ = message;
  17351. cv_.notify_all();
  17352. }
  17353. private:
  17354. mutex m_;
  17355. condition_variable cv_;
  17356. atomic_int id_{0};
  17357. atomic_int cid_{-1};
  17358. string message_;
  17359. };
  17360. TEST(ClientInThreadTest, Issue2068) {
  17361. EventDispatcher ed;
  17362. Server svr;
  17363. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  17364. res.set_chunked_content_provider("text/event-stream",
  17365. [&](size_t /*offset*/, DataSink &sink) {
  17366. return ed.wait_event(&sink);
  17367. });
  17368. });
  17369. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  17370. svr.wait_until_ready();
  17371. thread event_thread([&] {
  17372. int id = 0;
  17373. while (svr.is_running()) {
  17374. this_thread::sleep_for(chrono::milliseconds(500));
  17375. std::stringstream ss;
  17376. ss << "data: " << id << "\n\n";
  17377. ed.send_event(ss.str());
  17378. id++;
  17379. }
  17380. });
  17381. auto se = detail::scope_exit([&] {
  17382. svr.stop();
  17383. listen_thread.join();
  17384. event_thread.join();
  17385. ASSERT_FALSE(svr.is_running());
  17386. });
  17387. {
  17388. auto client = detail::make_unique<Client>(HOST, PORT);
  17389. client->set_read_timeout(std::chrono::minutes(10));
  17390. std::atomic<bool> stop{false};
  17391. std::thread t([&] {
  17392. client->Get("/event1",
  17393. [&](const char *, size_t) -> bool { return !stop; });
  17394. });
  17395. std::this_thread::sleep_for(std::chrono::seconds(2));
  17396. stop = true;
  17397. client->stop();
  17398. t.join();
  17399. // Reset client after thread has finished
  17400. client.reset();
  17401. }
  17402. }
  17403. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  17404. auto handled = false;
  17405. Server svr;
  17406. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17407. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17408. auto se = detail::scope_exit([&] {
  17409. svr.stop();
  17410. t.join();
  17411. ASSERT_FALSE(svr.is_running());
  17412. ASSERT_FALSE(handled);
  17413. });
  17414. svr.wait_until_ready();
  17415. // Two Content-Length headers with different values — must be rejected
  17416. auto req = "POST /test HTTP/1.1\r\n"
  17417. "Content-Length: 5\r\n"
  17418. "Content-Length: 10\r\n"
  17419. "\r\n"
  17420. "hello";
  17421. std::string response;
  17422. ASSERT_TRUE(send_request(1, req, &response));
  17423. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17424. response.substr(0, response.find("\r\n")));
  17425. }
  17426. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  17427. auto handled = false;
  17428. Server svr;
  17429. svr.Post("/test", [&](const Request &, Response &res) {
  17430. handled = true;
  17431. res.set_content("ok", "text/plain");
  17432. });
  17433. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17434. auto se = detail::scope_exit([&] {
  17435. svr.stop();
  17436. t.join();
  17437. ASSERT_FALSE(svr.is_running());
  17438. ASSERT_TRUE(handled);
  17439. });
  17440. svr.wait_until_ready();
  17441. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  17442. auto req = "POST /test HTTP/1.1\r\n"
  17443. "Host: localhost\r\n"
  17444. "Content-Length: 5\r\n"
  17445. "Content-Length: 5\r\n"
  17446. "\r\n"
  17447. "hello";
  17448. std::string response;
  17449. ASSERT_TRUE(send_request(1, req, &response));
  17450. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  17451. }
  17452. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  17453. Server svr;
  17454. svr.Get("/test", [](const Request &, Response &res) {
  17455. res.set_content("ok", "text/plain");
  17456. });
  17457. auto port = svr.bind_to_any_port(HOST);
  17458. thread t = thread([&] { svr.listen_after_bind(); });
  17459. auto se = detail::scope_exit([&] {
  17460. svr.stop();
  17461. t.join();
  17462. ASSERT_FALSE(svr.is_running());
  17463. });
  17464. svr.wait_until_ready();
  17465. auto status_line = [&](const std::string &host_lines) {
  17466. std::string res;
  17467. send_request(
  17468. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  17469. &res, port);
  17470. return res.substr(0, res.find("\r\n"));
  17471. };
  17472. const char *accepted[] = {
  17473. "Host: localhost\r\n",
  17474. "Host: a.example:8080\r\n",
  17475. "Host: my_service\r\n",
  17476. "Host: [::1]:8080\r\n",
  17477. "Host: [fe80::1%25eth0]\r\n",
  17478. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  17479. };
  17480. for (auto host_lines : accepted) {
  17481. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  17482. }
  17483. const char *rejected[] = {
  17484. "Host: a.example\r\nHost: b.example\r\n",
  17485. "Host: a.example\r\nHost: a.example\r\n",
  17486. "Host: a@b.example\r\n",
  17487. "Host: a.example/b\r\n",
  17488. "Host: a.example\\b\r\n",
  17489. "Host: a.example?b\r\n",
  17490. "Host: a.example#b\r\n",
  17491. "Host: a.example b.example\r\n",
  17492. };
  17493. for (auto host_lines : rejected) {
  17494. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  17495. << host_lines;
  17496. }
  17497. }
  17498. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  17499. Server svr;
  17500. svr.Get("/", [](const Request &req, Response &res) {
  17501. EXPECT_EQ(2U, req.trailers.size());
  17502. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  17503. // Denied
  17504. EXPECT_FALSE(req.has_trailer("Content-Length"));
  17505. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  17506. // Accepted
  17507. EXPECT_TRUE(req.has_trailer("X-Hello"));
  17508. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  17509. EXPECT_TRUE(req.has_trailer("X-World"));
  17510. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  17511. res.set_content("ok", "text/plain");
  17512. });
  17513. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17514. auto se = detail::scope_exit([&] {
  17515. svr.stop();
  17516. t.join();
  17517. ASSERT_FALSE(svr.is_running());
  17518. });
  17519. svr.wait_until_ready();
  17520. const std::string req = "GET / HTTP/1.1\r\n"
  17521. "Transfer-Encoding: chunked\r\n"
  17522. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  17523. "\r\n"
  17524. "0\r\n"
  17525. "Content-Length: 10\r\n"
  17526. "Host: internal.local\r\n"
  17527. "Content-Type: malicious/content\r\n"
  17528. "Cookie: any\r\n"
  17529. "Set-Cookie: any\r\n"
  17530. "X-Forwarded-For: attacker.com\r\n"
  17531. "X-Real-Ip: 1.1.1.1\r\n"
  17532. "X-Hello: hello\r\n"
  17533. "X-World: world\r\n"
  17534. "\r\n";
  17535. std::string res;
  17536. ASSERT_TRUE(send_request(1, req, &res));
  17537. }
  17538. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  17539. // several field lines, and the combined value is what has to be parsed. A
  17540. // Trailer field split across lines therefore declares every name it lists;
  17541. // reading only the first line silently drops the trailers the later lines
  17542. // declare. The prohibited-trailer filter still applies to every line.
  17543. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  17544. Server svr;
  17545. size_t observed_trailer_count = 0;
  17546. std::string observed_hello;
  17547. std::string observed_world;
  17548. bool observed_content_length = true;
  17549. svr.Get("/", [&](const Request &req, Response &res) {
  17550. observed_trailer_count = req.trailers.size();
  17551. observed_hello = req.get_trailer_value("X-Hello");
  17552. observed_world = req.get_trailer_value("X-World");
  17553. observed_content_length = req.has_trailer("Content-Length");
  17554. res.set_content("ok", "text/plain");
  17555. });
  17556. auto port = svr.bind_to_any_port(HOST);
  17557. thread t = thread([&]() { svr.listen_after_bind(); });
  17558. auto se = detail::scope_exit([&] {
  17559. svr.stop();
  17560. t.join();
  17561. ASSERT_FALSE(svr.is_running());
  17562. });
  17563. svr.wait_until_ready();
  17564. const std::string req = "GET / HTTP/1.1\r\n"
  17565. "Host: localhost\r\n"
  17566. "Transfer-Encoding: chunked\r\n"
  17567. "Trailer: X-Hello\r\n"
  17568. "Trailer: X-World, Content-Length\r\n"
  17569. "\r\n"
  17570. "0\r\n"
  17571. "X-Hello: hello\r\n"
  17572. "X-World: world\r\n"
  17573. "Content-Length: 10\r\n"
  17574. "\r\n";
  17575. std::string res;
  17576. ASSERT_TRUE(send_request(1, req, &res, port));
  17577. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  17578. // Accepted: both field lines contribute to the declared set
  17579. EXPECT_EQ(2U, observed_trailer_count);
  17580. EXPECT_EQ(observed_hello, "hello");
  17581. EXPECT_EQ(observed_world, "world");
  17582. // Denied: a prohibited name stays prohibited on a later field line
  17583. EXPECT_FALSE(observed_content_length);
  17584. }
  17585. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  17586. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  17587. // unbounded run of fields that are never declared, because the counter would
  17588. // only advance for declared fields.
  17589. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  17590. Server svr;
  17591. bool handler_called = false;
  17592. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  17593. handler_called = true;
  17594. res.set_content("ok", "text/plain");
  17595. });
  17596. auto port = svr.bind_to_any_port(HOST);
  17597. thread t = thread([&]() { svr.listen_after_bind(); });
  17598. auto se = detail::scope_exit([&] {
  17599. svr.stop();
  17600. t.join();
  17601. ASSERT_FALSE(svr.is_running());
  17602. });
  17603. svr.wait_until_ready();
  17604. // Declare nothing, then send far more undeclared trailer fields than the
  17605. // header-count limit. Parsing must stop and reject the request rather than
  17606. // read every line.
  17607. std::string req = "GET / HTTP/1.1\r\n"
  17608. "Transfer-Encoding: chunked\r\n"
  17609. "\r\n"
  17610. "0\r\n";
  17611. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  17612. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  17613. }
  17614. req += "\r\n";
  17615. std::string res;
  17616. ASSERT_TRUE(send_request(1, req, &res, port));
  17617. // The request is rejected before the handler runs.
  17618. EXPECT_FALSE(handler_called);
  17619. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  17620. }
  17621. // The set of declared trailer names is capped so a peer cannot grow it without
  17622. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  17623. // declared past the cap is not honored, even if the field is actually sent.
  17624. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  17625. Server svr;
  17626. // One name inside the cap and one past it, so the test tracks the cap rather
  17627. // than a fixed count.
  17628. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  17629. const std::string within_cap_name = "X-T-0";
  17630. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  17631. bool observed_within_cap = false;
  17632. bool observed_past_cap = false;
  17633. svr.Get("/", [&](const Request &req, Response &res) {
  17634. observed_within_cap = req.has_trailer(within_cap_name);
  17635. observed_past_cap = req.has_trailer(past_cap_name);
  17636. res.set_content("ok", "text/plain");
  17637. });
  17638. auto port = svr.bind_to_any_port(HOST);
  17639. thread t = thread([&]() { svr.listen_after_bind(); });
  17640. auto se = detail::scope_exit([&] {
  17641. svr.stop();
  17642. t.join();
  17643. ASSERT_FALSE(svr.is_running());
  17644. });
  17645. svr.wait_until_ready();
  17646. // Declare more trailer names than the cap in a single Trailer field, then
  17647. // actually send the first (within the cap) and the last (past it).
  17648. std::string trailer_decl = "Trailer: ";
  17649. for (int i = 0; i < declared_count; i++) {
  17650. if (i != 0) { trailer_decl += ", "; }
  17651. trailer_decl += "X-T-" + std::to_string(i);
  17652. }
  17653. trailer_decl += "\r\n";
  17654. const std::string req = "GET / HTTP/1.1\r\n"
  17655. "Host: localhost\r\n"
  17656. "Transfer-Encoding: chunked\r\n" +
  17657. trailer_decl +
  17658. "\r\n"
  17659. "0\r\n" +
  17660. within_cap_name + ": a\r\n" + past_cap_name +
  17661. ": b\r\n"
  17662. "\r\n";
  17663. std::string res;
  17664. ASSERT_TRUE(send_request(1, req, &res, port));
  17665. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  17666. // A name within the cap is honored; one declared past the cap is dropped.
  17667. EXPECT_TRUE(observed_within_cap);
  17668. EXPECT_FALSE(observed_past_cap);
  17669. }
  17670. // A direct client that is not listed in trusted_proxies must not be able to
  17671. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  17672. // the peer address on the actual TCP connection determines whether the
  17673. // header is honored.
  17674. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  17675. Server svr;
  17676. // Deliberately does NOT include the loopback address the test client
  17677. // actually connects from, so the direct connection is not a trusted proxy.
  17678. svr.set_trusted_proxies({"203.0.113.66"});
  17679. std::string observed_remote_addr;
  17680. svr.Get("/ip", [&](const Request &req, Response &res) {
  17681. observed_remote_addr = req.remote_addr;
  17682. res.set_content("ok", "text/plain");
  17683. });
  17684. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17685. auto se = detail::scope_exit([&] {
  17686. svr.stop();
  17687. t.join();
  17688. ASSERT_FALSE(svr.is_running());
  17689. });
  17690. svr.wait_until_ready();
  17691. Client cli(HOST, PORT);
  17692. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  17693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17694. EXPECT_EQ(StatusCode::OK_200, res->status);
  17695. // The connecting peer is not a trusted proxy, so the spoofed header must be
  17696. // ignored entirely and the real connection-level address retained.
  17697. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17698. observed_remote_addr == "127.0.0.1");
  17699. }
  17700. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  17701. Server svr;
  17702. std::string observed_remote_addr;
  17703. std::string observed_xff;
  17704. svr.Get("/ip", [&](const Request &req, Response &res) {
  17705. observed_remote_addr = req.remote_addr;
  17706. observed_xff = req.get_header_value("X-Forwarded-For");
  17707. res.set_content("ok", "text/plain");
  17708. });
  17709. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17710. auto se = detail::scope_exit([&] {
  17711. svr.stop();
  17712. t.join();
  17713. ASSERT_FALSE(svr.is_running());
  17714. });
  17715. svr.wait_until_ready();
  17716. Client cli(HOST, PORT);
  17717. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  17718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17719. EXPECT_EQ(StatusCode::OK_200, res->status);
  17720. EXPECT_EQ(observed_xff, "203.0.113.66");
  17721. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17722. observed_remote_addr == "127.0.0.1");
  17723. }
  17724. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  17725. Server svr;
  17726. svr.set_trusted_proxies({"203.0.113.66"});
  17727. std::string observed_remote_addr;
  17728. std::string observed_xff;
  17729. svr.Get("/ip", [&](const Request &req, Response &res) {
  17730. observed_remote_addr = req.remote_addr;
  17731. observed_xff = req.get_header_value("X-Forwarded-For");
  17732. res.set_content("ok", "text/plain");
  17733. });
  17734. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17735. auto se = detail::scope_exit([&] {
  17736. svr.stop();
  17737. t.join();
  17738. ASSERT_FALSE(svr.is_running());
  17739. });
  17740. svr.wait_until_ready();
  17741. Client cli(HOST, PORT);
  17742. auto res = cli.Get("/ip");
  17743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17744. EXPECT_EQ(StatusCode::OK_200, res->status);
  17745. EXPECT_EQ(observed_xff, "");
  17746. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17747. observed_remote_addr == "127.0.0.1");
  17748. }
  17749. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  17750. Server svr;
  17751. // Include the loopback address the test client actually connects from, so
  17752. // the direct connection itself is recognized as the trusted proxy hop.
  17753. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  17754. std::string observed_remote_addr;
  17755. std::string observed_xff;
  17756. svr.Get("/ip", [&](const Request &req, Response &res) {
  17757. observed_remote_addr = req.remote_addr;
  17758. observed_xff = req.get_header_value("X-Forwarded-For");
  17759. res.set_content("ok", "text/plain");
  17760. });
  17761. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17762. auto se = detail::scope_exit([&] {
  17763. svr.stop();
  17764. t.join();
  17765. ASSERT_FALSE(svr.is_running());
  17766. });
  17767. svr.wait_until_ready();
  17768. Client cli(HOST, PORT);
  17769. auto res = cli.Get(
  17770. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  17771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17772. EXPECT_EQ(StatusCode::OK_200, res->status);
  17773. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  17774. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17775. }
  17776. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  17777. Server svr;
  17778. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  17779. std::string observed_remote_addr;
  17780. std::string observed_xff;
  17781. svr.Get("/ip", [&](const Request &req, Response &res) {
  17782. observed_remote_addr = req.remote_addr;
  17783. observed_xff = req.get_header_value("X-Forwarded-For");
  17784. res.set_content("ok", "text/plain");
  17785. });
  17786. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17787. auto se = detail::scope_exit([&] {
  17788. svr.stop();
  17789. t.join();
  17790. ASSERT_FALSE(svr.is_running());
  17791. });
  17792. svr.wait_until_ready();
  17793. Client cli(HOST, PORT);
  17794. auto res = cli.Get(
  17795. "/ip",
  17796. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17798. EXPECT_EQ(StatusCode::OK_200, res->status);
  17799. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17800. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17801. }
  17802. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  17803. Server svr;
  17804. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17805. std::string observed_remote_addr;
  17806. std::string observed_xff;
  17807. svr.Get("/ip", [&](const Request &req, Response &res) {
  17808. observed_remote_addr = req.remote_addr;
  17809. observed_xff = req.get_header_value("X-Forwarded-For");
  17810. res.set_content("ok", "text/plain");
  17811. });
  17812. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17813. auto se = detail::scope_exit([&] {
  17814. svr.stop();
  17815. t.join();
  17816. ASSERT_FALSE(svr.is_running());
  17817. });
  17818. svr.wait_until_ready();
  17819. Client cli(HOST, PORT);
  17820. auto res = cli.Get(
  17821. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  17822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17823. EXPECT_EQ(StatusCode::OK_200, res->status);
  17824. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  17825. // by the closest hop) is used. The leftmost entry is fully client-controlled
  17826. // and must not be selected.
  17827. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  17828. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  17829. }
  17830. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  17831. Server svr;
  17832. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  17833. std::string observed_remote_addr;
  17834. svr.Get("/ip", [&](const Request &req, Response &res) {
  17835. observed_remote_addr = req.remote_addr;
  17836. res.set_content("ok", "text/plain");
  17837. });
  17838. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17839. auto se = detail::scope_exit([&] {
  17840. svr.stop();
  17841. t.join();
  17842. ASSERT_FALSE(svr.is_running());
  17843. });
  17844. svr.wait_until_ready();
  17845. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  17846. // a forged address and the trusted proxy's own address; the forged value must
  17847. // not win over the address the trusted proxy actually recorded.
  17848. Client cli(HOST, PORT);
  17849. auto res = cli.Get(
  17850. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  17851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17852. EXPECT_EQ(StatusCode::OK_200, res->status);
  17853. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  17854. }
  17855. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  17856. Server svr;
  17857. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17858. std::string observed_remote_addr;
  17859. std::string observed_xff;
  17860. svr.Get("/ip", [&](const Request &req, Response &res) {
  17861. observed_remote_addr = req.remote_addr;
  17862. observed_xff = req.get_header_value("X-Forwarded-For");
  17863. res.set_content("ok", "text/plain");
  17864. });
  17865. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17866. auto se = detail::scope_exit([&] {
  17867. svr.stop();
  17868. t.join();
  17869. ASSERT_FALSE(svr.is_running());
  17870. });
  17871. svr.wait_until_ready();
  17872. Client cli(HOST, PORT);
  17873. auto res = cli.Get(
  17874. "/ip",
  17875. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17877. EXPECT_EQ(StatusCode::OK_200, res->status);
  17878. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17879. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17880. }
  17881. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  17882. Server svr;
  17883. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17884. std::string observed_remote_addr;
  17885. std::string observed_xff;
  17886. svr.Get("/ip", [&](const Request &req, Response &res) {
  17887. observed_remote_addr = req.remote_addr;
  17888. observed_xff = req.get_header_value("X-Forwarded-For");
  17889. res.set_content("ok", "text/plain");
  17890. });
  17891. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17892. auto se = detail::scope_exit([&] {
  17893. svr.stop();
  17894. t.join();
  17895. ASSERT_FALSE(svr.is_running());
  17896. });
  17897. svr.wait_until_ready();
  17898. std::string raw_req =
  17899. "GET /ip HTTP/1.1\r\n"
  17900. "Host: localhost\r\n"
  17901. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  17902. "Connection: close\r\n"
  17903. "\r\n";
  17904. std::string out;
  17905. ASSERT_TRUE(send_request(5, raw_req, &out));
  17906. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17907. // Header parser trims surrounding whitespace of the header value
  17908. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  17909. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17910. }
  17911. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  17912. // one comma-joined value, in the order received. Proxies such as HAProxy append
  17913. // their own X-Forwarded-For as a separate field line rather than extending the
  17914. // one the client sent, so every occurrence has to be taken into account.
  17915. // Reading only the first one hands back the address the client chose.
  17916. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  17917. Server svr;
  17918. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17919. std::string observed_remote_addr;
  17920. size_t observed_xff_count = 0;
  17921. svr.Get("/ip", [&](const Request &req, Response &res) {
  17922. observed_remote_addr = req.remote_addr;
  17923. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  17924. res.set_content("ok", "text/plain");
  17925. });
  17926. auto port = svr.bind_to_any_port(HOST);
  17927. thread t = thread([&]() { svr.listen_after_bind(); });
  17928. auto se = detail::scope_exit([&] {
  17929. svr.stop();
  17930. t.join();
  17931. ASSERT_FALSE(svr.is_running());
  17932. });
  17933. svr.wait_until_ready();
  17934. // The client supplies the first field line; the trusted proxy appends the
  17935. // address it observed as a second one.
  17936. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  17937. "Host: localhost\r\n"
  17938. "X-Forwarded-For: 1.2.3.4\r\n"
  17939. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  17940. "Connection: close\r\n"
  17941. "\r\n";
  17942. std::string out;
  17943. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17944. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17945. EXPECT_EQ(observed_xff_count, 2U);
  17946. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17947. // The same chain spread over one field line per hop derives the same client
  17948. // address, i.e. the split and the comma-joined representations agree.
  17949. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  17950. "Host: localhost\r\n"
  17951. "X-Forwarded-For: 1.2.3.4\r\n"
  17952. "X-Forwarded-For: 198.51.100.23\r\n"
  17953. "X-Forwarded-For: 192.0.2.45\r\n"
  17954. "Connection: close\r\n"
  17955. "\r\n";
  17956. out.clear();
  17957. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  17958. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17959. EXPECT_EQ(observed_xff_count, 3U);
  17960. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17961. }
  17962. // An X-Forwarded-For header whose value parses to zero IP segments must not
  17963. // crash the server (it used to call front() on an empty vector inside
  17964. // get_client_ip). The connection-level remote address must be retained instead.
  17965. static void run_malformed_xff_test(const std::string &xff_value) {
  17966. Server svr;
  17967. svr.set_trusted_proxies({"192.0.2.45"});
  17968. std::string observed_remote_addr;
  17969. svr.Get("/ip", [&](const Request &req, Response &res) {
  17970. observed_remote_addr = req.remote_addr;
  17971. res.set_content("ok", "text/plain");
  17972. });
  17973. int port = 0;
  17974. thread t = thread([&]() {
  17975. port = svr.bind_to_any_port(HOST);
  17976. svr.listen_after_bind();
  17977. });
  17978. auto se = detail::scope_exit([&] {
  17979. svr.stop();
  17980. t.join();
  17981. ASSERT_FALSE(svr.is_running());
  17982. });
  17983. svr.wait_until_ready();
  17984. Client cli(HOST, port);
  17985. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  17986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17987. EXPECT_EQ(StatusCode::OK_200, res->status);
  17988. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17989. observed_remote_addr == "127.0.0.1");
  17990. }
  17991. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  17992. run_malformed_xff_test("");
  17993. }
  17994. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  17995. run_malformed_xff_test(",");
  17996. }
  17997. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  17998. run_malformed_xff_test(", , ,");
  17999. }
  18000. // The same rule applies to Accept: a request whose acceptable types are spread
  18001. // over several field lines must be negotiated against all of them.
  18002. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  18003. // case-insensitive connection options. Comparing the whole field value against
  18004. // one option misses a client that sends several of them, and misses every
  18005. // casing but the one written in the comparison.
  18006. //
  18007. // Sends req, reads the response, then reuses the same socket for a second
  18008. // request to find out whether the server kept the connection.
  18009. static void probe_connection_reuse(int port, const std::string &req,
  18010. bool *announced_close, bool *reusable) {
  18011. auto error = Error::Success;
  18012. auto sock = detail::create_client_socket(
  18013. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18014. /*connection_timeout_sec=*/5, 0,
  18015. /*read_timeout_sec=*/1, 0,
  18016. /*write_timeout_sec=*/5, 0, std::string(), error);
  18017. ASSERT_NE(sock, INVALID_SOCKET);
  18018. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  18019. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  18020. "Host: localhost\r\n"
  18021. "Connection: close\r\n"
  18022. "\r\n";
  18023. std::string first_response;
  18024. std::string second_response;
  18025. detail::process_client_socket(
  18026. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  18027. [&](Stream &strm) {
  18028. if (strm.write(req.data(), req.size()) !=
  18029. static_cast<ssize_t>(req.size())) {
  18030. return false;
  18031. }
  18032. char buf[512];
  18033. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  18034. // Headers plus the two-byte body of the handler below
  18035. while (reader.getline()) {
  18036. first_response += reader.ptr();
  18037. if (first_response.find("ok") != std::string::npos) { break; }
  18038. }
  18039. if (strm.write(second.data(), second.size()) !=
  18040. static_cast<ssize_t>(second.size())) {
  18041. return true;
  18042. }
  18043. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  18044. while (reader2.getline()) {
  18045. second_response += reader2.ptr();
  18046. if (second_response.find("ok") != std::string::npos) { break; }
  18047. }
  18048. return true;
  18049. });
  18050. *announced_close =
  18051. first_response.find("Connection: close") != std::string::npos;
  18052. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  18053. }
  18054. class ConnectionTokenTest : public ::testing::Test {
  18055. protected:
  18056. void SetUp() override {
  18057. svr_.Get("/keepalive", [](const Request &, Response &res) {
  18058. res.set_content("ok", "text/plain");
  18059. });
  18060. port_ = svr_.bind_to_any_port(HOST);
  18061. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18062. svr_.wait_until_ready();
  18063. }
  18064. void TearDown() override {
  18065. svr_.stop();
  18066. if (thread_.joinable()) { thread_.join(); }
  18067. }
  18068. Server svr_;
  18069. int port_ = 0;
  18070. thread thread_;
  18071. };
  18072. // "close" alongside another option still closes the connection, and the
  18073. // response says so rather than leaving the peer to discover it.
  18074. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  18075. bool announced_close = false;
  18076. bool reusable = true;
  18077. probe_connection_reuse(port_,
  18078. "GET /keepalive HTTP/1.1\r\n"
  18079. "Host: localhost\r\n"
  18080. "Connection: keep-alive, close\r\n"
  18081. "\r\n",
  18082. &announced_close, &reusable);
  18083. EXPECT_TRUE(announced_close);
  18084. EXPECT_FALSE(reusable);
  18085. }
  18086. // "close" split over two field lines is the same list, so it is honored too.
  18087. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  18088. bool announced_close = false;
  18089. bool reusable = true;
  18090. probe_connection_reuse(port_,
  18091. "GET /keepalive HTTP/1.1\r\n"
  18092. "Host: localhost\r\n"
  18093. "Connection: keep-alive\r\n"
  18094. "Connection: close\r\n"
  18095. "\r\n",
  18096. &announced_close, &reusable);
  18097. EXPECT_TRUE(announced_close);
  18098. EXPECT_FALSE(reusable);
  18099. }
  18100. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  18101. // keep-alive in the spelling everyone actually sends keeps its connection.
  18102. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  18103. bool announced_close = false;
  18104. bool reusable = false;
  18105. probe_connection_reuse(port_,
  18106. "GET /keepalive HTTP/1.0\r\n"
  18107. "Host: localhost\r\n"
  18108. "Connection: keep-alive\r\n"
  18109. "\r\n",
  18110. &announced_close, &reusable);
  18111. EXPECT_FALSE(announced_close);
  18112. EXPECT_TRUE(reusable);
  18113. }
  18114. // A token the value merely contains is not the token itself.
  18115. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  18116. bool announced_close = false;
  18117. bool reusable = false;
  18118. probe_connection_reuse(port_,
  18119. "GET /keepalive HTTP/1.1\r\n"
  18120. "Host: localhost\r\n"
  18121. "Connection: notclose\r\n"
  18122. "\r\n",
  18123. &announced_close, &reusable);
  18124. EXPECT_FALSE(announced_close);
  18125. EXPECT_TRUE(reusable);
  18126. }
  18127. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  18128. Server svr;
  18129. std::vector<std::string> observed_types;
  18130. svr.Get("/", [&](const Request &req, Response &res) {
  18131. observed_types = req.accept_content_types;
  18132. res.set_content("ok", "text/plain");
  18133. });
  18134. auto port = svr.bind_to_any_port(HOST);
  18135. thread t = thread([&]() { svr.listen_after_bind(); });
  18136. auto se = detail::scope_exit([&] {
  18137. svr.stop();
  18138. t.join();
  18139. ASSERT_FALSE(svr.is_running());
  18140. });
  18141. svr.wait_until_ready();
  18142. Client cli(HOST, port);
  18143. Headers headers;
  18144. headers.emplace("Accept", "text/plain;q=0.5");
  18145. headers.emplace("Accept", "application/json");
  18146. auto res = cli.Get("/", headers);
  18147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18148. EXPECT_EQ(StatusCode::OK_200, res->status);
  18149. // Sorted by q-value, so the second field line's type comes first
  18150. ASSERT_EQ(2U, observed_types.size());
  18151. EXPECT_EQ("application/json", observed_types[0]);
  18152. EXPECT_EQ("text/plain", observed_types[1]);
  18153. }
  18154. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  18155. // empty field line must not contribute a bare comma to the combined value.
  18156. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  18157. Server svr;
  18158. std::vector<std::string> observed_types;
  18159. svr.Get("/", [&](const Request &req, Response &res) {
  18160. observed_types = req.accept_content_types;
  18161. res.set_content("ok", "text/plain");
  18162. });
  18163. auto port = svr.bind_to_any_port(HOST);
  18164. thread t = thread([&]() { svr.listen_after_bind(); });
  18165. auto se = detail::scope_exit([&] {
  18166. svr.stop();
  18167. t.join();
  18168. ASSERT_FALSE(svr.is_running());
  18169. });
  18170. svr.wait_until_ready();
  18171. // Empty first field line, then a real one
  18172. std::string raw_req = "GET / HTTP/1.1\r\n"
  18173. "Host: localhost\r\n"
  18174. "Accept:\r\n"
  18175. "Accept: application/json\r\n"
  18176. "Connection: close\r\n"
  18177. "\r\n";
  18178. std::string out;
  18179. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18180. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18181. ASSERT_EQ(1U, observed_types.size());
  18182. EXPECT_EQ("application/json", observed_types[0]);
  18183. }
  18184. // The skip in get_combined_header_value() is what keeps an empty field line
  18185. // from contributing a bare comma. Only a trailing empty field line exercises
  18186. // it: a leading one is already covered by the "combined is still empty" check,
  18187. // and parse_accept_header() now ignores the empty element either way, so the
  18188. // request-level test above can no longer tell the two apart.
  18189. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  18190. Headers headers;
  18191. headers.emplace("Accept", "text/html");
  18192. headers.emplace("Accept", "");
  18193. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  18194. headers.clear();
  18195. headers.emplace("Accept", "");
  18196. headers.emplace("Accept", "application/json");
  18197. EXPECT_EQ("application/json",
  18198. detail::get_combined_header_value(headers, "Accept"));
  18199. }
  18200. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18201. // An encoding offered on a later Accept-Encoding field line is still offered.
  18202. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  18203. Server svr;
  18204. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18205. res.set_content(std::string(1024, 'x'), "text/plain");
  18206. });
  18207. auto port = svr.bind_to_any_port(HOST);
  18208. thread t = thread([&]() { svr.listen_after_bind(); });
  18209. auto se = detail::scope_exit([&] {
  18210. svr.stop();
  18211. t.join();
  18212. ASSERT_FALSE(svr.is_running());
  18213. });
  18214. svr.wait_until_ready();
  18215. Client cli(HOST, port);
  18216. cli.set_decompress(false);
  18217. Headers headers;
  18218. headers.emplace("Accept-Encoding", "identity");
  18219. headers.emplace("Accept-Encoding", "gzip");
  18220. auto res = cli.Get("/", headers);
  18221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18222. EXPECT_EQ(StatusCode::OK_200, res->status);
  18223. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  18224. }
  18225. #endif
  18226. #ifndef _WIN32
  18227. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  18228. Server svr;
  18229. svr.Post("/post", [&](const Request &req, Response &res) {
  18230. res.set_content(req.body, "text/plain");
  18231. });
  18232. svr.Put("/put", [&](const Request &req, Response &res) {
  18233. res.set_content(req.body, "text/plain");
  18234. });
  18235. svr.Patch("/patch", [&](const Request &req, Response &res) {
  18236. res.set_content(req.body, "text/plain");
  18237. });
  18238. svr.Delete("/delete", [&](const Request &req, Response &res) {
  18239. res.set_content(req.body, "text/plain");
  18240. });
  18241. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18242. auto se = detail::scope_exit([&] {
  18243. svr.stop();
  18244. t.join();
  18245. ASSERT_FALSE(svr.is_running());
  18246. });
  18247. svr.wait_until_ready();
  18248. std::string resp;
  18249. // POST without Content-Length
  18250. ASSERT_TRUE(send_request(5,
  18251. "POST /post HTTP/1.1\r\n"
  18252. "Host: localhost\r\n"
  18253. "Connection: close\r\n"
  18254. "\r\n",
  18255. &resp));
  18256. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18257. // PUT without Content-Length
  18258. resp.clear();
  18259. ASSERT_TRUE(send_request(5,
  18260. "PUT /put HTTP/1.1\r\n"
  18261. "Host: localhost\r\n"
  18262. "Connection: close\r\n"
  18263. "\r\n",
  18264. &resp));
  18265. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18266. // PATCH without Content-Length
  18267. resp.clear();
  18268. ASSERT_TRUE(send_request(5,
  18269. "PATCH /patch HTTP/1.1\r\n"
  18270. "Host: localhost\r\n"
  18271. "Connection: close\r\n"
  18272. "\r\n",
  18273. &resp));
  18274. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18275. // DELETE without Content-Length
  18276. resp.clear();
  18277. ASSERT_TRUE(send_request(5,
  18278. "DELETE /delete HTTP/1.1\r\n"
  18279. "Host: localhost\r\n"
  18280. "Connection: close\r\n"
  18281. "\r\n",
  18282. &resp));
  18283. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18284. }
  18285. #endif
  18286. //==============================================================================
  18287. // open_stream() Tests
  18288. //==============================================================================
  18289. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  18290. std::string result;
  18291. char buf[8192];
  18292. ssize_t n;
  18293. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18294. result.append(buf, static_cast<size_t>(n));
  18295. }
  18296. return result;
  18297. }
  18298. // Mock stream for unit tests
  18299. class MockStream : public Stream {
  18300. public:
  18301. std::string data;
  18302. size_t pos = 0;
  18303. ssize_t error_after = -1; // -1 = no error
  18304. explicit MockStream(const std::string &d, ssize_t err = -1)
  18305. : data(d), error_after(err) {}
  18306. bool is_readable() const override { return true; }
  18307. bool wait_readable() const override { return true; }
  18308. bool wait_writable() const override { return true; }
  18309. ssize_t read(char *ptr, size_t size) override {
  18310. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  18311. if (pos >= data.size()) return 0;
  18312. size_t limit =
  18313. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  18314. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  18315. std::memcpy(ptr, data.data() + pos, to_read);
  18316. pos += to_read;
  18317. return static_cast<ssize_t>(to_read);
  18318. }
  18319. ssize_t write(const char *, size_t) override { return -1; }
  18320. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  18321. ip = "127.0.0.1";
  18322. port = 0;
  18323. }
  18324. void get_local_ip_and_port(std::string &ip, int &port) const override {
  18325. ip = "127.0.0.1";
  18326. port = 0;
  18327. }
  18328. socket_t socket() const override { return INVALID_SOCKET; }
  18329. time_t duration() const override { return 0; }
  18330. };
  18331. TEST(StreamHandleTest, Basic) {
  18332. ClientImpl::StreamHandle handle;
  18333. EXPECT_FALSE(handle.is_valid());
  18334. handle.response = detail::make_unique<Response>();
  18335. handle.error = Error::Connection;
  18336. EXPECT_FALSE(handle.is_valid());
  18337. handle.error = Error::Success;
  18338. EXPECT_TRUE(handle.is_valid());
  18339. }
  18340. TEST(BodyReaderTest, Basic) {
  18341. MockStream stream("Hello, World!");
  18342. detail::BodyReader reader;
  18343. reader.stream = &stream;
  18344. reader.content_length = 13;
  18345. char buf[32];
  18346. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  18347. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  18348. EXPECT_TRUE(reader.eof);
  18349. }
  18350. TEST(BodyReaderTest, NoStream) {
  18351. detail::BodyReader reader;
  18352. char buf[32];
  18353. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18354. EXPECT_EQ(Error::Connection, reader.last_error);
  18355. }
  18356. TEST(BodyReaderTest, Error) {
  18357. MockStream stream("Hello, World!", 5);
  18358. detail::BodyReader reader;
  18359. reader.stream = &stream;
  18360. reader.content_length = 13;
  18361. char buf[32];
  18362. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  18363. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18364. EXPECT_EQ(Error::Read, reader.last_error);
  18365. }
  18366. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  18367. // Mock-based StreamHandle tests relying on private internals are removed.
  18368. class OpenStreamTest : public ::testing::Test {
  18369. protected:
  18370. void SetUp() override {
  18371. svr_.Get("/hello", [](const Request &, Response &res) {
  18372. res.set_content("Hello World!", "text/plain");
  18373. });
  18374. svr_.Get("/large", [](const Request &, Response &res) {
  18375. res.set_content(std::string(10000, 'X'), "text/plain");
  18376. });
  18377. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  18378. res.set_content("Hello World!", "image/jpeg");
  18379. res.set_header("Content-Encoding", "UTF-8");
  18380. });
  18381. svr_.Get("/chunked", [](const Request &, Response &res) {
  18382. res.set_chunked_content_provider("text/plain",
  18383. [](size_t offset, DataSink &sink) {
  18384. if (offset < 15) {
  18385. sink.write("chunk", 5);
  18386. return true;
  18387. }
  18388. sink.done();
  18389. return true;
  18390. });
  18391. });
  18392. svr_.Get("/compressible", [](const Request &, Response &res) {
  18393. res.set_chunked_content_provider("text/plain", [](size_t offset,
  18394. DataSink &sink) {
  18395. if (offset < 100 * 1024) {
  18396. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  18397. sink.write(chunk.data(), chunk.size());
  18398. return true;
  18399. }
  18400. sink.done();
  18401. return true;
  18402. });
  18403. });
  18404. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  18405. [](const Request & /*req*/, Response &res) {
  18406. auto i = new int(0);
  18407. res.set_header("Trailer", "Content-Length, X-Allowed");
  18408. res.set_chunked_content_provider(
  18409. "text/plain",
  18410. [i](size_t /*offset*/, DataSink &sink) {
  18411. switch (*i) {
  18412. case 0: sink.os << "123"; break;
  18413. case 1: sink.os << "456"; break;
  18414. case 2: sink.os << "789"; break;
  18415. case 3: {
  18416. sink.done_with_trailer(
  18417. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  18418. } break;
  18419. }
  18420. (*i)++;
  18421. return true;
  18422. },
  18423. [i](bool success) {
  18424. EXPECT_TRUE(success);
  18425. delete i;
  18426. });
  18427. });
  18428. // Echo headers endpoint for header-related tests
  18429. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  18430. std::string body;
  18431. for (const auto &h : req.headers) {
  18432. body.append(h.first);
  18433. body.push_back(':');
  18434. body.append(h.second);
  18435. body.push_back('\n');
  18436. }
  18437. res.set_content(body, "text/plain");
  18438. });
  18439. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  18440. std::string body;
  18441. for (const auto &h : req.headers) {
  18442. body.append(h.first);
  18443. body.push_back(':');
  18444. body.append(h.second);
  18445. body.push_back('\n');
  18446. }
  18447. res.set_content(body, "text/plain");
  18448. });
  18449. port_ = svr_.bind_to_any_port("127.0.0.1");
  18450. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18451. svr_.wait_until_ready();
  18452. }
  18453. void TearDown() override {
  18454. svr_.stop();
  18455. if (thread_.joinable()) thread_.join();
  18456. }
  18457. Server svr_;
  18458. std::thread thread_;
  18459. int port_ = 0;
  18460. };
  18461. TEST_F(OpenStreamTest, Basic) {
  18462. Client cli("127.0.0.1", port_);
  18463. auto handle = cli.open_stream("GET", "/hello");
  18464. EXPECT_TRUE(handle.is_valid());
  18465. EXPECT_EQ("Hello World!", read_all(handle));
  18466. }
  18467. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  18468. Client cli("127.0.0.1", port_);
  18469. auto handle = cli.open_stream("GET", "/unknown-encoding");
  18470. ASSERT_TRUE(handle.is_valid());
  18471. EXPECT_EQ("Hello World!", read_all(handle));
  18472. }
  18473. TEST_F(OpenStreamTest, SmallBuffer) {
  18474. Client cli("127.0.0.1", port_);
  18475. auto handle = cli.open_stream("GET", "/hello");
  18476. std::string result;
  18477. char buf[4];
  18478. ssize_t n;
  18479. while ((n = handle.read(buf, sizeof(buf))) > 0)
  18480. result.append(buf, static_cast<size_t>(n));
  18481. EXPECT_EQ("Hello World!", result);
  18482. }
  18483. TEST_F(OpenStreamTest, DefaultHeaders) {
  18484. Client cli("127.0.0.1", port_);
  18485. // open_stream GET should include Host, User-Agent and Accept-Encoding
  18486. {
  18487. auto handle = cli.open_stream("GET", "/echo-headers");
  18488. ASSERT_TRUE(handle.is_valid());
  18489. auto body = read_all(handle);
  18490. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  18491. std::string::npos);
  18492. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  18493. std::string::npos);
  18494. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  18495. }
  18496. // open_stream POST with body and no explicit content_type should NOT add
  18497. // text/plain Content-Type (behavior differs from non-streaming path), but
  18498. // should include Content-Length
  18499. {
  18500. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  18501. ASSERT_TRUE(handle.is_valid());
  18502. auto body = read_all(handle);
  18503. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  18504. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  18505. }
  18506. // open_stream POST with explicit Content-Type should preserve it
  18507. {
  18508. auto handle = cli.open_stream("POST", "/echo-headers", {},
  18509. {{"Content-Type", "application/custom"}},
  18510. "{}", "application/custom");
  18511. ASSERT_TRUE(handle.is_valid());
  18512. auto body = read_all(handle);
  18513. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  18514. }
  18515. // User-specified User-Agent must not be overwritten for stream API
  18516. {
  18517. auto handle = cli.open_stream("GET", "/echo-headers", {},
  18518. {{"User-Agent", "MyAgent/1.2"}});
  18519. ASSERT_TRUE(handle.is_valid());
  18520. auto body = read_all(handle);
  18521. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  18522. }
  18523. }
  18524. TEST_F(OpenStreamTest, Large) {
  18525. Client cli("127.0.0.1", port_);
  18526. auto handle = cli.open_stream("GET", "/large");
  18527. EXPECT_EQ(10000u, read_all(handle).size());
  18528. }
  18529. TEST_F(OpenStreamTest, ConnectionError) {
  18530. Client cli("127.0.0.1", 9999);
  18531. auto handle = cli.open_stream("GET", "/hello");
  18532. EXPECT_FALSE(handle.is_valid());
  18533. }
  18534. TEST_F(OpenStreamTest, Chunked) {
  18535. Client cli("127.0.0.1", port_);
  18536. auto handle = cli.open_stream("GET", "/chunked");
  18537. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18538. "Transfer-Encoding") == "chunked");
  18539. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  18540. }
  18541. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  18542. Client cli("127.0.0.1", port_);
  18543. auto handle =
  18544. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  18545. ASSERT_TRUE(handle.is_valid());
  18546. // Consume body to allow trailers to be received/parsed
  18547. auto body = read_all(handle);
  18548. // Explicitly parse trailers (ensure trailers are available for assertion)
  18549. handle.parse_trailers_if_needed();
  18550. EXPECT_EQ(std::string("123456789"), body);
  18551. // The response should include a Trailer header declaring both names
  18552. ASSERT_TRUE(handle.response);
  18553. EXPECT_TRUE(handle.response->has_header("Trailer"));
  18554. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  18555. handle.response->get_header_value("Trailer"));
  18556. // Prohibited trailer must not be present
  18557. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  18558. // Allowed trailer should be present
  18559. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  18560. EXPECT_EQ(std::string("yes"),
  18561. handle.response->get_trailer_value("X-Allowed"));
  18562. // Verify trailers are NOT present as regular headers
  18563. EXPECT_EQ(std::string(""),
  18564. handle.response->get_header_value("Content-Length"));
  18565. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  18566. }
  18567. static std::thread serve_single_response(std::promise<int> &port_promise,
  18568. const std::string &response) {
  18569. return std::thread([&port_promise, response] {
  18570. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18571. default_socket_options(srv);
  18572. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18573. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  18574. sockaddr_in addr{};
  18575. addr.sin_family = AF_INET;
  18576. addr.sin_port = htons(0); // Let OS assign a free port
  18577. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18578. int opt = 1;
  18579. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  18580. #ifdef _WIN32
  18581. reinterpret_cast<const char *>(&opt),
  18582. #else
  18583. &opt,
  18584. #endif
  18585. sizeof(opt));
  18586. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  18587. ::listen(srv, 1) != 0) {
  18588. port_promise.set_value(-1);
  18589. detail::close_socket(srv);
  18590. return;
  18591. }
  18592. socklen_t addr_len = sizeof(addr);
  18593. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  18594. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  18595. sockaddr_in cli_addr{};
  18596. socklen_t cli_len = sizeof(cli_addr);
  18597. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18598. if (cli != INVALID_SOCKET) {
  18599. // Read the complete HTTP request (until the blank line that terminates
  18600. // headers) before sending the response. If the server closes the socket
  18601. // while the client's request data is still unread in the kernel receive
  18602. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  18603. // connection on both sides: it discards the client's receive buffer
  18604. // (which already holds our response) and causes any in-progress write on
  18605. // the client to fail with ECONNRESET. Reading all request data first
  18606. // ensures close() emits a graceful FIN.
  18607. {
  18608. char rbuf[256];
  18609. std::string req;
  18610. while (req.find("\r\n\r\n") == std::string::npos) {
  18611. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  18612. if (n <= 0) { break; }
  18613. req.append(rbuf, static_cast<size_t>(n));
  18614. }
  18615. }
  18616. ::send(cli,
  18617. #ifdef _WIN32
  18618. static_cast<const char *>(response.c_str()),
  18619. static_cast<int>(response.size()),
  18620. #else
  18621. response.c_str(), response.size(),
  18622. #endif
  18623. 0);
  18624. detail::close_socket(cli);
  18625. }
  18626. detail::close_socket(srv);
  18627. });
  18628. }
  18629. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  18630. #ifndef _WIN32
  18631. signal(SIGPIPE, SIG_IGN);
  18632. #endif
  18633. std::promise<int> port_promise;
  18634. auto port_future = port_promise.get_future();
  18635. auto server_thread =
  18636. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  18637. "Content-Type: text/plain\r\n"
  18638. "Content-Length: not-a-number\r\n"
  18639. "Connection: close\r\n"
  18640. "\r\n"
  18641. "hello");
  18642. auto port = port_future.get();
  18643. ASSERT_GT(port, 0);
  18644. Client cli("127.0.0.1", port);
  18645. auto handle = cli.open_stream("GET", "/");
  18646. EXPECT_FALSE(handle.is_valid());
  18647. server_thread.join();
  18648. }
  18649. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  18650. #ifndef _WIN32
  18651. signal(SIGPIPE, SIG_IGN);
  18652. #endif
  18653. std::promise<int> port_promise;
  18654. auto port_future = port_promise.get_future();
  18655. auto server_thread = serve_single_response(
  18656. port_promise, "HTTP/1.1 200 OK\r\n"
  18657. "Content-Type: text/plain\r\n"
  18658. "Content-Length: 99999999999999999999999999\r\n"
  18659. "Connection: close\r\n"
  18660. "\r\n"
  18661. "hello");
  18662. auto port = port_future.get();
  18663. ASSERT_GT(port, 0);
  18664. // Historically std::stoull would throw std::out_of_range here and crash
  18665. // the process, then parsing silently clamped to a bogus framing length and
  18666. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  18667. // so the stream fails to open, matching the not-a-number case above. The
  18668. // process still must NOT terminate.
  18669. Client cli("127.0.0.1", port);
  18670. auto handle = cli.open_stream("GET", "/");
  18671. EXPECT_FALSE(handle.is_valid());
  18672. server_thread.join();
  18673. }
  18674. // Serves `response` to the single request `fn` makes with a fresh client.
  18675. template <typename Fn>
  18676. static void with_single_response(const std::string &response, Fn fn) {
  18677. #ifndef _WIN32
  18678. signal(SIGPIPE, SIG_IGN);
  18679. #endif
  18680. std::promise<int> port_promise;
  18681. auto port_future = port_promise.get_future();
  18682. auto server_thread = serve_single_response(port_promise, response);
  18683. auto se = detail::scope_exit([&] { server_thread.join(); });
  18684. auto port = port_future.get();
  18685. ASSERT_GT(port, 0);
  18686. Client cli("127.0.0.1", port);
  18687. fn(cli);
  18688. }
  18689. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  18690. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  18691. // the chunked coding and drop Content-Length, so a front-end that trusts
  18692. // Content-Length would disagree about where the body ends (response
  18693. // smuggling). The client must reject such a response.
  18694. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  18695. for (const char *te : {"chunked", "gzip, chunked"}) {
  18696. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  18697. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  18698. "\r\n" + "Connection: close\r\n" + "\r\n" +
  18699. "5\r\nhello\r\n0\r\n\r\n";
  18700. with_single_response(response, [&](Client &cli) {
  18701. auto res = cli.Get("/");
  18702. EXPECT_FALSE(static_cast<bool>(res)) << te;
  18703. EXPECT_EQ(Error::Read, res.error()) << te;
  18704. });
  18705. with_single_response(response, [&](Client &cli) {
  18706. auto handle = cli.open_stream("GET", "/");
  18707. EXPECT_FALSE(handle.is_valid()) << te;
  18708. EXPECT_EQ(Error::Read, handle.error) << te;
  18709. });
  18710. }
  18711. }
  18712. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  18713. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  18714. // closing the connection (unlike a request, which must be rejected).
  18715. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  18716. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18717. "Transfer-Encoding: chunked\r\n"
  18718. "Connection: close\r\n"
  18719. "\r\n"
  18720. "5\r\nhello\r\n0\r\n\r\n",
  18721. "HTTP/1.1 200 OK\r\n"
  18722. "Transfer-Encoding: gzip\r\n"
  18723. "Connection: close\r\n"
  18724. "\r\n"
  18725. "hello"}) {
  18726. with_single_response(response, [&](Client &cli) {
  18727. auto res = cli.Get("/");
  18728. ASSERT_TRUE(static_cast<bool>(res)) << response;
  18729. EXPECT_EQ("hello", res->body);
  18730. });
  18731. with_single_response(response, [&](Client &cli) {
  18732. auto handle = cli.open_stream("GET", "/");
  18733. ASSERT_TRUE(handle.is_valid()) << response;
  18734. EXPECT_EQ("hello", read_all(handle));
  18735. });
  18736. }
  18737. }
  18738. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  18739. // framing headers describe nothing to read and must not be rejected.
  18740. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  18741. const std::string framing = "Content-Length: 5\r\n"
  18742. "Transfer-Encoding: chunked\r\n"
  18743. "Connection: close\r\n"
  18744. "\r\n";
  18745. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18746. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  18747. });
  18748. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18749. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  18750. });
  18751. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  18752. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  18753. with_single_response(response, [&](Client &cli) {
  18754. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  18755. });
  18756. with_single_response(response, [&](Client &cli) {
  18757. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  18758. });
  18759. }
  18760. }
  18761. // A payload max length of 0 means no limit, however the body is framed.
  18762. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  18763. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18764. "Transfer-Encoding: chunked\r\n"
  18765. "\r\n"
  18766. "5\r\nhello\r\n0\r\n\r\n",
  18767. "HTTP/1.1 200 OK\r\n"
  18768. "Connection: close\r\n"
  18769. "\r\n"
  18770. "hello"}) {
  18771. with_single_response(response, [&](Client &cli) {
  18772. cli.set_payload_max_length(0);
  18773. auto res = cli.Get("/");
  18774. ASSERT_TRUE(res) << response;
  18775. EXPECT_EQ("hello", res->body) << response;
  18776. });
  18777. }
  18778. }
  18779. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  18780. Server svr;
  18781. svr.set_payload_max_length(0);
  18782. svr.Post("/echo", [](const Request &req, Response &res) {
  18783. res.set_content(req.body, "text/plain");
  18784. });
  18785. auto port = svr.bind_to_any_port(HOST);
  18786. thread t = thread([&] { svr.listen_after_bind(); });
  18787. auto se = detail::scope_exit([&] {
  18788. svr.stop();
  18789. t.join();
  18790. ASSERT_FALSE(svr.is_running());
  18791. });
  18792. svr.wait_until_ready();
  18793. Client cli(HOST, port);
  18794. auto res = cli.Post(
  18795. "/echo",
  18796. [](size_t /*offset*/, DataSink &sink) {
  18797. sink.write("hello", 5);
  18798. sink.done();
  18799. return true;
  18800. },
  18801. "text/plain");
  18802. ASSERT_TRUE(res);
  18803. EXPECT_EQ(StatusCode::OK_200, res->status);
  18804. EXPECT_EQ("hello", res->body);
  18805. }
  18806. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18807. TEST_F(OpenStreamTest, Gzip) {
  18808. Client cli("127.0.0.1", port_);
  18809. auto handle = cli.open_stream("GET", "/compressible", {},
  18810. {{"Accept-Encoding", "gzip"}});
  18811. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  18812. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18813. }
  18814. #endif
  18815. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18816. TEST_F(OpenStreamTest, Brotli) {
  18817. Client cli("127.0.0.1", port_);
  18818. auto handle =
  18819. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  18820. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  18821. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18822. }
  18823. #endif
  18824. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18825. TEST_F(OpenStreamTest, Zstd) {
  18826. Client cli("127.0.0.1", port_);
  18827. auto handle = cli.open_stream("GET", "/compressible", {},
  18828. {{"Accept-Encoding", "zstd"}});
  18829. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  18830. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18831. }
  18832. #endif
  18833. #ifdef CPPHTTPLIB_SSL_ENABLED
  18834. class SSLOpenStreamTest : public ::testing::Test {
  18835. protected:
  18836. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  18837. void SetUp() override {
  18838. svr_.Get("/hello", [](const Request &, Response &res) {
  18839. res.set_content("Hello SSL World!", "text/plain");
  18840. });
  18841. svr_.Get("/chunked", [](const Request &, Response &res) {
  18842. res.set_chunked_content_provider("text/plain",
  18843. [](size_t offset, DataSink &sink) {
  18844. if (offset < 15) {
  18845. sink.write("chunk", 5);
  18846. return true;
  18847. }
  18848. sink.done();
  18849. return true;
  18850. });
  18851. });
  18852. svr_.Post("/echo", [](const Request &req, Response &res) {
  18853. res.set_content(req.body, req.get_header_value("Content-Type"));
  18854. });
  18855. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  18856. std::string body = req.body;
  18857. res.set_chunked_content_provider(
  18858. "text/plain", [body](size_t offset, DataSink &sink) {
  18859. if (offset < body.size()) {
  18860. sink.write(body.data() + offset, body.size() - offset);
  18861. }
  18862. sink.done();
  18863. return true;
  18864. });
  18865. });
  18866. port_ = svr_.bind_to_any_port("127.0.0.1");
  18867. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18868. svr_.wait_until_ready();
  18869. }
  18870. void TearDown() override {
  18871. svr_.stop();
  18872. if (thread_.joinable()) thread_.join();
  18873. }
  18874. SSLServer svr_;
  18875. std::thread thread_;
  18876. int port_ = 0;
  18877. };
  18878. TEST_F(SSLOpenStreamTest, Basic) {
  18879. SSLClient cli("127.0.0.1", port_);
  18880. cli.enable_server_certificate_verification(false);
  18881. auto handle = cli.open_stream("GET", "/hello");
  18882. ASSERT_TRUE(handle.is_valid());
  18883. EXPECT_EQ("Hello SSL World!", read_all(handle));
  18884. }
  18885. TEST_F(SSLOpenStreamTest, Chunked) {
  18886. SSLClient cli("127.0.0.1", port_);
  18887. cli.enable_server_certificate_verification(false);
  18888. auto handle = cli.open_stream("GET", "/chunked");
  18889. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18890. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18891. "Transfer-Encoding") == "chunked");
  18892. auto body = read_all(handle);
  18893. EXPECT_EQ("chunkchunkchunk", body);
  18894. }
  18895. TEST_F(SSLOpenStreamTest, Post) {
  18896. SSLClient cli("127.0.0.1", port_);
  18897. cli.enable_server_certificate_verification(false);
  18898. auto handle =
  18899. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  18900. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18901. EXPECT_EQ(200, handle.response->status);
  18902. auto body = read_all(handle);
  18903. EXPECT_EQ("Hello SSL POST", body);
  18904. }
  18905. TEST_F(SSLOpenStreamTest, PostChunked) {
  18906. SSLClient cli("127.0.0.1", port_);
  18907. cli.enable_server_certificate_verification(false);
  18908. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  18909. "Chunked SSL Data", "text/plain");
  18910. ASSERT_TRUE(handle.is_valid());
  18911. EXPECT_EQ(200, handle.response->status);
  18912. auto body = read_all(handle);
  18913. EXPECT_EQ("Chunked SSL Data", body);
  18914. }
  18915. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  18916. // Content-Length is terminated by the server closing the connection. When the
  18917. // SSL peer sends a close_notify after the body, the client must treat it as a
  18918. // clean EOF and return a successful response rather than an error.
  18919. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  18920. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18921. ASSERT_TRUE(svr.is_valid());
  18922. svr.set_keep_alive_max_count(1);
  18923. const std::string expected_body = "Hello from connection-close response!";
  18924. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  18925. res.set_content_provider("text/plain",
  18926. [&](size_t offset, DataSink &sink) -> bool {
  18927. if (offset < expected_body.size()) {
  18928. sink.write(expected_body.data() + offset,
  18929. expected_body.size() - offset);
  18930. }
  18931. sink.done();
  18932. return true;
  18933. });
  18934. });
  18935. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  18936. auto se = detail::scope_exit([&] {
  18937. svr.stop();
  18938. listen_thread.join();
  18939. ASSERT_FALSE(svr.is_running());
  18940. });
  18941. svr.wait_until_ready();
  18942. SSLClient cli(HOST, PORT);
  18943. cli.enable_server_certificate_verification(false);
  18944. auto res = cli.Get("/no-content-length");
  18945. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  18946. EXPECT_EQ(StatusCode::OK_200, res->status);
  18947. EXPECT_EQ(expected_body, res->body);
  18948. }
  18949. #endif // CPPHTTPLIB_SSL_ENABLED
  18950. //==============================================================================
  18951. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  18952. // results for various scenarios.
  18953. //==============================================================================
  18954. TEST(ParityTest, GetVsOpenStream) {
  18955. Server svr;
  18956. const std::string path = "/parity";
  18957. const std::string content = "Parity test content: hello world";
  18958. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18959. res.set_content(content, "text/plain");
  18960. });
  18961. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18962. auto se = detail::scope_exit([&] {
  18963. svr.stop();
  18964. t.join();
  18965. ASSERT_FALSE(svr.is_running());
  18966. });
  18967. svr.wait_until_ready();
  18968. Client cli(HOST, PORT);
  18969. // Non-stream path
  18970. auto r1 = cli.Get(path);
  18971. ASSERT_TRUE(r1);
  18972. EXPECT_EQ(StatusCode::OK_200, r1->status);
  18973. // Stream path
  18974. auto h = cli.open_stream("GET", path);
  18975. ASSERT_TRUE(h.is_valid());
  18976. EXPECT_EQ(r1->body, read_all(h));
  18977. }
  18978. // Helper to compress data with provided compressor type T
  18979. template <typename Compressor>
  18980. static std::string compress_payload_for_parity(const std::string &in) {
  18981. std::string out;
  18982. Compressor compressor;
  18983. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  18984. [&](const char *data, size_t n) {
  18985. out.append(data, n);
  18986. return true;
  18987. });
  18988. EXPECT_TRUE(ok);
  18989. return out;
  18990. }
  18991. // Helper function for compression parity tests
  18992. template <typename Compressor>
  18993. static void test_compression_parity(const std::string &original,
  18994. const std::string &path,
  18995. const std::string &encoding) {
  18996. const std::string compressed =
  18997. compress_payload_for_parity<Compressor>(original);
  18998. Server svr;
  18999. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19000. res.set_content(compressed, "application/octet-stream");
  19001. res.set_header("Content-Encoding", encoding);
  19002. });
  19003. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  19004. auto se = detail::scope_exit([&] {
  19005. svr.stop();
  19006. t.join();
  19007. ASSERT_FALSE(svr.is_running());
  19008. });
  19009. svr.wait_until_ready();
  19010. Client cli(HOST, PORT);
  19011. // Non-streaming
  19012. {
  19013. auto res = cli.Get(path);
  19014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19015. EXPECT_EQ(StatusCode::OK_200, res->status);
  19016. EXPECT_EQ(original, res->body);
  19017. }
  19018. // Streaming
  19019. {
  19020. auto h = cli.open_stream("GET", path);
  19021. ASSERT_TRUE(h.is_valid());
  19022. EXPECT_EQ(original, read_all(h));
  19023. }
  19024. }
  19025. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19026. TEST(ParityTest, Gzip) {
  19027. test_compression_parity<detail::gzip_compressor>(
  19028. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  19029. }
  19030. #endif
  19031. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19032. TEST(ParityTest, Brotli) {
  19033. test_compression_parity<detail::brotli_compressor>(
  19034. "Hello, brotli parity test payload", "/parity-br", "br");
  19035. }
  19036. #endif
  19037. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19038. TEST(ParityTest, Zstd) {
  19039. test_compression_parity<detail::zstd_compressor>(
  19040. "Zstandard parity test payload", "/parity-zstd", "zstd");
  19041. }
  19042. #endif
  19043. //==============================================================================
  19044. // New Stream API Tests
  19045. //==============================================================================
  19046. inline std::string read_body(httplib::stream::Result &result) {
  19047. std::string body;
  19048. while (result.next()) {
  19049. body.append(result.data(), result.size());
  19050. }
  19051. return body;
  19052. }
  19053. TEST(ClientConnectionTest, Basic) {
  19054. httplib::ClientConnection conn;
  19055. EXPECT_FALSE(conn.is_open());
  19056. conn.sock = 1;
  19057. EXPECT_TRUE(conn.is_open());
  19058. httplib::ClientConnection conn2(std::move(conn));
  19059. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  19060. conn2.sock = INVALID_SOCKET;
  19061. }
  19062. // Unified test server for all stream::* tests
  19063. class StreamApiTest : public ::testing::Test {
  19064. protected:
  19065. void SetUp() override {
  19066. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19067. res.set_content("Hello World!", "text/plain");
  19068. });
  19069. svr_.Get("/echo-params",
  19070. [](const httplib::Request &req, httplib::Response &res) {
  19071. std::string r;
  19072. for (const auto &p : req.params) {
  19073. if (!r.empty()) r += "&";
  19074. r += p.first + "=" + p.second;
  19075. }
  19076. res.set_content(r, "text/plain");
  19077. });
  19078. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19079. res.set_content(req.body, req.get_header_value("Content-Type"));
  19080. });
  19081. svr_.Post("/echo-headers",
  19082. [](const httplib::Request &req, httplib::Response &res) {
  19083. std::string r;
  19084. for (const auto &h : req.headers)
  19085. r += h.first + ": " + h.second + "\n";
  19086. res.set_content(r, "text/plain");
  19087. });
  19088. svr_.Post("/echo-params",
  19089. [](const httplib::Request &req, httplib::Response &res) {
  19090. std::string r = "params:";
  19091. for (const auto &p : req.params)
  19092. r += p.first + "=" + p.second + ";";
  19093. res.set_content(r + " body:" + req.body, "text/plain");
  19094. });
  19095. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  19096. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  19097. });
  19098. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19099. res.set_content("PUT:" + req.body, "text/plain");
  19100. });
  19101. svr_.Patch("/echo",
  19102. [](const httplib::Request &req, httplib::Response &res) {
  19103. res.set_content("PATCH:" + req.body, "text/plain");
  19104. });
  19105. svr_.Delete(
  19106. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  19107. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  19108. "text/plain");
  19109. });
  19110. svr_.Get("/head-test",
  19111. [](const httplib::Request &, httplib::Response &res) {
  19112. res.set_content("body for HEAD", "text/plain");
  19113. });
  19114. svr_.Options("/options",
  19115. [](const httplib::Request &, httplib::Response &res) {
  19116. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  19117. });
  19118. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  19119. svr_.wait_until_ready();
  19120. }
  19121. void TearDown() override {
  19122. svr_.stop();
  19123. if (thread_.joinable()) thread_.join();
  19124. }
  19125. httplib::Server svr_;
  19126. std::thread thread_;
  19127. };
  19128. // stream::Get tests
  19129. TEST_F(StreamApiTest, GetBasic) {
  19130. httplib::Client cli(HOST, PORT);
  19131. auto result = httplib::stream::Get(cli, "/hello");
  19132. ASSERT_TRUE(result.is_valid());
  19133. EXPECT_EQ(200, result.status());
  19134. EXPECT_EQ("Hello World!", read_body(result));
  19135. }
  19136. TEST_F(StreamApiTest, GetWithParams) {
  19137. httplib::Client cli(HOST, PORT);
  19138. httplib::Params params{{"foo", "bar"}};
  19139. auto result = httplib::stream::Get(cli, "/echo-params", params);
  19140. ASSERT_TRUE(result.is_valid());
  19141. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  19142. }
  19143. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19144. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  19145. httplib::Client cli(HOST, PORT);
  19146. cli.set_payload_max_length(0);
  19147. auto result = httplib::stream::Get(cli, "/hello");
  19148. ASSERT_TRUE(result.is_valid());
  19149. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  19150. EXPECT_EQ("Hello World!", read_body(result));
  19151. }
  19152. #endif
  19153. TEST_F(StreamApiTest, GetConnectionError) {
  19154. httplib::Client cli(HOST, 9999);
  19155. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  19156. }
  19157. TEST_F(StreamApiTest, Get404) {
  19158. httplib::Client cli(HOST, PORT);
  19159. auto result = httplib::stream::Get(cli, "/nonexistent");
  19160. EXPECT_TRUE(result.is_valid());
  19161. EXPECT_EQ(404, result.status());
  19162. }
  19163. // stream::Post tests
  19164. TEST_F(StreamApiTest, PostBasic) {
  19165. httplib::Client cli(HOST, PORT);
  19166. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  19167. "application/json");
  19168. ASSERT_TRUE(result.is_valid());
  19169. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  19170. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  19171. }
  19172. TEST_F(StreamApiTest, PostWithHeaders) {
  19173. httplib::Client cli(HOST, PORT);
  19174. httplib::Headers headers{{"X-Custom", "value"}};
  19175. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  19176. "text/plain");
  19177. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  19178. }
  19179. TEST_F(StreamApiTest, PostWithParams) {
  19180. httplib::Client cli(HOST, PORT);
  19181. httplib::Params params{{"k", "v"}};
  19182. auto result =
  19183. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  19184. auto body = read_body(result);
  19185. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  19186. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  19187. }
  19188. TEST_F(StreamApiTest, PostLarge) {
  19189. httplib::Client cli(HOST, PORT);
  19190. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  19191. size_t total = 0;
  19192. while (result.next()) {
  19193. total += result.size();
  19194. }
  19195. EXPECT_EQ(100u * 1024u, total);
  19196. }
  19197. // stream::Put/Patch tests
  19198. TEST_F(StreamApiTest, PutAndPatch) {
  19199. httplib::Client cli(HOST, PORT);
  19200. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  19201. EXPECT_EQ("PUT:test", read_body(put));
  19202. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  19203. EXPECT_EQ("PATCH:test", read_body(patch));
  19204. }
  19205. // stream::Delete tests
  19206. TEST_F(StreamApiTest, Delete) {
  19207. httplib::Client cli(HOST, PORT);
  19208. auto del1 = httplib::stream::Delete(cli, "/resource");
  19209. EXPECT_EQ("Deleted", read_body(del1));
  19210. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  19211. EXPECT_EQ("Deleted:data", read_body(del2));
  19212. }
  19213. // stream::Head/Options tests
  19214. TEST_F(StreamApiTest, HeadAndOptions) {
  19215. httplib::Client cli(HOST, PORT);
  19216. auto head = httplib::stream::Head(cli, "/head-test");
  19217. EXPECT_TRUE(head.is_valid());
  19218. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  19219. auto opts = httplib::stream::Options(cli, "/options");
  19220. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  19221. }
  19222. // SSL stream::* tests
  19223. #ifdef CPPHTTPLIB_SSL_ENABLED
  19224. class SSLStreamApiTest : public ::testing::Test {
  19225. protected:
  19226. void SetUp() override {
  19227. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19228. res.set_content("Hello SSL!", "text/plain");
  19229. });
  19230. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19231. res.set_content(req.body, "text/plain");
  19232. });
  19233. port_ = svr_.bind_to_any_port("127.0.0.1");
  19234. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19235. svr_.wait_until_ready();
  19236. }
  19237. void TearDown() override {
  19238. svr_.stop();
  19239. if (thread_.joinable()) thread_.join();
  19240. }
  19241. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  19242. std::thread thread_;
  19243. int port_ = 0;
  19244. };
  19245. TEST_F(SSLStreamApiTest, GetAndPost) {
  19246. httplib::SSLClient cli("127.0.0.1", port_);
  19247. cli.enable_server_certificate_verification(false);
  19248. auto get = httplib::stream::Get(cli, "/hello");
  19249. EXPECT_EQ("Hello SSL!", read_body(get));
  19250. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  19251. EXPECT_EQ("test", read_body(post));
  19252. }
  19253. #endif
  19254. // Tests for Error::Timeout and Error::ConnectionClosed error types
  19255. // These errors are set in SocketStream/SSLSocketStream and propagated through
  19256. // BodyReader
  19257. TEST(ErrorHandlingTest, StreamReadTimeout) {
  19258. // Test that read timeout during streaming is detected
  19259. // Use a large content-length response where server delays mid-stream
  19260. Server svr;
  19261. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19262. // Send a large response with delay in the middle
  19263. res.set_content_provider(
  19264. 1000, // content_length
  19265. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  19266. if (offset < 100) {
  19267. // Send first 100 bytes immediately
  19268. std::string data(100, 'A');
  19269. sink.write(data.c_str(), data.size());
  19270. return true;
  19271. }
  19272. // Then delay longer than client timeout
  19273. std::this_thread::sleep_for(std::chrono::seconds(3));
  19274. std::string data(900, 'B');
  19275. sink.write(data.c_str(), data.size());
  19276. return true;
  19277. });
  19278. });
  19279. auto port = 8091;
  19280. std::thread t([&]() { svr.listen("localhost", port); });
  19281. svr.wait_until_ready();
  19282. Client cli("localhost", port);
  19283. cli.set_read_timeout(1, 0); // 1 second timeout
  19284. auto handle = cli.open_stream("GET", "/slow-stream");
  19285. ASSERT_TRUE(handle.is_valid());
  19286. char buf[256];
  19287. ssize_t total = 0;
  19288. ssize_t n;
  19289. bool got_error = false;
  19290. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19291. total += n;
  19292. }
  19293. if (n < 0) {
  19294. got_error = true;
  19295. // Should be timeout or read error
  19296. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19297. handle.get_read_error() == Error::Read)
  19298. << "Actual error: " << to_string(handle.get_read_error());
  19299. }
  19300. // Either we got an error, or we got less data than expected
  19301. EXPECT_TRUE(got_error || total < 1000)
  19302. << "Expected timeout but got all " << total << " bytes";
  19303. svr.stop();
  19304. t.join();
  19305. }
  19306. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  19307. // Test connection closed detection via BodyReader
  19308. Server svr;
  19309. std::atomic<bool> close_now{false};
  19310. svr.Get("/will-close", [&](const Request &, Response &res) {
  19311. res.set_content_provider(
  19312. 10000, // Large content_length that we won't fully send
  19313. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19314. if (offset < 100) {
  19315. std::string data(100, 'X');
  19316. sink.write(data.c_str(), data.size());
  19317. return true;
  19318. }
  19319. // Wait for signal then abort
  19320. while (!close_now) {
  19321. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19322. }
  19323. return false; // Abort - server will close connection
  19324. });
  19325. });
  19326. auto port = 8092;
  19327. std::thread t([&]() { svr.listen("localhost", port); });
  19328. svr.wait_until_ready();
  19329. Client cli("localhost", port);
  19330. auto handle = cli.open_stream("GET", "/will-close");
  19331. ASSERT_TRUE(handle.is_valid());
  19332. char buf[256];
  19333. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19334. EXPECT_GT(n, 0) << "First read should succeed";
  19335. // Signal server to close
  19336. close_now = true;
  19337. // Keep reading until error or EOF
  19338. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19339. // Keep reading
  19340. }
  19341. // Should get an error since content_length wasn't satisfied
  19342. if (n < 0) {
  19343. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19344. handle.get_read_error() == Error::Read)
  19345. << "Actual error: " << to_string(handle.get_read_error());
  19346. }
  19347. svr.stop();
  19348. t.join();
  19349. }
  19350. #ifdef CPPHTTPLIB_SSL_ENABLED
  19351. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  19352. // Test that read timeout during SSL streaming is detected
  19353. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19354. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19355. res.set_content_provider(
  19356. 1000, "text/plain",
  19357. [](size_t offset, size_t /*length*/, DataSink &sink) {
  19358. if (offset < 100) {
  19359. std::string data(100, 'A');
  19360. sink.write(data.c_str(), data.size());
  19361. return true;
  19362. }
  19363. std::this_thread::sleep_for(std::chrono::seconds(3));
  19364. std::string data(900, 'B');
  19365. sink.write(data.c_str(), data.size());
  19366. return true;
  19367. });
  19368. });
  19369. auto port = 8093;
  19370. std::thread t([&]() { svr.listen("localhost", port); });
  19371. svr.wait_until_ready();
  19372. SSLClient cli("localhost", port);
  19373. cli.enable_server_certificate_verification(false);
  19374. cli.set_read_timeout(1, 0); // 1 second timeout
  19375. auto handle = cli.open_stream("GET", "/slow-stream");
  19376. ASSERT_TRUE(handle.is_valid());
  19377. char buf[256];
  19378. ssize_t total = 0;
  19379. ssize_t n;
  19380. bool got_error = false;
  19381. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19382. total += n;
  19383. }
  19384. if (n < 0) {
  19385. got_error = true;
  19386. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19387. handle.get_read_error() == Error::Read)
  19388. << "Actual error: " << to_string(handle.get_read_error());
  19389. }
  19390. EXPECT_TRUE(got_error || total < 1000)
  19391. << "Expected timeout but got all " << total << " bytes";
  19392. svr.stop();
  19393. t.join();
  19394. }
  19395. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  19396. // Test SSL connection closed detection
  19397. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19398. std::atomic<bool> close_now{false};
  19399. svr.Get("/will-close", [&](const Request &, Response &res) {
  19400. res.set_content_provider(
  19401. 10000, "text/plain",
  19402. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19403. if (offset < 100) {
  19404. std::string data(100, 'X');
  19405. sink.write(data.c_str(), data.size());
  19406. return true;
  19407. }
  19408. while (!close_now) {
  19409. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19410. }
  19411. return false;
  19412. });
  19413. });
  19414. auto port = 8094;
  19415. std::thread t([&]() { svr.listen("localhost", port); });
  19416. svr.wait_until_ready();
  19417. SSLClient cli("localhost", port);
  19418. cli.enable_server_certificate_verification(false);
  19419. auto handle = cli.open_stream("GET", "/will-close");
  19420. ASSERT_TRUE(handle.is_valid());
  19421. char buf[256];
  19422. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19423. EXPECT_GT(n, 0);
  19424. // Signal server to close
  19425. close_now = true;
  19426. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19427. // Keep reading
  19428. }
  19429. if (n < 0) {
  19430. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19431. handle.get_read_error() == Error::Read)
  19432. << "Actual error: " << to_string(handle.get_read_error());
  19433. }
  19434. svr.stop();
  19435. t.join();
  19436. }
  19437. #endif
  19438. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  19439. using namespace httplib;
  19440. // Create a test file
  19441. const char *fname = "etag_testfile.txt";
  19442. const char *content = "etag-content";
  19443. {
  19444. std::ofstream ofs(fname);
  19445. ofs << content;
  19446. ASSERT_TRUE(ofs.good());
  19447. }
  19448. Server svr;
  19449. svr.set_mount_point("/static", ".");
  19450. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19451. svr.wait_until_ready();
  19452. Client cli(HOST, PORT);
  19453. // First request: should get 200 with ETag header
  19454. auto res1 = cli.Get("/static/etag_testfile.txt");
  19455. ASSERT_TRUE(res1);
  19456. ASSERT_EQ(200, res1->status);
  19457. ASSERT_TRUE(res1->has_header("ETag"));
  19458. std::string etag = res1->get_header_value("ETag");
  19459. EXPECT_FALSE(etag.empty());
  19460. // Verify ETag format: W/"hex-hex"
  19461. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  19462. EXPECT_EQ('W', etag[0]);
  19463. EXPECT_EQ('/', etag[1]);
  19464. EXPECT_EQ('"', etag[2]);
  19465. EXPECT_EQ('"', etag.back());
  19466. // Exact match: expect 304 Not Modified
  19467. Headers h2 = {{"If-None-Match", etag}};
  19468. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  19469. ASSERT_TRUE(res2);
  19470. EXPECT_EQ(304, res2->status);
  19471. // Wildcard match: expect 304 Not Modified
  19472. Headers h3 = {{"If-None-Match", "*"}};
  19473. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  19474. ASSERT_TRUE(res3);
  19475. EXPECT_EQ(304, res3->status);
  19476. // Non-matching ETag: expect 200
  19477. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  19478. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  19479. ASSERT_TRUE(res4);
  19480. EXPECT_EQ(200, res4->status);
  19481. // Multiple ETags with one matching: expect 304
  19482. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  19483. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  19484. ASSERT_TRUE(res5);
  19485. EXPECT_EQ(304, res5->status);
  19486. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  19487. // that equivalent to the single comma-separated list above, so the match on
  19488. // the second line must still be found.
  19489. Headers h6;
  19490. h6.emplace("If-None-Match", "W/\"other\"");
  19491. h6.emplace("If-None-Match", etag);
  19492. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  19493. ASSERT_TRUE(res6);
  19494. EXPECT_EQ(304, res6->status);
  19495. svr.stop();
  19496. t.join();
  19497. std::remove(fname);
  19498. }
  19499. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  19500. using namespace httplib;
  19501. Server svr;
  19502. svr.set_mount_point("/static", ".");
  19503. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19504. svr.wait_until_ready();
  19505. Client cli(HOST, PORT);
  19506. // Send If-None-Match: * to a non-existent file
  19507. Headers h = {{"If-None-Match", "*"}};
  19508. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  19509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19510. EXPECT_EQ(404, res->status);
  19511. svr.stop();
  19512. t.join();
  19513. }
  19514. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  19515. using namespace httplib;
  19516. // Create a test file
  19517. const char *fname = "etag_boundary_testfile.txt";
  19518. const char *content = "boundary-test";
  19519. {
  19520. std::ofstream ofs(fname);
  19521. ofs << content;
  19522. ASSERT_TRUE(ofs.good());
  19523. }
  19524. Server svr;
  19525. svr.set_mount_point("/static", ".");
  19526. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19527. svr.wait_until_ready();
  19528. Client cli(HOST, PORT);
  19529. // Get the actual ETag
  19530. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  19531. ASSERT_TRUE(res1);
  19532. ASSERT_EQ(200, res1->status);
  19533. ASSERT_TRUE(res1->has_header("ETag"));
  19534. std::string etag = res1->get_header_value("ETag");
  19535. // Test 1: Very long ETag value (longer than actual ETag)
  19536. // Should NOT match and return 200 (not trigger out-of-bounds read)
  19537. Headers h1 = {{"If-None-Match", "W/"
  19538. "\"very-long-etag-value-that-is-much-longer-"
  19539. "than-the-actual-etag-value\""}};
  19540. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  19541. ASSERT_TRUE(res2);
  19542. EXPECT_EQ(200, res2->status); // Should not match
  19543. // Test 2: Long string followed by wildcard
  19544. // Should match on "*" and return 304 (without out-of-bounds read on the long
  19545. // string)
  19546. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  19547. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  19548. ASSERT_TRUE(res3);
  19549. EXPECT_EQ(304, res3->status); // Should match on "*"
  19550. // Test 3: Wildcard followed by long string
  19551. // Should match on "*" immediately and return 304
  19552. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  19553. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  19554. ASSERT_TRUE(res4);
  19555. EXPECT_EQ(304, res4->status); // Should match on "*"
  19556. // Test 4: Multiple long non-matching values
  19557. // Should NOT match and return 200 (test that all comparisons are safe)
  19558. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  19559. "W/\"second-long-non-matching-value\", "
  19560. "W/\"third-long-non-matching-value\""}};
  19561. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  19562. ASSERT_TRUE(res5);
  19563. EXPECT_EQ(200, res5->status); // Should not match
  19564. // Test 5: Single character that is not "*" (edge case)
  19565. Headers h5 = {{"If-None-Match", "X"}};
  19566. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  19567. ASSERT_TRUE(res6);
  19568. EXPECT_EQ(200, res6->status); // Should not match
  19569. svr.stop();
  19570. t.join();
  19571. std::remove(fname);
  19572. }
  19573. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  19574. using namespace httplib;
  19575. // Create a test file
  19576. const char *fname = "ims_testfile.txt";
  19577. const char *content = "if-modified-since-test";
  19578. {
  19579. std::ofstream ofs(fname);
  19580. ofs << content;
  19581. ASSERT_TRUE(ofs.good());
  19582. }
  19583. Server svr;
  19584. svr.set_mount_point("/static", ".");
  19585. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19586. svr.wait_until_ready();
  19587. Client cli(HOST, PORT);
  19588. // First request: should get 200 with Last-Modified header
  19589. auto res1 = cli.Get("/static/ims_testfile.txt");
  19590. ASSERT_TRUE(res1);
  19591. ASSERT_EQ(200, res1->status);
  19592. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19593. std::string last_modified = res1->get_header_value("Last-Modified");
  19594. EXPECT_FALSE(last_modified.empty());
  19595. // If-Modified-Since with same time: expect 304
  19596. Headers h2 = {{"If-Modified-Since", last_modified}};
  19597. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  19598. ASSERT_TRUE(res2);
  19599. EXPECT_EQ(304, res2->status);
  19600. // If-Modified-Since with future time: expect 304
  19601. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19602. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  19603. ASSERT_TRUE(res3);
  19604. EXPECT_EQ(304, res3->status);
  19605. // If-Modified-Since with past time: expect 200
  19606. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19607. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  19608. ASSERT_TRUE(res4);
  19609. EXPECT_EQ(200, res4->status);
  19610. // If-None-Match takes precedence over If-Modified-Since
  19611. // (send matching ETag with old If-Modified-Since -> should still be 304)
  19612. ASSERT_TRUE(res1->has_header("ETag"));
  19613. std::string etag = res1->get_header_value("ETag");
  19614. Headers h5 = {{"If-None-Match", etag},
  19615. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19616. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  19617. ASSERT_TRUE(res5);
  19618. EXPECT_EQ(304, res5->status);
  19619. svr.stop();
  19620. t.join();
  19621. std::remove(fname);
  19622. }
  19623. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  19624. using namespace httplib;
  19625. Server svr;
  19626. // Endpoint that returns compressible content
  19627. svr.Get("/compressible", [](const Request &, Response &res) {
  19628. // Return a large enough body to trigger compression
  19629. std::string body(1000, 'a');
  19630. res.set_content(body, "text/plain");
  19631. });
  19632. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19633. svr.wait_until_ready();
  19634. Client cli(HOST, PORT);
  19635. // Request with gzip support: should get Vary header when compressed
  19636. cli.set_compress(true);
  19637. auto res1 = cli.Get("/compressible");
  19638. ASSERT_TRUE(res1);
  19639. EXPECT_EQ(200, res1->status);
  19640. // If Content-Encoding is set, Vary should also be set
  19641. if (res1->has_header("Content-Encoding")) {
  19642. EXPECT_TRUE(res1->has_header("Vary"));
  19643. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  19644. }
  19645. // Request without Accept-Encoding header: should not have compression
  19646. Headers h_no_compress;
  19647. auto res2 = cli.Get("/compressible", h_no_compress);
  19648. ASSERT_TRUE(res2);
  19649. EXPECT_EQ(200, res2->status);
  19650. // Verify Vary header is present when compression is applied
  19651. // (the exact behavior depends on server configuration)
  19652. svr.stop();
  19653. t.join();
  19654. }
  19655. TEST(ETagTest, IfRangeWithETag) {
  19656. using namespace httplib;
  19657. // Create a test file with known content
  19658. const char *fname = "if_range_testfile.txt";
  19659. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  19660. {
  19661. std::ofstream ofs(fname);
  19662. ofs << content;
  19663. ASSERT_TRUE(ofs.good());
  19664. }
  19665. Server svr;
  19666. svr.set_mount_point("/static", ".");
  19667. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19668. svr.wait_until_ready();
  19669. Client cli(HOST, PORT);
  19670. // First request: get ETag
  19671. auto res1 = cli.Get("/static/if_range_testfile.txt");
  19672. ASSERT_TRUE(res1);
  19673. ASSERT_EQ(200, res1->status);
  19674. ASSERT_TRUE(res1->has_header("ETag"));
  19675. std::string etag = res1->get_header_value("ETag");
  19676. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  19677. // Since our server generates weak ETags (W/"..."), If-Range with our
  19678. // ETag should NOT result in partial content - it should return full content.
  19679. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  19680. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  19681. ASSERT_TRUE(res2);
  19682. // Weak ETag in If-Range -> full content (200), not partial (206)
  19683. EXPECT_EQ(200, res2->status);
  19684. EXPECT_EQ(content, res2->body);
  19685. EXPECT_FALSE(res2->has_header("Content-Range"));
  19686. // Range request with non-matching If-Range (ETag): should get 200 (full
  19687. // content)
  19688. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  19689. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  19690. ASSERT_TRUE(res3);
  19691. EXPECT_EQ(200, res3->status);
  19692. EXPECT_EQ(content, res3->body);
  19693. EXPECT_FALSE(res3->has_header("Content-Range"));
  19694. // Range request with strong ETag (hypothetical - our server doesn't generate
  19695. // strong ETags, but if client sends a strong ETag that doesn't match, it
  19696. // should return full content)
  19697. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  19698. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  19699. ASSERT_TRUE(res4);
  19700. EXPECT_EQ(200, res4->status);
  19701. EXPECT_EQ(content, res4->body);
  19702. EXPECT_FALSE(res4->has_header("Content-Range"));
  19703. svr.stop();
  19704. t.join();
  19705. std::remove(fname);
  19706. }
  19707. TEST(ETagTest, IfRangeWithDate) {
  19708. using namespace httplib;
  19709. // Create a test file
  19710. const char *fname = "if_range_date_testfile.txt";
  19711. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  19712. {
  19713. std::ofstream ofs(fname);
  19714. ofs << content;
  19715. ASSERT_TRUE(ofs.good());
  19716. }
  19717. Server svr;
  19718. svr.set_mount_point("/static", ".");
  19719. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19720. svr.wait_until_ready();
  19721. Client cli(HOST, PORT);
  19722. // First request: get Last-Modified
  19723. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  19724. ASSERT_TRUE(res1);
  19725. ASSERT_EQ(200, res1->status);
  19726. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19727. std::string last_modified = res1->get_header_value("Last-Modified");
  19728. // Range request with matching If-Range (date): should get 206
  19729. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  19730. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  19731. ASSERT_TRUE(res2);
  19732. EXPECT_EQ(206, res2->status);
  19733. EXPECT_EQ("FGHIJ", res2->body);
  19734. // Range request with old If-Range date: should get 200 (full content)
  19735. Headers h3 = {{"Range", "bytes=5-9"},
  19736. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19737. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  19738. ASSERT_TRUE(res3);
  19739. EXPECT_EQ(200, res3->status);
  19740. EXPECT_EQ(content, res3->body);
  19741. // Range request with future If-Range date: should get 206
  19742. Headers h4 = {{"Range", "bytes=0-4"},
  19743. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19744. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  19745. ASSERT_TRUE(res4);
  19746. EXPECT_EQ(206, res4->status);
  19747. EXPECT_EQ("ABCDE", res4->body);
  19748. svr.stop();
  19749. t.join();
  19750. std::remove(fname);
  19751. }
  19752. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  19753. using namespace httplib;
  19754. const char *fname = "etag_malformed.txt";
  19755. const char *content = "malformed-etag";
  19756. {
  19757. std::ofstream ofs(fname);
  19758. ofs << content;
  19759. ASSERT_TRUE(ofs.good());
  19760. }
  19761. Server svr;
  19762. svr.set_mount_point("/static", ".");
  19763. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19764. svr.wait_until_ready();
  19765. Client cli(HOST, PORT);
  19766. // baseline: should get 200 and an ETag
  19767. auto res1 = cli.Get("/static/etag_malformed.txt");
  19768. ASSERT_TRUE(res1);
  19769. ASSERT_EQ(200, res1->status);
  19770. ASSERT_TRUE(res1->has_header("ETag"));
  19771. // Malformed ETag value (missing quotes) should be treated as non-matching
  19772. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  19773. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  19774. ASSERT_TRUE(res_bad);
  19775. EXPECT_EQ(200, res_bad->status);
  19776. // Whitespace-only header value should be considered invalid / non-matching
  19777. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  19778. "Host: localhost\r\n"
  19779. "If-None-Match: \r\n"
  19780. "Connection: close\r\n"
  19781. "\r\n";
  19782. std::string out;
  19783. ASSERT_TRUE(send_request(5, raw_req, &out));
  19784. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19785. svr.stop();
  19786. t.join();
  19787. std::remove(fname);
  19788. }
  19789. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  19790. using namespace httplib;
  19791. const char *fname = "ims_invalid_format.txt";
  19792. const char *content = "ims-bad-format";
  19793. {
  19794. std::ofstream ofs(fname);
  19795. ofs << content;
  19796. ASSERT_TRUE(ofs.good());
  19797. }
  19798. Server svr;
  19799. svr.set_mount_point("/static", ".");
  19800. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19801. svr.wait_until_ready();
  19802. Client cli(HOST, PORT);
  19803. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  19804. ASSERT_TRUE(res1);
  19805. ASSERT_EQ(200, res1->status);
  19806. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19807. // If-Modified-Since with invalid format should not result in 304
  19808. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  19809. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  19810. ASSERT_TRUE(res_bad);
  19811. EXPECT_EQ(200, res_bad->status);
  19812. // If-Range with invalid date format should be treated as mismatch -> full
  19813. // content (200)
  19814. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  19815. {"If-Range", "invalid-date"}};
  19816. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  19817. ASSERT_TRUE(res_ifrange);
  19818. EXPECT_EQ(200, res_ifrange->status);
  19819. svr.stop();
  19820. t.join();
  19821. std::remove(fname);
  19822. }
  19823. TEST(ETagTest, IfRangeWithMalformedETag) {
  19824. using namespace httplib;
  19825. const char *fname = "ifrange_malformed.txt";
  19826. const std::string content = "0123456789";
  19827. {
  19828. std::ofstream ofs(fname);
  19829. ofs << content;
  19830. ASSERT_TRUE(ofs.good());
  19831. }
  19832. Server svr;
  19833. svr.set_mount_point("/static", ".");
  19834. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19835. svr.wait_until_ready();
  19836. Client cli(HOST, PORT);
  19837. // First request: get ETag
  19838. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  19839. ASSERT_TRUE(res1);
  19840. ASSERT_EQ(200, res1->status);
  19841. ASSERT_TRUE(res1->has_header("ETag"));
  19842. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  19843. // full content (200)
  19844. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  19845. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  19846. ASSERT_TRUE(res2);
  19847. EXPECT_EQ(200, res2->status);
  19848. EXPECT_EQ(content, res2->body);
  19849. svr.stop();
  19850. t.join();
  19851. std::remove(fname);
  19852. }
  19853. TEST(ETagTest, ExtremeLargeDateValues) {
  19854. using namespace httplib;
  19855. const char *fname = "ims_extreme_date.txt";
  19856. const char *content = "ims-extreme-date";
  19857. {
  19858. std::ofstream ofs(fname);
  19859. ofs << content;
  19860. ASSERT_TRUE(ofs.good());
  19861. }
  19862. Server svr;
  19863. svr.set_mount_point("/static", ".");
  19864. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19865. svr.wait_until_ready();
  19866. Client cli(HOST, PORT);
  19867. auto res1 = cli.Get(std::string("/static/") + fname);
  19868. ASSERT_TRUE(res1);
  19869. ASSERT_EQ(200, res1->status);
  19870. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19871. // Extremely large year that may overflow date parsing routines.
  19872. Headers h_large_date = {
  19873. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19874. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  19875. ASSERT_TRUE(res_bad);
  19876. // Expect server to treat this as invalid/mismatch and return full content
  19877. EXPECT_EQ(200, res_bad->status);
  19878. // If-Range with extremely large date should be treated as mismatch -> full
  19879. // content (200)
  19880. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  19881. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19882. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  19883. ASSERT_TRUE(res_ifrange);
  19884. EXPECT_EQ(200, res_ifrange->status);
  19885. svr.stop();
  19886. t.join();
  19887. std::remove(fname);
  19888. }
  19889. TEST(ETagTest, NegativeFileModificationTime) {
  19890. using namespace httplib;
  19891. const char *fname = "ims_negative_mtime.txt";
  19892. const std::string content = "negative-mtime";
  19893. {
  19894. std::ofstream ofs(fname);
  19895. ofs << content;
  19896. ASSERT_TRUE(ofs.good());
  19897. }
  19898. // Try to set file mtime to a negative value. This may fail on some
  19899. // platforms/filesystems; if it fails, the test will still verify server
  19900. // behaves safely by performing a regular conditional request.
  19901. #if defined(__APPLE__) || defined(__linux__)
  19902. bool set_negative = false;
  19903. do {
  19904. struct timeval times[2];
  19905. // access time: now
  19906. times[0].tv_sec = time(nullptr);
  19907. times[0].tv_usec = 0;
  19908. // modification time: negative (e.g., -1)
  19909. times[1].tv_sec = -1;
  19910. times[1].tv_usec = 0;
  19911. if (utimes(fname, times) == 0) { set_negative = true; }
  19912. } while (0);
  19913. #else
  19914. bool set_negative = false;
  19915. #endif
  19916. Server svr;
  19917. svr.set_mount_point("/static", ".");
  19918. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19919. svr.wait_until_ready();
  19920. Client cli(HOST, PORT);
  19921. auto res1 = cli.Get(std::string("/static/") + fname);
  19922. ASSERT_TRUE(res1);
  19923. ASSERT_EQ(200, res1->status);
  19924. bool has_last_modified = res1->has_header("Last-Modified");
  19925. std::string last_modified;
  19926. if (has_last_modified) {
  19927. last_modified = res1->get_header_value("Last-Modified");
  19928. }
  19929. if (set_negative) {
  19930. // If we successfully set a negative mtime, ensure server returns a
  19931. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  19932. // with an old date and ensure server handles it without crash.
  19933. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  19934. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  19935. ASSERT_TRUE(res2);
  19936. // Behavior may vary; at minimum ensure server responds (200 or 304).
  19937. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  19938. } else {
  19939. // Could not set negative mtime on this platform; fall back to verifying
  19940. // that normal invalid/malformed dates are treated safely (non-304).
  19941. Headers h_bad_date = {
  19942. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19943. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  19944. ASSERT_TRUE(res_bad);
  19945. EXPECT_EQ(200, res_bad->status);
  19946. }
  19947. svr.stop();
  19948. t.join();
  19949. std::remove(fname);
  19950. }
  19951. //==============================================================================
  19952. // Integration Tests with Server
  19953. //==============================================================================
  19954. class SSEIntegrationTest : public ::testing::Test {
  19955. protected:
  19956. void SetUp() override {
  19957. stop_server_.store(false);
  19958. events_.clear();
  19959. server_ = httplib::detail::make_unique<Server>();
  19960. setup_server();
  19961. start_server();
  19962. }
  19963. void TearDown() override {
  19964. stop_server_.store(true);
  19965. event_cv_.notify_all();
  19966. server_->stop();
  19967. if (server_thread_.joinable()) { server_thread_.join(); }
  19968. }
  19969. void setup_server() {
  19970. // Simple SSE endpoint
  19971. server_->Get("/events", [this](const Request &req, Response &res) {
  19972. auto last_id = req.get_header_value("Last-Event-ID");
  19973. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  19974. res.set_chunked_content_provider(
  19975. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  19976. std::unique_lock<std::mutex> lock(event_mutex_);
  19977. if (event_cv_.wait_for(
  19978. lock, std::chrono::milliseconds(200), [this] {
  19979. return !events_.empty() || stop_server_.load();
  19980. })) {
  19981. if (stop_server_.load()) { return false; }
  19982. if (!events_.empty()) {
  19983. std::string event = events_.front();
  19984. events_.erase(events_.begin());
  19985. sink.write(event.data(), event.size());
  19986. return true;
  19987. }
  19988. }
  19989. return !stop_server_.load();
  19990. });
  19991. });
  19992. // Endpoint that returns error
  19993. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  19994. res.status = 500;
  19995. res.set_content("Internal Server Error", "text/plain");
  19996. });
  19997. // Endpoint for custom event types
  19998. server_->Get("/custom-events", [](const Request &, Response &res) {
  19999. res.set_chunked_content_provider(
  20000. "text/event-stream", [](size_t offset, DataSink &sink) {
  20001. if (offset == 0) {
  20002. std::string event = "event: update\ndata: updated\n\n"
  20003. "event: delete\ndata: deleted\n\n";
  20004. sink.write(event.data(), event.size());
  20005. }
  20006. return false; // End stream after sending
  20007. });
  20008. });
  20009. }
  20010. void start_server() {
  20011. port_ = server_->bind_to_any_port(HOST);
  20012. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20013. // Wait for server to start
  20014. while (!server_->is_running()) {
  20015. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20016. }
  20017. }
  20018. int get_port() const { return port_; }
  20019. void send_event(const std::string &event) {
  20020. std::lock_guard<std::mutex> lock(event_mutex_);
  20021. events_.push_back(event);
  20022. event_cv_.notify_all();
  20023. }
  20024. std::unique_ptr<Server> server_;
  20025. std::thread server_thread_;
  20026. std::mutex event_mutex_;
  20027. std::condition_variable event_cv_;
  20028. std::vector<std::string> events_;
  20029. std::atomic<bool> stop_server_{false};
  20030. std::string last_received_event_id_;
  20031. int port_ = 0;
  20032. };
  20033. //==============================================================================
  20034. // SSE Parsing Tests
  20035. //==============================================================================
  20036. class SSEParsingTest : public SSEIntegrationTest {
  20037. protected:
  20038. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  20039. // A trailing sentinel event tells when the whole stream has been parsed.
  20040. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  20041. auto body = stream + "event: end\ndata: end\n\n";
  20042. server_->Get("/parse", [body](const Request &, Response &res) {
  20043. res.set_content(body, "text/event-stream");
  20044. });
  20045. return collect("/parse");
  20046. }
  20047. // Runs SSEClient against path until an "end" event arrives and returns the
  20048. // messages dispatched before it
  20049. std::vector<sse::SSEMessage> collect(const std::string &path) {
  20050. Client client(HOST, get_port());
  20051. sse::SSEClient sse(client, path);
  20052. std::mutex mutex;
  20053. std::condition_variable cv;
  20054. std::vector<sse::SSEMessage> messages;
  20055. auto done = false;
  20056. sse.on_message([&](const sse::SSEMessage &msg) {
  20057. std::lock_guard<std::mutex> lock(mutex);
  20058. // Ignore a replay from a reconnect that races with stop()
  20059. if (!done) { messages.push_back(msg); }
  20060. });
  20061. sse.on_event("end", [&](const sse::SSEMessage &) {
  20062. std::lock_guard<std::mutex> lock(mutex);
  20063. done = true;
  20064. cv.notify_all();
  20065. });
  20066. sse.set_reconnect_interval(100);
  20067. sse.start_async();
  20068. {
  20069. std::unique_lock<std::mutex> lock(mutex);
  20070. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  20071. }
  20072. sse.stop();
  20073. EXPECT_TRUE(done);
  20074. return messages;
  20075. }
  20076. };
  20077. TEST_F(SSEParsingTest, SingleLineData) {
  20078. auto msgs = parse("data: hello\n\n");
  20079. ASSERT_EQ(msgs.size(), 1u);
  20080. EXPECT_EQ(msgs[0].data, "hello");
  20081. EXPECT_EQ(msgs[0].event, "message");
  20082. }
  20083. TEST_F(SSEParsingTest, MultiLineData) {
  20084. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  20085. ASSERT_EQ(msgs.size(), 1u);
  20086. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  20087. }
  20088. TEST_F(SSEParsingTest, CustomEventType) {
  20089. auto msgs = parse("event: update\ndata: payload\n\n");
  20090. ASSERT_EQ(msgs.size(), 1u);
  20091. EXPECT_EQ(msgs[0].event, "update");
  20092. EXPECT_EQ(msgs[0].data, "payload");
  20093. }
  20094. TEST_F(SSEParsingTest, EventIdHandling) {
  20095. auto msgs = parse("id: 12345\ndata: test\n\n");
  20096. ASSERT_EQ(msgs.size(), 1u);
  20097. EXPECT_EQ(msgs[0].id, "12345");
  20098. }
  20099. TEST_F(SSEParsingTest, EmptyEventId) {
  20100. auto msgs = parse("id:\ndata: test\n\n");
  20101. ASSERT_EQ(msgs.size(), 1u);
  20102. EXPECT_EQ(msgs[0].id, "");
  20103. }
  20104. TEST_F(SSEParsingTest, CommentsIgnored) {
  20105. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  20106. ASSERT_EQ(msgs.size(), 1u);
  20107. EXPECT_EQ(msgs[0].data, "hello");
  20108. EXPECT_EQ(msgs[0].event, "message");
  20109. }
  20110. TEST_F(SSEParsingTest, ColonInValue) {
  20111. auto msgs = parse("data: hello:world:test\n\n");
  20112. ASSERT_EQ(msgs.size(), 1u);
  20113. EXPECT_EQ(msgs[0].data, "hello:world:test");
  20114. }
  20115. TEST_F(SSEParsingTest, FieldNameOnly) {
  20116. // A line without a colon is a field name with an empty value
  20117. auto msgs = parse("data\n\n");
  20118. ASSERT_EQ(msgs.size(), 1u);
  20119. EXPECT_EQ(msgs[0].data, "");
  20120. }
  20121. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  20122. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  20123. ASSERT_EQ(msgs.size(), 1u);
  20124. EXPECT_EQ(msgs[0].event, "update");
  20125. EXPECT_EQ(msgs[0].data, "hello");
  20126. }
  20127. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  20128. auto msgs = parse("data\r\n\r\n");
  20129. ASSERT_EQ(msgs.size(), 1u);
  20130. EXPECT_EQ(msgs[0].data, "");
  20131. }
  20132. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  20133. auto msgs = parse("event: update\rdata: hello\r\r");
  20134. ASSERT_EQ(msgs.size(), 1u);
  20135. EXPECT_EQ(msgs[0].event, "update");
  20136. EXPECT_EQ(msgs[0].data, "hello");
  20137. }
  20138. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  20139. // Chunk boundaries fall inside every \r\n and right before the first one
  20140. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  20141. "\n\r", "\nevent: end\ndata: end\n\n"};
  20142. server_->Get("/split", [chunks](const Request &, Response &res) {
  20143. auto i = std::make_shared<size_t>(0);
  20144. res.set_chunked_content_provider(
  20145. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  20146. if (*i == chunks.size()) {
  20147. sink.done();
  20148. } else {
  20149. sink.write(chunks[*i].data(), chunks[*i].size());
  20150. (*i)++;
  20151. }
  20152. return true;
  20153. });
  20154. });
  20155. auto msgs = collect("/split");
  20156. ASSERT_EQ(msgs.size(), 1u);
  20157. EXPECT_EQ(msgs[0].event, "update");
  20158. EXPECT_EQ(msgs[0].data, "hello");
  20159. }
  20160. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  20161. // Only a BOM at the start of the stream is ignored
  20162. auto msgs = parse("\xEF\xBB\xBF"
  20163. "data: first\n\n"
  20164. "\xEF\xBB\xBF"
  20165. "data: second\n\n");
  20166. ASSERT_EQ(msgs.size(), 1u);
  20167. EXPECT_EQ(msgs[0].data, "first");
  20168. }
  20169. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  20170. auto msgs = parse("unknown: value\ndata: hello\n\n");
  20171. ASSERT_EQ(msgs.size(), 1u);
  20172. EXPECT_EQ(msgs[0].data, "hello");
  20173. EXPECT_EQ(msgs[0].event, "message");
  20174. }
  20175. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  20176. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  20177. ASSERT_EQ(msgs.size(), 2u);
  20178. EXPECT_EQ(msgs[0].data, "hello");
  20179. EXPECT_EQ(msgs[1].data, "hello");
  20180. }
  20181. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  20182. // An event without data is not dispatched, and its type must not leak
  20183. // into the next event
  20184. auto msgs = parse("event: update\n\ndata: hello\n\n");
  20185. ASSERT_EQ(msgs.size(), 1u);
  20186. EXPECT_EQ(msgs[0].event, "message");
  20187. EXPECT_EQ(msgs[0].data, "hello");
  20188. }
  20189. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  20190. // The first connection sends only an id; the second echoes back the
  20191. // Last-Event-ID it was reconnected with
  20192. std::atomic<int> connection_count{0};
  20193. server_->Get("/id-only", [&](const Request &req, Response &res) {
  20194. if (connection_count++ == 0) {
  20195. res.set_content("id: 42\n\n", "text/event-stream");
  20196. } else {
  20197. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20198. "\n\nevent: end\ndata: end\n\n",
  20199. "text/event-stream");
  20200. }
  20201. });
  20202. auto msgs = collect("/id-only");
  20203. ASSERT_EQ(msgs.size(), 1u);
  20204. EXPECT_EQ(msgs[0].data, "42");
  20205. }
  20206. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  20207. // The first connection sets an id and then clears it with an empty one; the
  20208. // second reports whether it was reconnected with a Last-Event-ID
  20209. std::atomic<int> connection_count{0};
  20210. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  20211. if (connection_count++ == 0) {
  20212. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  20213. "text/event-stream");
  20214. } else {
  20215. res.set_content(
  20216. std::string("data: ") +
  20217. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  20218. "\n\nevent: end\ndata: end\n\n",
  20219. "text/event-stream");
  20220. }
  20221. });
  20222. auto msgs = collect("/id-clear");
  20223. ASSERT_EQ(msgs.size(), 3u);
  20224. EXPECT_EQ(msgs[0].id, "1");
  20225. EXPECT_EQ(msgs[1].id, "");
  20226. EXPECT_EQ(msgs[2].data, "not sent");
  20227. }
  20228. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  20229. // The first connection sets an id and then sends ids that cannot be carried
  20230. // in a header; the second echoes back the Last-Event-ID it was reconnected
  20231. // with
  20232. std::atomic<int> connection_count{0};
  20233. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  20234. if (connection_count++ == 0) {
  20235. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  20236. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  20237. "text/event-stream");
  20238. } else {
  20239. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20240. "\n\nevent: end\ndata: end\n\n",
  20241. "text/event-stream");
  20242. }
  20243. });
  20244. auto msgs = collect("/id-unsendable");
  20245. ASSERT_EQ(msgs.size(), 1u);
  20246. EXPECT_EQ(msgs[0].data, "42");
  20247. }
  20248. TEST_F(SSEParsingTest, CompleteEventParsing) {
  20249. auto msgs = parse("event: notification\nid: evt-42\n"
  20250. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  20251. ASSERT_EQ(msgs.size(), 1u);
  20252. EXPECT_EQ(msgs[0].event, "notification");
  20253. EXPECT_EQ(msgs[0].id, "evt-42");
  20254. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  20255. }
  20256. TEST(SSEMessageTest, Clear) {
  20257. sse::SSEMessage msg;
  20258. msg.event = "custom";
  20259. msg.data = "some data";
  20260. msg.id = "123";
  20261. msg.clear();
  20262. EXPECT_EQ(msg.event, "message");
  20263. EXPECT_EQ(msg.data, "");
  20264. EXPECT_EQ(msg.id, "");
  20265. }
  20266. //==============================================================================
  20267. // SSE Integration Tests
  20268. //==============================================================================
  20269. // Test: Successful connection and on_open callback
  20270. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  20271. // Add a simple endpoint that sends one event and closes
  20272. server_->Get("/simple-event", [](const Request &, Response &res) {
  20273. res.set_chunked_content_provider(
  20274. "text/event-stream", [](size_t offset, DataSink &sink) {
  20275. if (offset == 0) {
  20276. std::string event = "data: hello\n\n";
  20277. sink.write(event.data(), event.size());
  20278. }
  20279. return false; // Close stream after sending
  20280. });
  20281. });
  20282. Client client("localhost", get_port());
  20283. sse::SSEClient sse(client, "/simple-event");
  20284. std::atomic<bool> open_called{false};
  20285. std::atomic<bool> message_received{false};
  20286. sse.on_open([&open_called]() { open_called.store(true); });
  20287. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  20288. if (msg.data == "hello") { message_received.store(true); }
  20289. });
  20290. sse.set_reconnect_interval(100);
  20291. sse.set_max_reconnect_attempts(1);
  20292. // Start async
  20293. sse.start_async();
  20294. // Wait for message to be processed
  20295. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20296. sse.stop();
  20297. EXPECT_TRUE(open_called.load());
  20298. EXPECT_TRUE(message_received.load());
  20299. }
  20300. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  20301. // A data line that never ends.
  20302. server_->Get("/endless-line", [](const Request &, Response &res) {
  20303. res.set_chunked_content_provider(
  20304. "text/event-stream", [](size_t offset, DataSink &sink) {
  20305. if (offset == 0) { sink.write("data: ", 6); }
  20306. std::string chunk(64 * 1024, 'A');
  20307. return sink.write(chunk.data(), chunk.size());
  20308. });
  20309. });
  20310. Client client("localhost", get_port());
  20311. // A stream that may run forever, so that only the event is bounded.
  20312. client.set_payload_max_length(0);
  20313. sse::SSEClient sse(client, "/endless-line");
  20314. std::atomic<bool> too_long{false};
  20315. sse.on_error([&](Error err) {
  20316. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  20317. });
  20318. sse.set_max_reconnect_attempts(1);
  20319. sse.start_async();
  20320. for (int i = 0; i < 500 && !too_long; i++) {
  20321. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20322. }
  20323. sse.stop();
  20324. EXPECT_TRUE(too_long);
  20325. }
  20326. // Test: on_message callback
  20327. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  20328. // Endpoint that sends multiple events then closes
  20329. server_->Get("/multi-event", [](const Request &, Response &res) {
  20330. res.set_chunked_content_provider(
  20331. "text/event-stream", [](size_t offset, DataSink &sink) {
  20332. if (offset == 0) {
  20333. std::string events = "data: message1\n\ndata: message2\n\n";
  20334. sink.write(events.data(), events.size());
  20335. }
  20336. return false;
  20337. });
  20338. });
  20339. Client client("localhost", get_port());
  20340. sse::SSEClient sse(client, "/multi-event");
  20341. std::vector<std::string> received_messages;
  20342. std::mutex messages_mutex;
  20343. sse.on_message([&](const sse::SSEMessage &msg) {
  20344. std::lock_guard<std::mutex> lock(messages_mutex);
  20345. received_messages.push_back(msg.data);
  20346. });
  20347. sse.set_reconnect_interval(100);
  20348. sse.set_max_reconnect_attempts(1);
  20349. sse.start_async();
  20350. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20351. sse.stop();
  20352. std::lock_guard<std::mutex> lock(messages_mutex);
  20353. EXPECT_GE(received_messages.size(), 2u);
  20354. if (received_messages.size() >= 2) {
  20355. EXPECT_EQ(received_messages[0], "message1");
  20356. EXPECT_EQ(received_messages[1], "message2");
  20357. }
  20358. }
  20359. // Test: on_event for specific types
  20360. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  20361. Client client("localhost", get_port());
  20362. sse::SSEClient sse(client, "/custom-events");
  20363. std::atomic<bool> update_received{false};
  20364. std::atomic<bool> delete_received{false};
  20365. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  20366. if (msg.data == "updated") { update_received.store(true); }
  20367. });
  20368. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  20369. if (msg.data == "deleted") { delete_received.store(true); }
  20370. });
  20371. sse.set_max_reconnect_attempts(1);
  20372. sse.start_async();
  20373. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  20374. sse.stop();
  20375. EXPECT_TRUE(update_received.load());
  20376. EXPECT_TRUE(delete_received.load());
  20377. }
  20378. // Test: on_error callback on connection failure
  20379. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  20380. // Connect to a non-existent port
  20381. Client client("localhost", 59999);
  20382. sse::SSEClient sse(client, "/events");
  20383. std::atomic<bool> error_called{false};
  20384. Error received_error = Error::Success;
  20385. sse.on_error([&](Error err) {
  20386. error_called.store(true);
  20387. received_error = err;
  20388. });
  20389. sse.set_reconnect_interval(50);
  20390. sse.set_max_reconnect_attempts(1);
  20391. sse.start_async();
  20392. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20393. sse.stop();
  20394. EXPECT_TRUE(error_called.load());
  20395. EXPECT_NE(received_error, Error::Success);
  20396. }
  20397. // Test: Last-Event-ID header sent on reconnect
  20398. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  20399. // Endpoint that sends event with ID
  20400. server_->Get("/event-with-id", [](const Request &, Response &res) {
  20401. res.set_chunked_content_provider(
  20402. "text/event-stream", [](size_t offset, DataSink &sink) {
  20403. if (offset == 0) {
  20404. std::string event = "id: evt-123\ndata: test\n\n";
  20405. sink.write(event.data(), event.size());
  20406. }
  20407. return false;
  20408. });
  20409. });
  20410. Client client("localhost", get_port());
  20411. sse::SSEClient sse(client, "/event-with-id");
  20412. std::atomic<bool> id_received{false};
  20413. sse.on_message([&](const sse::SSEMessage &msg) {
  20414. if (!msg.id.empty()) { id_received.store(true); }
  20415. });
  20416. sse.set_reconnect_interval(100);
  20417. sse.set_max_reconnect_attempts(1);
  20418. sse.start_async();
  20419. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20420. sse.stop();
  20421. EXPECT_TRUE(id_received.load());
  20422. EXPECT_EQ(sse.last_event_id(), "evt-123");
  20423. }
  20424. // Test: Manual stop
  20425. TEST_F(SSEIntegrationTest, ManualStop) {
  20426. // Endpoint that sends one event and stays open briefly
  20427. std::atomic<bool> handler_running{true};
  20428. server_->Get("/stay-open", [&handler_running](const Request &,
  20429. Response &res) {
  20430. res.set_chunked_content_provider(
  20431. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  20432. if (offset == 0) {
  20433. std::string event = "data: connected\n\n";
  20434. sink.write(event.data(), event.size());
  20435. }
  20436. // Keep connection open while handler_running is true
  20437. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  20438. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20439. }
  20440. return false;
  20441. });
  20442. });
  20443. Client client("localhost", get_port());
  20444. sse::SSEClient sse(client, "/stay-open");
  20445. std::atomic<bool> connected{false};
  20446. sse.on_open([&connected]() { connected.store(true); });
  20447. sse.set_reconnect_interval(100);
  20448. sse.set_max_reconnect_attempts(1);
  20449. sse.start_async();
  20450. // Wait for connection to establish
  20451. for (int i = 0; i < 20 && !connected.load(); ++i) {
  20452. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20453. }
  20454. EXPECT_TRUE(connected.load());
  20455. EXPECT_TRUE(sse.is_connected());
  20456. // Signal handler to stop
  20457. handler_running.store(false);
  20458. // Stop SSE client
  20459. sse.stop();
  20460. EXPECT_FALSE(sse.is_connected());
  20461. }
  20462. // Test: SSEClient with custom headers
  20463. TEST_F(SSEIntegrationTest, CustomHeaders) {
  20464. // Setup a server endpoint that checks for custom header
  20465. std::atomic<bool> header_received{false};
  20466. server_->Get("/header-check", [&](const Request &req, Response &res) {
  20467. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  20468. header_received.store(true);
  20469. }
  20470. res.set_chunked_content_provider("text/event-stream",
  20471. [](size_t, DataSink &) { return false; });
  20472. });
  20473. Client client("localhost", get_port());
  20474. Headers headers = {{"X-Custom-Header", "custom-value"}};
  20475. sse::SSEClient sse(client, "/header-check", headers);
  20476. sse.set_max_reconnect_attempts(1);
  20477. sse.start_async();
  20478. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20479. sse.stop();
  20480. EXPECT_TRUE(header_received.load());
  20481. }
  20482. // Test: Reconnect interval configuration
  20483. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  20484. Client client("localhost", get_port());
  20485. sse::SSEClient sse(client, "/events");
  20486. auto &result = sse.set_reconnect_interval(500);
  20487. // Builder pattern should return reference to self
  20488. EXPECT_EQ(&result, &sse);
  20489. }
  20490. // Test: Max reconnect attempts
  20491. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  20492. // Connect to non-existent port to force reconnects
  20493. Client client("localhost", 59998);
  20494. sse::SSEClient sse(client, "/events");
  20495. std::atomic<int> error_count{0};
  20496. sse.on_error([&](Error) { error_count.fetch_add(1); });
  20497. sse.set_reconnect_interval(50);
  20498. sse.set_max_reconnect_attempts(2);
  20499. auto start = std::chrono::steady_clock::now();
  20500. sse.start(); // Blocking call
  20501. auto end = std::chrono::steady_clock::now();
  20502. // Should have stopped after 2 failed attempts
  20503. EXPECT_GE(error_count.load(), 2);
  20504. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  20505. auto duration =
  20506. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  20507. #ifdef _WIN32
  20508. // Windows is much slower for socket connection failures
  20509. EXPECT_LT(duration.count(), 7000);
  20510. #else
  20511. EXPECT_LT(duration.count(), 1000);
  20512. #endif
  20513. }
  20514. // Test: Multi-line data in integration
  20515. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  20516. // Endpoint with multi-line data
  20517. server_->Get("/multiline-data", [](const Request &, Response &res) {
  20518. res.set_chunked_content_provider(
  20519. "text/event-stream", [](size_t offset, DataSink &sink) {
  20520. if (offset == 0) {
  20521. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  20522. sink.write(event.data(), event.size());
  20523. }
  20524. return false;
  20525. });
  20526. });
  20527. Client client("localhost", get_port());
  20528. sse::SSEClient sse(client, "/multiline-data");
  20529. std::string received_data;
  20530. std::mutex data_mutex;
  20531. sse.on_message([&](const sse::SSEMessage &msg) {
  20532. std::lock_guard<std::mutex> lock(data_mutex);
  20533. received_data = msg.data;
  20534. });
  20535. sse.set_reconnect_interval(100);
  20536. sse.set_max_reconnect_attempts(1);
  20537. sse.start_async();
  20538. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20539. sse.stop();
  20540. std::lock_guard<std::mutex> lock(data_mutex);
  20541. EXPECT_EQ(received_data, "line1\nline2\nline3");
  20542. }
  20543. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  20544. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  20545. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  20546. DataSink &sink) {
  20547. if (offset == 0) {
  20548. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  20549. sink.write(events.data(), events.size());
  20550. }
  20551. return false;
  20552. });
  20553. });
  20554. Client client("localhost", get_port());
  20555. sse::SSEClient sse(client, "/empty-data-lines");
  20556. std::mutex mutex;
  20557. std::condition_variable cv;
  20558. std::vector<std::string> received;
  20559. sse.on_message([&](const sse::SSEMessage &msg) {
  20560. std::lock_guard<std::mutex> lock(mutex);
  20561. received.push_back(msg.data);
  20562. cv.notify_all();
  20563. });
  20564. sse.set_max_reconnect_attempts(1);
  20565. sse.start_async();
  20566. {
  20567. std::unique_lock<std::mutex> lock(mutex);
  20568. cv.wait_for(lock, std::chrono::seconds(2),
  20569. [&] { return received.size() >= 3; });
  20570. }
  20571. sse.stop();
  20572. ASSERT_GE(received.size(), 3u);
  20573. EXPECT_EQ(received[0], "");
  20574. EXPECT_EQ(received[1], "\nhello");
  20575. EXPECT_EQ(received[2], "");
  20576. }
  20577. // Test: Auto-reconnect after server disconnection
  20578. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  20579. std::atomic<int> connection_count{0};
  20580. std::atomic<int> message_count{0};
  20581. // Endpoint that sends one event and closes, forcing reconnect
  20582. server_->Get("/reconnect-test",
  20583. [&connection_count](const Request &, Response &res) {
  20584. connection_count.fetch_add(1);
  20585. res.set_chunked_content_provider(
  20586. "text/event-stream", [](size_t offset, DataSink &sink) {
  20587. if (offset == 0) {
  20588. std::string event = "data: hello\n\n";
  20589. sink.write(event.data(), event.size());
  20590. }
  20591. return false; // Close connection after sending
  20592. });
  20593. });
  20594. Client client("localhost", get_port());
  20595. sse::SSEClient sse(client, "/reconnect-test");
  20596. sse.on_message([&message_count](const sse::SSEMessage &) {
  20597. message_count.fetch_add(1);
  20598. });
  20599. sse.set_reconnect_interval(100);
  20600. sse.set_max_reconnect_attempts(3);
  20601. sse.start_async();
  20602. // Wait long enough for multiple reconnects
  20603. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20604. sse.stop();
  20605. // Should have connected multiple times (initial + reconnects)
  20606. EXPECT_GE(connection_count.load(), 2);
  20607. // Should have received messages from multiple connections
  20608. EXPECT_GE(message_count.load(), 2);
  20609. }
  20610. // Test: A retry field that is not all ASCII digits is ignored
  20611. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  20612. std::atomic<int> connection_count{0};
  20613. server_->Get("/bad-retry",
  20614. [&connection_count](const Request &, Response &res) {
  20615. connection_count.fetch_add(1);
  20616. res.set_chunked_content_provider(
  20617. "text/event-stream", [](size_t offset, DataSink &sink) {
  20618. if (offset == 0) {
  20619. std::string event = "retry: -1\ndata: hello\n\n";
  20620. sink.write(event.data(), event.size());
  20621. }
  20622. return false;
  20623. });
  20624. });
  20625. Client client("localhost", get_port());
  20626. sse::SSEClient sse(client, "/bad-retry");
  20627. sse.set_reconnect_interval(10000);
  20628. sse.start_async();
  20629. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20630. sse.stop();
  20631. EXPECT_EQ(connection_count.load(), 1);
  20632. }
  20633. // Test: A retry field of all ASCII digits sets the reconnection time
  20634. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  20635. std::mutex mutex;
  20636. std::condition_variable cv;
  20637. std::vector<std::chrono::steady_clock::time_point> connected_at;
  20638. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  20639. {
  20640. std::lock_guard<std::mutex> lock(mutex);
  20641. connected_at.push_back(std::chrono::steady_clock::now());
  20642. cv.notify_all();
  20643. }
  20644. res.set_chunked_content_provider(
  20645. "text/event-stream", [](size_t offset, DataSink &sink) {
  20646. if (offset == 0) {
  20647. std::string event = "retry: 0\ndata: hello\n\n";
  20648. sink.write(event.data(), event.size());
  20649. }
  20650. return false;
  20651. });
  20652. });
  20653. Client client("localhost", get_port());
  20654. sse::SSEClient sse(client, "/zero-retry");
  20655. sse.set_reconnect_interval(10000);
  20656. sse.start_async();
  20657. {
  20658. std::unique_lock<std::mutex> lock(mutex);
  20659. cv.wait_for(lock, std::chrono::seconds(5),
  20660. [&] { return connected_at.size() >= 2; });
  20661. }
  20662. sse.stop();
  20663. // The server-supplied interval is applied, but never below 100ms, so
  20664. // "retry: 0" does not cause a busy reconnect loop
  20665. std::lock_guard<std::mutex> lock(mutex);
  20666. ASSERT_GE(connected_at.size(), 2u);
  20667. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  20668. connected_at[1] - connected_at[0])
  20669. .count();
  20670. EXPECT_GE(interval_ms, 100);
  20671. }
  20672. // Test: Last-Event-ID sent on reconnect
  20673. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  20674. std::atomic<int> connection_count{0};
  20675. std::vector<std::string> received_last_event_ids;
  20676. std::mutex id_mutex;
  20677. // Endpoint that checks Last-Event-ID header and sends event with ID
  20678. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  20679. int conn = connection_count.fetch_add(1);
  20680. // Capture the Last-Event-ID header from each connection
  20681. {
  20682. std::lock_guard<std::mutex> lock(id_mutex);
  20683. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  20684. }
  20685. res.set_chunked_content_provider(
  20686. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  20687. if (offset == 0) {
  20688. std::string event =
  20689. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  20690. sink.write(event.data(), event.size());
  20691. }
  20692. return false;
  20693. });
  20694. });
  20695. Client client("localhost", get_port());
  20696. sse::SSEClient sse(client, "/reconnect-with-id");
  20697. sse.set_reconnect_interval(100);
  20698. sse.set_max_reconnect_attempts(3);
  20699. sse.start_async();
  20700. // Wait for at least 2 connections
  20701. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20702. sse.stop();
  20703. // Verify behavior
  20704. std::lock_guard<std::mutex> lock(id_mutex);
  20705. EXPECT_GE(received_last_event_ids.size(), 2u);
  20706. // First connection should have no Last-Event-ID
  20707. if (!received_last_event_ids.empty()) {
  20708. EXPECT_EQ(received_last_event_ids[0], "");
  20709. }
  20710. // Second connection should have Last-Event-ID from first connection
  20711. if (received_last_event_ids.size() >= 2) {
  20712. EXPECT_EQ(received_last_event_ids[1], "event-0");
  20713. }
  20714. }
  20715. // Test: set_headers updates headers used on reconnect
  20716. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  20717. std::vector<std::string> received_tokens;
  20718. std::mutex token_mutex;
  20719. // Endpoint that captures Authorization header
  20720. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  20721. {
  20722. std::lock_guard<std::mutex> lock(token_mutex);
  20723. received_tokens.push_back(req.get_header_value("Authorization"));
  20724. }
  20725. res.set_chunked_content_provider(
  20726. "text/event-stream", [](size_t offset, DataSink &sink) {
  20727. if (offset == 0) {
  20728. std::string event = "data: hello\n\n";
  20729. sink.write(event.data(), event.size());
  20730. }
  20731. return false; // Close connection to trigger reconnect
  20732. });
  20733. });
  20734. Client client("localhost", get_port());
  20735. Headers headers = {{"Authorization", "Bearer old-token"}};
  20736. sse::SSEClient sse(client, "/auth-check", headers);
  20737. // Update headers on each successful connection
  20738. sse.on_open(
  20739. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  20740. sse.set_reconnect_interval(100);
  20741. sse.set_max_reconnect_attempts(3);
  20742. sse.start_async();
  20743. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20744. sse.stop();
  20745. std::lock_guard<std::mutex> lock(token_mutex);
  20746. ASSERT_GE(received_tokens.size(), 2u);
  20747. // First connection uses original header
  20748. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  20749. // Second connection uses updated header from set_headers
  20750. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  20751. }
  20752. // Test: 401 allows reconnection (so on_error can refresh headers)
  20753. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  20754. std::atomic<int> connection_count{0};
  20755. // Endpoint: returns 401 on first attempt, 200 on second
  20756. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  20757. int conn = connection_count.fetch_add(1);
  20758. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  20759. res.status = StatusCode::Unauthorized_401;
  20760. res.set_content("Unauthorized", "text/plain");
  20761. return;
  20762. }
  20763. res.set_chunked_content_provider(
  20764. "text/event-stream", [](size_t offset, DataSink &sink) {
  20765. if (offset == 0) {
  20766. std::string event = "data: authenticated\n\n";
  20767. sink.write(event.data(), event.size());
  20768. }
  20769. return false;
  20770. });
  20771. });
  20772. Client client("localhost", get_port());
  20773. Headers headers = {{"Authorization", "Bearer expired"}};
  20774. sse::SSEClient sse(client, "/auth-retry", headers);
  20775. std::atomic<bool> message_received{false};
  20776. // Refresh token on error
  20777. sse.on_error(
  20778. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  20779. sse.on_message([&](const sse::SSEMessage &msg) {
  20780. if (msg.data == "authenticated") { message_received.store(true); }
  20781. });
  20782. sse.set_reconnect_interval(100);
  20783. sse.set_max_reconnect_attempts(3);
  20784. sse.start_async();
  20785. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20786. sse.stop();
  20787. // Should have reconnected after 401 and succeeded with new token
  20788. EXPECT_GE(connection_count.load(), 2);
  20789. EXPECT_TRUE(message_received.load());
  20790. }
  20791. TEST(Issue2318Test, EmptyHostString) {
  20792. {
  20793. httplib::Client cli_empty("", PORT);
  20794. auto res = cli_empty.Get("/");
  20795. ASSERT_FALSE(res);
  20796. EXPECT_EQ(httplib::Error::Connection, res.error());
  20797. }
  20798. {
  20799. httplib::Client cli(" ", PORT);
  20800. auto res = cli.Get("/");
  20801. ASSERT_FALSE(res);
  20802. EXPECT_EQ(httplib::Error::Connection, res.error());
  20803. }
  20804. }
  20805. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20806. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  20807. Server svr;
  20808. // Set a small payload limit (1KB)
  20809. svr.set_payload_max_length(1024);
  20810. svr.Post("/test", [&](const Request &req, Response &res) {
  20811. res.set_content("Body size: " + std::to_string(req.body.size()),
  20812. "text/plain");
  20813. });
  20814. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  20815. auto se = detail::scope_exit([&] {
  20816. svr.stop();
  20817. listen_thread.join();
  20818. });
  20819. svr.wait_until_ready();
  20820. // Create data that compresses well but exceeds limit when decompressed
  20821. // 8KB of repeated null bytes compresses to a very small size
  20822. std::string original_data(8 * 1024, '\0');
  20823. // Compress the data using gzip
  20824. std::string compressed_data;
  20825. detail::gzip_compressor compressor;
  20826. compressor.compress(original_data.data(), original_data.size(), true,
  20827. [&](const char *data, size_t size) {
  20828. compressed_data.append(data, size);
  20829. return true;
  20830. });
  20831. // Verify compression worked (compressed should be much smaller)
  20832. ASSERT_LT(compressed_data.size(), original_data.size());
  20833. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  20834. // Send compressed data with Content-Encoding: gzip
  20835. Client cli(HOST, PORT);
  20836. Headers headers = {{"Content-Encoding", "gzip"}};
  20837. auto res =
  20838. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  20839. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  20840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20841. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  20842. }
  20843. #endif
  20844. // ============================================================================
  20845. // OpenSSL-Specific Tests
  20846. // ============================================================================
  20847. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  20848. X509 *readCertificate(const std::string &strFileName) {
  20849. std::ifstream inStream(strFileName);
  20850. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  20851. std::istreambuf_iterator<char>());
  20852. if (strCertPEM.empty()) return (nullptr);
  20853. BIO *pbCert = BIO_new(BIO_s_mem());
  20854. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  20855. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  20856. BIO_free(pbCert);
  20857. return (pCert);
  20858. }
  20859. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  20860. std::ifstream inStream(strFileName);
  20861. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  20862. std::istreambuf_iterator<char>());
  20863. if (strPrivateKeyPEM.empty()) return (nullptr);
  20864. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  20865. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  20866. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  20867. BIO_free(pbPrivKey);
  20868. return (pPrivateKey);
  20869. }
  20870. TEST(BindServerTest, UpdateCerts) {
  20871. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20872. int port = svr.bind_to_any_port("0.0.0.0");
  20873. ASSERT_TRUE(svr.is_valid());
  20874. ASSERT_TRUE(port > 0);
  20875. X509 *cert = readCertificate(SERVER_CERT_FILE);
  20876. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  20877. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  20878. ASSERT_TRUE(cert != nullptr);
  20879. ASSERT_TRUE(ca_cert != nullptr);
  20880. ASSERT_TRUE(key != nullptr);
  20881. X509_STORE *cert_store = X509_STORE_new();
  20882. X509_STORE_add_cert(cert_store, ca_cert);
  20883. // svr.update_certs(cert, key, cert_store); // deprecated
  20884. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  20885. CLIENT_CA_CERT_FILE);
  20886. ASSERT_TRUE(svr.is_valid());
  20887. svr.stop();
  20888. X509_STORE_free(cert_store);
  20889. X509_free(cert);
  20890. X509_free(ca_cert);
  20891. EVP_PKEY_free(key);
  20892. }
  20893. // Test that update_certs() updates client CA list correctly
  20894. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  20895. // Start with file-based constructor
  20896. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20897. ASSERT_TRUE(svr.is_valid());
  20898. // Initially no client CA list should be set
  20899. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20900. ASSERT_TRUE(ssl_ctx != nullptr);
  20901. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  20902. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  20903. EXPECT_EQ(0, count_before);
  20904. // Now update with client CA (PEM string)
  20905. std::string cert_pem, key_pem, ca_pem;
  20906. read_file(SERVER_CERT_FILE, cert_pem);
  20907. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  20908. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  20909. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  20910. ASSERT_TRUE(svr.is_valid());
  20911. // Now client CA list should be set
  20912. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  20913. ASSERT_TRUE(ca_list_after != nullptr);
  20914. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  20915. }
  20916. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  20917. // Test that the file-path SSLServer constructor properly sets the client CA
  20918. // list that is sent to clients during the TLS handshake (CertificateRequest)
  20919. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20920. ASSERT_TRUE(svr.is_valid());
  20921. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20922. ASSERT_TRUE(ssl_ctx != nullptr);
  20923. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  20924. ASSERT_TRUE(ca_list != nullptr);
  20925. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  20926. }
  20927. #endif
  20928. // ============================================================================
  20929. // MbedTLS-Specific Tests
  20930. // ============================================================================
  20931. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  20932. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  20933. using namespace httplib::tls;
  20934. // Track if callback was invoked
  20935. bool callback_invoked = false;
  20936. // The callback receives void* ctx which is actually MbedTlsContext*
  20937. // We can access the mbedtls_ssl_config via the context
  20938. auto setup_callback = [&callback_invoked](void *ctx) {
  20939. callback_invoked = true;
  20940. // Cast to MbedTlsContext* to access the ssl config
  20941. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  20942. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  20943. // Use static variables to hold certificate data (simplified for test)
  20944. static mbedtls_x509_crt own_cert;
  20945. static mbedtls_pk_context own_key;
  20946. static mbedtls_x509_crt ca_chain;
  20947. static bool initialized = false;
  20948. if (!initialized) {
  20949. mbedtls_x509_crt_init(&own_cert);
  20950. mbedtls_pk_init(&own_key);
  20951. mbedtls_x509_crt_init(&ca_chain);
  20952. // Load server certificate
  20953. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  20954. return false;
  20955. }
  20956. // Load server private key.
  20957. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  20958. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  20959. #if MBEDTLS_VERSION_MAJOR == 3
  20960. ,
  20961. mbedtls_ctr_drbg_random, nullptr
  20962. #endif
  20963. ) != 0) {
  20964. return false;
  20965. }
  20966. // Load CA chain for client verification
  20967. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  20968. return false;
  20969. }
  20970. initialized = true;
  20971. }
  20972. // Configure the SSL config
  20973. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  20974. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  20975. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  20976. // Set minimum TLS version using mbedTLS native API
  20977. #if MBEDTLS_VERSION_MAJOR >= 3
  20978. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  20979. #else
  20980. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  20981. MBEDTLS_SSL_MINOR_VERSION_3);
  20982. #endif
  20983. return true;
  20984. };
  20985. SSLServer svr(setup_callback);
  20986. ASSERT_TRUE(svr.is_valid());
  20987. ASSERT_TRUE(callback_invoked);
  20988. svr.Get("/test", [&](const Request &req, Response &res) {
  20989. res.set_content("test", "text/plain");
  20990. auto cert = req.peer_cert();
  20991. ASSERT_TRUE(static_cast<bool>(cert));
  20992. auto common_name = cert.subject_cn();
  20993. EXPECT_EQ("Common Name", common_name);
  20994. });
  20995. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20996. auto se = detail::scope_exit([&] {
  20997. svr.stop();
  20998. t.join();
  20999. ASSERT_FALSE(svr.is_running());
  21000. });
  21001. svr.wait_until_ready();
  21002. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  21003. cli.enable_server_certificate_verification(false);
  21004. cli.set_connection_timeout(30);
  21005. auto res = cli.Get("/test");
  21006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21007. ASSERT_EQ(StatusCode::OK_200, res->status);
  21008. }
  21009. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  21010. // context (owning mbedtls_ssl_config) before shutting down a still-open
  21011. // keep-alive SSL session, which reads through that config in
  21012. // mbedtls_ssl_close_notify.
  21013. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  21014. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21015. ASSERT_TRUE(svr.is_valid());
  21016. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  21017. res.set_content("test", "text/plain");
  21018. });
  21019. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21020. auto se = detail::scope_exit([&] {
  21021. svr.stop();
  21022. t.join();
  21023. ASSERT_FALSE(svr.is_running());
  21024. });
  21025. svr.wait_until_ready();
  21026. {
  21027. SSLClient cli(HOST, PORT);
  21028. cli.enable_server_certificate_verification(false);
  21029. cli.set_keep_alive(true);
  21030. auto res = cli.Get("/test");
  21031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21032. ASSERT_EQ(StatusCode::OK_200, res->status);
  21033. // cli is destructed here with the keep-alive SSL session still open.
  21034. }
  21035. }
  21036. #endif
  21037. // WebSocket Tests
  21038. TEST(WebSocketTest, RSVBitsMustBeZero) {
  21039. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  21040. // defining the meaning of these bits has been negotiated.
  21041. auto make_frame = [](uint8_t first_byte) {
  21042. std::string frame;
  21043. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  21044. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  21045. frame += "Hello";
  21046. return frame;
  21047. };
  21048. // RSV1 set (0x40)
  21049. {
  21050. detail::BufferStream strm;
  21051. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  21052. ws::Opcode opcode;
  21053. std::string payload;
  21054. bool fin;
  21055. EXPECT_EQ(
  21056. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21057. ws::impl::FrameRead::Fail);
  21058. }
  21059. // RSV2 set (0x20)
  21060. {
  21061. detail::BufferStream strm;
  21062. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  21063. ws::Opcode opcode;
  21064. std::string payload;
  21065. bool fin;
  21066. EXPECT_EQ(
  21067. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21068. ws::impl::FrameRead::Fail);
  21069. }
  21070. // RSV3 set (0x10)
  21071. {
  21072. detail::BufferStream strm;
  21073. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  21074. ws::Opcode opcode;
  21075. std::string payload;
  21076. bool fin;
  21077. EXPECT_EQ(
  21078. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21079. ws::impl::FrameRead::Fail);
  21080. }
  21081. // No RSV bits set - should succeed
  21082. {
  21083. detail::BufferStream strm;
  21084. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  21085. ws::Opcode opcode;
  21086. std::string payload;
  21087. bool fin;
  21088. EXPECT_EQ(
  21089. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21090. ws::impl::FrameRead::Ok);
  21091. EXPECT_EQ(ws::Opcode::Text, opcode);
  21092. EXPECT_EQ("Hello", payload);
  21093. EXPECT_TRUE(fin);
  21094. }
  21095. }
  21096. TEST(WebSocketTest, ControlFrameValidation) {
  21097. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  21098. // payload length <= 125.
  21099. // Ping with FIN=0 - must be rejected
  21100. {
  21101. detail::BufferStream strm;
  21102. std::string frame;
  21103. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  21104. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21105. strm.write(frame.data(), frame.size());
  21106. ws::Opcode opcode;
  21107. std::string payload;
  21108. bool fin;
  21109. EXPECT_EQ(
  21110. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21111. ws::impl::FrameRead::Fail);
  21112. }
  21113. // Close with FIN=0 - must be rejected
  21114. {
  21115. detail::BufferStream strm;
  21116. std::string frame;
  21117. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  21118. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21119. strm.write(frame.data(), frame.size());
  21120. ws::Opcode opcode;
  21121. std::string payload;
  21122. bool fin;
  21123. EXPECT_EQ(
  21124. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21125. ws::impl::FrameRead::Fail);
  21126. }
  21127. // Ping with payload_len=126 (extended length) - must be rejected
  21128. {
  21129. detail::BufferStream strm;
  21130. std::string frame;
  21131. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21132. frame += static_cast<char>(126); // payload_len=126 (>125)
  21133. frame += static_cast<char>(0x00); // extended length high byte
  21134. frame += static_cast<char>(126); // extended length low byte
  21135. frame += std::string(126, 'x');
  21136. strm.write(frame.data(), frame.size());
  21137. ws::Opcode opcode;
  21138. std::string payload;
  21139. bool fin;
  21140. EXPECT_EQ(
  21141. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21142. ws::impl::FrameRead::Fail);
  21143. }
  21144. // Ping with FIN=1 and payload_len=125 - should succeed
  21145. {
  21146. detail::BufferStream strm;
  21147. std::string frame;
  21148. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21149. frame += static_cast<char>(125); // payload_len=125
  21150. frame += std::string(125, 'x');
  21151. strm.write(frame.data(), frame.size());
  21152. ws::Opcode opcode;
  21153. std::string payload;
  21154. bool fin;
  21155. EXPECT_EQ(
  21156. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21157. ws::impl::FrameRead::Ok);
  21158. EXPECT_EQ(ws::Opcode::Ping, opcode);
  21159. EXPECT_EQ(125u, payload.size());
  21160. EXPECT_TRUE(fin);
  21161. }
  21162. }
  21163. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  21164. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  21165. // length MUST be 0.
  21166. // MSB set - must be rejected
  21167. {
  21168. detail::BufferStream strm;
  21169. std::string frame;
  21170. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21171. frame += static_cast<char>(127); // 64-bit extended length
  21172. frame += static_cast<char>(0x80); // MSB set (invalid)
  21173. frame += std::string(7, '\0'); // remaining 7 bytes of length
  21174. strm.write(frame.data(), frame.size());
  21175. ws::Opcode opcode;
  21176. std::string payload;
  21177. bool fin;
  21178. EXPECT_EQ(
  21179. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21180. ws::impl::FrameRead::Fail);
  21181. }
  21182. // MSB clear - should pass length parsing (will be rejected by max_len,
  21183. // but that's a different check; use a small length to verify)
  21184. {
  21185. detail::BufferStream strm;
  21186. std::string frame;
  21187. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21188. frame += static_cast<char>(127); // 64-bit extended length
  21189. frame += std::string(7, '\0'); // high bytes = 0
  21190. frame += static_cast<char>(0x03); // length = 3
  21191. frame += "abc";
  21192. strm.write(frame.data(), frame.size());
  21193. ws::Opcode opcode;
  21194. std::string payload;
  21195. bool fin;
  21196. EXPECT_EQ(
  21197. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21198. ws::impl::FrameRead::Ok);
  21199. EXPECT_EQ(ws::Opcode::Text, opcode);
  21200. EXPECT_EQ("abc", payload);
  21201. }
  21202. }
  21203. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  21204. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  21205. // Valid UTF-8
  21206. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  21207. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  21208. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  21209. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  21210. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  21211. // Invalid UTF-8
  21212. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  21213. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  21214. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  21215. EXPECT_FALSE(
  21216. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  21217. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  21218. }
  21219. TEST(WebSocketTest, ConnectAndDisconnect) {
  21220. Server svr;
  21221. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21222. std::string msg;
  21223. while (ws.read(msg)) {}
  21224. });
  21225. auto port = svr.bind_to_any_port(HOST);
  21226. std::thread t([&]() { svr.listen_after_bind(); });
  21227. svr.wait_until_ready();
  21228. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21229. auto res = client.connect();
  21230. ASSERT_TRUE(res);
  21231. EXPECT_EQ(Error::Success, res.error());
  21232. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  21233. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  21234. EXPECT_TRUE(client.is_open());
  21235. client.close();
  21236. EXPECT_FALSE(client.is_open());
  21237. svr.stop();
  21238. t.join();
  21239. }
  21240. TEST(WebSocketTest, ValidURL) {
  21241. ws::WebSocketClient ws1("ws://localhost:8080/path");
  21242. EXPECT_TRUE(ws1.is_valid());
  21243. ws::WebSocketClient ws2("ws://example.com/path");
  21244. EXPECT_TRUE(ws2.is_valid());
  21245. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  21246. EXPECT_TRUE(ws3.is_valid());
  21247. #ifdef CPPHTTPLIB_SSL_ENABLED
  21248. ws::WebSocketClient wss1("wss://example.com/path");
  21249. EXPECT_TRUE(wss1.is_valid());
  21250. ws::WebSocketClient wss2("wss://example.com:443/path");
  21251. EXPECT_TRUE(wss2.is_valid());
  21252. #endif
  21253. }
  21254. TEST(WebSocketTest, InvalidURL) {
  21255. // No scheme
  21256. ws::WebSocketClient ws1("localhost:8080/path");
  21257. EXPECT_FALSE(ws1.is_valid());
  21258. // No path
  21259. ws::WebSocketClient ws2("ws://localhost:8080");
  21260. EXPECT_FALSE(ws2.is_valid());
  21261. // Empty string
  21262. ws::WebSocketClient ws3("");
  21263. EXPECT_FALSE(ws3.is_valid());
  21264. // Missing host
  21265. ws::WebSocketClient ws4("ws://:8080/path");
  21266. EXPECT_FALSE(ws4.is_valid());
  21267. // Port number overflow — should not crash
  21268. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  21269. EXPECT_FALSE(ws5.is_valid());
  21270. // Port out of range
  21271. ws::WebSocketClient ws6("ws://localhost:99999/path");
  21272. EXPECT_FALSE(ws6.is_valid());
  21273. }
  21274. TEST(WebSocketTest, UnsupportedScheme) {
  21275. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  21276. ws::WebSocketClient ws1("http://localhost:8080/path");
  21277. EXPECT_FALSE(ws1.is_valid());
  21278. ws::WebSocketClient ws2("https://localhost:8080/path");
  21279. EXPECT_FALSE(ws2.is_valid());
  21280. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  21281. EXPECT_FALSE(ws3.is_valid());
  21282. #else
  21283. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  21284. std::invalid_argument);
  21285. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  21286. std::invalid_argument);
  21287. #endif
  21288. }
  21289. TEST(WebSocketTest, ConnectWhenInvalid) {
  21290. ws::WebSocketClient ws("not a valid url");
  21291. EXPECT_FALSE(ws.is_valid());
  21292. auto res = ws.connect();
  21293. EXPECT_FALSE(res);
  21294. EXPECT_EQ(Error::Connection, res.error());
  21295. EXPECT_EQ(-1, res.status());
  21296. }
  21297. TEST(WebSocketTest, ConnectRefusedReportsError) {
  21298. // Grab a port that is free, then close it again so nothing listens there
  21299. Server svr;
  21300. auto port = svr.bind_to_any_port(HOST);
  21301. svr.stop();
  21302. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21303. auto res = client.connect();
  21304. ASSERT_FALSE(res);
  21305. EXPECT_EQ(Error::Connection, res.error());
  21306. EXPECT_EQ(-1, res.status());
  21307. }
  21308. TEST(WebSocketTest, DefaultPort) {
  21309. ws::WebSocketClient ws1("ws://example.com/path");
  21310. EXPECT_TRUE(ws1.is_valid());
  21311. // ws:// defaults to port 80 (verified by successful parse)
  21312. #ifdef CPPHTTPLIB_SSL_ENABLED
  21313. ws::WebSocketClient ws2("wss://example.com/path");
  21314. EXPECT_TRUE(ws2.is_valid());
  21315. // wss:// defaults to port 443 (verified by successful parse)
  21316. #endif
  21317. }
  21318. TEST(WebSocketTest, IPv6LiteralAddress) {
  21319. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  21320. EXPECT_TRUE(ws1.is_valid());
  21321. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  21322. EXPECT_TRUE(ws2.is_valid());
  21323. }
  21324. TEST(WebSocketTest, ComplexPath) {
  21325. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  21326. EXPECT_TRUE(ws1.is_valid());
  21327. ws::WebSocketClient ws2("ws://localhost:8080/");
  21328. EXPECT_TRUE(ws2.is_valid());
  21329. }
  21330. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  21331. Server svr;
  21332. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21333. std::string msg;
  21334. while (ws.read(msg)) {}
  21335. });
  21336. auto port = svr.bind_to_any_port(HOST);
  21337. std::thread t([&]() { svr.listen_after_bind(); });
  21338. svr.wait_until_ready();
  21339. auto another_host = "example.com";
  21340. auto wrong_ip = "192.0.2.1";
  21341. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21342. client.set_hostname_addr_map({{another_host, wrong_ip}});
  21343. ASSERT_TRUE(client.connect());
  21344. EXPECT_TRUE(client.is_open());
  21345. client.close();
  21346. svr.stop();
  21347. t.join();
  21348. }
  21349. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  21350. Server svr;
  21351. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21352. std::string msg;
  21353. while (ws.read(msg)) {}
  21354. });
  21355. auto port = svr.bind_to_any_port(HOST);
  21356. std::thread t([&]() { svr.listen_after_bind(); });
  21357. svr.wait_until_ready();
  21358. auto wrong_ip = "192.0.2.1";
  21359. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21360. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  21361. client.set_connection_timeout(1);
  21362. client.set_read_timeout(1);
  21363. client.set_write_timeout(1);
  21364. EXPECT_FALSE(client.connect());
  21365. EXPECT_FALSE(client.is_open());
  21366. svr.stop();
  21367. t.join();
  21368. }
  21369. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  21370. // A mapped value that is not an IP literal must be resolved. HOST resolves
  21371. // from the hosts file, so this test needs no external DNS. "target.invalid"
  21372. // (RFC 6761) is only a map key and the Host header value.
  21373. auto host = "target.invalid";
  21374. Server svr;
  21375. std::string received_host;
  21376. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21377. received_host = req.get_header_value("Host");
  21378. std::string msg;
  21379. while (ws.read(msg)) {}
  21380. });
  21381. auto port = svr.bind_to_any_port(HOST);
  21382. std::thread t([&]() { svr.listen_after_bind(); });
  21383. // ASSERT_* below returns from the test body, which would leave t joinable
  21384. // and make ~thread call std::terminate.
  21385. auto se = detail::scope_exit([&] {
  21386. svr.stop();
  21387. if (t.joinable()) { t.join(); }
  21388. });
  21389. svr.wait_until_ready();
  21390. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  21391. std::to_string(port) + "/ws");
  21392. client.set_hostname_addr_map({{host, HOST}});
  21393. ASSERT_TRUE(client.connect());
  21394. EXPECT_TRUE(client.is_open());
  21395. client.close();
  21396. svr.stop();
  21397. t.join();
  21398. // The mapping only redirects the connection; the identity stays host_.
  21399. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  21400. }
  21401. class WebSocketIntegrationTest : public ::testing::Test {
  21402. protected:
  21403. void SetUp() override {
  21404. server_ = httplib::detail::make_unique<Server>();
  21405. setup_server();
  21406. start_server();
  21407. }
  21408. void TearDown() override {
  21409. server_->stop();
  21410. if (server_thread_.joinable()) { server_thread_.join(); }
  21411. }
  21412. void setup_server() {
  21413. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21414. std::string msg;
  21415. ws::ReadResult ret;
  21416. while ((ret = ws.read(msg))) {
  21417. if (ret == ws::Binary) {
  21418. ws.send(msg.data(), msg.size());
  21419. } else {
  21420. ws.send(msg);
  21421. }
  21422. }
  21423. });
  21424. server_->WebSocket("/ws-echo-string",
  21425. [](const Request &, ws::WebSocket &ws) {
  21426. std::string msg;
  21427. while (ws.read(msg)) {
  21428. ws.send("echo: " + msg);
  21429. }
  21430. });
  21431. server_->WebSocket(
  21432. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  21433. // Echo back request metadata
  21434. ws.send("path:" + req.path);
  21435. ws.send("header:" + req.get_header_value("X-Test-Header"));
  21436. std::string msg;
  21437. while (ws.read(msg)) {}
  21438. });
  21439. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  21440. std::string msg;
  21441. ws.read(msg); // wait for a message
  21442. ws.close();
  21443. });
  21444. server_->WebSocket("/ws-close-status",
  21445. [](const Request &, ws::WebSocket &ws) {
  21446. std::string msg;
  21447. ws.read(msg); // wait for a message
  21448. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  21449. });
  21450. server_->WebSocket(
  21451. "/ws-subprotocol",
  21452. [](const Request &, ws::WebSocket &ws) {
  21453. std::string msg;
  21454. while (ws.read(msg)) {
  21455. ws.send(msg);
  21456. }
  21457. },
  21458. [](const std::vector<std::string> &protocols) -> std::string {
  21459. for (const auto &p : protocols) {
  21460. if (p == "graphql-ws") { return p; }
  21461. }
  21462. return "";
  21463. });
  21464. server_->WebSocket(
  21465. "/ws-subprotocol-unoffered",
  21466. [](const Request &, ws::WebSocket &ws) {
  21467. std::string msg;
  21468. while (ws.read(msg)) {
  21469. ws.send(msg);
  21470. }
  21471. },
  21472. [](const std::vector<std::string> &) -> std::string {
  21473. return "admin";
  21474. });
  21475. }
  21476. void start_server() {
  21477. port_ = server_->bind_to_any_port(HOST);
  21478. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21479. server_->wait_until_ready();
  21480. }
  21481. std::unique_ptr<Server> server_;
  21482. std::thread server_thread_;
  21483. int port_ = 0;
  21484. };
  21485. TEST_F(WebSocketIntegrationTest, TextEcho) {
  21486. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21487. "/ws-echo");
  21488. ASSERT_TRUE(client.connect());
  21489. ASSERT_TRUE(client.is_open());
  21490. ASSERT_TRUE(client.send("Hello WebSocket"));
  21491. std::string msg;
  21492. EXPECT_EQ(ws::Text, client.read(msg));
  21493. EXPECT_EQ("Hello WebSocket", msg);
  21494. client.close();
  21495. }
  21496. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  21497. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21498. "/ws-echo");
  21499. ASSERT_TRUE(client.connect());
  21500. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  21501. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  21502. std::string msg;
  21503. EXPECT_EQ(ws::Binary, client.read(msg));
  21504. EXPECT_EQ(binary_data, msg);
  21505. client.close();
  21506. }
  21507. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  21508. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21509. "/ws-echo");
  21510. ASSERT_TRUE(client.connect());
  21511. for (int i = 0; i < 10; i++) {
  21512. auto text = "message " + std::to_string(i);
  21513. ASSERT_TRUE(client.send(text));
  21514. std::string msg;
  21515. ASSERT_TRUE(client.read(msg));
  21516. EXPECT_EQ(text, msg);
  21517. }
  21518. client.close();
  21519. }
  21520. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  21521. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21522. "/ws-close");
  21523. ASSERT_TRUE(client.connect());
  21524. // Send a message to trigger the server to close
  21525. ASSERT_TRUE(client.send("trigger close"));
  21526. // The server will close, so read should return false
  21527. std::string msg;
  21528. EXPECT_FALSE(client.read(msg));
  21529. EXPECT_FALSE(client.is_open());
  21530. }
  21531. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  21532. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21533. "/ws-echo");
  21534. ASSERT_TRUE(client.connect());
  21535. // 128KB message
  21536. std::string large_data(128 * 1024, 'X');
  21537. ASSERT_TRUE(client.send(large_data));
  21538. std::string msg;
  21539. ASSERT_TRUE(client.read(msg));
  21540. EXPECT_EQ(large_data, msg);
  21541. client.close();
  21542. }
  21543. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  21544. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21545. "/ws-echo");
  21546. ASSERT_TRUE(client.connect());
  21547. const int num_threads = 4;
  21548. std::vector<std::thread> threads;
  21549. std::atomic<int> send_count{0};
  21550. for (int t = 0; t < num_threads; t++) {
  21551. threads.emplace_back([&client, &send_count, t]() {
  21552. for (int i = 0; i < 5; i++) {
  21553. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  21554. if (client.send(text)) { send_count++; }
  21555. }
  21556. });
  21557. }
  21558. for (auto &th : threads) {
  21559. th.join();
  21560. }
  21561. int received = 0;
  21562. std::string msg;
  21563. while (received < send_count.load()) {
  21564. if (!client.read(msg)) { break; }
  21565. received++;
  21566. }
  21567. EXPECT_EQ(send_count.load(), received);
  21568. client.close();
  21569. }
  21570. TEST_F(WebSocketIntegrationTest, ReadString) {
  21571. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21572. "/ws-echo-string");
  21573. ASSERT_TRUE(client.connect());
  21574. ASSERT_TRUE(client.send("hello"));
  21575. std::string msg;
  21576. ASSERT_TRUE(client.read(msg));
  21577. EXPECT_EQ("echo: hello", msg);
  21578. ASSERT_TRUE(client.send("world"));
  21579. ASSERT_TRUE(client.read(msg));
  21580. EXPECT_EQ("echo: world", msg);
  21581. client.close();
  21582. }
  21583. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  21584. Headers headers = {{"X-Test-Header", "test-value"}};
  21585. ws::WebSocketClient client(
  21586. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  21587. ASSERT_TRUE(client.connect());
  21588. std::string msg;
  21589. ASSERT_TRUE(client.read(msg));
  21590. EXPECT_EQ("path:/ws-request-info", msg);
  21591. ASSERT_TRUE(client.read(msg));
  21592. EXPECT_EQ("header:test-value", msg);
  21593. client.close();
  21594. }
  21595. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  21596. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21597. "/ws-echo");
  21598. client.set_read_timeout(1, 0); // 1 second
  21599. ASSERT_TRUE(client.connect());
  21600. // Don't send anything — server echo handler waits for a message, so read()
  21601. // should time out. The connection survives it: nothing was consumed.
  21602. std::string msg;
  21603. EXPECT_EQ(client.read(msg), ws::Timeout);
  21604. EXPECT_TRUE(client.is_open());
  21605. // And it is still usable afterwards.
  21606. EXPECT_TRUE(client.send("after timeout"));
  21607. EXPECT_EQ(client.read(msg), ws::Text);
  21608. EXPECT_EQ(msg, "after timeout");
  21609. }
  21610. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  21611. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21612. "/ws-echo");
  21613. client.set_read_timeout(1, 0);
  21614. ASSERT_TRUE(client.connect());
  21615. ASSERT_TRUE(client.send("first"));
  21616. std::string msg;
  21617. ASSERT_EQ(client.read(msg), ws::Text);
  21618. ASSERT_EQ(msg, "first");
  21619. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  21620. // not be used with a read timeout: it would reprocess the previous message.
  21621. EXPECT_EQ(client.read(msg), ws::Timeout);
  21622. EXPECT_EQ(msg, "first");
  21623. }
  21624. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  21625. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21626. "/ws-echo");
  21627. ASSERT_TRUE(client.connect());
  21628. // Setting it once the connection is open reaches the live stream, not just
  21629. // the seed for the next connect().
  21630. client.set_read_timeout(1, 0);
  21631. std::string msg;
  21632. EXPECT_EQ(client.read(msg), ws::Timeout);
  21633. EXPECT_TRUE(client.is_open());
  21634. }
  21635. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  21636. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21637. "/ws-echo");
  21638. client.set_read_timeout(5, 0);
  21639. ASSERT_TRUE(client.connect());
  21640. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21641. // The server should reject it and close the connection.
  21642. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  21643. client.send(oversized);
  21644. // The server's read() should have failed due to payload limit,
  21645. // so our read() should return false (connection closed).
  21646. std::string msg;
  21647. EXPECT_FALSE(client.read(msg));
  21648. }
  21649. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  21650. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21651. "/ws-echo");
  21652. client.set_read_timeout(10, 0);
  21653. ASSERT_TRUE(client.connect());
  21654. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21655. // This should succeed.
  21656. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  21657. ASSERT_TRUE(client.send(at_limit));
  21658. std::string msg;
  21659. ASSERT_TRUE(client.read(msg));
  21660. EXPECT_EQ(at_limit.size(), msg.size());
  21661. client.close();
  21662. }
  21663. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  21664. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21665. "/nonexistent");
  21666. auto res = client.connect();
  21667. EXPECT_FALSE(res);
  21668. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21669. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  21670. EXPECT_FALSE(client.is_open());
  21671. }
  21672. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  21673. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21674. "/ws-echo");
  21675. ASSERT_TRUE(client.connect());
  21676. ASSERT_TRUE(client.send(""));
  21677. std::string msg;
  21678. EXPECT_EQ(ws::Text, client.read(msg));
  21679. EXPECT_EQ("", msg);
  21680. client.close();
  21681. }
  21682. TEST_F(WebSocketIntegrationTest, Reconnect) {
  21683. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21684. "/ws-echo");
  21685. // First connection
  21686. ASSERT_TRUE(client.connect());
  21687. ASSERT_TRUE(client.send("first"));
  21688. std::string msg;
  21689. ASSERT_TRUE(client.read(msg));
  21690. EXPECT_EQ("first", msg);
  21691. client.close();
  21692. EXPECT_FALSE(client.is_open());
  21693. // Reconnect using the same client object
  21694. ASSERT_TRUE(client.connect());
  21695. ASSERT_TRUE(client.is_open());
  21696. ASSERT_TRUE(client.send("second"));
  21697. ASSERT_TRUE(client.read(msg));
  21698. EXPECT_EQ("second", msg);
  21699. client.close();
  21700. }
  21701. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  21702. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21703. "/ws-close-status");
  21704. ASSERT_TRUE(client.connect());
  21705. // Trigger the server to close with GoingAway status
  21706. ASSERT_TRUE(client.send("trigger"));
  21707. // read() should return false after receiving the close frame
  21708. std::string msg;
  21709. EXPECT_FALSE(client.read(msg));
  21710. EXPECT_FALSE(client.is_open());
  21711. }
  21712. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  21713. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21714. "/ws-echo");
  21715. ASSERT_TRUE(client.connect());
  21716. client.close(ws::CloseStatus::GoingAway, "client leaving");
  21717. EXPECT_FALSE(client.is_open());
  21718. }
  21719. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  21720. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  21721. ws::WebSocketClient client(
  21722. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21723. ASSERT_TRUE(client.connect());
  21724. // Server should have selected graphql-ws
  21725. EXPECT_EQ("graphql-ws", client.subprotocol());
  21726. client.close();
  21727. }
  21728. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  21729. Headers headers;
  21730. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  21731. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  21732. ws::WebSocketClient client(
  21733. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21734. ASSERT_TRUE(client.connect());
  21735. // The offer on the second field line counts too, so graphql-ws is selected
  21736. EXPECT_EQ("graphql-ws", client.subprotocol());
  21737. client.close();
  21738. }
  21739. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  21740. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  21741. ws::WebSocketClient client(
  21742. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21743. ASSERT_TRUE(client.connect());
  21744. // Server should not have selected any subprotocol
  21745. EXPECT_TRUE(client.subprotocol().empty());
  21746. client.close();
  21747. }
  21748. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  21749. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21750. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21751. "/ws-subprotocol-unoffered",
  21752. headers);
  21753. ASSERT_TRUE(client.connect());
  21754. EXPECT_TRUE(client.subprotocol().empty());
  21755. client.close();
  21756. }
  21757. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  21758. // Connect without requesting any subprotocol
  21759. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21760. "/ws-subprotocol");
  21761. ASSERT_TRUE(client.connect());
  21762. EXPECT_TRUE(client.subprotocol().empty());
  21763. client.close();
  21764. }
  21765. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  21766. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21767. "/ws-echo");
  21768. client.set_tcp_nodelay(true);
  21769. client.set_connection_timeout(3, 0);
  21770. bool socket_options_called = false;
  21771. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  21772. ASSERT_TRUE(client.connect());
  21773. ASSERT_TRUE(client.is_open());
  21774. EXPECT_TRUE(socket_options_called);
  21775. ASSERT_TRUE(client.send("hello"));
  21776. std::string msg;
  21777. auto result = client.read(msg);
  21778. EXPECT_EQ(result, ws::ReadResult::Text);
  21779. EXPECT_EQ(msg, "hello");
  21780. client.close();
  21781. }
  21782. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  21783. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21784. "/ws-echo");
  21785. client.set_connection_timeout(std::chrono::seconds(3));
  21786. client.set_write_timeout(std::chrono::seconds(3));
  21787. // A sub-second remainder exercises the seconds/microseconds split.
  21788. client.set_read_timeout(std::chrono::milliseconds(1500));
  21789. ASSERT_TRUE(client.connect());
  21790. auto start = std::chrono::steady_clock::now();
  21791. std::string msg;
  21792. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  21793. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  21794. std::chrono::steady_clock::now() - start)
  21795. .count();
  21796. // Above 1s so that dropping the microseconds half of the split fails here.
  21797. // Ignoring the setter altogether would not reach this line at all: a client
  21798. // waits forever by default.
  21799. EXPECT_GE(elapsed, 1400);
  21800. EXPECT_LT(elapsed, 30000);
  21801. }
  21802. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  21803. Server svr;
  21804. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  21805. if (!req.has_header("Authorization")) {
  21806. res.status = StatusCode::Unauthorized_401;
  21807. res.set_content("Unauthorized", "text/plain");
  21808. return Server::HandlerResponse::Handled;
  21809. }
  21810. return Server::HandlerResponse::Unhandled;
  21811. });
  21812. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21813. std::string msg;
  21814. while (ws.read(msg)) {
  21815. ws.send(msg);
  21816. }
  21817. });
  21818. auto port = svr.bind_to_any_port("localhost");
  21819. std::thread t([&]() { svr.listen_after_bind(); });
  21820. svr.wait_until_ready();
  21821. // Without Authorization header - should be rejected before upgrade
  21822. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  21823. EXPECT_FALSE(client1.connect());
  21824. // The rejection is framed like any other HTTP response
  21825. {
  21826. Client cli("localhost", port);
  21827. Headers headers = {{"Upgrade", "websocket"},
  21828. {"Connection", "Upgrade"},
  21829. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21830. {"Sec-WebSocket-Version", "13"}};
  21831. auto res = cli.Get("/ws", headers);
  21832. ASSERT_TRUE(res);
  21833. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21834. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21835. EXPECT_EQ("Unauthorized", res->body);
  21836. }
  21837. // With Authorization header - should succeed
  21838. Headers headers = {{"Authorization", "Bearer token123"}};
  21839. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  21840. headers);
  21841. ASSERT_TRUE(client2.connect());
  21842. ASSERT_TRUE(client2.send("hello"));
  21843. std::string msg;
  21844. ASSERT_TRUE(client2.read(msg));
  21845. EXPECT_EQ("hello", msg);
  21846. client2.close();
  21847. svr.stop();
  21848. t.join();
  21849. }
  21850. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  21851. Server svr;
  21852. std::atomic<int> pre_request_calls{0};
  21853. std::atomic<bool> route_matched{false};
  21854. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  21855. pre_request_calls++;
  21856. if (req.matched_route == "/ws/:id") { route_matched = true; }
  21857. if (req.get_header_value("Authorization") != "Bearer token123") {
  21858. res.status = StatusCode::Unauthorized_401;
  21859. res.set_content("Unauthorized", "text/plain");
  21860. return Server::HandlerResponse::Handled;
  21861. }
  21862. return Server::HandlerResponse::Unhandled;
  21863. });
  21864. std::atomic<bool> handler_called{false};
  21865. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  21866. handler_called = true;
  21867. ws.send(req.matched_route + " " + req.path_params.at("id"));
  21868. });
  21869. auto port = svr.bind_to_any_port("localhost");
  21870. std::thread t([&]() { svr.listen_after_bind(); });
  21871. svr.wait_until_ready();
  21872. // Without Authorization header - should be rejected before upgrade
  21873. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  21874. "/ws/1");
  21875. EXPECT_FALSE(client1.connect());
  21876. EXPECT_FALSE(handler_called);
  21877. EXPECT_EQ(1, pre_request_calls);
  21878. EXPECT_TRUE(route_matched);
  21879. // The rejection is an ordinary HTTP response, not a protocol switch
  21880. {
  21881. Client cli("localhost", port);
  21882. Headers headers = {{"Upgrade", "websocket"},
  21883. {"Connection", "Upgrade"},
  21884. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21885. {"Sec-WebSocket-Version", "13"}};
  21886. auto res = cli.Get("/ws/1", headers);
  21887. ASSERT_TRUE(res);
  21888. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21889. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21890. EXPECT_EQ("Unauthorized", res->body);
  21891. }
  21892. EXPECT_FALSE(handler_called);
  21893. // With Authorization header - should succeed
  21894. Headers headers = {{"Authorization", "Bearer token123"}};
  21895. ws::WebSocketClient client2(
  21896. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  21897. ASSERT_TRUE(client2.connect());
  21898. std::string msg;
  21899. ASSERT_TRUE(client2.read(msg));
  21900. EXPECT_EQ("/ws/:id 2", msg);
  21901. EXPECT_TRUE(handler_called);
  21902. client2.close();
  21903. svr.stop();
  21904. t.join();
  21905. }
  21906. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  21907. Server svr;
  21908. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21909. // A read timeout is how a handler gets control back. Without it, a handler
  21910. // parked in read() can never write on the connection it is reading.
  21911. ws.set_read_timeout(std::chrono::milliseconds(100));
  21912. std::string msg;
  21913. while (ws.is_open()) {
  21914. auto r = ws.read(msg);
  21915. if (r == httplib::ws::Timeout) {
  21916. ws.send("tick");
  21917. continue;
  21918. }
  21919. if (r == httplib::ws::Fail) { break; }
  21920. ws.send(msg);
  21921. }
  21922. });
  21923. auto port = svr.bind_to_any_port("localhost");
  21924. std::thread t([&]() { svr.listen_after_bind(); });
  21925. svr.wait_until_ready();
  21926. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21927. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  21928. ASSERT_TRUE(client.connect());
  21929. // The client sends nothing, so anything it receives came out of the
  21930. // handler's timeout path.
  21931. std::string msg;
  21932. ASSERT_EQ(client.read(msg), ws::Text);
  21933. EXPECT_EQ("tick", msg);
  21934. client.close();
  21935. svr.stop();
  21936. t.join();
  21937. }
  21938. // Stream::read may return fewer bytes than asked for. This is that contract at
  21939. // its worst -- one byte per call -- which is what a frame header straddling a
  21940. // read buffer's boundary looks like to the frame parser.
  21941. class WsByteAtATimeStream : public Stream {
  21942. public:
  21943. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  21944. bool is_readable() const override { return true; }
  21945. bool wait_readable() const override { return true; }
  21946. bool wait_writable() const override { return true; }
  21947. ssize_t read(char *ptr, size_t size) override {
  21948. if (size == 0 || pos_ >= data_.size()) { return 0; }
  21949. *ptr = data_[pos_++];
  21950. return 1;
  21951. }
  21952. ssize_t write(const char *, size_t size) override {
  21953. return static_cast<ssize_t>(size);
  21954. }
  21955. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  21956. ip = "127.0.0.1";
  21957. port = 0;
  21958. }
  21959. void get_local_ip_and_port(std::string &ip, int &port) const override {
  21960. ip = "127.0.0.1";
  21961. port = 0;
  21962. }
  21963. socket_t socket() const override { return INVALID_SOCKET; }
  21964. time_t duration() const override { return 0; }
  21965. private:
  21966. std::string data_;
  21967. size_t pos_ = 0;
  21968. };
  21969. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  21970. // The payload uses the 16-bit extended length, so the header, the length
  21971. // and the mask key are all multi-byte fields here. Each used to be read
  21972. // with a single read() call, which fails as soon as one is split. The
  21973. // payload is also a little over one read chunk, so it is read in two.
  21974. std::string body;
  21975. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  21976. body += static_cast<char>(i % 251);
  21977. }
  21978. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  21979. std::string frame;
  21980. frame += static_cast<char>(0x81); // FIN + Text
  21981. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  21982. frame += static_cast<char>(body.size() >> 8);
  21983. frame += static_cast<char>(body.size() & 0xff);
  21984. for (size_t i = 0; i < 4; i++) {
  21985. frame += static_cast<char>(mask[i]);
  21986. }
  21987. for (size_t i = 0; i < body.size(); i++) {
  21988. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  21989. }
  21990. WsByteAtATimeStream strm(frame);
  21991. ws::Opcode opcode;
  21992. std::string payload;
  21993. bool fin = false;
  21994. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  21995. /*expect_masked=*/true, body.size()),
  21996. ws::impl::FrameRead::Ok);
  21997. EXPECT_TRUE(fin);
  21998. EXPECT_EQ(opcode, ws::Opcode::Text);
  21999. EXPECT_EQ(payload, body);
  22000. }
  22001. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  22002. std::string body(2000, 'x');
  22003. std::string frame;
  22004. frame += static_cast<char>(0x82); // FIN + Binary
  22005. frame += static_cast<char>(126); // 16-bit length follows
  22006. frame += static_cast<char>(body.size() >> 8);
  22007. frame += static_cast<char>(body.size() & 0xff);
  22008. frame += body;
  22009. detail::BufferStream strm;
  22010. strm.write(frame.data(), frame.size());
  22011. ws::Opcode opcode;
  22012. std::string payload;
  22013. bool fin;
  22014. EXPECT_EQ(
  22015. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  22016. ws::impl::FrameRead::Ok);
  22017. EXPECT_EQ(body, payload);
  22018. }
  22019. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  22020. // The header announces the largest payload allowed, and only 3 bytes of it
  22021. // ever arrive.
  22022. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  22023. std::string frame;
  22024. frame += static_cast<char>(0x82); // FIN + Binary
  22025. frame += static_cast<char>(127); // 64-bit length follows
  22026. for (int shift = 56; shift >= 0; shift -= 8) {
  22027. frame += static_cast<char>((len >> shift) & 0xff);
  22028. }
  22029. frame += "abc";
  22030. detail::BufferStream strm;
  22031. strm.write(frame.data(), frame.size());
  22032. ws::Opcode opcode;
  22033. std::string payload;
  22034. bool fin;
  22035. EXPECT_EQ(
  22036. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  22037. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  22038. ws::impl::FrameRead::Fail);
  22039. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  22040. }
  22041. TEST(WebSocketTest, QueryStringInHandshake) {
  22042. Server svr;
  22043. std::mutex mtx;
  22044. std::string received_target;
  22045. std::string received_token;
  22046. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22047. {
  22048. std::lock_guard<std::mutex> lock(mtx);
  22049. received_target = req.target;
  22050. if (req.has_param("token")) {
  22051. received_token = req.get_param_value("token");
  22052. }
  22053. }
  22054. std::string msg;
  22055. while (ws.read(msg)) {
  22056. ws.send(msg);
  22057. }
  22058. });
  22059. auto port = svr.bind_to_any_port("localhost");
  22060. std::thread t([&]() { svr.listen_after_bind(); });
  22061. svr.wait_until_ready();
  22062. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  22063. "/ws?token=ABC&session=123");
  22064. ASSERT_TRUE(client.connect());
  22065. // Round-trip ensures the handler has run and captured the request.
  22066. ASSERT_TRUE(client.send("hello"));
  22067. std::string msg;
  22068. ASSERT_TRUE(client.read(msg));
  22069. EXPECT_EQ("hello", msg);
  22070. client.close();
  22071. {
  22072. std::lock_guard<std::mutex> lock(mtx);
  22073. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  22074. EXPECT_EQ("ABC", received_token);
  22075. }
  22076. svr.stop();
  22077. t.join();
  22078. }
  22079. // Run a handshake against a throwaway server and hand the request the server
  22080. // received back to the caller, so tests can assert on the headers the client
  22081. // actually put on the wire.
  22082. static void capture_websocket_handshake_request(
  22083. const Headers &client_headers,
  22084. std::function<void(const Request &, int port)> verify) {
  22085. Server svr;
  22086. std::mutex mtx;
  22087. Request received;
  22088. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22089. {
  22090. std::lock_guard<std::mutex> lock(mtx);
  22091. received = req;
  22092. }
  22093. std::string msg;
  22094. while (ws.read(msg)) {
  22095. ws.send(msg);
  22096. }
  22097. });
  22098. auto port = svr.bind_to_any_port("localhost");
  22099. std::thread t([&]() { svr.listen_after_bind(); });
  22100. auto se = detail::scope_exit([&] {
  22101. svr.stop();
  22102. t.join();
  22103. });
  22104. svr.wait_until_ready();
  22105. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  22106. client_headers);
  22107. ASSERT_TRUE(client.connect());
  22108. ASSERT_TRUE(client.send("hello"));
  22109. std::string msg;
  22110. ASSERT_TRUE(client.read(msg));
  22111. client.close();
  22112. {
  22113. std::lock_guard<std::mutex> lock(mtx);
  22114. verify(received, port);
  22115. }
  22116. }
  22117. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  22118. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  22119. // Non-default port must be present in the Host header. Default ports
  22120. // (80/443) are omitted; that logic is covered by
  22121. // MakeHostAndPortStringTest.
  22122. EXPECT_EQ("localhost:" + std::to_string(port),
  22123. req.get_header_value("Host"));
  22124. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  22125. req.get_header_value("User-Agent"));
  22126. EXPECT_FALSE(req.has_header("Accept"));
  22127. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  22128. EXPECT_FALSE(req.has_header("Content-Length"));
  22129. });
  22130. }
  22131. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  22132. capture_websocket_handshake_request(
  22133. {{"Host", "example.com"},
  22134. {"User-Agent", "custom-agent"},
  22135. {"X-Custom", "value"}},
  22136. [](const Request &req, int) {
  22137. EXPECT_EQ("example.com", req.get_header_value("Host"));
  22138. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  22139. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  22140. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  22141. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  22142. });
  22143. }
  22144. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  22145. capture_websocket_handshake_request(
  22146. {{"Upgrade", "bogus"},
  22147. {"Connection", "close"},
  22148. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  22149. {"Sec-WebSocket-Version", "8"}},
  22150. [](const Request &req, int) {
  22151. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  22152. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  22153. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  22154. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  22155. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  22156. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  22157. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  22158. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  22159. req.get_header_value("Sec-WebSocket-Key"));
  22160. });
  22161. }
  22162. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  22163. // A header the client refuses to send must abort the handshake before any
  22164. // part of it reaches the wire; a lone request line would otherwise sit in
  22165. // the peer's buffer as a truncated request.
  22166. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  22167. ASSERT_NE(INVALID_SOCKET, srv);
  22168. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  22169. sockaddr_in addr{};
  22170. addr.sin_family = AF_INET;
  22171. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  22172. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22173. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  22174. ASSERT_EQ(0, ::listen(srv, 1));
  22175. sockaddr_in bound{};
  22176. socklen_t bound_len = sizeof(bound);
  22177. ASSERT_EQ(
  22178. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  22179. auto port = ntohs(bound.sin_port);
  22180. ssize_t received = -1;
  22181. std::thread t([&] {
  22182. // Bound every blocking call so a regression fails the test with a bad
  22183. // value instead of hanging the suite.
  22184. fd_set rfds;
  22185. FD_ZERO(&rfds);
  22186. FD_SET(srv, &rfds);
  22187. timeval tv{5, 0};
  22188. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  22189. 0) {
  22190. return;
  22191. }
  22192. sockaddr_in cli_addr{};
  22193. socklen_t cli_len = sizeof(cli_addr);
  22194. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  22195. if (cli == INVALID_SOCKET) { return; }
  22196. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  22197. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22198. char buf[4096];
  22199. received = ::recv(cli, buf, sizeof(buf), 0);
  22200. });
  22201. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  22202. // connect() has already shut the socket down by the time it returns false,
  22203. // so the peer sees EOF without waiting for the client to be destroyed.
  22204. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  22205. {{"X-Bad", "a\r\nInjected: 1"}});
  22206. EXPECT_FALSE(client.connect());
  22207. t.join();
  22208. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  22209. EXPECT_EQ(0, received);
  22210. }
  22211. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  22212. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  22213. // contains "upgrade" as a substring is a different token and must not
  22214. // start a WebSocket handshake.
  22215. auto make_request = [](const std::vector<std::string> &connection_values) {
  22216. Request req;
  22217. req.method = "GET";
  22218. req.headers.emplace("Upgrade", "websocket");
  22219. for (const auto &value : connection_values) {
  22220. req.headers.emplace("Connection", value);
  22221. }
  22222. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22223. req.headers.emplace("Sec-WebSocket-Version", "13");
  22224. return req;
  22225. };
  22226. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  22227. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  22228. EXPECT_TRUE(
  22229. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  22230. EXPECT_TRUE(
  22231. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  22232. EXPECT_TRUE(
  22233. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  22234. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  22235. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  22236. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  22237. EXPECT_FALSE(
  22238. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  22239. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  22240. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22241. }
  22242. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  22243. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  22244. // asks recipients to match each protocol-name case-insensitively, and RFC
  22245. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  22246. // client naming websocket alongside another protocol, or on a second field
  22247. // line, is offering websocket; a value that merely contains "websocket" as a
  22248. // substring is a different protocol name and is not.
  22249. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  22250. Request req;
  22251. req.method = "GET";
  22252. for (const auto &value : upgrade_values) {
  22253. req.headers.emplace("Upgrade", value);
  22254. }
  22255. req.headers.emplace("Connection", "Upgrade");
  22256. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22257. req.headers.emplace("Sec-WebSocket-Version", "13");
  22258. return req;
  22259. };
  22260. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  22261. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  22262. EXPECT_TRUE(
  22263. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  22264. EXPECT_TRUE(
  22265. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  22266. EXPECT_TRUE(
  22267. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  22268. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  22269. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  22270. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  22271. EXPECT_FALSE(
  22272. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  22273. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  22274. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22275. }
  22276. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  22277. Server svr;
  22278. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  22279. auto port = svr.bind_to_any_port("localhost");
  22280. std::thread t([&]() { svr.listen_after_bind(); });
  22281. auto se = detail::scope_exit([&] {
  22282. svr.stop();
  22283. t.join();
  22284. });
  22285. svr.wait_until_ready();
  22286. Headers headers = {{"Upgrade", "websocket"},
  22287. {"Connection", "notupgrade"},
  22288. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22289. {"Sec-WebSocket-Version", "13"}};
  22290. Client cli("localhost", port);
  22291. auto res = cli.Get("/ws", headers);
  22292. // The route exists only as a WebSocket route, so a request that fails the
  22293. // handshake check falls through to ordinary routing.
  22294. ASSERT_TRUE(res);
  22295. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  22296. }
  22297. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  22298. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  22299. // Connection value is the only thing left for the client to reject.
  22300. Server svr;
  22301. svr.Get("/ws", [](const Request &req, Response &res) {
  22302. res.status = StatusCode::SwitchingProtocol_101;
  22303. res.set_header("Upgrade", "websocket");
  22304. res.set_header("Connection", "notupgrade");
  22305. res.set_header("Sec-WebSocket-Accept",
  22306. detail::websocket_accept_key(
  22307. req.get_header_value("Sec-WebSocket-Key")));
  22308. });
  22309. auto port = svr.bind_to_any_port("localhost");
  22310. std::thread t([&]() { svr.listen_after_bind(); });
  22311. auto se = detail::scope_exit([&] {
  22312. svr.stop();
  22313. t.join();
  22314. });
  22315. svr.wait_until_ready();
  22316. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22317. auto res = client.connect();
  22318. EXPECT_FALSE(res);
  22319. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22320. EXPECT_FALSE(client.is_open());
  22321. }
  22322. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  22323. Server svr;
  22324. svr.Get("/ws", [](const Request &req, Response &res) {
  22325. res.status = StatusCode::SwitchingProtocol_101;
  22326. res.set_header("Upgrade", "websocket");
  22327. res.set_header("Connection", "Upgrade");
  22328. res.set_header("Sec-WebSocket-Accept",
  22329. detail::websocket_accept_key(
  22330. req.get_header_value("Sec-WebSocket-Key")));
  22331. res.set_header("Sec-WebSocket-Protocol", "admin");
  22332. });
  22333. auto port = svr.bind_to_any_port("localhost");
  22334. std::thread t([&]() { svr.listen_after_bind(); });
  22335. auto se = detail::scope_exit([&] {
  22336. svr.stop();
  22337. t.join();
  22338. });
  22339. svr.wait_until_ready();
  22340. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  22341. // Server selects a subprotocol the client never offered
  22342. {
  22343. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22344. ws::WebSocketClient client(url, headers);
  22345. auto res = client.connect();
  22346. EXPECT_FALSE(res);
  22347. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22348. EXPECT_FALSE(client.is_open());
  22349. EXPECT_TRUE(client.subprotocol().empty());
  22350. }
  22351. // Client offered none but the server named one anyway
  22352. {
  22353. ws::WebSocketClient client(url);
  22354. auto res = client.connect();
  22355. EXPECT_FALSE(res);
  22356. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22357. EXPECT_FALSE(client.is_open());
  22358. EXPECT_TRUE(client.subprotocol().empty());
  22359. }
  22360. }
  22361. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  22362. // The socket path doubles as the URL host, so it must not contain '/'.
  22363. const char *shard = getenv("GTEST_SHARD_INDEX");
  22364. const std::string sock_path =
  22365. shard ? std::string("httplib-ws-") + shard + ".sock"
  22366. : std::string("httplib-ws.sock");
  22367. std::remove(sock_path.c_str());
  22368. Server svr;
  22369. std::mutex mtx;
  22370. std::string received_host;
  22371. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22372. {
  22373. std::lock_guard<std::mutex> lock(mtx);
  22374. received_host = req.get_header_value("Host");
  22375. }
  22376. std::string msg;
  22377. while (ws.read(msg)) {
  22378. ws.send(msg);
  22379. }
  22380. });
  22381. svr.set_address_family(AF_UNIX);
  22382. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  22383. auto se = detail::scope_exit([&] {
  22384. svr.stop();
  22385. t.join();
  22386. std::remove(sock_path.c_str());
  22387. });
  22388. svr.wait_until_ready();
  22389. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  22390. client.set_address_family(AF_UNIX);
  22391. ASSERT_TRUE(client.connect());
  22392. ASSERT_TRUE(client.send("hello"));
  22393. std::string msg;
  22394. ASSERT_TRUE(client.read(msg));
  22395. client.close();
  22396. {
  22397. std::lock_guard<std::mutex> lock(mtx);
  22398. // There is no host:port for a Unix socket, so the same "localhost"
  22399. // placeholder the HTTP client uses is expected.
  22400. EXPECT_EQ("localhost", received_host);
  22401. }
  22402. }
  22403. // Two threads must never parse WebSocket frames from the same stream.
  22404. // close() used to read the peer's Close reply with its own frame read, so it
  22405. // raced a reader thread that was in the middle of a payload: the payload loop
  22406. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  22407. // so bytes taken by close() were replaced with bytes from further along the
  22408. // stream. The message kept its length and silently changed content.
  22409. //
  22410. // The raw peer below sends a frame header plus part of the payload, waits for
  22411. // the handler to call close(), and only then sends the rest. Whichever thread
  22412. // would win the race for those bytes, the message must arrive intact, because
  22413. // close() must not touch the stream while read() owns it.
  22414. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  22415. #ifndef _WIN32
  22416. signal(SIGPIPE, SIG_IGN);
  22417. #endif
  22418. const size_t payload_len = 120; // fits the 7-bit length field
  22419. const size_t prefix_len = 8;
  22420. const int attempts = 8;
  22421. std::string expected(payload_len, '\0');
  22422. for (size_t i = 0; i < payload_len; i++) {
  22423. expected[i] = static_cast<char>('a' + i % 26);
  22424. }
  22425. std::atomic<bool> peer_stalled{false};
  22426. std::atomic<bool> handler_done{false};
  22427. std::mutex received_mutex;
  22428. std::vector<std::string> received;
  22429. // Bound every wait, so a regression fails the test instead of hanging the
  22430. // suite.
  22431. auto wait_for = [](const std::atomic<bool> &flag) {
  22432. for (int i = 0; i < 500 && !flag; i++) {
  22433. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22434. }
  22435. };
  22436. Server svr;
  22437. svr.set_websocket_ping_interval(0);
  22438. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22439. std::thread reader([&]() {
  22440. std::string msg;
  22441. while (ws.read(msg)) {
  22442. std::lock_guard<std::mutex> guard(received_mutex);
  22443. received.push_back(msg);
  22444. }
  22445. });
  22446. // Wait until the peer stalls mid-payload, so the reader thread is parked
  22447. // inside read_websocket_frame() when close() runs.
  22448. wait_for(peer_stalled);
  22449. ws.close();
  22450. reader.join();
  22451. handler_done = true;
  22452. });
  22453. auto port = svr.bind_to_any_port("127.0.0.1");
  22454. std::thread t([&]() { svr.listen_after_bind(); });
  22455. auto se = detail::scope_exit([&] {
  22456. svr.stop();
  22457. t.join();
  22458. });
  22459. svr.wait_until_ready();
  22460. auto send_bytes = [](socket_t s, const std::string &data) {
  22461. #ifdef _WIN32
  22462. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  22463. #else
  22464. auto n = ::send(s, data.data(), data.size(), 0);
  22465. #endif
  22466. return n == static_cast<decltype(n)>(data.size());
  22467. };
  22468. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  22469. // Every length used here fits the 7-bit length field.
  22470. auto masked_header = [](uint8_t first_byte, size_t len) {
  22471. std::string h;
  22472. h += static_cast<char>(first_byte);
  22473. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  22474. h.append(4, '\0'); // mask key
  22475. return h;
  22476. };
  22477. for (int attempt = 0; attempt < attempts; attempt++) {
  22478. peer_stalled = false;
  22479. handler_done = false;
  22480. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22481. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  22482. auto se_sock = detail::scope_exit([&] {
  22483. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  22484. });
  22485. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22486. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  22487. sockaddr_in addr{};
  22488. addr.sin_family = AF_INET;
  22489. addr.sin_port = htons(static_cast<uint16_t>(port));
  22490. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22491. ASSERT_EQ(
  22492. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  22493. << "attempt " << attempt;
  22494. ASSERT_TRUE(send_bytes(sock,
  22495. "GET /ws HTTP/1.1\r\n"
  22496. "Host: 127.0.0.1\r\n"
  22497. "Upgrade: websocket\r\n"
  22498. "Connection: Upgrade\r\n"
  22499. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22500. "Sec-WebSocket-Version: 13\r\n"
  22501. "\r\n"))
  22502. << "attempt " << attempt;
  22503. std::string response;
  22504. while (response.find("\r\n\r\n") == std::string::npos) {
  22505. char buf[512];
  22506. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  22507. if (n <= 0) { break; }
  22508. response.append(buf, static_cast<size_t>(n));
  22509. }
  22510. ASSERT_NE(std::string::npos, response.find(" 101 "))
  22511. << "attempt " << attempt;
  22512. // Send the header of a Binary message but only the first prefix_len bytes
  22513. // of its payload, leaving the reader thread stalled inside the payload.
  22514. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  22515. expected.substr(0, prefix_len)))
  22516. << "attempt " << attempt;
  22517. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22518. peer_stalled = true;
  22519. // Let close() send its Close frame and park in its own read before the
  22520. // rest of the payload arrives, so both threads are waiting for it.
  22521. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22522. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  22523. close_frame += static_cast<char>(0x03); // status 1000
  22524. close_frame += static_cast<char>(0xE8);
  22525. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  22526. << "attempt " << attempt;
  22527. // Closing the peer releases the reader thread even on the buggy path,
  22528. // where it waits for bytes another thread already consumed.
  22529. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22530. detail::close_socket(sock);
  22531. sock = INVALID_SOCKET;
  22532. wait_for(handler_done);
  22533. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  22534. }
  22535. std::lock_guard<std::mutex> guard(received_mutex);
  22536. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  22537. << "a message in flight when close() ran was dropped";
  22538. for (size_t i = 0; i < received.size(); i++) {
  22539. EXPECT_EQ(expected, received[i]) << "message " << i;
  22540. }
  22541. }
  22542. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  22543. // returning the socket, or INVALID_SOCKET.
  22544. static socket_t connect_raw_websocket(int port, const std::string &path) {
  22545. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22546. if (sock == INVALID_SOCKET) { return sock; }
  22547. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22548. sockaddr_in addr{};
  22549. addr.sin_family = AF_INET;
  22550. addr.sin_port = htons(static_cast<uint16_t>(port));
  22551. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22552. std::string req = "GET " + path +
  22553. " HTTP/1.1\r\n"
  22554. "Host: 127.0.0.1\r\n"
  22555. "Upgrade: websocket\r\n"
  22556. "Connection: Upgrade\r\n"
  22557. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22558. "Sec-WebSocket-Version: 13\r\n"
  22559. "\r\n";
  22560. std::string res;
  22561. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  22562. ::send(sock, req.data(), static_cast<int>(req.size()), 0) ==
  22563. static_cast<int>(req.size())) {
  22564. char c;
  22565. while (res.find("\r\n\r\n") == std::string::npos &&
  22566. ::recv(sock, &c, 1, 0) == 1) {
  22567. res += c;
  22568. }
  22569. }
  22570. if (res.find(" 101 ") == std::string::npos) {
  22571. detail::close_socket(sock);
  22572. return INVALID_SOCKET;
  22573. }
  22574. return sock;
  22575. }
  22576. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  22577. // The payload must fit the 7-bit length field.
  22578. static std::string masked_frame(uint8_t first_byte,
  22579. const std::string &payload) {
  22580. std::string f;
  22581. f += static_cast<char>(first_byte);
  22582. f += static_cast<char>(0x80 | payload.size());
  22583. f.append(4, '\0');
  22584. return f + payload;
  22585. }
  22586. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  22587. std::atomic<bool> done{false};
  22588. std::string received;
  22589. Server svr;
  22590. svr.set_websocket_ping_interval(0);
  22591. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22592. std::string msg;
  22593. if (ws.read(msg) == ws::Binary) { received = msg; }
  22594. done = true;
  22595. });
  22596. auto port = svr.bind_to_any_port("127.0.0.1");
  22597. std::thread t([&]() { svr.listen_after_bind(); });
  22598. auto se = detail::scope_exit([&] {
  22599. svr.stop();
  22600. t.join();
  22601. });
  22602. svr.wait_until_ready();
  22603. auto sock = connect_raw_websocket(port, "/ws");
  22604. ASSERT_NE(INVALID_SOCKET, sock);
  22605. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  22606. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  22607. masked_frame(0x89, "p") + // FIN + Ping
  22608. masked_frame(0x80, "lo"); // FIN + Continuation
  22609. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  22610. for (int i = 0; i < 500 && !done; i++) {
  22611. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22612. }
  22613. ASSERT_TRUE(done);
  22614. EXPECT_EQ("Hello", received);
  22615. }
  22616. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  22617. Server svr;
  22618. svr.set_websocket_ping_interval(0);
  22619. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22620. std::string msg;
  22621. while (ws.read(msg)) {}
  22622. });
  22623. auto port = svr.bind_to_any_port("127.0.0.1");
  22624. std::thread t([&]() { svr.listen_after_bind(); });
  22625. auto se = detail::scope_exit([&] {
  22626. svr.stop();
  22627. t.join();
  22628. });
  22629. svr.wait_until_ready();
  22630. // The Close each payload is answered with: an echo when it is valid, and
  22631. // 1002 otherwise.
  22632. std::vector<std::pair<std::string, std::string>> cases = {
  22633. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  22634. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  22635. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  22636. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  22637. };
  22638. for (const auto &c : cases) {
  22639. auto sock = connect_raw_websocket(port, "/ws");
  22640. ASSERT_NE(INVALID_SOCKET, sock);
  22641. auto close_frame = masked_frame(0x88, c.first);
  22642. ::send(sock, close_frame.data(), static_cast<int>(close_frame.size()), 0);
  22643. std::string reply;
  22644. char buf[256];
  22645. while (reply.size() < 2 + c.second.size()) {
  22646. auto n = ::recv(sock, buf, sizeof(buf), 0);
  22647. if (n <= 0) { break; }
  22648. reply.append(buf, static_cast<size_t>(n));
  22649. }
  22650. detail::close_socket(sock);
  22651. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  22652. c.second,
  22653. reply);
  22654. }
  22655. }
  22656. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22657. class WebSocketSSLIntegrationTest : public ::testing::Test {
  22658. protected:
  22659. void SetUp() override {
  22660. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  22661. SERVER_PRIVATE_KEY_FILE);
  22662. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22663. std::string msg;
  22664. ws::ReadResult ret;
  22665. while ((ret = ws.read(msg))) {
  22666. if (ret == ws::Binary) {
  22667. ws.send(msg.data(), msg.size());
  22668. } else {
  22669. ws.send(msg);
  22670. }
  22671. }
  22672. });
  22673. port_ = server_->bind_to_any_port(HOST);
  22674. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22675. server_->wait_until_ready();
  22676. }
  22677. void TearDown() override {
  22678. server_->stop();
  22679. if (server_thread_.joinable()) { server_thread_.join(); }
  22680. }
  22681. std::unique_ptr<SSLServer> server_;
  22682. std::thread server_thread_;
  22683. int port_ = 0;
  22684. };
  22685. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  22686. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22687. "/ws-echo");
  22688. client.enable_server_certificate_verification(false);
  22689. ASSERT_TRUE(client.connect());
  22690. ASSERT_TRUE(client.is_open());
  22691. ASSERT_TRUE(client.send("Hello WSS"));
  22692. std::string msg;
  22693. EXPECT_EQ(ws::Text, client.read(msg));
  22694. EXPECT_EQ("Hello WSS", msg);
  22695. client.close();
  22696. }
  22697. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  22698. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  22699. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  22700. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  22701. // client (without calling close() first) is the only path that runs
  22702. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  22703. // bug exactly.
  22704. //
  22705. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  22706. // when linked against an instrumented libssl; run under Valgrind to catch it
  22707. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  22708. // suite (the freed session otherwise stalls on the close handshake) — this test
  22709. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  22710. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  22711. {
  22712. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22713. "/ws-echo");
  22714. client.enable_server_certificate_verification(false);
  22715. client.set_read_timeout(2, 0);
  22716. client.set_write_timeout(2, 0);
  22717. ASSERT_TRUE(client.connect());
  22718. ASSERT_TRUE(client.is_open());
  22719. ASSERT_TRUE(client.send("still open"));
  22720. // Intentionally do NOT call client.close(): leaving scope runs
  22721. // shutdown_and_close() with the WebSocket still open, which must send the
  22722. // close frame while the TLS session is still alive.
  22723. }
  22724. }
  22725. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  22726. // shutdown_and_close() at the start of connect(), reproducing the same
  22727. // use-after-free within the test body rather than at scope exit. The second
  22728. // connect must succeed and echo, proving the close handshake ran over a live
  22729. // session. See the note above about memory-tool requirements.
  22730. TEST_F(WebSocketSSLIntegrationTest,
  22731. ReconnectWhileOpenSendsCloseOverLiveSession) {
  22732. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22733. "/ws-echo");
  22734. client.enable_server_certificate_verification(false);
  22735. client.set_read_timeout(2, 0);
  22736. client.set_write_timeout(2, 0);
  22737. ASSERT_TRUE(client.connect());
  22738. ASSERT_TRUE(client.is_open());
  22739. ASSERT_TRUE(client.send("still open"));
  22740. // Reconnect without closing first: connect() calls shutdown_and_close() on
  22741. // the still-open connection, which must not touch a freed TLS session.
  22742. ASSERT_TRUE(client.connect());
  22743. ASSERT_TRUE(client.is_open());
  22744. ASSERT_TRUE(client.send("after reconnect"));
  22745. std::string msg;
  22746. EXPECT_EQ(ws::Text, client.read(msg));
  22747. EXPECT_EQ("after reconnect", msg);
  22748. client.close();
  22749. }
  22750. #endif
  22751. #ifdef CPPHTTPLIB_SSL_ENABLED
  22752. class WebSocketSSLCATest : public ::testing::Test {
  22753. protected:
  22754. void SetUp() override {
  22755. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  22756. SERVER_PRIVATE_KEY_FILE);
  22757. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22758. std::string msg;
  22759. while (ws.read(msg)) {
  22760. ws.send(msg);
  22761. }
  22762. });
  22763. port_ = server_->bind_to_any_port("127.0.0.1");
  22764. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22765. server_->wait_until_ready();
  22766. }
  22767. void TearDown() override {
  22768. server_->stop();
  22769. if (server_thread_.joinable()) { server_thread_.join(); }
  22770. }
  22771. std::string url() const {
  22772. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  22773. }
  22774. std::unique_ptr<SSLServer> server_;
  22775. std::thread server_thread_;
  22776. int port_ = 0;
  22777. };
  22778. // A custom CA loaded as PEM verifies the server with full certificate
  22779. // verification enabled
  22780. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  22781. ws::WebSocketClient client(url());
  22782. std::string cert;
  22783. read_file(SERVER_CERT2_FILE, cert);
  22784. client.load_ca_cert_store(cert.c_str(), cert.size());
  22785. ASSERT_TRUE(client.connect());
  22786. ASSERT_TRUE(client.send("hello"));
  22787. std::string msg;
  22788. EXPECT_EQ(ws::Text, client.read(msg));
  22789. EXPECT_EQ("hello", msg);
  22790. client.close();
  22791. }
  22792. // A custom CA that does not cover the server must fail verification (the
  22793. // custom CA is exclusive; system certs are not loaded alongside it)
  22794. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  22795. ws::WebSocketClient client(url());
  22796. std::string cert;
  22797. read_file(CLIENT_CA_CERT_FILE, cert);
  22798. client.load_ca_cert_store(cert.c_str(), cert.size());
  22799. auto res = client.connect();
  22800. ASSERT_FALSE(res);
  22801. EXPECT_EQ(Error::SSLServerVerification, res.error());
  22802. EXPECT_EQ(-1, res.status());
  22803. EXPECT_NE(0u, res.ssl_backend_error());
  22804. }
  22805. // The same CA as a file path rather than PEM in memory
  22806. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  22807. ws::WebSocketClient client(url());
  22808. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22809. ASSERT_TRUE(client.connect());
  22810. ASSERT_TRUE(client.send("hello"));
  22811. std::string msg;
  22812. EXPECT_EQ(ws::Text, client.read(msg));
  22813. EXPECT_EQ("hello", msg);
  22814. client.close();
  22815. }
  22816. // ...and a CA file that does not cover the server still fails, so it is the
  22817. // path above that decides the outcome
  22818. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  22819. ws::WebSocketClient client(url());
  22820. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22821. ASSERT_FALSE(client.connect());
  22822. }
  22823. // Regression test: reconnecting with a native custom CA store used to reuse
  22824. // a store handle the previous TLS context had already freed (use-after-free
  22825. // under the OpenSSL backend). The context now lives as long as the client.
  22826. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  22827. ws::WebSocketClient client(url());
  22828. std::string cert;
  22829. read_file(SERVER_CERT2_FILE, cert);
  22830. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  22831. ASSERT_TRUE(client.connect());
  22832. client.close();
  22833. ASSERT_TRUE(client.connect());
  22834. ASSERT_TRUE(client.send("again"));
  22835. std::string msg;
  22836. EXPECT_EQ(ws::Text, client.read(msg));
  22837. EXPECT_EQ("again", msg);
  22838. client.close();
  22839. }
  22840. // Regression test: a certificate with a trusted chain but no identity match
  22841. // for the server IP must be rejected. The Mbed TLS backend used to skip
  22842. // verification entirely for IP hosts, so this connection succeeded there.
  22843. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  22844. // chain verification while the identity check must still fail.
  22845. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  22846. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22847. ASSERT_TRUE(svr.is_valid());
  22848. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22849. std::string msg;
  22850. while (ws.read(msg)) {
  22851. ws.send(msg);
  22852. }
  22853. });
  22854. auto port = svr.bind_to_any_port("127.0.0.1");
  22855. auto t = std::thread([&]() { svr.listen_after_bind(); });
  22856. auto se = detail::scope_exit([&] {
  22857. svr.stop();
  22858. t.join();
  22859. });
  22860. svr.wait_until_ready();
  22861. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  22862. "/echo");
  22863. std::string cert;
  22864. read_file(SERVER_CERT_FILE, cert);
  22865. client.load_ca_cert_store(cert.c_str(), cert.size());
  22866. ASSERT_FALSE(client.connect());
  22867. }
  22868. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  22869. // SNI, so nothing binds the host name to the TLS session. These bind the
  22870. // server to "localhost" instead, the only shape that exercises the SNI and
  22871. // hostname-verification path with certificate verification left enabled.
  22872. class WebSocketSSLDnsHostTest : public ::testing::Test {
  22873. protected:
  22874. void Start(const char *cert_file) {
  22875. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  22876. SERVER_PRIVATE_KEY_FILE);
  22877. ASSERT_TRUE(server_->is_valid());
  22878. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22879. std::string msg;
  22880. while (ws.read(msg)) {
  22881. ws.send(msg);
  22882. }
  22883. });
  22884. port_ = server_->bind_to_any_port("localhost");
  22885. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22886. server_->wait_until_ready();
  22887. }
  22888. void TearDown() override {
  22889. if (server_) { server_->stop(); }
  22890. if (server_thread_.joinable()) { server_thread_.join(); }
  22891. }
  22892. std::string url() const {
  22893. return "wss://localhost:" + std::to_string(port_) + "/echo";
  22894. }
  22895. std::unique_ptr<SSLServer> server_;
  22896. std::thread server_thread_;
  22897. int port_ = 0;
  22898. };
  22899. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  22900. // out and the connection is usable
  22901. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  22902. Start(SERVER_CERT2_FILE);
  22903. ws::WebSocketClient client(url());
  22904. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22905. ASSERT_TRUE(client.connect());
  22906. ASSERT_TRUE(client.send("hello"));
  22907. std::string msg;
  22908. EXPECT_EQ(ws::Text, client.read(msg));
  22909. EXPECT_EQ("hello", msg);
  22910. client.close();
  22911. }
  22912. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  22913. // while the identity check must still reject "localhost"
  22914. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  22915. Start(SERVER_CERT_FILE);
  22916. ws::WebSocketClient client(url());
  22917. client.set_ca_cert_path(SERVER_CERT_FILE);
  22918. auto res = client.connect();
  22919. ASSERT_FALSE(res);
  22920. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  22921. EXPECT_EQ(-1, res.status());
  22922. }
  22923. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  22924. // disabled: the chain is still checked, only the identity check is skipped
  22925. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  22926. Start(SERVER_CERT_FILE);
  22927. ws::WebSocketClient client(url());
  22928. client.set_ca_cert_path(SERVER_CERT_FILE);
  22929. client.enable_server_hostname_verification(false);
  22930. ASSERT_TRUE(client.connect());
  22931. ASSERT_TRUE(client.send("hello"));
  22932. std::string msg;
  22933. EXPECT_EQ(ws::Text, client.read(msg));
  22934. EXPECT_EQ("hello", msg);
  22935. client.close();
  22936. }
  22937. // A CA that did not sign the server certificate fails the chain, even though
  22938. // the name would match
  22939. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  22940. Start(SERVER_CERT2_FILE);
  22941. ws::WebSocketClient client(url());
  22942. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22943. ASSERT_FALSE(client.connect());
  22944. }
  22945. // With verification disabled, neither the chain nor the name is checked
  22946. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  22947. Start(SERVER_CERT_FILE);
  22948. ws::WebSocketClient client(url());
  22949. client.enable_server_certificate_verification(false);
  22950. ASSERT_TRUE(client.connect());
  22951. ASSERT_TRUE(client.send("hello"));
  22952. std::string msg;
  22953. EXPECT_EQ(ws::Text, client.read(msg));
  22954. EXPECT_EQ("hello", msg);
  22955. client.close();
  22956. }
  22957. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  22958. protected:
  22959. void SetUp() override {
  22960. server_ = httplib::detail::make_unique<SSLServer>(
  22961. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22962. ASSERT_TRUE(server_->is_valid());
  22963. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22964. std::string msg;
  22965. while (ws.read(msg)) {
  22966. ws.send(msg);
  22967. }
  22968. });
  22969. port_ = server_->bind_to_any_port("localhost");
  22970. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22971. server_->wait_until_ready();
  22972. }
  22973. void TearDown() override {
  22974. server_->stop();
  22975. if (server_thread_.joinable()) { server_thread_.join(); }
  22976. }
  22977. std::string url() const {
  22978. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  22979. }
  22980. void ConnectWithClientCert(const std::string &client_cert_file,
  22981. const std::string &client_private_key_file,
  22982. const char *private_key_password) {
  22983. std::string cert_pem, key_pem;
  22984. read_file(client_cert_file, cert_pem);
  22985. read_file(client_private_key_file, key_pem);
  22986. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  22987. key_pem.c_str(), key_pem.size(),
  22988. private_key_password};
  22989. ws::WebSocketClient client(url(), pem);
  22990. ASSERT_TRUE(client.is_valid());
  22991. client.enable_server_certificate_verification(false);
  22992. ASSERT_TRUE(client.connect());
  22993. ASSERT_TRUE(client.send("hello"));
  22994. std::string msg;
  22995. EXPECT_EQ(ws::Text, client.read(msg));
  22996. EXPECT_EQ("hello", msg);
  22997. client.close();
  22998. }
  22999. std::unique_ptr<SSLServer> server_;
  23000. std::thread server_thread_;
  23001. int port_ = 0;
  23002. };
  23003. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  23004. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  23005. }
  23006. // Control for the tests above: the fixture's server really does require a
  23007. // client certificate, so it is the PEM the constructor installed that decides
  23008. // the outcome.
  23009. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  23010. ws::WebSocketClient client(url());
  23011. ASSERT_TRUE(client.is_valid());
  23012. client.enable_server_certificate_verification(false);
  23013. EXPECT_FALSE(client.connect());
  23014. }
  23015. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  23016. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  23017. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  23018. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  23019. }
  23020. #endif
  23021. #if !defined(_WIN32)
  23022. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  23023. auto secret_dir = std::string("./symlink_test_secret");
  23024. auto served_dir = std::string("./symlink_test_served");
  23025. auto secret_file = secret_dir + "/secret.txt";
  23026. auto symlink_path = served_dir + "/escape";
  23027. // Setup: create directories and files
  23028. mkdir(secret_dir.c_str(), 0755);
  23029. mkdir(served_dir.c_str(), 0755);
  23030. {
  23031. std::ofstream ofs(secret_file);
  23032. ofs << "SECRET_DATA";
  23033. }
  23034. // Create symlink using absolute path so it resolves correctly
  23035. #ifdef PATH_MAX
  23036. char abs_secret[PATH_MAX];
  23037. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  23038. #else
  23039. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  23040. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  23041. ASSERT_NE(nullptr, abs_secret);
  23042. #endif
  23043. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  23044. auto se = detail::scope_exit([&] {
  23045. unlink(symlink_path.c_str());
  23046. unlink(secret_file.c_str());
  23047. rmdir(served_dir.c_str());
  23048. rmdir(secret_dir.c_str());
  23049. });
  23050. Server svr;
  23051. svr.set_mount_point("/", served_dir);
  23052. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  23053. auto se2 = detail::scope_exit([&] {
  23054. svr.stop();
  23055. listen_thread.join();
  23056. });
  23057. svr.wait_until_ready();
  23058. Client cli("localhost", PORT);
  23059. // Symlink pointing outside base dir should be blocked
  23060. auto res = cli.Get("/escape/secret.txt");
  23061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23062. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  23063. }
  23064. #endif
  23065. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  23066. // "GET /smuggled" request), reads the first response, and only then sends the
  23067. // embedded request as the body. Returns how many times /smuggled ran.
  23068. //
  23069. // The body is sent AFTER receiving the first response (as in the original
  23070. // PoC) so that the stream_line_reader cannot buffer it together with the
  23071. // headers of the first request.
  23072. static int count_smuggled_requests(const std::string &outer_head,
  23073. std::string &first_response) {
  23074. Server svr;
  23075. svr.set_mount_point("/", "./www");
  23076. std::atomic<int> smuggled_count(0);
  23077. svr.Get("/smuggled", [&](const Request &, Response &res) {
  23078. smuggled_count++;
  23079. res.set_content("oops", "text/plain");
  23080. });
  23081. svr.Post("/post", [&](const Request &req, Response &res) {
  23082. res.set_content(req.body, "text/plain");
  23083. });
  23084. auto port = svr.bind_to_any_port("localhost");
  23085. thread t = thread([&] { svr.listen_after_bind(); });
  23086. auto se = detail::scope_exit([&] {
  23087. svr.stop();
  23088. t.join();
  23089. });
  23090. svr.wait_until_ready();
  23091. auto error = Error::Success;
  23092. auto sock = detail::create_client_socket(
  23093. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  23094. /*connection_timeout_sec=*/2, 0,
  23095. /*read_timeout_sec=*/2, 0,
  23096. /*write_timeout_sec=*/2, 0, std::string(), error);
  23097. EXPECT_NE(INVALID_SOCKET, sock);
  23098. if (sock == INVALID_SOCKET) { return -1; }
  23099. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23100. // The "smuggled" request will be sent as the body of the outer request
  23101. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  23102. "Host: localhost\r\n"
  23103. "Connection: close\r\n"
  23104. "\r\n";
  23105. auto head = outer_head;
  23106. auto len = std::to_string(smuggled.size());
  23107. for (auto pos = head.find("{len}"); pos != std::string::npos;
  23108. pos = head.find("{len}", pos + len.size())) {
  23109. head.replace(pos, 5, len);
  23110. }
  23111. // Step 1: Send only the outer request headers (no body yet)
  23112. auto sent = send(sock, head.data(), head.size(), 0);
  23113. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  23114. // Step 2: Read the first response
  23115. char buf[4096];
  23116. for (;;) {
  23117. auto n = recv(sock, buf, sizeof(buf), 0);
  23118. if (n <= 0) break;
  23119. first_response.append(buf, static_cast<size_t>(n));
  23120. // Stop once we have a complete response (headers + body)
  23121. auto hdr_end = first_response.find("\r\n\r\n");
  23122. if (hdr_end != std::string::npos) {
  23123. // Check for Content-Length to know when the body is complete
  23124. auto cl_pos = first_response.find("Content-Length:");
  23125. if (cl_pos != std::string::npos) {
  23126. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  23127. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  23128. auto cl = std::stoul(
  23129. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  23130. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  23131. } else {
  23132. break; // No Content-Length, assume headers-only response
  23133. }
  23134. }
  23135. }
  23136. // Step 3: Now send the body, which looks like a new HTTP request. On a
  23137. // vulnerable server the keep-alive loop reads this as a second request. The
  23138. // server may already have closed the connection, so the result is ignored.
  23139. send(sock, smuggled.data(), smuggled.size(), 0);
  23140. // Half-close so that a server which drained the body sees EOF and closes,
  23141. // instead of the read below waiting for the read timeout.
  23142. #ifdef _WIN32
  23143. ::shutdown(sock, SD_SEND);
  23144. #else
  23145. ::shutdown(sock, SHUT_WR);
  23146. #endif
  23147. // Step 4: Read until the server closes the connection
  23148. for (;;) {
  23149. auto n = recv(sock, buf, sizeof(buf), 0);
  23150. if (n <= 0) break;
  23151. }
  23152. return smuggled_count.load();
  23153. }
  23154. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  23155. // A GET request with Content-Length to a static file handler must have its
  23156. // body drained before the keep-alive connection is reused. Otherwise the
  23157. // unread body bytes are interpreted as the next HTTP request.
  23158. std::string first_response;
  23159. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23160. "Host: localhost\r\n"
  23161. "Content-Length: {len}\r\n"
  23162. "\r\n",
  23163. first_response));
  23164. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  23165. }
  23166. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  23167. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  23168. // be answered with 400 and the connection closed. Treating it as "no body"
  23169. // leaves the body to be parsed as the next request.
  23170. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  23171. const char *targets[] = {
  23172. "GET /file", // handler that never reads the body
  23173. "GET /not-found", // no handler matches (404)
  23174. "POST /post", // handler that reads the body
  23175. };
  23176. for (auto target : targets) {
  23177. for (auto value : values) {
  23178. std::string first_response;
  23179. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  23180. " HTTP/1.1\r\n"
  23181. "Host: localhost\r\n"
  23182. "Content-Length: " +
  23183. value + "\r\n\r\n",
  23184. first_response))
  23185. << target << " with Content-Length: " << value;
  23186. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  23187. << target << " with Content-Length: " << value;
  23188. }
  23189. }
  23190. }
  23191. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  23192. // A 400 for an unparseable request line leaves the rest of the message
  23193. // unread, so the connection must be closed rather than reused.
  23194. std::string first_response;
  23195. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  23196. "Host: localhost\r\n"
  23197. "Content-Length: {len}\r\n"
  23198. "\r\n",
  23199. first_response));
  23200. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  23201. }
  23202. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  23203. // Same as above for a header block that fails to parse.
  23204. std::string first_response;
  23205. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23206. "Host: localhost\r\n"
  23207. "Bad Header\r\n"
  23208. "Content-Length: {len}\r\n"
  23209. "\r\n",
  23210. first_response));
  23211. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  23212. }
  23213. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  23214. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  23215. // server must not read another request on that connection, even when the
  23216. // request had no body to drain.
  23217. std::string first_response;
  23218. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  23219. "Host: localhost\r\n"
  23220. "\r\n",
  23221. first_response));
  23222. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  23223. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  23224. }
  23225. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  23226. // A content reader that stops early leaves the stream inside the body.
  23227. // Draining the whole Content-Length from there, or reading the body again,
  23228. // reads into the next request, and whatever follows is parsed as a request
  23229. // of its own.
  23230. Server svr;
  23231. std::atomic<int> smuggled_count(0);
  23232. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  23233. svr.Post("/upload", [](const Request &req, Response &res,
  23234. const ContentReader &content_reader) {
  23235. // Stop at the last chunk, so the whole body has been read however it
  23236. // arrives.
  23237. auto length = req.get_header_value_u64("Content-Length");
  23238. size_t total = 0;
  23239. auto consumed = content_reader([&](const char *, size_t n) {
  23240. total += n;
  23241. return total < length;
  23242. });
  23243. EXPECT_FALSE(consumed);
  23244. if (req.has_param("retry")) {
  23245. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  23246. }
  23247. // Replace the 400 the aborted read set, which would close the connection.
  23248. res.set_redirect("/done");
  23249. });
  23250. auto port = svr.bind_to_any_port(HOST);
  23251. thread t = thread([&] { svr.listen_after_bind(); });
  23252. auto se = detail::scope_exit([&] {
  23253. svr.stop();
  23254. t.join();
  23255. });
  23256. svr.wait_until_ready();
  23257. // A front end sees the second request as a POST whose body is the GET. The
  23258. // first body is as long as the POST's headers, so draining it again reads
  23259. // exactly those and leaves the GET to be parsed next.
  23260. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  23261. "Host: localhost\r\n"
  23262. "\r\n";
  23263. std::string second_head = "POST /post HTTP/1.1\r\n"
  23264. "Host: localhost\r\n"
  23265. "Content-Length: " +
  23266. std::to_string(inner.size()) +
  23267. "\r\n"
  23268. "\r\n";
  23269. for (auto target : {"/upload", "/upload?retry"}) {
  23270. smuggled_count = 0;
  23271. std::string request = "POST " + std::string(target) +
  23272. " HTTP/1.1\r\n"
  23273. "Host: localhost\r\n"
  23274. "Content-Length: " +
  23275. std::to_string(second_head.size()) +
  23276. "\r\n"
  23277. "\r\n" +
  23278. std::string(second_head.size(), 'A') + second_head +
  23279. inner;
  23280. std::string response;
  23281. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  23282. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  23283. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  23284. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  23285. EXPECT_EQ(0, smuggled_count.load()) << target;
  23286. }
  23287. }
  23288. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  23289. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  23290. // must be rejected with 400 Bad Request.
  23291. Server svr;
  23292. svr.Post("/test", [&](const Request &, Response &res) {
  23293. res.set_content("ok", "text/plain");
  23294. });
  23295. thread t = thread([&] { svr.listen(HOST, PORT); });
  23296. auto se = detail::scope_exit([&] {
  23297. svr.stop();
  23298. t.join();
  23299. ASSERT_FALSE(svr.is_running());
  23300. });
  23301. svr.wait_until_ready();
  23302. // Exact "chunked"
  23303. {
  23304. auto req = "POST /test HTTP/1.1\r\n"
  23305. "Host: localhost\r\n"
  23306. "Content-Length: 5\r\n"
  23307. "Transfer-Encoding: chunked\r\n"
  23308. "Connection: close\r\n"
  23309. "\r\n"
  23310. "hello";
  23311. std::string response;
  23312. ASSERT_TRUE(send_request(1, req, &response));
  23313. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23314. response.substr(0, response.find("\r\n")));
  23315. }
  23316. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  23317. {
  23318. auto req = "POST /test HTTP/1.1\r\n"
  23319. "Host: localhost\r\n"
  23320. "Content-Length: 5\r\n"
  23321. "Transfer-Encoding: gzip, chunked\r\n"
  23322. "Connection: close\r\n"
  23323. "\r\n"
  23324. "hello";
  23325. std::string response;
  23326. ASSERT_TRUE(send_request(1, req, &response));
  23327. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23328. response.substr(0, response.find("\r\n")));
  23329. }
  23330. }
  23331. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  23332. Server svr;
  23333. svr.Post("/test", [&](const Request &, Response &res) {
  23334. res.set_content("ok", "text/plain");
  23335. });
  23336. thread t = thread([&] { svr.listen(HOST, PORT); });
  23337. auto se = detail::scope_exit([&] {
  23338. svr.stop();
  23339. t.join();
  23340. ASSERT_FALSE(svr.is_running());
  23341. });
  23342. svr.wait_until_ready();
  23343. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  23344. // length cannot be determined, so the server must answer 400 and close
  23345. // rather than treat the request as bodyless and leave the body in the
  23346. // socket for the next request to pick up.
  23347. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  23348. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  23349. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  23350. std::string response;
  23351. ASSERT_TRUE(send_request(1, req, &response));
  23352. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23353. response.substr(0, response.find("\r\n")))
  23354. << transfer_encoding;
  23355. }
  23356. // RFC 9110 5.3: the codings may also be split across several
  23357. // Transfer-Encoding lines, which combine in the order they were received.
  23358. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  23359. // just like the single-line "chunked, gzip" above.
  23360. {
  23361. auto req = "POST /test HTTP/1.1\r\n"
  23362. "Host: localhost\r\n"
  23363. "Transfer-Encoding: chunked\r\n"
  23364. "Transfer-Encoding: gzip\r\n"
  23365. "\r\n"
  23366. "0\r\n\r\n";
  23367. std::string response;
  23368. ASSERT_TRUE(send_request(1, req, &response));
  23369. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23370. response.substr(0, response.find("\r\n")));
  23371. }
  23372. // A sequence ending in chunked stays valid.
  23373. auto req = "POST /test HTTP/1.1\r\n"
  23374. "Host: localhost\r\n"
  23375. "Transfer-Encoding: gzip, chunked\r\n"
  23376. "Connection: close\r\n"
  23377. "\r\n"
  23378. "0\r\n\r\n";
  23379. std::string response;
  23380. ASSERT_TRUE(send_request(1, req, &response));
  23381. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  23382. // ...including when it is spread over several lines.
  23383. auto split_req = "POST /test HTTP/1.1\r\n"
  23384. "Host: localhost\r\n"
  23385. "Transfer-Encoding: gzip\r\n"
  23386. "Transfer-Encoding: chunked\r\n"
  23387. "Connection: close\r\n"
  23388. "\r\n"
  23389. "0\r\n\r\n";
  23390. std::string split_response;
  23391. ASSERT_TRUE(send_request(1, split_req, &split_response));
  23392. EXPECT_EQ("HTTP/1.1 200 OK",
  23393. split_response.substr(0, split_response.find("\r\n")));
  23394. }
  23395. // Regression for issue #2450: a DELETE without Content-Length on a
  23396. // keep-alive connection must not let the post-response drain consume the
  23397. // next request's bytes.
  23398. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  23399. Server svr;
  23400. std::atomic<int> delete_count(0);
  23401. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  23402. delete_count++;
  23403. res.status = StatusCode::NoContent_204;
  23404. });
  23405. auto port = svr.bind_to_any_port(HOST);
  23406. thread t = thread([&] { svr.listen_after_bind(); });
  23407. auto se = detail::scope_exit([&] {
  23408. svr.stop();
  23409. t.join();
  23410. });
  23411. svr.wait_until_ready();
  23412. auto error = Error::Success;
  23413. auto sock = detail::create_client_socket(
  23414. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23415. /*connection_timeout_sec=*/2, 0,
  23416. /*read_timeout_sec=*/2, 0,
  23417. /*write_timeout_sec=*/2, 0, std::string(), error);
  23418. ASSERT_NE(INVALID_SOCKET, sock);
  23419. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23420. auto send_request_and_read_response = [&](const std::string &req,
  23421. std::string &out) -> bool {
  23422. auto sent = send(sock, req.data(), req.size(), 0);
  23423. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  23424. char buf[4096];
  23425. for (;;) {
  23426. auto n = recv(sock, buf, sizeof(buf), 0);
  23427. if (n <= 0) { return !out.empty(); }
  23428. out.append(buf, static_cast<size_t>(n));
  23429. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  23430. }
  23431. };
  23432. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  23433. "Host: localhost\r\n"
  23434. "\r\n";
  23435. std::string resp1;
  23436. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  23437. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  23438. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  23439. "Host: localhost\r\n"
  23440. "Connection: close\r\n"
  23441. "\r\n";
  23442. std::string resp2;
  23443. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  23444. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  23445. EXPECT_EQ(2, delete_count.load());
  23446. }
  23447. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  23448. Server svr;
  23449. svr.Post("/ingest", [&](const Request &, Response &res,
  23450. const ContentReader &content_reader) {
  23451. auto consumed = content_reader([](const char *, size_t) { return false; });
  23452. EXPECT_FALSE(consumed);
  23453. res.status = StatusCode::Conflict_409;
  23454. res.set_header("Connection", "close");
  23455. });
  23456. auto port = svr.bind_to_any_port(HOST);
  23457. thread t = thread([&] { svr.listen_after_bind(); });
  23458. auto se = detail::scope_exit([&] {
  23459. svr.stop();
  23460. t.join();
  23461. });
  23462. svr.wait_until_ready();
  23463. auto error = Error::Success;
  23464. auto sock = detail::create_client_socket(
  23465. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23466. /*connection_timeout_sec=*/2, 0,
  23467. /*read_timeout_sec=*/1, 0,
  23468. /*write_timeout_sec=*/2, 0, std::string(), error);
  23469. ASSERT_NE(INVALID_SOCKET, sock);
  23470. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23471. std::string request = "POST /ingest HTTP/1.1\r\n"
  23472. "Host: localhost\r\n"
  23473. "Transfer-Encoding: chunked\r\n"
  23474. "\r\n"
  23475. "4\r\n"
  23476. "data\r\n";
  23477. auto sent = send(sock, request.data(), request.size(), 0);
  23478. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  23479. std::string response;
  23480. ssize_t received = 0;
  23481. do {
  23482. char buf[4096];
  23483. received = recv(sock, buf, sizeof(buf), 0);
  23484. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  23485. } while (received > 0);
  23486. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  23487. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  23488. EXPECT_EQ(0, received);
  23489. }
  23490. namespace no_proxy_test {
  23491. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  23492. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  23493. // calling listen().
  23494. class ScopedServer {
  23495. public:
  23496. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  23497. ~ScopedServer() {
  23498. svr_.stop();
  23499. if (th_.joinable()) { th_.join(); }
  23500. }
  23501. Server &svr() { return svr_; }
  23502. int port() const { return port_; }
  23503. void listen() {
  23504. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23505. svr_.wait_until_ready();
  23506. }
  23507. private:
  23508. Server svr_;
  23509. std::thread th_;
  23510. int port_ = 0;
  23511. };
  23512. class ProxyAndTargetServers {
  23513. public:
  23514. ProxyAndTargetServers() {
  23515. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  23516. proxy_hits_++;
  23517. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23518. res.set_content("via-proxy", "text/plain");
  23519. });
  23520. target_.Get(".*", [this](const Request &req, Response &res) {
  23521. target_hits_++;
  23522. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23523. res.set_content("direct", "text/plain");
  23524. });
  23525. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  23526. target_port_ = target_.bind_to_any_port("127.0.0.1");
  23527. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  23528. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  23529. proxy_mock_.wait_until_ready();
  23530. target_.wait_until_ready();
  23531. }
  23532. ~ProxyAndTargetServers() {
  23533. proxy_mock_.stop();
  23534. target_.stop();
  23535. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  23536. if (target_thread_.joinable()) { target_thread_.join(); }
  23537. }
  23538. Server &proxy_mock() { return proxy_mock_; }
  23539. Server &target() { return target_; }
  23540. int proxy_port() const { return proxy_port_; }
  23541. int target_port() const { return target_port_; }
  23542. int proxy_hits() const { return proxy_hits_.load(); }
  23543. int target_hits() const { return target_hits_.load(); }
  23544. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  23545. void reset_counters() {
  23546. proxy_hits_ = 0;
  23547. target_hits_ = 0;
  23548. last_had_proxy_authz_ = false;
  23549. }
  23550. private:
  23551. Server proxy_mock_;
  23552. Server target_;
  23553. std::thread proxy_thread_;
  23554. std::thread target_thread_;
  23555. int proxy_port_ = 0;
  23556. int target_port_ = 0;
  23557. std::atomic<int> proxy_hits_{0};
  23558. std::atomic<int> target_hits_{0};
  23559. std::atomic<bool> last_had_proxy_authz_{false};
  23560. };
  23561. inline std::unique_ptr<Client> make_client(const std::string &host,
  23562. ProxyAndTargetServers &s) {
  23563. auto cli = detail::make_unique<Client>(host, s.target_port());
  23564. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  23565. cli->set_proxy("127.0.0.1", s.proxy_port());
  23566. return cli;
  23567. }
  23568. } // namespace no_proxy_test
  23569. using no_proxy_test::make_client;
  23570. using no_proxy_test::ProxyAndTargetServers;
  23571. TEST(NoProxyTest, ExactHostnameBypasses) {
  23572. ProxyAndTargetServers s;
  23573. auto cli = make_client("example.com", s);
  23574. cli->set_no_proxy({"example.com"});
  23575. auto res = cli->Get("/");
  23576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23577. EXPECT_EQ(0, s.proxy_hits());
  23578. EXPECT_EQ(1, s.target_hits());
  23579. }
  23580. TEST(NoProxyTest, SubdomainBypasses) {
  23581. ProxyAndTargetServers s;
  23582. auto cli = make_client("foo.example.com", s);
  23583. cli->set_no_proxy({"example.com"});
  23584. auto res = cli->Get("/");
  23585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23586. EXPECT_EQ(0, s.proxy_hits());
  23587. EXPECT_EQ(1, s.target_hits());
  23588. }
  23589. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  23590. // Regression guard: "evilexample.com" must not be considered a subdomain
  23591. // of "example.com". Without the dot-boundary rule, a naive endsWith
  23592. // check would let traffic bypass the proxy and leak credentials direct
  23593. // to the attacker host.
  23594. ProxyAndTargetServers s;
  23595. auto cli = make_client("evilexample.com", s);
  23596. cli->set_no_proxy({"example.com"});
  23597. auto res = cli->Get("/");
  23598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23599. EXPECT_GE(s.proxy_hits(), 1);
  23600. EXPECT_EQ(0, s.target_hits());
  23601. }
  23602. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  23603. ProxyAndTargetServers s;
  23604. auto cli = make_client("example.com.evil.com", s);
  23605. cli->set_no_proxy({"example.com"});
  23606. auto res = cli->Get("/");
  23607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23608. EXPECT_GE(s.proxy_hits(), 1);
  23609. EXPECT_EQ(0, s.target_hits());
  23610. }
  23611. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  23612. ProxyAndTargetServers s;
  23613. auto cli = make_client("example.com", s);
  23614. cli->set_no_proxy({".example.com"});
  23615. auto res = cli->Get("/");
  23616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23617. EXPECT_EQ(0, s.proxy_hits());
  23618. EXPECT_EQ(1, s.target_hits());
  23619. }
  23620. TEST(NoProxyTest, CaseInsensitiveHostname) {
  23621. ProxyAndTargetServers s;
  23622. auto cli = make_client("Example.COM", s);
  23623. cli->set_no_proxy({"EXAMPLE.com"});
  23624. auto res = cli->Get("/");
  23625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23626. EXPECT_EQ(0, s.proxy_hits());
  23627. EXPECT_EQ(1, s.target_hits());
  23628. }
  23629. TEST(NoProxyTest, TrailingDotIsNormalized) {
  23630. ProxyAndTargetServers s;
  23631. auto cli = make_client("example.com.", s);
  23632. cli->set_no_proxy({"example.com"});
  23633. auto res = cli->Get("/");
  23634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23635. EXPECT_EQ(0, s.proxy_hits());
  23636. EXPECT_EQ(1, s.target_hits());
  23637. }
  23638. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  23639. // Trailing dots must be normalized on BOTH sides — host and entry.
  23640. // An implementation that only strips the host-side trailing dot would
  23641. // fail to match host "example.com" against entry "example.com." because
  23642. // a literal substring search would compare 11 chars against 12.
  23643. ProxyAndTargetServers s;
  23644. auto cli = make_client("example.com", s);
  23645. cli->set_no_proxy({"example.com."});
  23646. auto res = cli->Get("/");
  23647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23648. EXPECT_EQ(0, s.proxy_hits());
  23649. EXPECT_EQ(1, s.target_hits());
  23650. }
  23651. TEST(NoProxyTest, WildcardBypassesEverything) {
  23652. ProxyAndTargetServers s;
  23653. auto cli = make_client("anything.invalid.test", s);
  23654. cli->set_no_proxy({"*"});
  23655. auto res = cli->Get("/");
  23656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23657. EXPECT_EQ(0, s.proxy_hits());
  23658. EXPECT_EQ(1, s.target_hits());
  23659. }
  23660. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  23661. ProxyAndTargetServers s;
  23662. Client cli("127.0.0.1", s.target_port());
  23663. cli.set_proxy("127.0.0.1", s.proxy_port());
  23664. cli.set_no_proxy({"127.0.0.1"});
  23665. auto res = cli.Get("/");
  23666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23667. EXPECT_EQ(0, s.proxy_hits());
  23668. EXPECT_EQ(1, s.target_hits());
  23669. }
  23670. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  23671. ProxyAndTargetServers s;
  23672. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  23673. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  23674. cli.set_proxy("127.0.0.1", s.proxy_port());
  23675. cli.set_no_proxy({"::1"});
  23676. auto res = cli.Get("/");
  23677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23678. EXPECT_EQ(0, s.proxy_hits());
  23679. EXPECT_EQ(1, s.target_hits());
  23680. }
  23681. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  23682. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  23683. // must still be recognized as IPv6 for CIDR matching. Implementations
  23684. // that detect IPv6 only when the host begins with '[' would parse the
  23685. // host as a hostname and miss the match.
  23686. ProxyAndTargetServers s;
  23687. Client cli("fe80::1", s.target_port());
  23688. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23689. cli.set_proxy("127.0.0.1", s.proxy_port());
  23690. cli.set_no_proxy({"fe80::/10"});
  23691. auto res = cli.Get("/");
  23692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23693. EXPECT_EQ(0, s.proxy_hits());
  23694. EXPECT_EQ(1, s.target_hits());
  23695. }
  23696. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  23697. ProxyAndTargetServers s;
  23698. Client cli("::1", s.target_port());
  23699. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  23700. cli.set_proxy("127.0.0.1", s.proxy_port());
  23701. cli.set_no_proxy({"[::1]"});
  23702. auto res = cli.Get("/");
  23703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23704. EXPECT_EQ(0, s.proxy_hits());
  23705. EXPECT_EQ(1, s.target_hits());
  23706. }
  23707. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  23708. ProxyAndTargetServers s;
  23709. Client cli("fe80::1", s.target_port());
  23710. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23711. cli.set_proxy("127.0.0.1", s.proxy_port());
  23712. cli.set_no_proxy({"[fe80::]/10"});
  23713. auto res = cli.Get("/");
  23714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23715. EXPECT_EQ(0, s.proxy_hits());
  23716. EXPECT_EQ(1, s.target_hits());
  23717. }
  23718. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  23719. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  23720. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  23721. // tricks via address-family conversion.
  23722. ProxyAndTargetServers s;
  23723. Client cli("::ffff:127.0.0.1", s.target_port());
  23724. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  23725. cli.set_proxy("127.0.0.1", s.proxy_port());
  23726. cli.set_no_proxy({"127.0.0.1"});
  23727. auto res = cli.Get("/");
  23728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23729. EXPECT_GE(s.proxy_hits(), 1);
  23730. EXPECT_EQ(0, s.target_hits());
  23731. }
  23732. TEST(NoProxyTest, IPv4CidrMatch) {
  23733. ProxyAndTargetServers s;
  23734. Client cli("127.0.0.1", s.target_port());
  23735. cli.set_proxy("127.0.0.1", s.proxy_port());
  23736. cli.set_no_proxy({"127.0.0.0/8"});
  23737. auto res = cli.Get("/");
  23738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23739. EXPECT_EQ(0, s.proxy_hits());
  23740. EXPECT_EQ(1, s.target_hits());
  23741. }
  23742. TEST(NoProxyTest, IPv4CidrNonMatch) {
  23743. ProxyAndTargetServers s;
  23744. Client cli("127.0.0.1", s.target_port());
  23745. cli.set_proxy("127.0.0.1", s.proxy_port());
  23746. cli.set_no_proxy({"10.0.0.0/8"});
  23747. auto res = cli.Get("/");
  23748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23749. EXPECT_GE(s.proxy_hits(), 1);
  23750. EXPECT_EQ(0, s.target_hits());
  23751. }
  23752. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  23753. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  23754. // IPv4 target matches.
  23755. ProxyAndTargetServers s;
  23756. Client cli("127.0.0.1", s.target_port());
  23757. cli.set_proxy("127.0.0.1", s.proxy_port());
  23758. cli.set_no_proxy({"0.0.0.0/0"});
  23759. auto res = cli.Get("/");
  23760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23761. EXPECT_EQ(0, s.proxy_hits());
  23762. EXPECT_EQ(1, s.target_hits());
  23763. }
  23764. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  23765. ProxyAndTargetServers s;
  23766. Client cli("127.0.0.1", s.target_port());
  23767. cli.set_proxy("127.0.0.1", s.proxy_port());
  23768. cli.set_no_proxy({"127.0.0.1"});
  23769. auto res = cli.Get("/");
  23770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23771. EXPECT_EQ(0, s.proxy_hits());
  23772. EXPECT_EQ(1, s.target_hits());
  23773. }
  23774. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  23775. ProxyAndTargetServers s;
  23776. Client cli("127.0.0.1", s.target_port());
  23777. cli.set_proxy("127.0.0.1", s.proxy_port());
  23778. cli.set_no_proxy({"127.0.0.0/33"});
  23779. auto res = cli.Get("/");
  23780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23781. EXPECT_GE(s.proxy_hits(), 1);
  23782. EXPECT_EQ(0, s.target_hits());
  23783. }
  23784. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  23785. // Empty prefix after the slash must be rejected, not silently treated as /32.
  23786. ProxyAndTargetServers s;
  23787. Client cli("127.0.0.1", s.target_port());
  23788. cli.set_proxy("127.0.0.1", s.proxy_port());
  23789. cli.set_no_proxy({"127.0.0.1/"});
  23790. auto res = cli.Get("/");
  23791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23792. EXPECT_GE(s.proxy_hits(), 1);
  23793. EXPECT_EQ(0, s.target_hits());
  23794. }
  23795. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  23796. ProxyAndTargetServers s;
  23797. auto cli = make_client("internal.corp", s);
  23798. cli->set_proxy_basic_auth("u", "p");
  23799. cli->set_no_proxy({"internal.corp"});
  23800. auto res = cli->Get("/");
  23801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23802. EXPECT_EQ(1, s.target_hits());
  23803. EXPECT_EQ(0, s.proxy_hits());
  23804. EXPECT_FALSE(s.last_had_proxy_authz())
  23805. << "Proxy-Authorization must not be sent direct to the target";
  23806. }
  23807. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  23808. ProxyAndTargetServers s;
  23809. auto cli = make_client("public.example", s);
  23810. cli->set_proxy_basic_auth("u", "p");
  23811. cli->set_no_proxy({"internal.corp"}); // does not match
  23812. auto res = cli->Get("/");
  23813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23814. EXPECT_GE(s.proxy_hits(), 1);
  23815. EXPECT_TRUE(s.last_had_proxy_authz());
  23816. }
  23817. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  23818. std::atomic<int> hits{0};
  23819. std::atomic<int> hits_with_authz{0};
  23820. no_proxy_test::ScopedServer proxy_mock;
  23821. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23822. hits++;
  23823. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  23824. if (req.target.find("/redir") != std::string::npos) {
  23825. res.set_redirect("http://other.example/landed");
  23826. } else {
  23827. res.set_content("via-proxy", "text/plain");
  23828. }
  23829. });
  23830. proxy_mock.listen();
  23831. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  23832. hits = 0;
  23833. hits_with_authz = 0;
  23834. Client cli("public.example", 80);
  23835. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23836. cli.set_proxy_basic_auth(c.first, c.second);
  23837. cli.set_follow_location(true);
  23838. // The redirect to another host goes through the proxy as well
  23839. auto res = cli.Get("/redir");
  23840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23841. EXPECT_EQ(2, hits.load());
  23842. EXPECT_EQ(2, hits_with_authz.load());
  23843. }
  23844. }
  23845. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  23846. ProxyAndTargetServers s;
  23847. auto cli = make_client("anything.test", s);
  23848. auto res = cli->Get("/");
  23849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23850. EXPECT_GE(s.proxy_hits(), 1);
  23851. EXPECT_EQ(0, s.target_hits());
  23852. }
  23853. TEST(NoProxyTest, PortSpecificEntryRejected) {
  23854. ProxyAndTargetServers s;
  23855. auto cli = make_client("example.com", s);
  23856. cli->set_no_proxy({"example.com:8080"});
  23857. auto res = cli->Get("/");
  23858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23859. EXPECT_GE(s.proxy_hits(), 1);
  23860. EXPECT_EQ(0, s.target_hits());
  23861. }
  23862. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  23863. ProxyAndTargetServers s;
  23864. auto cli = make_client("anything.test", s);
  23865. cli->set_no_proxy({"", " ", "\t"});
  23866. auto res = cli->Get("/");
  23867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23868. EXPECT_GE(s.proxy_hits(), 1);
  23869. EXPECT_EQ(0, s.target_hits());
  23870. }
  23871. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  23872. // An entry with leading/trailing whitespace must still match — env-style
  23873. // values are commonly pasted with stray spaces and an implementation
  23874. // that feeds the raw token directly to inet_pton would fail to match
  23875. // valid CIDRs because of the spaces.
  23876. ProxyAndTargetServers s;
  23877. Client cli("127.0.0.1", s.target_port());
  23878. cli.set_proxy("127.0.0.1", s.proxy_port());
  23879. cli.set_no_proxy({" 127.0.0.0/8 "});
  23880. auto res = cli.Get("/");
  23881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23882. EXPECT_EQ(0, s.proxy_hits());
  23883. EXPECT_EQ(1, s.target_hits());
  23884. }
  23885. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  23886. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  23887. // go direct and must NOT carry Proxy-Authorization.
  23888. std::atomic<int> proxy_hits{0};
  23889. std::atomic<int> target_hits{0};
  23890. std::atomic<bool> target_saw_authz{false};
  23891. no_proxy_test::ScopedServer proxy_mock, target;
  23892. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23893. proxy_hits++;
  23894. res.status = 302;
  23895. res.set_header("Location", "http://127.0.0.1:" +
  23896. std::to_string(target.port()) + "/landed");
  23897. });
  23898. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23899. target_hits++;
  23900. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  23901. res.set_content("direct", "text/plain");
  23902. });
  23903. proxy_mock.listen();
  23904. target.listen();
  23905. Client cli("public.example", target.port());
  23906. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23907. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23908. cli.set_proxy_basic_auth("u", "p");
  23909. cli.set_no_proxy({"127.0.0.1"});
  23910. cli.set_follow_location(true);
  23911. auto res = cli.Get("/redir");
  23912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23913. EXPECT_GE(proxy_hits.load(), 1);
  23914. EXPECT_GE(target_hits.load(), 1);
  23915. EXPECT_FALSE(target_saw_authz.load());
  23916. }
  23917. #ifdef CPPHTTPLIB_SSL_ENABLED
  23918. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  23919. // Direct origin replying 407 must not trigger the digest retry; otherwise
  23920. // proxy creds would be sent to the (possibly hostile) origin.
  23921. std::atomic<int> target_hits{0};
  23922. std::atomic<bool> target_saw_proxy_authz{false};
  23923. no_proxy_test::ScopedServer target;
  23924. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23925. target_hits++;
  23926. if (req.has_header("Proxy-Authorization")) {
  23927. target_saw_proxy_authz = true;
  23928. }
  23929. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23930. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  23931. "nonce=\"abc\", algorithm=MD5");
  23932. });
  23933. target.listen();
  23934. // The proxy address is set to the target's port: the bypass MUST kick in;
  23935. // if it doesn't, the test still routes "via proxy" to the same server and
  23936. // the Proxy-Authorization assertion below catches the leak.
  23937. Client cli("evil.example", target.port());
  23938. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  23939. cli.set_proxy("127.0.0.1", target.port());
  23940. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23941. cli.set_no_proxy({"evil.example"});
  23942. auto res = cli.Get("/x");
  23943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23944. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23945. EXPECT_EQ(1, target_hits.load());
  23946. EXPECT_FALSE(target_saw_proxy_authz.load());
  23947. }
  23948. #endif
  23949. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  23950. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  23951. std::atomic<int> proxy_hits{0};
  23952. std::atomic<int> bypass_hits{0};
  23953. std::atomic<bool> proxy_saw_c_url{false};
  23954. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  23955. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23956. proxy_hits++;
  23957. if (req.path.find("/start") != std::string::npos) {
  23958. res.status = 302;
  23959. res.set_header("Location", "http://127.0.0.1:" +
  23960. std::to_string(bypass_server.port()) +
  23961. "/middle");
  23962. return;
  23963. }
  23964. if (req.path.find("/end") != std::string::npos) {
  23965. proxy_saw_c_url = true;
  23966. res.set_content("c-via-proxy", "text/plain");
  23967. return;
  23968. }
  23969. res.set_content("unexpected", "text/plain");
  23970. });
  23971. // public.example's "advertised" port is arbitrary (the request never lands
  23972. // there — it goes through the proxy), but use a dynamic value to stay
  23973. // friendly with sharded parallel runs.
  23974. int public_port = bypass_server.port();
  23975. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  23976. bypass_hits++;
  23977. res.status = 302;
  23978. res.set_header("Location", "http://public.example:" +
  23979. std::to_string(public_port) + "/end");
  23980. });
  23981. proxy_mock.listen();
  23982. bypass_server.listen();
  23983. Client cli("public.example", public_port);
  23984. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23985. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23986. cli.set_no_proxy({"127.0.0.1"});
  23987. cli.set_follow_location(true);
  23988. auto res = cli.Get("/start");
  23989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23990. EXPECT_EQ(StatusCode::OK_200, res->status);
  23991. EXPECT_EQ("c-via-proxy", res->body);
  23992. EXPECT_GE(proxy_hits.load(), 2);
  23993. EXPECT_GE(bypass_hits.load(), 1);
  23994. EXPECT_TRUE(proxy_saw_c_url.load());
  23995. }
  23996. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  23997. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  23998. // request reconnects to the correct endpoint.
  23999. std::atomic<int> proxy_hits{0};
  24000. std::atomic<int> target_hits{0};
  24001. no_proxy_test::ScopedServer proxy_mock, target;
  24002. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  24003. proxy_hits++;
  24004. res.set_content("via-proxy", "text/plain");
  24005. });
  24006. target.svr().Get(".*", [&](const Request &, Response &res) {
  24007. target_hits++;
  24008. res.set_content("direct", "text/plain");
  24009. });
  24010. proxy_mock.listen();
  24011. target.listen();
  24012. Client cli("public.example", target.port());
  24013. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24014. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24015. cli.set_keep_alive(true);
  24016. auto res1 = cli.Get("/a");
  24017. ASSERT_TRUE(res1);
  24018. EXPECT_EQ("via-proxy", res1->body);
  24019. EXPECT_EQ(1, proxy_hits.load());
  24020. EXPECT_EQ(0, target_hits.load());
  24021. cli.set_no_proxy({"public.example"});
  24022. auto res2 = cli.Get("/b");
  24023. ASSERT_TRUE(res2);
  24024. EXPECT_EQ("direct", res2->body);
  24025. EXPECT_EQ(1, proxy_hits.load());
  24026. EXPECT_EQ(1, target_hits.load());
  24027. }
  24028. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  24029. namespace proxy_tunnel_test {
  24030. // SSLServer counterpart to no_proxy_test::ScopedServer.
  24031. class ScopedSSLServer {
  24032. public:
  24033. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  24034. port_ = svr_.bind_to_any_port("127.0.0.1");
  24035. }
  24036. ~ScopedSSLServer() {
  24037. svr_.stop();
  24038. if (th_.joinable()) { th_.join(); }
  24039. }
  24040. SSLServer &svr() { return svr_; }
  24041. int port() const { return port_; }
  24042. void listen() {
  24043. th_ = std::thread([this] { svr_.listen_after_bind(); });
  24044. svr_.wait_until_ready();
  24045. }
  24046. private:
  24047. SSLServer svr_;
  24048. std::thread th_;
  24049. int port_ = 0;
  24050. };
  24051. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  24052. class ScopedConnectProxy {
  24053. public:
  24054. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  24055. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  24056. if (listen_fd_ < 0) { return; }
  24057. int yes = 1;
  24058. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  24059. sockaddr_in a{};
  24060. a.sin_family = AF_INET;
  24061. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24062. a.sin_port = 0;
  24063. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  24064. return;
  24065. }
  24066. socklen_t alen = sizeof(a);
  24067. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  24068. 0) {
  24069. return;
  24070. }
  24071. port_ = ntohs(a.sin_port);
  24072. if (::listen(listen_fd_, 1) != 0) { return; }
  24073. th_ = std::thread([this] { run(); });
  24074. }
  24075. ~ScopedConnectProxy() {
  24076. stop_ = true;
  24077. if (listen_fd_ >= 0) {
  24078. ::shutdown(listen_fd_, SHUT_RDWR);
  24079. ::close(listen_fd_);
  24080. }
  24081. if (th_.joinable()) { th_.join(); }
  24082. }
  24083. int port() const { return port_; }
  24084. int connect_hits() const { return connect_hits_.load(); }
  24085. // Head of the last CONNECT request, as the proxy saw it on the wire.
  24086. std::string connect_request() const {
  24087. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24088. return connect_request_;
  24089. }
  24090. private:
  24091. void run() {
  24092. while (!stop_.load()) {
  24093. fd_set rfds;
  24094. FD_ZERO(&rfds);
  24095. FD_SET(listen_fd_, &rfds);
  24096. timeval tv{0, 100 * 1000};
  24097. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  24098. if (sel <= 0) { continue; }
  24099. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  24100. if (client_fd < 0) { continue; }
  24101. std::string req;
  24102. char buf[2048];
  24103. while (req.find("\r\n\r\n") == std::string::npos) {
  24104. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  24105. if (n <= 0) { break; }
  24106. req.append(buf, static_cast<size_t>(n));
  24107. }
  24108. if (req.compare(0, 7, "CONNECT") != 0) {
  24109. ::close(client_fd);
  24110. continue;
  24111. }
  24112. connect_hits_++;
  24113. {
  24114. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24115. connect_request_ = req;
  24116. }
  24117. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  24118. ::send(client_fd, ok, std::strlen(ok), 0);
  24119. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  24120. sockaddr_in o{};
  24121. o.sin_family = AF_INET;
  24122. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24123. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  24124. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  24125. 0) {
  24126. ::close(client_fd);
  24127. ::close(origin_fd);
  24128. continue;
  24129. }
  24130. auto forward = [](int from, int to) {
  24131. char b[8192];
  24132. for (;;) {
  24133. ssize_t n = ::recv(from, b, sizeof(b), 0);
  24134. if (n <= 0) { break; }
  24135. ssize_t off = 0;
  24136. while (off < n) {
  24137. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  24138. if (s <= 0) {
  24139. off = n;
  24140. break;
  24141. }
  24142. off += s;
  24143. }
  24144. }
  24145. ::shutdown(to, SHUT_WR);
  24146. };
  24147. std::thread t1([&] { forward(client_fd, origin_fd); });
  24148. std::thread t2([&] { forward(origin_fd, client_fd); });
  24149. t1.join();
  24150. t2.join();
  24151. ::close(client_fd);
  24152. ::close(origin_fd);
  24153. }
  24154. }
  24155. int forward_port_ = -1;
  24156. int listen_fd_ = -1;
  24157. int port_ = 0;
  24158. std::thread th_;
  24159. std::atomic<bool> stop_{false};
  24160. std::atomic<int> connect_hits_{0};
  24161. mutable std::mutex connect_request_mutex_;
  24162. std::string connect_request_;
  24163. };
  24164. // Sends one request through the CONNECT proxy to the TLS origin with a
  24165. // credential configured for each hop, and checks that each credential reaches
  24166. // only the hop it was configured for: the proxy's on the CONNECT request, the
  24167. // origin's (every header in origin_headers) on the tunnelled request.
  24168. void CredentialsStayWithTheirHop(
  24169. const std::function<void(SSLClient &)> &set_credentials,
  24170. const std::string &scheme,
  24171. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  24172. std::atomic<int> origin_hits{0};
  24173. std::atomic<bool> origin_saw_proxy_authz{false};
  24174. std::atomic<bool> origin_saw_headers{false};
  24175. ScopedSSLServer origin;
  24176. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24177. origin_hits++;
  24178. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  24179. origin_saw_headers =
  24180. std::all_of(origin_headers.begin(), origin_headers.end(),
  24181. [&](const std::string &h) { return req.has_header(h); });
  24182. res.set_content("ok", "text/plain");
  24183. });
  24184. origin.listen();
  24185. ScopedConnectProxy proxy(origin.port());
  24186. ASSERT_NE(0, proxy.port());
  24187. // Pinned to 127.0.0.1 for the same reason as the test below.
  24188. SSLClient cli("127.0.0.1", origin.port());
  24189. cli.enable_server_certificate_verification(false);
  24190. cli.set_proxy("127.0.0.1", proxy.port());
  24191. set_credentials(cli);
  24192. auto res = cli.Get("/x");
  24193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24194. EXPECT_EQ(StatusCode::OK_200, res->status);
  24195. EXPECT_EQ(1, origin_hits.load());
  24196. EXPECT_EQ(1, proxy.connect_hits());
  24197. EXPECT_TRUE(origin_saw_headers.load());
  24198. EXPECT_FALSE(origin_saw_proxy_authz.load())
  24199. << "Proxy-Authorization must not be sent inside the tunnel";
  24200. auto connect_req = proxy.connect_request();
  24201. EXPECT_NE(std::string::npos,
  24202. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  24203. for (const auto &h : origin_headers) {
  24204. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  24205. << h << " must not be sent to the proxy on CONNECT";
  24206. }
  24207. }
  24208. } // namespace proxy_tunnel_test
  24209. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  24210. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24211. [](SSLClient &cli) {
  24212. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  24213. cli.set_basic_auth("origin-user", "origin-pass");
  24214. },
  24215. "Basic");
  24216. }
  24217. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  24218. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24219. [](SSLClient &cli) {
  24220. cli.set_proxy_bearer_token_auth("proxy-token");
  24221. cli.set_bearer_token_auth("origin-token");
  24222. },
  24223. "Bearer");
  24224. }
  24225. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  24226. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24227. [](SSLClient &cli) {
  24228. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  24229. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  24230. {"Cookie", "sid=origin-session"},
  24231. {"X-Api-Key", "origin-key"}});
  24232. },
  24233. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  24234. }
  24235. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  24236. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  24237. // retry; otherwise proxy creds would be sent to the origin.
  24238. std::atomic<int> origin_hits{0};
  24239. std::atomic<bool> origin_saw_proxy_authz{false};
  24240. proxy_tunnel_test::ScopedSSLServer origin;
  24241. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24242. origin_hits++;
  24243. if (req.has_header("Proxy-Authorization")) {
  24244. origin_saw_proxy_authz = true;
  24245. }
  24246. res.status = StatusCode::ProxyAuthenticationRequired_407;
  24247. res.set_header("Proxy-Authenticate",
  24248. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  24249. "algorithm=MD5");
  24250. });
  24251. origin.listen();
  24252. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  24253. ASSERT_NE(0, proxy.port());
  24254. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  24255. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  24256. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  24257. // and answer with its own status, making this test flaky.
  24258. SSLClient cli("127.0.0.1", origin.port());
  24259. cli.enable_server_certificate_verification(false);
  24260. cli.set_proxy("127.0.0.1", proxy.port());
  24261. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  24262. auto res = cli.Get("/x");
  24263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24264. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  24265. EXPECT_EQ(1, origin_hits.load());
  24266. EXPECT_FALSE(origin_saw_proxy_authz.load());
  24267. EXPECT_EQ(1, proxy.connect_hits());
  24268. }
  24269. #endif