test.cc 923 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definition is linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. } // namespace tls
  68. } // namespace httplib
  69. #endif
  70. using namespace std;
  71. using namespace httplib;
  72. const char *HOST = "localhost";
  73. static int get_base_port() {
  74. const char *shard = getenv("GTEST_SHARD_INDEX");
  75. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  76. }
  77. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  78. // New standalone tests MUST use svr.bind_to_any_port() instead.
  79. const int PORT = get_base_port();
  80. const string LONG_QUERY_VALUE = string(25000, '@');
  81. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  82. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  83. const string TOO_LONG_QUERY_URL =
  84. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  85. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  86. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  87. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  88. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  89. return file.name == key;
  90. });
  91. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  92. return *it;
  93. #else
  94. if (it != items.end()) { return *it; }
  95. throw std::runtime_error("invalid multipart form data name error");
  96. #endif
  97. }
  98. static void read_file(const std::string &path, std::string &out) {
  99. std::ifstream fs(path, std::ios_base::binary);
  100. if (!fs) {
  101. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  102. return;
  103. #else
  104. throw std::runtime_error("File not found: " + path);
  105. #endif
  106. }
  107. fs.seekg(0, std::ios_base::end);
  108. auto size = fs.tellg();
  109. fs.seekg(0);
  110. out.resize(static_cast<size_t>(size));
  111. fs.read(&out[0], static_cast<std::streamsize>(size));
  112. }
  113. class UnixSocketTest : public ::testing::Test {
  114. protected:
  115. void TearDown() override { std::remove(pathname_.c_str()); }
  116. void client_GET(const std::string &addr) {
  117. httplib::Client cli{addr};
  118. cli.set_address_family(AF_UNIX);
  119. ASSERT_TRUE(cli.is_valid());
  120. const auto &result = cli.Get(pattern_);
  121. ASSERT_TRUE(result) << "error: " << result.error();
  122. const auto &resp = result.value();
  123. EXPECT_EQ(resp.status, StatusCode::OK_200);
  124. EXPECT_EQ(resp.body, content_);
  125. }
  126. static std::string make_sock_path() {
  127. const char *shard = getenv("GTEST_SHARD_INDEX");
  128. return shard ? std::string("./httplib-server-") + shard + ".sock"
  129. : "./httplib-server.sock";
  130. }
  131. const std::string pathname_{make_sock_path()};
  132. const std::string pattern_{"/hi"};
  133. const std::string content_{"Hello World!"};
  134. };
  135. TEST_F(UnixSocketTest, pathname) {
  136. httplib::Server svr;
  137. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  138. res.set_content(content_, "text/plain");
  139. });
  140. std::thread t{[&] {
  141. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  142. }};
  143. auto se = detail::scope_exit([&] {
  144. svr.stop();
  145. t.join();
  146. ASSERT_FALSE(svr.is_running());
  147. });
  148. svr.wait_until_ready();
  149. ASSERT_TRUE(svr.is_running());
  150. client_GET(pathname_);
  151. }
  152. #if defined(__linux__) || \
  153. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  154. TEST_F(UnixSocketTest, PeerPid) {
  155. httplib::Server svr;
  156. std::string remote_port_val;
  157. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  158. res.set_content(content_, "text/plain");
  159. remote_port_val = std::to_string(req.remote_port);
  160. });
  161. std::thread t{[&] {
  162. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  163. }};
  164. auto se = detail::scope_exit([&] {
  165. svr.stop();
  166. t.join();
  167. ASSERT_FALSE(svr.is_running());
  168. });
  169. svr.wait_until_ready();
  170. ASSERT_TRUE(svr.is_running());
  171. client_GET(pathname_);
  172. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  173. }
  174. #endif
  175. #ifdef __linux__
  176. TEST_F(UnixSocketTest, abstract) {
  177. constexpr char svr_path[]{"\x00httplib-server.sock"};
  178. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  179. httplib::Server svr;
  180. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  181. res.set_content(content_, "text/plain");
  182. });
  183. std::thread t{[&] {
  184. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  185. }};
  186. auto se = detail::scope_exit([&] {
  187. svr.stop();
  188. t.join();
  189. ASSERT_FALSE(svr.is_running());
  190. });
  191. svr.wait_until_ready();
  192. ASSERT_TRUE(svr.is_running());
  193. client_GET(abstract_addr);
  194. }
  195. #endif
  196. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  197. httplib::Server svr;
  198. std::string received_host_header;
  199. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  200. // Capture the Host header sent by the client
  201. auto host_iter = req.headers.find("Host");
  202. if (host_iter != req.headers.end()) {
  203. received_host_header = host_iter->second;
  204. }
  205. res.set_content(content_, "text/plain");
  206. });
  207. std::thread t{[&] {
  208. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  209. }};
  210. auto se = detail::scope_exit([&] {
  211. svr.stop();
  212. t.join();
  213. ASSERT_FALSE(svr.is_running());
  214. });
  215. svr.wait_until_ready();
  216. ASSERT_TRUE(svr.is_running());
  217. // Test that Host header is automatically set to "localhost" for Unix socket
  218. // connections
  219. httplib::Client cli{pathname_};
  220. cli.set_address_family(AF_UNIX);
  221. ASSERT_TRUE(cli.is_valid());
  222. const auto &result = cli.Get(pattern_);
  223. ASSERT_TRUE(result) << "error: " << result.error();
  224. const auto &resp = result.value();
  225. EXPECT_EQ(resp.status, StatusCode::OK_200);
  226. EXPECT_EQ(resp.body, content_);
  227. // Verify that Host header was automatically set to "localhost"
  228. EXPECT_EQ(received_host_header, "localhost");
  229. }
  230. #ifndef _WIN32
  231. TEST(SocketStream, wait_writable_UNIX) {
  232. int fds[2];
  233. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  234. const auto asSocketStream = [&](socket_t fd,
  235. std::function<bool(Stream &)> func) {
  236. return detail::process_client_socket(
  237. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  238. };
  239. asSocketStream(fds[0], [&](Stream &s0) {
  240. EXPECT_EQ(s0.socket(), fds[0]);
  241. EXPECT_TRUE(s0.wait_writable());
  242. EXPECT_TRUE(s0.is_peer_alive());
  243. EXPECT_EQ(0, close(fds[1]));
  244. EXPECT_FALSE(s0.is_peer_alive());
  245. return true;
  246. });
  247. EXPECT_EQ(0, close(fds[0]));
  248. }
  249. TEST(SocketStream, wait_writable_INET) {
  250. sockaddr_in addr;
  251. memset(&addr, 0, sizeof(addr));
  252. addr.sin_family = AF_INET;
  253. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  254. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  255. int disconnected_svr_sock = -1;
  256. std::thread svr{[&] {
  257. const int s = socket(AF_INET, SOCK_STREAM, 0);
  258. ASSERT_LE(0, s);
  259. // PORT + 1 is shared with the SSL redirect tests and with
  260. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  261. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  262. // because that happens on a worker thread the ASSERT does not stop the
  263. // test: it runs on and fails at the disconnected_svr_sock check instead.
  264. default_socket_options(s);
  265. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  266. ASSERT_EQ(0, listen(s, 1));
  267. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  268. ASSERT_EQ(0, close(s));
  269. }};
  270. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  271. std::thread cli{[&] {
  272. const int s = socket(AF_INET, SOCK_STREAM, 0);
  273. ASSERT_LE(0, s);
  274. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  275. ASSERT_EQ(0, close(s));
  276. }};
  277. cli.join();
  278. svr.join();
  279. ASSERT_NE(disconnected_svr_sock, -1);
  280. const auto asSocketStream = [&](socket_t fd,
  281. std::function<bool(Stream &)> func) {
  282. return detail::process_client_socket(
  283. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  284. };
  285. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  286. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  287. // wait_writable() returns true because select_write() only checks if the
  288. // send buffer has space. Peer disconnection is detected later by send().
  289. EXPECT_TRUE(ss.wait_writable());
  290. return true;
  291. });
  292. ASSERT_EQ(0, close(disconnected_svr_sock));
  293. }
  294. #endif // #ifndef _WIN32
  295. TEST(SetSocketOptTest, TcpNoDelay) {
  296. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  297. ASSERT_NE(sock, INVALID_SOCKET);
  298. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  299. int val = 0;
  300. socklen_t len = sizeof(val);
  301. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  302. reinterpret_cast<char *>(&val), &len));
  303. EXPECT_NE(val, 0);
  304. detail::close_socket(sock);
  305. }
  306. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  307. // accept() reports failures through WSAGetLastError() on Windows and through
  308. // errno everywhere else. Asking the wrong one is what made the accept loop
  309. // treat every recoverable failure as fatal on Windows.
  310. struct Classification {
  311. bool resource;
  312. bool transient;
  313. };
  314. auto classify = [](int err) {
  315. #ifdef _WIN32
  316. WSASetLastError(err);
  317. #else
  318. errno = err;
  319. #endif
  320. // Read both before asserting: an assertion may clobber the error slot.
  321. Classification c;
  322. c.resource = detail::is_accept_resource_error();
  323. c.transient = detail::is_accept_transient_error();
  324. return c;
  325. };
  326. #ifdef _WIN32
  327. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  328. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  329. WSAECONNRESET, WSAECONNABORTED};
  330. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  331. #else
  332. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  333. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  334. ECONNABORTED};
  335. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  336. #endif
  337. for (auto err : resource_errors) {
  338. const auto c = classify(err);
  339. EXPECT_TRUE(c.resource) << "error " << err;
  340. EXPECT_FALSE(c.transient) << "error " << err;
  341. }
  342. for (auto err : transient_errors) {
  343. const auto c = classify(err);
  344. EXPECT_TRUE(c.transient) << "error " << err;
  345. EXPECT_FALSE(c.resource) << "error " << err;
  346. }
  347. for (auto err : fatal_errors) {
  348. const auto c = classify(err);
  349. EXPECT_FALSE(c.resource) << "error " << err;
  350. EXPECT_FALSE(c.transient) << "error " << err;
  351. }
  352. #ifdef _WIN32
  353. WSASetLastError(0);
  354. #else
  355. errno = 0;
  356. #endif
  357. }
  358. TEST(ClientTest, MoveConstructible) {
  359. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  360. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  361. }
  362. TEST(ClientTest, MoveAssignable) {
  363. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  364. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  365. }
  366. #ifdef _WIN32
  367. TEST(StartupTest, WSAStartup) {
  368. WSADATA wsaData;
  369. int ret = WSAStartup(0x0002, &wsaData);
  370. ASSERT_EQ(0, ret);
  371. }
  372. #endif
  373. TEST(DecodePathTest, PercentCharacter) {
  374. EXPECT_EQ(
  375. decode_path_component(
  376. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  377. U8("descrip=Gastos áéíóúñÑ 6"));
  378. }
  379. TEST(DecodePathTest, PercentCharacterNUL) {
  380. string expected;
  381. expected.push_back('x');
  382. expected.push_back('\0');
  383. expected.push_back('x');
  384. EXPECT_EQ(decode_path_component("x%00x"), expected);
  385. }
  386. TEST(DecodePathTest, UnicodeEncoding) {
  387. // %u0041 = 'A' (1-byte UTF-8)
  388. EXPECT_EQ("A", decode_path_component("%u0041"));
  389. // %u00E9 = 'é' (2-byte UTF-8)
  390. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  391. // %u3042 = 'あ' (3-byte UTF-8)
  392. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  393. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  394. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  395. // %uD800 = surrogate (invalid, silently dropped)
  396. EXPECT_EQ("", decode_path_component("%uD800"));
  397. }
  398. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  399. // A sign or whitespace inside the two-character escape window must not be
  400. // accepted as a valid percent-encoding; the sequence is passed through
  401. // literally, matching decode_uri_component / decode_path_component.
  402. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  403. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  404. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  405. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  406. // Well-formed escapes still decode.
  407. EXPECT_EQ("-", decode_query_component("%2D", false));
  408. EXPECT_EQ("A", decode_query_component("%41", false));
  409. }
  410. TEST(SanitizeFilenameTest, VariousPatterns) {
  411. // Path traversal
  412. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  413. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  414. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  415. // Normal and edge cases
  416. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  417. EXPECT_EQ("filename.txt",
  418. httplib::sanitize_filename("/path/to/filename.txt"));
  419. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  420. EXPECT_EQ("", httplib::sanitize_filename(".."));
  421. EXPECT_EQ("", httplib::sanitize_filename(""));
  422. // Null bytes stripped
  423. EXPECT_EQ("safe.txt",
  424. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  425. // Whitespace-only rejected
  426. EXPECT_EQ("", httplib::sanitize_filename(" "));
  427. }
  428. // Forward declaration (see the base64_encode note below): split builds move the
  429. // definition into httplib.cc, so re-declaring it here lets the test link.
  430. namespace httplib {
  431. namespace detail {
  432. bool is_chunked_transfer_encoding(const Headers &headers);
  433. } // namespace detail
  434. } // namespace httplib
  435. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  436. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  437. auto make = [](std::initializer_list<const char *> lines) {
  438. Headers h;
  439. for (auto te : lines) {
  440. if (te) { h.emplace("Transfer-Encoding", te); }
  441. }
  442. return h;
  443. };
  444. // Sole coding, matched case-insensitively.
  445. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  446. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  448. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  450. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  452. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  453. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  454. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  455. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  456. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  457. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  458. // were received, into one list. Headers preserves that order, so the answer
  459. // is decided by the last coding of the last line and the order the lines
  460. // arrived in is significant.
  461. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  462. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  463. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  464. // The split can fall anywhere in the list.
  465. EXPECT_TRUE(
  466. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  467. EXPECT_FALSE(
  468. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  469. // A trailing line naming no coding leaves the list ending in nothing, so it
  470. // must not inherit the chunked from the line before it.
  471. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  472. }
  473. // Forward declarations (see the base64_encode note below).
  474. namespace httplib {
  475. namespace detail {
  476. bool parse_status_line(const char *line, std::string &version, int &status,
  477. std::string &reason);
  478. std::string file_extension(const std::string &path);
  479. std::string
  480. find_content_type(const std::string &path,
  481. const std::map<std::string, std::string> &user_data,
  482. const std::string &default_content_type);
  483. bool can_compress_content_type(const std::string &content_type);
  484. bool is_prohibited_header_name(const std::string &name);
  485. } // namespace detail
  486. } // namespace httplib
  487. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  488. struct {
  489. const char *line;
  490. const char *version;
  491. int status;
  492. const char *reason;
  493. } cases[] = {
  494. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  495. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  496. // The reason phrase may be empty, or left out along with its space.
  497. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  498. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  499. };
  500. for (const auto &c : cases) {
  501. std::string version;
  502. int status = 0;
  503. std::string reason = "unset";
  504. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  505. << c.line;
  506. EXPECT_EQ(c.version, version);
  507. EXPECT_EQ(c.status, status);
  508. EXPECT_EQ(c.reason, reason);
  509. }
  510. }
  511. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  512. const char *lines[] = {
  513. "HTTP/2 200 OK\r\n",
  514. "HTTP/1.2 200 OK\r\n",
  515. "HTTP/1.1 20 OK\r\n",
  516. "HTTP/1.1 2000 OK\r\n",
  517. "HTTP/1.1 2x0 OK\r\n",
  518. "HTTP/1.1 200 OK\r\n",
  519. "HTTP/1.1 200OK\r\n",
  520. "HTTP/1.1 200 O\rK\r\n",
  521. "HTTP/1.1 200 OK",
  522. "HTTP/1.1 200 OK\r\nX",
  523. "",
  524. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  525. "HTTP/1.1 200 OK\n",
  526. #endif
  527. };
  528. for (auto line : lines) {
  529. std::string version;
  530. int status = 0;
  531. std::string reason;
  532. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  533. << line;
  534. }
  535. }
  536. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  537. // Long enough to overflow the stack when matched with std::regex.
  538. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  539. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  540. std::string version;
  541. int status = 0;
  542. std::string reason;
  543. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  544. EXPECT_EQ(200, status);
  545. EXPECT_EQ(long_reason, reason);
  546. }
  547. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  548. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  549. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  550. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  551. EXPECT_EQ("", detail::file_extension("noext"));
  552. EXPECT_EQ("", detail::file_extension("a."));
  553. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  554. EXPECT_EQ("", detail::file_extension("a.b-c"));
  555. // Long enough to overflow the stack when matched with std::regex.
  556. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  557. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  558. }
  559. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  560. detail::case_ignore::hash hash;
  561. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  562. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  563. // Long enough to overflow the stack if hashed one call per character.
  564. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  565. }
  566. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  567. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  568. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  569. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  570. // Same 26-bit hash as html, svg and js.
  571. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  572. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  573. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  574. }
  575. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  576. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  577. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  578. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  579. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  580. // Same 26-bit hash as application/json.
  581. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  582. }
  583. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  584. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  585. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  586. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  587. // Same 26-bit hash as REMOTE_ADDR.
  588. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  589. }
  590. // Forward declaration: in split builds split.py strips `inline` and moves the
  591. // definition into httplib.cc, so detail::base64_encode is not visible from the
  592. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  593. // in both header-only and split builds.
  594. namespace httplib {
  595. namespace detail {
  596. std::string base64_encode(const std::string &in);
  597. } // namespace detail
  598. } // namespace httplib
  599. TEST(Base64EncodeTest, KnownAnswers) {
  600. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  601. // where the accumulator's top bit is already set before the next shift.
  602. EXPECT_EQ("", detail::base64_encode(""));
  603. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  604. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  605. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  606. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  607. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  608. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  609. // High bytes keep the top bit set across several rounds.
  610. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  611. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  612. }
  613. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  614. string unescapedCharacters = "-_.!~*'()";
  615. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  616. }
  617. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  618. string reservedCharacters = ";,/?:@&=+$";
  619. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  620. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  621. }
  622. TEST(ClientQueryOrder, PreserveOrder) {
  623. // This test reproduces Issue #2259: client may reorder query parameters
  624. // when sending a GET request. The expected behavior is that the client
  625. // preserves the original query string order when the caller supplied it
  626. // as part of the path.
  627. Server svr;
  628. svr.Get("/", [&](const Request &req, Response &res) {
  629. // Echo back the raw target so the test can assert ordering
  630. res.set_content(req.target, "text/plain");
  631. });
  632. std::thread t{[&] { svr.listen(HOST, PORT); }};
  633. auto se = detail::scope_exit([&] {
  634. svr.stop();
  635. t.join();
  636. ASSERT_FALSE(svr.is_running());
  637. });
  638. svr.wait_until_ready();
  639. Client cli(HOST, PORT);
  640. ASSERT_TRUE(cli.is_valid());
  641. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  642. auto res = cli.Get(original);
  643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  644. // Expect the echoed target to exactly match the original path (order
  645. // preserved)
  646. EXPECT_EQ(res->body, original);
  647. }
  648. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  649. string chineseCharacters = U8("中国語");
  650. string russianCharacters = U8("дом");
  651. string brazilianCharacters = U8("óculos");
  652. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  653. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  654. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  655. "%D0%B4%D0%BE%D0%BC");
  656. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  657. }
  658. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  659. string unescapedCharacters = "-_.!~*'()";
  660. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  661. }
  662. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  663. string reservedCharacters = ";,/?:@&=+$";
  664. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  665. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  666. }
  667. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  668. string chineseCharacters = U8("中国語");
  669. string russianCharacters = U8("дом");
  670. string brazilianCharacters = U8("óculos");
  671. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  672. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  673. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  674. "%D0%B4%D0%BE%D0%BC");
  675. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  676. }
  677. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  678. // Issue #2082 use case: encoding path component with ampersand
  679. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  680. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  681. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  682. }
  683. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  684. string unescapedCharacters = "-_.!~*'()";
  685. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  686. }
  687. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  688. string reservedCharacters = ";,/?:@&=+$#";
  689. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  690. }
  691. TEST(EncodeUriTest, TestUTF8Characters) {
  692. string chineseCharacters = U8("中国語");
  693. string russianCharacters = U8("дом");
  694. string brazilianCharacters = U8("óculos");
  695. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  696. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  697. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  698. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  699. }
  700. TEST(EncodeUriTest, TestCompleteUri) {
  701. string uri =
  702. "https://example.com/path/to/resource?query=value&param=test#fragment";
  703. EXPECT_EQ(
  704. httplib::encode_uri(uri),
  705. "https://example.com/path/to/resource?query=value&param=test#fragment");
  706. }
  707. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  708. string uri =
  709. "https://example.com/path with spaces/file name.html?q=hello world";
  710. EXPECT_EQ(httplib::encode_uri(uri),
  711. "https://example.com/path%20with%20spaces/"
  712. "file%20name.html?q=hello%20world");
  713. }
  714. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  715. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  716. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  717. }
  718. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  719. string unescapedCharacters = "-_.!~*'()";
  720. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  721. }
  722. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  723. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  724. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  725. string encodedBrazilian = "%C3%B3culos";
  726. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  727. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  728. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  729. }
  730. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  731. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  732. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  733. "Piri Tommy Villiers - on & on");
  734. }
  735. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  736. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  737. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  738. }
  739. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  740. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  741. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  742. }
  743. TEST(DecodeUriTest, TestUTF8Characters) {
  744. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  745. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  746. string encodedBrazilian = "%C3%B3culos";
  747. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  748. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  749. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  750. }
  751. TEST(DecodeUriTest, TestCompleteUri) {
  752. string encodedUri = "https://example.com/path%20with%20spaces/"
  753. "file%20name.html?q=hello%20world";
  754. EXPECT_EQ(
  755. httplib::decode_uri(encodedUri),
  756. "https://example.com/path with spaces/file name.html?q=hello world");
  757. }
  758. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  759. string original =
  760. "https://example.com/path with spaces/file name.html?q=hello world";
  761. string encoded = httplib::encode_uri(original);
  762. string decoded = httplib::decode_uri(encoded);
  763. EXPECT_EQ(decoded, original);
  764. }
  765. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  766. // decode_uri is the inverse of encode_uri: an escaped reserved character
  767. // stays encoded so it is not promoted into a real delimiter, while
  768. // non-reserved escapes still decode (like JS decodeURI).
  769. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  770. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  771. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  772. "%3F%3A%40%26%3D%2B%24%2C%3B");
  773. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  774. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  775. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  776. "http://example.com/a%2Fb");
  777. // decode_uri_component still decodes the reserved character.
  778. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  779. }
  780. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  781. string original = "Piri Tommy Villiers - on & on";
  782. string encoded = httplib::encode_uri_component(original);
  783. string decoded = httplib::decode_uri_component(encoded);
  784. EXPECT_EQ(decoded, original);
  785. }
  786. TEST(TrimTests, TrimStringTests) {
  787. EXPECT_EQ("abc", detail::trim_copy("abc"));
  788. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  789. EXPECT_TRUE(detail::trim_copy("").empty());
  790. }
  791. TEST(AsciiTest, LocaleIndependentClassification) {
  792. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  793. // which consult the global C locale: std::isalnum(0xC5) can return true
  794. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  795. // helpers must classify every byte by the ASCII grammar alone.
  796. for (int i = 0; i < 256; i++) {
  797. auto c = static_cast<char>(i);
  798. auto is_digit = i >= '0' && i <= '9';
  799. auto is_upper = i >= 'A' && i <= 'Z';
  800. auto is_lower = i >= 'a' && i <= 'z';
  801. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  802. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  803. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  804. << "byte " << i;
  805. }
  806. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  807. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  808. // Non-ASCII bytes must be percent-encoded, never passed through as
  809. // alphanumeric.
  810. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  811. }
  812. TEST(FromCharsTest, Double) {
  813. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  814. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  815. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  816. auto parse = [](const std::string &s, double &v) {
  817. return detail::from_chars(s.data(), s.data() + s.size(), v);
  818. };
  819. double v = -1.0;
  820. // Representative quality values.
  821. EXPECT_EQ(parse("0", v).ec, std::errc{});
  822. EXPECT_DOUBLE_EQ(v, 0.0);
  823. EXPECT_EQ(parse("1", v).ec, std::errc{});
  824. EXPECT_DOUBLE_EQ(v, 1.0);
  825. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  826. EXPECT_DOUBLE_EQ(v, 0.8);
  827. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  828. EXPECT_DOUBLE_EQ(v, 0.001);
  829. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  830. EXPECT_DOUBLE_EQ(v, 1.0);
  831. // A missing integer or fractional part is tolerated.
  832. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  833. EXPECT_DOUBLE_EQ(v, 0.5);
  834. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  835. EXPECT_DOUBLE_EQ(v, 5.0);
  836. // Values outside [0, 1] still parse; the caller range-checks them.
  837. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  838. EXPECT_DOUBLE_EQ(v, 123.456);
  839. // Stops at the first byte that is not part of the number and reports where.
  840. std::string trailing = "0.9, text/html";
  841. auto r = parse(trailing, v);
  842. EXPECT_EQ(r.ec, std::errc{});
  843. EXPECT_DOUBLE_EQ(v, 0.9);
  844. EXPECT_EQ(*r.ptr, ',');
  845. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  846. // outright, and an 'e'/'E' simply ends the number.
  847. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  848. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  849. std::string exp_input = "1.5e3";
  850. r = parse(exp_input, v);
  851. EXPECT_EQ(r.ec, std::errc{});
  852. EXPECT_DOUBLE_EQ(v, 1.5);
  853. EXPECT_EQ(*r.ptr, 'e');
  854. // Invalid inputs.
  855. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  856. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  857. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  858. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  859. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  860. // Pathological but well-formed inputs must stay bounded (no overflow, no
  861. // out-of-bounds table access) and stay within [0, 1] for the caller.
  862. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  863. std::errc{});
  864. EXPECT_DOUBLE_EQ(v, 0.0);
  865. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  866. std::errc{});
  867. EXPECT_GE(v, 0.0);
  868. EXPECT_LE(v, 1.0);
  869. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  870. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  871. }
  872. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  873. // Simple case without quality values
  874. std::vector<std::string> result1;
  875. EXPECT_TRUE(detail::parse_accept_header(
  876. "text/html,application/json,text/plain", result1));
  877. EXPECT_EQ(result1.size(), 3U);
  878. EXPECT_EQ(result1[0], "text/html");
  879. EXPECT_EQ(result1[1], "application/json");
  880. EXPECT_EQ(result1[2], "text/plain");
  881. // With quality values
  882. std::vector<std::string> result2;
  883. EXPECT_TRUE(detail::parse_accept_header(
  884. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  885. EXPECT_EQ(result2.size(), 3U);
  886. EXPECT_EQ(result2[0], "application/json"); // highest q value
  887. EXPECT_EQ(result2[1], "text/html");
  888. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  889. }
  890. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  891. // Mixed with and without quality values
  892. std::vector<std::string> result;
  893. EXPECT_TRUE(detail::parse_accept_header(
  894. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  895. EXPECT_EQ(result.size(), 3U);
  896. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  897. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  898. EXPECT_EQ(result[2], "application/json"); // q=0.5
  899. }
  900. TEST(ParseAcceptHeaderTest, EdgeCases) {
  901. // Empty header
  902. std::vector<std::string> empty_result;
  903. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  904. EXPECT_TRUE(empty_result.empty());
  905. // Single type
  906. std::vector<std::string> single_result;
  907. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  908. EXPECT_EQ(single_result.size(), 1U);
  909. EXPECT_EQ(single_result[0], "application/json");
  910. // Wildcard types
  911. std::vector<std::string> wildcard_result;
  912. EXPECT_TRUE(detail::parse_accept_header(
  913. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  914. EXPECT_EQ(wildcard_result.size(), 3U);
  915. EXPECT_EQ(wildcard_result[0], "application/json");
  916. EXPECT_EQ(wildcard_result[1], "text/*");
  917. EXPECT_EQ(wildcard_result[2], "*/*");
  918. }
  919. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  920. // Common browser Accept header
  921. std::vector<std::string> browser_result;
  922. EXPECT_TRUE(
  923. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  924. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  925. browser_result));
  926. EXPECT_EQ(browser_result.size(), 6U);
  927. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  928. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  929. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  930. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  931. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  932. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  933. // API client header
  934. std::vector<std::string> api_result;
  935. EXPECT_TRUE(detail::parse_accept_header(
  936. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  937. api_result));
  938. EXPECT_EQ(api_result.size(), 3U);
  939. EXPECT_EQ(api_result[0], "application/json");
  940. EXPECT_EQ(api_result[1], "application/xml");
  941. EXPECT_EQ(api_result[2], "text/plain");
  942. }
  943. TEST(ParseAcceptHeaderTest, SpecialCases) {
  944. // Quality value with 3 decimal places
  945. std::vector<std::string> decimal_result;
  946. EXPECT_TRUE(detail::parse_accept_header(
  947. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  948. EXPECT_EQ(decimal_result.size(), 2U);
  949. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  950. EXPECT_EQ(decimal_result[1], "text/html");
  951. // Zero quality (should still be included but with lowest priority)
  952. std::vector<std::string> zero_q_result;
  953. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  954. zero_q_result));
  955. EXPECT_EQ(zero_q_result.size(), 2U);
  956. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  957. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  958. // No spaces around commas
  959. std::vector<std::string> no_space_result;
  960. EXPECT_TRUE(detail::parse_accept_header(
  961. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  962. no_space_result));
  963. EXPECT_EQ(no_space_result.size(), 3U);
  964. EXPECT_EQ(no_space_result[0], "text/html");
  965. EXPECT_EQ(no_space_result[1], "application/json");
  966. EXPECT_EQ(no_space_result[2], "text/plain");
  967. }
  968. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  969. // Quality values always use '.' as the decimal separator, so parsing must
  970. // not depend on the process locale. An embedding application may have
  971. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  972. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  973. std::string saved = cur ? cur : "C";
  974. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  975. "fr_FR.UTF-8"};
  976. bool switched = false;
  977. for (const auto loc : comma_locales) {
  978. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  979. std::localeconv()->decimal_point[0] == ',') {
  980. switched = true;
  981. break;
  982. }
  983. }
  984. if (!switched) {
  985. std::setlocale(LC_NUMERIC, saved.c_str());
  986. GTEST_SKIP() << "no comma-decimal locale available on this host";
  987. }
  988. // The higher-weighted type appears later in the list, so a correct parse
  989. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  990. // sensitive parse reads both weights as 0 and leaves the original order.
  991. std::vector<std::string> result;
  992. EXPECT_TRUE(detail::parse_accept_header(
  993. "application/json;q=0.1,text/html;q=0.9", result));
  994. ASSERT_EQ(result.size(), 2U);
  995. EXPECT_EQ(result[0], "text/html");
  996. EXPECT_EQ(result[1], "application/json");
  997. std::setlocale(LC_NUMERIC, saved.c_str());
  998. }
  999. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1000. std::vector<std::string> result;
  1001. // Invalid quality value (> 1.0)
  1002. EXPECT_FALSE(
  1003. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1004. // Invalid quality value (< 0.0)
  1005. EXPECT_FALSE(
  1006. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1007. // Invalid quality value (not a number)
  1008. EXPECT_FALSE(detail::parse_accept_header(
  1009. "text/html;q=invalid,application/json", result));
  1010. // A valid numeric prefix does not make the entire quality value valid.
  1011. EXPECT_FALSE(detail::parse_accept_header(
  1012. "text/html;q=0.5junk,application/json", result));
  1013. // Empty quality value
  1014. EXPECT_FALSE(
  1015. detail::parse_accept_header("text/html;q=,application/json", result));
  1016. // Invalid media type format (no slash and not wildcard)
  1017. EXPECT_FALSE(
  1018. detail::parse_accept_header("invalidtype,application/json", result));
  1019. // Valid cases should still work
  1020. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1021. EXPECT_EQ(result.size(), 1U);
  1022. EXPECT_EQ(result[0], "*/*");
  1023. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1024. EXPECT_EQ(result.size(), 1U);
  1025. EXPECT_EQ(result[0], "*");
  1026. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1027. EXPECT_EQ(result.size(), 1U);
  1028. EXPECT_EQ(result[0], "text/*");
  1029. }
  1030. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1031. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1032. // and must not be answered with 400 Bad Request.
  1033. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1034. struct {
  1035. const char *value;
  1036. std::vector<std::string> expected;
  1037. } cases[] = {
  1038. {",application/json", {"application/json"}},
  1039. {"text/html,", {"text/html"}},
  1040. {"text/html,,*/*", {"text/html", "*/*"}},
  1041. // An empty element may be spelled with whitespace in it
  1042. {"text/html, , application/json", {"text/html", "application/json"}},
  1043. // Nothing but empty elements is an empty list, which means the same
  1044. // thing as no Accept header at all
  1045. {",,,", {}},
  1046. // Quality values still apply across ignored empty elements
  1047. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1048. };
  1049. for (const auto &c : cases) {
  1050. std::vector<std::string> result;
  1051. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1052. << "value: " << c.value;
  1053. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1054. }
  1055. // An invalid entry is still rejected when empty elements surround it
  1056. std::vector<std::string> result;
  1057. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1058. }
  1059. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1060. // or ';' inside one does not end the list element or the parameter. Section
  1061. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1062. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1063. struct {
  1064. const char *value;
  1065. std::vector<std::string> expected;
  1066. } cases[] = {
  1067. {"text/html;profile=\"a,b\",application/json",
  1068. {"text/html", "application/json"}},
  1069. // A "q=" inside a quoted value is not the weight
  1070. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1071. {"text/html", "application/json"}},
  1072. // The weight after a quoted value still applies
  1073. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1074. {"application/json", "text/html"}},
  1075. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1076. {"application/json", "text/html"}},
  1077. {"text/html;profile=\"a\\\"b\",application/json",
  1078. {"text/html", "application/json"}},
  1079. // An escaped backslash does not escape the '"' after it
  1080. {"text/html;profile=\"a\\\\\",application/json",
  1081. {"text/html", "application/json"}},
  1082. };
  1083. for (const auto &c : cases) {
  1084. std::vector<std::string> result;
  1085. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1086. << "value: " << c.value;
  1087. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1088. }
  1089. }
  1090. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1091. Server svr;
  1092. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1093. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1094. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1095. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1096. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1097. res.set_content("ok", "text/plain");
  1098. });
  1099. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1100. EXPECT_TRUE(false);
  1101. res.set_content("bad request", "text/plain");
  1102. });
  1103. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1104. auto se = detail::scope_exit([&] {
  1105. svr.stop();
  1106. listen_thread.join();
  1107. ASSERT_FALSE(svr.is_running());
  1108. });
  1109. svr.wait_until_ready();
  1110. Client cli("localhost", PORT);
  1111. {
  1112. auto res = cli.Get(
  1113. "/accept_ok",
  1114. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1116. EXPECT_EQ(StatusCode::OK_200, res->status);
  1117. }
  1118. {
  1119. auto res = cli.Get("/accept_bad_request",
  1120. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1122. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1123. }
  1124. }
  1125. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1126. Server svr;
  1127. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1128. res.set_content("ok", "text/plain");
  1129. });
  1130. std::atomic<int> start_count{0};
  1131. std::atomic<bool> running_when_called{false};
  1132. svr.set_start_handler([&]() {
  1133. running_when_called = svr.is_running();
  1134. start_count++;
  1135. });
  1136. auto port = svr.bind_to_any_port(HOST);
  1137. std::thread t([&]() { svr.listen_after_bind(); });
  1138. auto se = detail::scope_exit([&] {
  1139. svr.stop();
  1140. t.join();
  1141. ASSERT_FALSE(svr.is_running());
  1142. });
  1143. svr.wait_until_ready();
  1144. // A successful request proves the accept loop is running, which the start
  1145. // handler precedes; so by now the handler must have run exactly once.
  1146. Client cli(HOST, port);
  1147. cli.set_connection_timeout(std::chrono::seconds(5));
  1148. auto res = cli.Get("/");
  1149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1150. EXPECT_EQ(StatusCode::OK_200, res->status);
  1151. EXPECT_EQ(1, start_count.load());
  1152. EXPECT_TRUE(running_when_called.load());
  1153. }
  1154. TEST(DivideTest, DivideStringTests) {
  1155. auto divide = [](const std::string &str, char d) {
  1156. std::string lhs;
  1157. std::string rhs;
  1158. detail::divide(str, d,
  1159. [&](const char *lhs_data, std::size_t lhs_size,
  1160. const char *rhs_data, std::size_t rhs_size) {
  1161. lhs.assign(lhs_data, lhs_size);
  1162. rhs.assign(rhs_data, rhs_size);
  1163. });
  1164. return std::make_pair(std::move(lhs), std::move(rhs));
  1165. };
  1166. {
  1167. const auto res = divide("", '=');
  1168. EXPECT_EQ(res.first, "");
  1169. EXPECT_EQ(res.second, "");
  1170. }
  1171. {
  1172. const auto res = divide("=", '=');
  1173. EXPECT_EQ(res.first, "");
  1174. EXPECT_EQ(res.second, "");
  1175. }
  1176. {
  1177. const auto res = divide(" ", '=');
  1178. EXPECT_EQ(res.first, " ");
  1179. EXPECT_EQ(res.second, "");
  1180. }
  1181. {
  1182. const auto res = divide("a", '=');
  1183. EXPECT_EQ(res.first, "a");
  1184. EXPECT_EQ(res.second, "");
  1185. }
  1186. {
  1187. const auto res = divide("a=", '=');
  1188. EXPECT_EQ(res.first, "a");
  1189. EXPECT_EQ(res.second, "");
  1190. }
  1191. {
  1192. const auto res = divide("=b", '=');
  1193. EXPECT_EQ(res.first, "");
  1194. EXPECT_EQ(res.second, "b");
  1195. }
  1196. {
  1197. const auto res = divide("a=b", '=');
  1198. EXPECT_EQ(res.first, "a");
  1199. EXPECT_EQ(res.second, "b");
  1200. }
  1201. {
  1202. const auto res = divide("a=b=", '=');
  1203. EXPECT_EQ(res.first, "a");
  1204. EXPECT_EQ(res.second, "b=");
  1205. }
  1206. {
  1207. const auto res = divide("a=b=c", '=');
  1208. EXPECT_EQ(res.first, "a");
  1209. EXPECT_EQ(res.second, "b=c");
  1210. }
  1211. }
  1212. TEST(SplitTest, ParseQueryString) {
  1213. string s = "key1=val1&key2=val2&key3=val3";
  1214. Params dic;
  1215. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1216. [&](const char *b, const char *e) {
  1217. string key, val;
  1218. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1219. if (key.empty()) {
  1220. key.assign(b2, e2);
  1221. } else {
  1222. val.assign(b2, e2);
  1223. }
  1224. });
  1225. dic.emplace(key, val);
  1226. });
  1227. EXPECT_EQ("val1", dic.find("key1")->second);
  1228. EXPECT_EQ("val2", dic.find("key2")->second);
  1229. EXPECT_EQ("val3", dic.find("key3")->second);
  1230. }
  1231. TEST(SplitTest, ParseInvalidQueryTests) {
  1232. {
  1233. string s = " ";
  1234. Params dict;
  1235. detail::parse_query_text(s, dict);
  1236. EXPECT_TRUE(dict.empty());
  1237. }
  1238. {
  1239. string s = " = =";
  1240. Params dict;
  1241. detail::parse_query_text(s, dict);
  1242. EXPECT_TRUE(dict.empty());
  1243. }
  1244. }
  1245. TEST(ParseQueryTest, ParseQueryString) {
  1246. {
  1247. std::string s = "key1=val1&key2=val2&key3=val3";
  1248. Params dic;
  1249. detail::parse_query_text(s, dic);
  1250. EXPECT_EQ("val1", dic.find("key1")->second);
  1251. EXPECT_EQ("val2", dic.find("key2")->second);
  1252. EXPECT_EQ("val3", dic.find("key3")->second);
  1253. }
  1254. {
  1255. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1256. Params dic;
  1257. detail::parse_query_text(s, dic);
  1258. EXPECT_EQ("", dic.find("key1")->second);
  1259. EXPECT_EQ("val1", dic.find("key2")->second);
  1260. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1261. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1262. }
  1263. }
  1264. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1265. Params dic;
  1266. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1267. dic.emplace("key1", "val1");
  1268. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1269. dic.emplace("key2", "val2");
  1270. dic.emplace("key3", "val3");
  1271. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1272. }
  1273. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1274. Params params;
  1275. params.emplace("a", "1");
  1276. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1277. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1278. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1279. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1280. // Long enough to overflow the stack when matched with std::regex.
  1281. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1282. EXPECT_EQ("/p?" + long_query + "&a=1",
  1283. append_query_params("/p?" + long_query, params));
  1284. }
  1285. // Joins every entry of a Headers or Params into "key=value " so a whole
  1286. // traversal can be compared in one assertion. Both are instantiations of the
  1287. // same insertion-ordered container, so one helper serves both.
  1288. template <typename Map> static std::string entries_to_string(const Map &m) {
  1289. std::string s;
  1290. for (const auto &entry : m) {
  1291. s += entry.first + "=" + entry.second + " ";
  1292. }
  1293. return s;
  1294. }
  1295. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1296. // Params used to be a std::multimap, which sorted by name and handed the
  1297. // caller's query back alphabetised. A client signing its query string could
  1298. // not reproduce the order it asked for.
  1299. Params dic;
  1300. dic.emplace("zulu", "1");
  1301. dic.emplace("alpha", "2");
  1302. dic.emplace("mike", "3");
  1303. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1304. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1305. }
  1306. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1307. Params dic;
  1308. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1309. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1310. }
  1311. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1312. Request req;
  1313. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1314. req.params);
  1315. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1316. EXPECT_EQ("first", req.get_param_value("tag"));
  1317. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1318. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1319. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1320. EXPECT_EQ("", req.get_param_value("tag", 3));
  1321. }
  1322. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1323. // Params shares its container with Headers, which matches field names
  1324. // case-insensitively. Parameter names must not pick that up.
  1325. Params dic;
  1326. dic.emplace("Key", "upper");
  1327. dic.emplace("key", "lower");
  1328. EXPECT_EQ(2U, dic.size());
  1329. EXPECT_EQ(1U, dic.count("Key"));
  1330. EXPECT_EQ(1U, dic.count("key"));
  1331. EXPECT_EQ("upper", dic.find("Key")->second);
  1332. EXPECT_EQ("lower", dic.find("key")->second);
  1333. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1334. }
  1335. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1336. Server svr;
  1337. std::string order;
  1338. svr.Get("/order", [&](const Request &req, Response &res) {
  1339. order = entries_to_string(req.params);
  1340. res.set_content("ok", "text/plain");
  1341. });
  1342. auto port = svr.bind_to_any_port(HOST);
  1343. thread t = thread([&] { svr.listen_after_bind(); });
  1344. auto se = detail::scope_exit([&] {
  1345. svr.stop();
  1346. t.join();
  1347. ASSERT_FALSE(svr.is_running());
  1348. });
  1349. svr.wait_until_ready();
  1350. Client cli(HOST, port);
  1351. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1352. ASSERT_TRUE(res);
  1353. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1354. }
  1355. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1356. Server svr;
  1357. std::string field_order, file_order;
  1358. svr.Post("/order", [&](const Request &req, Response &res) {
  1359. for (const auto &field : req.form.fields) {
  1360. field_order += field.first + "=" + field.second.content + " ";
  1361. }
  1362. for (const auto &file : req.form.files) {
  1363. file_order += file.first + "=" + file.second.filename + " ";
  1364. }
  1365. res.set_content("ok", "text/plain");
  1366. });
  1367. auto port = svr.bind_to_any_port(HOST);
  1368. thread t = thread([&] { svr.listen_after_bind(); });
  1369. auto se = detail::scope_exit([&] {
  1370. svr.stop();
  1371. t.join();
  1372. ASSERT_FALSE(svr.is_running());
  1373. });
  1374. svr.wait_until_ready();
  1375. UploadFormDataItems items = {
  1376. {"zulu", "1", "", ""},
  1377. {"alpha", "2", "", ""},
  1378. {"mike", "3", "", ""},
  1379. {"zebra", "z", "z.txt", "text/plain"},
  1380. {"apple", "a", "a.txt", "text/plain"},
  1381. };
  1382. Client cli(HOST, port);
  1383. auto res = cli.Post("/order", items);
  1384. ASSERT_TRUE(res);
  1385. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1386. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1387. }
  1388. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1389. Server svr;
  1390. std::vector<std::string> values;
  1391. std::string first, second, out_of_range, order;
  1392. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1393. values = req.form.get_fields("tag");
  1394. first = req.form.get_field("tag", 0);
  1395. second = req.form.get_field("tag", 1);
  1396. out_of_range = req.form.get_field("tag", 2);
  1397. for (const auto &field : req.form.fields) {
  1398. order += field.first + "=" + field.second.content + " ";
  1399. }
  1400. res.set_content("ok", "text/plain");
  1401. });
  1402. auto port = svr.bind_to_any_port(HOST);
  1403. thread t = thread([&] { svr.listen_after_bind(); });
  1404. auto se = detail::scope_exit([&] {
  1405. svr.stop();
  1406. t.join();
  1407. ASSERT_FALSE(svr.is_running());
  1408. });
  1409. svr.wait_until_ready();
  1410. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1411. // not adjacent in the container.
  1412. UploadFormDataItems items = {
  1413. {"tag", "first", "", ""},
  1414. {"other", "x", "", ""},
  1415. {"tag", "second", "", ""},
  1416. };
  1417. Client cli(HOST, port);
  1418. auto res = cli.Post("/repeated", items);
  1419. ASSERT_TRUE(res);
  1420. ASSERT_EQ(2U, values.size());
  1421. EXPECT_EQ("first", values[0]);
  1422. EXPECT_EQ("second", values[1]);
  1423. EXPECT_EQ("first", first);
  1424. EXPECT_EQ("second", second);
  1425. // std::multimap already kept entries sharing a name in insertion order, so
  1426. // everything above passes without this change too. The whole traversal is
  1427. // what tells the two apart: sorting by name would hoist "other" to the front
  1428. // and the two "tag" parts would end up adjacent.
  1429. EXPECT_EQ("tag=first other=x tag=second ", order);
  1430. // Advancing past the last entry of a name used to run off the container;
  1431. // the container's saturating increment makes it return the default instead.
  1432. EXPECT_EQ("", out_of_range);
  1433. }
  1434. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1435. // Server::read_content() keeps a FormFields::iterator alive across the
  1436. // content callbacks that fill the part it points at. The container is
  1437. // vector-backed, so a later emplace can reallocate and invalidate an older
  1438. // iterator; 64 parts grow the vector through seven reallocations, which
  1439. // checks that every part's content still lands in its own entry.
  1440. const size_t part_count = 64;
  1441. // One formula for both the parts sent and the values expected back, so the
  1442. // two cannot drift apart.
  1443. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1444. auto content_of = [](size_t i) {
  1445. return std::string(64, static_cast<char>('a' + (i % 26)));
  1446. };
  1447. Server svr;
  1448. std::vector<std::pair<std::string, std::string>> received;
  1449. svr.Post("/many", [&](const Request &req, Response &res) {
  1450. for (const auto &field : req.form.fields) {
  1451. received.emplace_back(field.first, field.second.content);
  1452. }
  1453. res.set_content("ok", "text/plain");
  1454. });
  1455. auto port = svr.bind_to_any_port(HOST);
  1456. thread t = thread([&] { svr.listen_after_bind(); });
  1457. auto se = detail::scope_exit([&] {
  1458. svr.stop();
  1459. t.join();
  1460. ASSERT_FALSE(svr.is_running());
  1461. });
  1462. svr.wait_until_ready();
  1463. UploadFormDataItems items;
  1464. for (size_t i = 0; i < part_count; i++) {
  1465. items.push_back({name_of(i), content_of(i), "", ""});
  1466. }
  1467. Client cli(HOST, port);
  1468. auto res = cli.Post("/many", items);
  1469. ASSERT_TRUE(res);
  1470. ASSERT_EQ(part_count, received.size());
  1471. for (size_t i = 0; i < part_count; i++) {
  1472. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1473. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1474. }
  1475. }
  1476. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1477. string content_type = "multipart/form-data; boundary=something";
  1478. string boundary;
  1479. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1480. EXPECT_TRUE(ret);
  1481. EXPECT_EQ(boundary, "something");
  1482. }
  1483. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1484. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1485. string boundary;
  1486. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1487. EXPECT_TRUE(ret);
  1488. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1489. }
  1490. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1491. string content_type =
  1492. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1493. string boundary;
  1494. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1495. EXPECT_TRUE(ret);
  1496. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1497. }
  1498. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1499. string content_type =
  1500. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1501. string boundary;
  1502. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1503. EXPECT_TRUE(ret);
  1504. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1505. }
  1506. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1507. const string boundary(70, 'a');
  1508. string content_type = "multipart/form-data; boundary=" + boundary;
  1509. string parsed;
  1510. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1511. EXPECT_TRUE(ret);
  1512. EXPECT_EQ(parsed, boundary);
  1513. }
  1514. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1515. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1516. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1517. string parsed;
  1518. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1519. EXPECT_FALSE(ret);
  1520. }
  1521. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1522. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1523. // is 72 characters on the wire and still valid.
  1524. const string boundary(70, 'a');
  1525. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1526. string parsed;
  1527. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1528. EXPECT_EQ(parsed, boundary);
  1529. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1530. parsed.clear();
  1531. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1532. }
  1533. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1534. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1535. // The parameter parser must not treat that '=' as the key/value separator.
  1536. string content_type =
  1537. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1538. "charset=UTF-8";
  1539. string parsed;
  1540. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1541. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1542. }
  1543. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1544. // A ';' inside the quoted-string is part of the value, not a parameter
  1545. // separator, so it must not truncate the boundary.
  1546. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1547. string parsed;
  1548. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1549. EXPECT_EQ(parsed, "a;b");
  1550. }
  1551. TEST(ParseDispositionParamsTest, QuotedValues) {
  1552. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1553. // ';' and '=' are ordinary characters inside one.
  1554. struct {
  1555. const char *value;
  1556. std::vector<std::pair<const char *, const char *>> expected;
  1557. } cases[] = {
  1558. {"name=\"file1\"; filename=\"a.txt\"",
  1559. {{"name", "file1"}, {"filename", "a.txt"}}},
  1560. // Whitespace around '=' and ';' is still trimmed
  1561. {"name=\"file2\" ;filename = \"a.html\"",
  1562. {{"name", "file2"}, {"filename", "a.html"}}},
  1563. // '=' inside the value used to leave only the text after the last one
  1564. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1565. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1566. {"name=\"x=y\"", {{"name", "x=y"}}},
  1567. // ';' inside the value used to truncate the pair and leave a bogus one
  1568. {"name=\"file3\"; filename=\"a;b.txt\"",
  1569. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1570. // An unquoted value keeps working, and so does filename*
  1571. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1572. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1573. // A parameter with no key is dropped rather than turned into one whose
  1574. // key is the value
  1575. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1576. // An escaped quote does not end the value
  1577. {"name=\"a\\\"; filename=evil.php\"",
  1578. {{"name", "a\"; filename=evil.php"}}},
  1579. // Other backslashes, as in a Windows path, are kept
  1580. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1581. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1582. };
  1583. for (const auto &c : cases) {
  1584. Params params;
  1585. detail::parse_disposition_params(c.value, params);
  1586. for (const auto &kv : c.expected) {
  1587. auto it = params.find(kv.first);
  1588. ASSERT_NE(it, params.end())
  1589. << "value: " << c.value << ", key: " << kv.first;
  1590. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1591. }
  1592. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1593. }
  1594. }
  1595. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1596. Server svr;
  1597. std::string filename;
  1598. std::string content;
  1599. svr.Post("/upload", [&](const Request &req, Response &) {
  1600. const auto &file = req.form.get_file("file");
  1601. filename = file.filename;
  1602. content = file.content;
  1603. });
  1604. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1605. auto se = detail::scope_exit([&] {
  1606. svr.stop();
  1607. thread.join();
  1608. ASSERT_FALSE(svr.is_running());
  1609. });
  1610. svr.wait_until_ready();
  1611. std::string body = "--B\r\n"
  1612. "Content-Disposition: form-data; name=\"file\"; "
  1613. "filename=\"a.txt\"\r\n"
  1614. "Content-Type: text/plain\r\n"
  1615. "\r\n"
  1616. "hello\r\n"
  1617. "--B--\r\n";
  1618. Client cli(HOST, PORT);
  1619. auto res = cli.Post(
  1620. "/upload",
  1621. [&](size_t offset, DataSink &sink) {
  1622. if (offset < body.size()) {
  1623. sink.write(&body[offset], 1);
  1624. } else {
  1625. sink.done();
  1626. }
  1627. return true;
  1628. },
  1629. "multipart/form-data; boundary=B");
  1630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1631. EXPECT_EQ(StatusCode::OK_200, res->status);
  1632. EXPECT_EQ("a.txt", filename);
  1633. EXPECT_EQ("hello", content);
  1634. }
  1635. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1636. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1637. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1638. Server svr;
  1639. std::string field_value, file_name, file_filename;
  1640. bool has_field = false, has_file = false;
  1641. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1642. has_field = req.form.has_field("x=y");
  1643. field_value = req.form.get_field("x=y");
  1644. has_file = req.form.has_file("file1");
  1645. const auto &file = req.form.get_file("file1");
  1646. file_name = file.name;
  1647. file_filename = file.filename;
  1648. res.set_content("ok", "text/plain");
  1649. });
  1650. auto port = svr.bind_to_any_port(HOST);
  1651. thread t = thread([&] { svr.listen_after_bind(); });
  1652. auto se = detail::scope_exit([&] {
  1653. svr.stop();
  1654. t.join();
  1655. ASSERT_FALSE(svr.is_running());
  1656. });
  1657. svr.wait_until_ready();
  1658. UploadFormDataItems items = {
  1659. {"x=y", "field-value", "", ""},
  1660. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1661. };
  1662. Client cli(HOST, port);
  1663. auto res = cli.Post("/quoted", items);
  1664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1665. ASSERT_EQ(StatusCode::OK_200, res->status);
  1666. EXPECT_TRUE(has_field);
  1667. EXPECT_EQ("field-value", field_value);
  1668. EXPECT_TRUE(has_file);
  1669. EXPECT_EQ("file1", file_name);
  1670. EXPECT_EQ("a;b=report.pdf", file_filename);
  1671. }
  1672. TEST(GetHeaderValueTest, DefaultValue) {
  1673. Headers headers = {{"Dummy", "Dummy"}};
  1674. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1675. EXPECT_STREQ("text/plain", val);
  1676. }
  1677. TEST(GetHeaderValueTest, DefaultValueInt) {
  1678. Headers headers = {{"Dummy", "Dummy"}};
  1679. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1680. EXPECT_EQ(100ull, val);
  1681. }
  1682. TEST(GetHeaderValueTest, RegularValue) {
  1683. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1684. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1685. EXPECT_STREQ("text/html", val);
  1686. }
  1687. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1688. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1689. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1690. EXPECT_STREQ("text/html", val);
  1691. }
  1692. TEST(GetHeaderValueTest, SetContent) {
  1693. Response res;
  1694. res.set_content("html", "text/html");
  1695. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1696. res.set_content("text", "text/plain");
  1697. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1698. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1699. }
  1700. TEST(GetHeaderValueTest, RegularValueInt) {
  1701. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1702. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1703. EXPECT_EQ(100ull, val);
  1704. }
  1705. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1706. Headers headers = {{"Content-Length", "x"}};
  1707. auto is_invalid_value = false;
  1708. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1709. is_invalid_value);
  1710. EXPECT_EQ(0ull, val);
  1711. EXPECT_TRUE(is_invalid_value);
  1712. }
  1713. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1714. // An all-digit value that overflows size_t must be reported as invalid, not
  1715. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1716. // a large length to a small one on 32-bit builds, leaving the framing length
  1717. // wrong while is_invalid_value stayed false.
  1718. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1719. auto is_invalid_value = false;
  1720. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1721. is_invalid_value);
  1722. EXPECT_TRUE(is_invalid_value);
  1723. // A well-formed length is unaffected.
  1724. Headers ok = {{"Content-Length", "1234"}};
  1725. is_invalid_value = false;
  1726. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1727. is_invalid_value);
  1728. EXPECT_EQ(1234ull, val);
  1729. EXPECT_FALSE(is_invalid_value);
  1730. }
  1731. TEST(GetHeaderValueTest, Range) {
  1732. {
  1733. Headers headers = {make_range_header({{1, -1}})};
  1734. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1735. EXPECT_STREQ("bytes=1-", val);
  1736. }
  1737. {
  1738. Headers headers = {make_range_header({{-1, 1}})};
  1739. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1740. EXPECT_STREQ("bytes=-1", val);
  1741. }
  1742. {
  1743. Headers headers = {make_range_header({{1, 10}})};
  1744. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1745. EXPECT_STREQ("bytes=1-10", val);
  1746. }
  1747. {
  1748. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1749. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1750. EXPECT_STREQ("bytes=1-10, 100-", val);
  1751. }
  1752. {
  1753. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1754. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1755. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1756. }
  1757. {
  1758. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1759. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1760. EXPECT_STREQ("bytes=0-0, -1", val);
  1761. }
  1762. }
  1763. TEST(BearerTokenAuthTest, SchemeValidation) {
  1764. // A value shorter than "Bearer " must not throw from the fixed-length
  1765. // substr, and a non-Bearer scheme must not be reported as a token.
  1766. struct {
  1767. const char *value;
  1768. const char *expected;
  1769. } cases[] = {
  1770. {"x", ""},
  1771. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1772. {"Bearer abc123", "abc123"},
  1773. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1774. };
  1775. for (const auto &c : cases) {
  1776. Request req;
  1777. req.set_header("Authorization", c.value);
  1778. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1779. }
  1780. }
  1781. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1782. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1783. // to depend on the standard library (libstdc++ handed back duplicates in
  1784. // reverse insertion order, libc++ in insertion order).
  1785. Request req;
  1786. req.set_header("Accept-Encoding", "gzip");
  1787. req.set_header("Accept-Encoding", "deflate");
  1788. req.set_header("Accept-Encoding", "br");
  1789. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1790. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1791. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1792. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1793. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1794. }
  1795. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1796. Request req;
  1797. req.set_header("X-Test", "only");
  1798. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1799. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1800. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1801. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1802. }
  1803. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1804. Request req;
  1805. req.set_header("X-First", "1");
  1806. req.set_header("X-Test", "2");
  1807. req.params.emplace("first", "1");
  1808. req.params.emplace("test", "2");
  1809. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1810. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1811. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1812. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1813. // The second one is negative when read as a signed value
  1814. const auto max_id = (std::numeric_limits<size_t>::max)();
  1815. for (auto id : {max_id / 2, max_id}) {
  1816. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1817. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1818. EXPECT_EQ("", req.get_param_value("test", id));
  1819. EXPECT_EQ("", req.form.get_field("test", id));
  1820. EXPECT_EQ("", req.form.get_file("test", id).content);
  1821. }
  1822. }
  1823. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1824. Headers headers;
  1825. headers.emplace("Host", "example.com");
  1826. headers.emplace("Accept-Encoding", "gzip");
  1827. headers.emplace("User-Agent", "test");
  1828. headers.emplace("Accept-Encoding", "deflate");
  1829. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1830. "Accept-Encoding=deflate ",
  1831. entries_to_string(headers));
  1832. }
  1833. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1834. Headers headers = {{"Content-Type", "text/html"},
  1835. {"CONTENT-TYPE", "text/xml"}};
  1836. EXPECT_EQ(2U, headers.count("content-type"));
  1837. auto it = headers.find("content-type");
  1838. ASSERT_TRUE(it != headers.end());
  1839. EXPECT_EQ("text/html", it->second);
  1840. }
  1841. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1842. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1843. // drop only those fields and leave everything positioned between them.
  1844. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1845. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1846. auto rng = headers.equal_range("a");
  1847. headers.erase(rng.first, rng.second);
  1848. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1849. }
  1850. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1851. Headers headers = {
  1852. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1853. EXPECT_EQ(3U, headers.erase("A"));
  1854. EXPECT_EQ(0U, headers.count("A"));
  1855. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1856. }
  1857. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1858. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1859. headers.emplace_front("Host", "example.com");
  1860. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1861. entries_to_string(headers));
  1862. }
  1863. TEST(ParseHeaderValueTest, Range) {
  1864. {
  1865. Ranges ranges;
  1866. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1867. EXPECT_TRUE(ret);
  1868. EXPECT_EQ(1u, ranges.size());
  1869. EXPECT_EQ(1u, ranges[0].first);
  1870. EXPECT_EQ(-1, ranges[0].second);
  1871. }
  1872. {
  1873. Ranges ranges;
  1874. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1875. EXPECT_TRUE(ret);
  1876. EXPECT_EQ(1u, ranges.size());
  1877. EXPECT_EQ(-1, ranges[0].first);
  1878. EXPECT_EQ(1u, ranges[0].second);
  1879. }
  1880. {
  1881. Ranges ranges;
  1882. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1883. EXPECT_TRUE(ret);
  1884. EXPECT_EQ(1u, ranges.size());
  1885. EXPECT_EQ(1u, ranges[0].first);
  1886. EXPECT_EQ(10u, ranges[0].second);
  1887. }
  1888. {
  1889. Ranges ranges;
  1890. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1891. EXPECT_FALSE(ret);
  1892. }
  1893. {
  1894. Ranges ranges;
  1895. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1896. EXPECT_TRUE(ret);
  1897. EXPECT_EQ(2u, ranges.size());
  1898. EXPECT_EQ(1u, ranges[0].first);
  1899. EXPECT_EQ(10u, ranges[0].second);
  1900. EXPECT_EQ(100u, ranges[1].first);
  1901. EXPECT_EQ(-1, ranges[1].second);
  1902. }
  1903. {
  1904. Ranges ranges;
  1905. auto ret =
  1906. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1907. EXPECT_TRUE(ret);
  1908. EXPECT_EQ(3u, ranges.size());
  1909. EXPECT_EQ(1u, ranges[0].first);
  1910. EXPECT_EQ(10u, ranges[0].second);
  1911. EXPECT_EQ(100u, ranges[1].first);
  1912. EXPECT_EQ(200u, ranges[1].second);
  1913. EXPECT_EQ(300u, ranges[2].first);
  1914. EXPECT_EQ(400u, ranges[2].second);
  1915. }
  1916. {
  1917. Ranges ranges;
  1918. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1919. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1920. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1921. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1922. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1923. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1924. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1925. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1926. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1927. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1928. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1929. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1930. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1931. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1932. EXPECT_FALSE(
  1933. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1934. EXPECT_TRUE(ranges.empty());
  1935. }
  1936. {
  1937. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1938. // remainder of the representation, so it stays accepted.
  1939. Ranges ranges;
  1940. auto ret =
  1941. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1942. EXPECT_TRUE(ret);
  1943. ASSERT_EQ(1u, ranges.size());
  1944. EXPECT_EQ(0, ranges[0].first);
  1945. EXPECT_EQ(-1, ranges[0].second);
  1946. }
  1947. // RFC 9110 14.1: range unit names are case-insensitive.
  1948. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  1949. Ranges ranges;
  1950. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  1951. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  1952. }
  1953. }
  1954. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1955. Request req;
  1956. req.set_header("Accept-Encoding", "gzip");
  1957. Response res;
  1958. res.set_header("Content-Type", "text/plain");
  1959. auto ret = detail::encoding_type(req, res);
  1960. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1961. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1962. #else
  1963. EXPECT_TRUE(ret == detail::EncodingType::None);
  1964. #endif
  1965. }
  1966. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1967. Request req;
  1968. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1969. Response res;
  1970. res.set_header("Content-Type", "text/plain");
  1971. auto ret = detail::encoding_type(req, res);
  1972. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1973. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1974. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1975. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1976. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1977. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1978. #else
  1979. EXPECT_TRUE(ret == detail::EncodingType::None);
  1980. #endif
  1981. }
  1982. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1983. Request req;
  1984. req.set_header("Accept-Encoding",
  1985. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1986. Response res;
  1987. res.set_header("Content-Type", "text/plain");
  1988. auto ret = detail::encoding_type(req, res);
  1989. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1990. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1991. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1992. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1993. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1994. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1995. #else
  1996. EXPECT_TRUE(ret == detail::EncodingType::None);
  1997. #endif
  1998. }
  1999. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2000. // All supported encodings rejected with q=0 should return None
  2001. Request req;
  2002. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2003. Response res;
  2004. res.set_header("Content-Type", "text/plain");
  2005. auto ret = detail::encoding_type(req, res);
  2006. EXPECT_TRUE(ret == detail::EncodingType::None);
  2007. }
  2008. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2009. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2010. Request req;
  2011. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2012. Response res;
  2013. res.set_header("Content-Type", "text/plain");
  2014. auto ret = detail::encoding_type(req, res);
  2015. EXPECT_TRUE(ret == detail::EncodingType::None);
  2016. }
  2017. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2018. Request req;
  2019. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2020. Response res;
  2021. res.set_header("Content-Type", "text/plain");
  2022. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2023. }
  2024. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2025. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2026. Request req;
  2027. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2028. Response res;
  2029. res.set_header("Content-Type", "text/plain");
  2030. auto ret = detail::encoding_type(req, res);
  2031. EXPECT_TRUE(ret == detail::EncodingType::None);
  2032. }
  2033. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2034. // RFC 7231: Accept-Encoding values are case-insensitive
  2035. Request req;
  2036. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2037. Response res;
  2038. res.set_header("Content-Type", "text/plain");
  2039. auto ret = detail::encoding_type(req, res);
  2040. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2041. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2042. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2043. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2044. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2045. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2046. #else
  2047. EXPECT_TRUE(ret == detail::EncodingType::None);
  2048. #endif
  2049. }
  2050. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2051. // q value should determine priority, not hardcoded order
  2052. Request req;
  2053. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2054. Response res;
  2055. res.set_header("Content-Type", "text/plain");
  2056. auto ret = detail::encoding_type(req, res);
  2057. // gzip has highest q=1.0, so it should be selected even though
  2058. // br and zstd are also supported
  2059. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2060. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2061. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2062. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2063. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2064. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2065. #else
  2066. EXPECT_TRUE(ret == detail::EncodingType::None);
  2067. #endif
  2068. }
  2069. TEST(BufferStreamTest, read) {
  2070. detail::BufferStream strm1;
  2071. Stream &strm = strm1;
  2072. EXPECT_EQ(5, strm.write("hello"));
  2073. char buf[512];
  2074. EXPECT_EQ(2, strm.read(buf, 2));
  2075. EXPECT_EQ('h', buf[0]);
  2076. EXPECT_EQ('e', buf[1]);
  2077. EXPECT_EQ(2, strm.read(buf, 2));
  2078. EXPECT_EQ('l', buf[0]);
  2079. EXPECT_EQ('l', buf[1]);
  2080. EXPECT_EQ(1, strm.read(buf, 1));
  2081. EXPECT_EQ('o', buf[0]);
  2082. EXPECT_EQ(0, strm.read(buf, 1));
  2083. }
  2084. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2085. auto host = "www.httpwatch.com";
  2086. auto ip = hosted_at(host);
  2087. EXPECT_EQ("23.96.13.243", ip);
  2088. std::vector<std::string> addrs;
  2089. hosted_at(host, addrs);
  2090. EXPECT_EQ(1u, addrs.size());
  2091. }
  2092. #if 0 // It depends on each test environment...
  2093. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2094. auto host = "www.youtube.com";
  2095. std::vector<std::string> addrs;
  2096. hosted_at(host, addrs);
  2097. EXPECT_EQ(20u, addrs.size());
  2098. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2099. EXPECT_TRUE(it != addrs.end());
  2100. }
  2101. #endif
  2102. class ChunkedEncodingTest : public ::testing::Test {
  2103. protected:
  2104. ChunkedEncodingTest()
  2105. : cli_(HOST, PORT)
  2106. #ifdef CPPHTTPLIB_SSL_ENABLED
  2107. ,
  2108. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2109. #endif
  2110. {
  2111. cli_.set_connection_timeout(2);
  2112. #ifdef CPPHTTPLIB_SSL_ENABLED
  2113. cli_.enable_server_certificate_verification(false);
  2114. #endif
  2115. }
  2116. virtual void SetUp() {
  2117. read_file("./image.jpg", image_data_);
  2118. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2119. res.set_content("Hello World!", "text/plain");
  2120. });
  2121. svr_.Get(
  2122. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2123. res.set_chunked_content_provider(
  2124. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2125. size_t remaining = image_data_.size() - offset;
  2126. if (remaining == 0) {
  2127. sink.done();
  2128. } else {
  2129. constexpr size_t CHUNK_SIZE = 1024;
  2130. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2131. sink.write(&image_data_[offset], send_size);
  2132. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2133. }
  2134. return true;
  2135. });
  2136. });
  2137. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2138. svr_.wait_until_ready();
  2139. }
  2140. virtual void TearDown() {
  2141. svr_.stop();
  2142. if (!request_threads_.empty()) {
  2143. std::this_thread::sleep_for(std::chrono::seconds(1));
  2144. for (auto &t : request_threads_) {
  2145. t.join();
  2146. }
  2147. }
  2148. t_.join();
  2149. }
  2150. #ifdef CPPHTTPLIB_SSL_ENABLED
  2151. SSLClient cli_;
  2152. SSLServer svr_;
  2153. #else
  2154. Client cli_;
  2155. Server svr_;
  2156. #endif
  2157. thread t_;
  2158. std::vector<thread> request_threads_;
  2159. std::string image_data_;
  2160. };
  2161. TEST_F(ChunkedEncodingTest, NormalGet) {
  2162. auto res = cli_.Get("/chunked");
  2163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2164. std::string out;
  2165. read_file("./image.jpg", out);
  2166. EXPECT_EQ(StatusCode::OK_200, res->status);
  2167. EXPECT_EQ(out, res->body);
  2168. }
  2169. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2170. std::string body;
  2171. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2172. body.append(data, data_length);
  2173. return true;
  2174. });
  2175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2176. std::string out;
  2177. read_file("./image.jpg", out);
  2178. EXPECT_EQ(StatusCode::OK_200, res->status);
  2179. EXPECT_EQ(out, body);
  2180. }
  2181. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2182. std::string body;
  2183. auto res = cli_.Get(
  2184. "/chunked",
  2185. [&](const Response &response) {
  2186. EXPECT_EQ(StatusCode::OK_200, response.status);
  2187. return true;
  2188. },
  2189. [&](const char *data, size_t data_length) {
  2190. body.append(data, data_length);
  2191. return true;
  2192. });
  2193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2194. std::string out;
  2195. read_file("./image.jpg", out);
  2196. EXPECT_EQ(StatusCode::OK_200, res->status);
  2197. EXPECT_EQ(out, body);
  2198. }
  2199. TEST(RangeTest, FromHTTPBin_Online) {
  2200. auto host = "httpbingo.org";
  2201. auto path = std::string{"/range/32"};
  2202. #ifdef CPPHTTPLIB_SSL_ENABLED
  2203. auto port = 443;
  2204. SSLClient cli(host, port);
  2205. #else
  2206. auto port = 80;
  2207. Client cli(host, port);
  2208. #endif
  2209. cli.set_connection_timeout(5);
  2210. {
  2211. auto res = cli.Get(path);
  2212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2213. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2214. EXPECT_EQ(StatusCode::OK_200, res->status);
  2215. }
  2216. {
  2217. Headers headers = {make_range_header({{1, -1}})};
  2218. auto res = cli.Get(path, headers);
  2219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2220. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2221. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2222. }
  2223. {
  2224. Headers headers = {make_range_header({{1, 10}})};
  2225. auto res = cli.Get(path, headers);
  2226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2227. EXPECT_EQ("bcdefghijk", res->body);
  2228. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2229. }
  2230. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2231. // entire resource, while the original httpbin returned 200. Both are
  2232. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2233. {
  2234. Headers headers = {make_range_header({{0, 31}})};
  2235. auto res = cli.Get(path, headers);
  2236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2237. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2238. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2239. res->status == StatusCode::PartialContent_206);
  2240. }
  2241. {
  2242. Headers headers = {make_range_header({{0, -1}})};
  2243. auto res = cli.Get(path, headers);
  2244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2245. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2246. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2247. res->status == StatusCode::PartialContent_206);
  2248. }
  2249. // go-httpbin returns 206 with clamped range for over-range requests,
  2250. // while the original httpbin returned 416. Both behaviors are observed
  2251. // in real servers, so we only verify the request succeeds.
  2252. {
  2253. Headers headers = {make_range_header({{0, 32}})};
  2254. auto res = cli.Get(path, headers);
  2255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2256. }
  2257. }
  2258. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2259. auto host = "unresolvableaddress.local";
  2260. auto path = std::string{"/"};
  2261. #ifdef CPPHTTPLIB_SSL_ENABLED
  2262. auto port = 443;
  2263. SSLClient cli(host, port);
  2264. #else
  2265. auto port = 80;
  2266. Client cli(host, port);
  2267. #endif
  2268. cli.set_connection_timeout(1);
  2269. {
  2270. auto res = cli.Get(path);
  2271. ASSERT_FALSE(res);
  2272. }
  2273. std::this_thread::sleep_for(std::chrono::seconds(8));
  2274. }
  2275. #if defined(__linux__) && defined(__GLIBC__) && \
  2276. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2277. // Forward declaration: in split builds split.py strips `inline` and moves the
  2278. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2279. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2280. // against the symbol in both header-only and split builds.
  2281. namespace httplib {
  2282. namespace detail {
  2283. int getaddrinfo_with_timeout(const char *node, const char *service,
  2284. const struct addrinfo *hints,
  2285. struct addrinfo **res, time_t timeout_sec);
  2286. } // namespace detail
  2287. } // namespace httplib
  2288. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2289. //
  2290. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2291. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2292. // gai_suspend() call hits the connection timeout the function calls
  2293. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2294. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2295. // still alive and still references the now-destroyed stack frame.
  2296. //
  2297. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2298. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2299. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2300. // and runs them in a container.
  2301. namespace {
  2302. bool should_run_issue_2431_tests() {
  2303. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2304. return v && *v && std::string(v) != "0";
  2305. }
  2306. std::string unique_unresolvable_host(int n) {
  2307. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2308. // glibc still asks the configured nameserver — which is exactly the path
  2309. // we want to exercise. A unique label per call avoids the resolver cache.
  2310. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2311. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2312. std::to_string(n) + ".invalid";
  2313. }
  2314. } // namespace
  2315. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2316. if (!should_run_issue_2431_tests()) {
  2317. GTEST_SKIP()
  2318. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2319. }
  2320. for (int i = 0; i < 8; ++i) {
  2321. struct addrinfo hints;
  2322. memset(&hints, 0, sizeof(hints));
  2323. hints.ai_family = AF_UNSPEC;
  2324. hints.ai_socktype = SOCK_STREAM;
  2325. auto host = unique_unresolvable_host(i);
  2326. struct addrinfo *result = nullptr;
  2327. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2328. &result, /*timeout_sec=*/1);
  2329. if (rc == 0 && result) { freeaddrinfo(result); }
  2330. }
  2331. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2332. // stack region they still believe holds their gaicb.
  2333. std::this_thread::sleep_for(std::chrono::seconds(3));
  2334. }
  2335. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2336. if (!should_run_issue_2431_tests()) {
  2337. GTEST_SKIP()
  2338. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2339. }
  2340. std::atomic<bool> stop{false};
  2341. std::vector<std::thread> threads;
  2342. for (int t = 0; t < 8; ++t) {
  2343. threads.emplace_back([t, &stop] {
  2344. int i = 0;
  2345. while (!stop.load(std::memory_order_relaxed)) {
  2346. struct addrinfo hints;
  2347. memset(&hints, 0, sizeof(hints));
  2348. hints.ai_family = AF_UNSPEC;
  2349. hints.ai_socktype = SOCK_STREAM;
  2350. auto host = unique_unresolvable_host(t * 100000 + i++);
  2351. struct addrinfo *result = nullptr;
  2352. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2353. &result, /*timeout_sec=*/1);
  2354. if (rc == 0 && result) { freeaddrinfo(result); }
  2355. }
  2356. });
  2357. }
  2358. std::this_thread::sleep_for(std::chrono::seconds(8));
  2359. stop.store(true, std::memory_order_relaxed);
  2360. for (auto &th : threads) {
  2361. th.join();
  2362. }
  2363. std::this_thread::sleep_for(std::chrono::seconds(3));
  2364. }
  2365. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2366. if (!should_run_issue_2431_tests()) {
  2367. GTEST_SKIP()
  2368. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2369. }
  2370. std::atomic<bool> stop{false};
  2371. std::vector<std::thread> threads;
  2372. for (int t = 0; t < 8; ++t) {
  2373. threads.emplace_back([t, &stop] {
  2374. int i = 0;
  2375. while (!stop.load(std::memory_order_relaxed)) {
  2376. auto host = unique_unresolvable_host(t * 100000 + i++);
  2377. Client cli(host, 80);
  2378. cli.set_connection_timeout(1, 0);
  2379. cli.set_read_timeout(1, 0);
  2380. cli.set_write_timeout(1, 0);
  2381. (void)cli.Get("/");
  2382. }
  2383. });
  2384. }
  2385. std::this_thread::sleep_for(std::chrono::seconds(8));
  2386. stop.store(true, std::memory_order_relaxed);
  2387. for (auto &th : threads) {
  2388. th.join();
  2389. }
  2390. std::this_thread::sleep_for(std::chrono::seconds(3));
  2391. }
  2392. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2393. TEST(ConnectionErrorTest, InvalidHost) {
  2394. auto host = "-abcde.com";
  2395. #ifdef CPPHTTPLIB_SSL_ENABLED
  2396. auto port = 443;
  2397. SSLClient cli(host, port);
  2398. #else
  2399. auto port = 80;
  2400. Client cli(host, port);
  2401. #endif
  2402. cli.set_connection_timeout(std::chrono::seconds(2));
  2403. auto res = cli.Get("/");
  2404. ASSERT_TRUE(!res);
  2405. EXPECT_EQ(Error::Connection, res.error());
  2406. }
  2407. TEST(ConnectionErrorTest, InvalidHost2) {
  2408. auto host = "httpcan.org/";
  2409. #ifdef CPPHTTPLIB_SSL_ENABLED
  2410. SSLClient cli(host);
  2411. #else
  2412. Client cli(host);
  2413. #endif
  2414. cli.set_connection_timeout(std::chrono::seconds(2));
  2415. auto res = cli.Get("/");
  2416. ASSERT_TRUE(!res);
  2417. EXPECT_EQ(Error::Connection, res.error());
  2418. }
  2419. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2420. auto host = "httpcan.org/";
  2421. #ifdef CPPHTTPLIB_SSL_ENABLED
  2422. SSLClient cli(host);
  2423. #else
  2424. Client cli(host);
  2425. #endif
  2426. cli.set_connection_timeout(std::chrono::seconds(2));
  2427. auto res = cli.Get("/");
  2428. ASSERT_TRUE(!res);
  2429. stringstream s;
  2430. s << "error code: " << res.error();
  2431. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2432. }
  2433. TEST(ConnectionErrorTest, InvalidPort) {
  2434. auto host = "localhost";
  2435. auto port = 44380;
  2436. #ifdef CPPHTTPLIB_SSL_ENABLED
  2437. SSLClient cli(host, port);
  2438. #else
  2439. Client cli(host, port);
  2440. #endif
  2441. cli.set_connection_timeout(std::chrono::seconds(2));
  2442. auto res = cli.Get("/");
  2443. ASSERT_TRUE(!res);
  2444. EXPECT_TRUE(Error::Connection == res.error() ||
  2445. Error::ConnectionTimeout == res.error());
  2446. }
  2447. TEST(ConnectionErrorTest, Timeout_Online) {
  2448. auto host = "google.com";
  2449. #ifdef CPPHTTPLIB_SSL_ENABLED
  2450. auto port = 44380;
  2451. SSLClient cli(host, port);
  2452. #else
  2453. auto port = 8080;
  2454. Client cli(host, port);
  2455. #endif
  2456. cli.set_connection_timeout(std::chrono::seconds(2));
  2457. // only probe one address type so that the error reason
  2458. // correlates to the timed-out IPv4, not the unsupported
  2459. // IPv6 connection attempt
  2460. cli.set_address_family(AF_INET);
  2461. auto res = cli.Get("/");
  2462. ASSERT_TRUE(!res);
  2463. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2464. }
  2465. TEST(CancelTest, NoCancel_Online) {
  2466. auto host = "httpbingo.org";
  2467. auto path = std::string{"/range/32"};
  2468. #ifdef CPPHTTPLIB_SSL_ENABLED
  2469. auto port = 443;
  2470. SSLClient cli(host, port);
  2471. #else
  2472. auto port = 80;
  2473. Client cli(host, port);
  2474. #endif
  2475. cli.set_connection_timeout(std::chrono::seconds(5));
  2476. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2478. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2479. EXPECT_EQ(StatusCode::OK_200, res->status);
  2480. }
  2481. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2482. // Use /bytes with a large payload so that the DownloadProgress callback
  2483. // (which only fires for Content-Length responses) is invoked before the
  2484. // entire body is received, giving cancellation a chance to fire.
  2485. auto host = "httpbingo.org";
  2486. auto path = std::string{"/bytes/524288"};
  2487. #ifdef CPPHTTPLIB_SSL_ENABLED
  2488. auto port = 443;
  2489. SSLClient cli(host, port);
  2490. #else
  2491. auto port = 80;
  2492. Client cli(host, port);
  2493. #endif
  2494. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2495. cli.set_connection_timeout(std::chrono::seconds(5));
  2496. ASSERT_TRUE(!res);
  2497. EXPECT_EQ(Error::Canceled, res.error());
  2498. }
  2499. TEST(CancelTest, WithCancelLargePayload_Online) {
  2500. auto host = "httpbingo.org";
  2501. auto path = std::string{"/bytes/524288"};
  2502. #ifdef CPPHTTPLIB_SSL_ENABLED
  2503. auto port = 443;
  2504. SSLClient cli(host, port);
  2505. #else
  2506. auto port = 80;
  2507. Client cli(host, port);
  2508. #endif
  2509. cli.set_connection_timeout(std::chrono::seconds(5));
  2510. uint32_t count = 0;
  2511. auto res =
  2512. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2513. ASSERT_TRUE(!res);
  2514. EXPECT_EQ(Error::Canceled, res.error());
  2515. }
  2516. TEST(CancelTest, NoCancelPost) {
  2517. Server svr;
  2518. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2519. res.set_content("Hello World!", "text/plain");
  2520. });
  2521. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2522. auto se = detail::scope_exit([&] {
  2523. svr.stop();
  2524. thread.join();
  2525. ASSERT_FALSE(svr.is_running());
  2526. });
  2527. svr.wait_until_ready();
  2528. Client cli(HOST, PORT);
  2529. cli.set_connection_timeout(std::chrono::seconds(5));
  2530. auto res =
  2531. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2532. "application/json", [](uint64_t, uint64_t) { return true; });
  2533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2534. EXPECT_EQ("Hello World!", res->body);
  2535. EXPECT_EQ(StatusCode::OK_200, res->status);
  2536. }
  2537. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2538. Server svr;
  2539. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2540. res.set_content("Hello World!", "text/plain");
  2541. });
  2542. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2543. auto se = detail::scope_exit([&] {
  2544. svr.stop();
  2545. thread.join();
  2546. ASSERT_FALSE(svr.is_running());
  2547. });
  2548. svr.wait_until_ready();
  2549. Client cli(HOST, PORT);
  2550. cli.set_connection_timeout(std::chrono::seconds(5));
  2551. auto res =
  2552. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2553. "application/json", [](uint64_t, uint64_t) { return false; });
  2554. ASSERT_TRUE(!res);
  2555. EXPECT_EQ(Error::Canceled, res.error());
  2556. }
  2557. TEST(CancelTest, WithCancelLargePayloadPost) {
  2558. Server svr;
  2559. svr.set_payload_max_length(200 * 1024 * 1024);
  2560. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2561. res.set_content(LARGE_DATA, "text/plain");
  2562. });
  2563. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2564. auto se = detail::scope_exit([&] {
  2565. svr.stop();
  2566. thread.join();
  2567. ASSERT_FALSE(svr.is_running());
  2568. });
  2569. svr.wait_until_ready();
  2570. Client cli(HOST, PORT);
  2571. cli.set_payload_max_length(200 * 1024 * 1024);
  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, NoCancelPut) {
  2580. Server svr;
  2581. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2582. res.set_content("Hello World!", "text/plain");
  2583. });
  2584. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2585. auto se = detail::scope_exit([&] {
  2586. svr.stop();
  2587. thread.join();
  2588. ASSERT_FALSE(svr.is_running());
  2589. });
  2590. svr.wait_until_ready();
  2591. Client cli(HOST, PORT);
  2592. cli.set_connection_timeout(std::chrono::seconds(5));
  2593. auto res =
  2594. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2595. "application/json", [](uint64_t, uint64_t) { return true; });
  2596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2597. EXPECT_EQ("Hello World!", res->body);
  2598. EXPECT_EQ(StatusCode::OK_200, res->status);
  2599. }
  2600. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2601. Server svr;
  2602. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2603. res.set_content("Hello World!", "text/plain");
  2604. });
  2605. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2606. auto se = detail::scope_exit([&] {
  2607. svr.stop();
  2608. thread.join();
  2609. ASSERT_FALSE(svr.is_running());
  2610. });
  2611. svr.wait_until_ready();
  2612. Client cli(HOST, PORT);
  2613. cli.set_connection_timeout(std::chrono::seconds(5));
  2614. auto res =
  2615. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2616. "application/json", [](uint64_t, uint64_t) { return false; });
  2617. ASSERT_TRUE(!res);
  2618. EXPECT_EQ(Error::Canceled, res.error());
  2619. }
  2620. TEST(CancelTest, WithCancelLargePayloadPut) {
  2621. Server svr;
  2622. svr.set_payload_max_length(200 * 1024 * 1024);
  2623. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2624. res.set_content(LARGE_DATA, "text/plain");
  2625. });
  2626. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2627. auto se = detail::scope_exit([&] {
  2628. svr.stop();
  2629. thread.join();
  2630. ASSERT_FALSE(svr.is_running());
  2631. });
  2632. svr.wait_until_ready();
  2633. Client cli(HOST, PORT);
  2634. cli.set_payload_max_length(200 * 1024 * 1024);
  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, NoCancelPatch) {
  2643. Server svr;
  2644. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2645. res.set_content("Hello World!", "text/plain");
  2646. });
  2647. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2648. auto se = detail::scope_exit([&] {
  2649. svr.stop();
  2650. thread.join();
  2651. ASSERT_FALSE(svr.is_running());
  2652. });
  2653. svr.wait_until_ready();
  2654. Client cli(HOST, PORT);
  2655. cli.set_connection_timeout(std::chrono::seconds(5));
  2656. auto res =
  2657. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2658. "application/json", [](uint64_t, uint64_t) { return true; });
  2659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2660. EXPECT_EQ("Hello World!", res->body);
  2661. EXPECT_EQ(StatusCode::OK_200, res->status);
  2662. }
  2663. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2664. Server svr;
  2665. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2666. res.set_content("Hello World!", "text/plain");
  2667. });
  2668. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2669. auto se = detail::scope_exit([&] {
  2670. svr.stop();
  2671. thread.join();
  2672. ASSERT_FALSE(svr.is_running());
  2673. });
  2674. svr.wait_until_ready();
  2675. Client cli(HOST, PORT);
  2676. cli.set_connection_timeout(std::chrono::seconds(5));
  2677. auto res =
  2678. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2679. "application/json", [](uint64_t, uint64_t) { return false; });
  2680. ASSERT_TRUE(!res);
  2681. EXPECT_EQ(Error::Canceled, res.error());
  2682. }
  2683. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2684. Server svr;
  2685. svr.set_payload_max_length(200 * 1024 * 1024);
  2686. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2687. res.set_content(LARGE_DATA, "text/plain");
  2688. });
  2689. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2690. auto se = detail::scope_exit([&] {
  2691. svr.stop();
  2692. thread.join();
  2693. ASSERT_FALSE(svr.is_running());
  2694. });
  2695. svr.wait_until_ready();
  2696. Client cli(HOST, PORT);
  2697. cli.set_payload_max_length(200 * 1024 * 1024);
  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, NoCancelDelete) {
  2706. Server svr;
  2707. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2708. res.set_content("Hello World!", "text/plain");
  2709. });
  2710. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2711. auto se = detail::scope_exit([&] {
  2712. svr.stop();
  2713. thread.join();
  2714. ASSERT_FALSE(svr.is_running());
  2715. });
  2716. svr.wait_until_ready();
  2717. Client cli(HOST, PORT);
  2718. cli.set_connection_timeout(std::chrono::seconds(5));
  2719. auto res =
  2720. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2721. "application/json", [](uint64_t, uint64_t) { return true; });
  2722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2723. EXPECT_EQ("Hello World!", res->body);
  2724. EXPECT_EQ(StatusCode::OK_200, res->status);
  2725. }
  2726. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2727. Server svr;
  2728. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2729. res.set_content("Hello World!", "text/plain");
  2730. });
  2731. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2732. auto se = detail::scope_exit([&] {
  2733. svr.stop();
  2734. thread.join();
  2735. ASSERT_FALSE(svr.is_running());
  2736. });
  2737. svr.wait_until_ready();
  2738. Client cli(HOST, PORT);
  2739. cli.set_connection_timeout(std::chrono::seconds(5));
  2740. auto res =
  2741. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2742. "application/json", [](uint64_t, uint64_t) { return false; });
  2743. ASSERT_TRUE(!res);
  2744. EXPECT_EQ(Error::Canceled, res.error());
  2745. }
  2746. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2747. Server svr;
  2748. svr.set_payload_max_length(200 * 1024 * 1024);
  2749. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2750. res.set_content(LARGE_DATA, "text/plain");
  2751. });
  2752. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2753. auto se = detail::scope_exit([&] {
  2754. svr.stop();
  2755. thread.join();
  2756. ASSERT_FALSE(svr.is_running());
  2757. });
  2758. svr.wait_until_ready();
  2759. Client cli(HOST, PORT);
  2760. cli.set_payload_max_length(200 * 1024 * 1024);
  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. static std::string remove_whitespace(const std::string &input) {
  2769. std::string output;
  2770. output.reserve(input.size());
  2771. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2772. [](unsigned char c) { return !std::isspace(c); });
  2773. return output;
  2774. }
  2775. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2776. auto host = "httpbingo.org";
  2777. auto path = std::string{"/basic-auth/hello/world"};
  2778. #ifdef CPPHTTPLIB_SSL_ENABLED
  2779. auto port = 443;
  2780. SSLClient cli(host, port);
  2781. #else
  2782. auto port = 80;
  2783. Client cli(host, port);
  2784. #endif
  2785. {
  2786. auto res = cli.Get(path);
  2787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2788. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2789. }
  2790. {
  2791. auto res = cli.Get(
  2792. path, Headers{make_basic_authentication_header("hello", "world")});
  2793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2794. auto body = remove_whitespace(res->body);
  2795. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2796. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2797. EXPECT_EQ(StatusCode::OK_200, res->status);
  2798. }
  2799. {
  2800. cli.set_basic_auth("hello", "world");
  2801. auto res = cli.Get(path);
  2802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2803. auto body = remove_whitespace(res->body);
  2804. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2805. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2806. EXPECT_EQ(StatusCode::OK_200, res->status);
  2807. }
  2808. {
  2809. cli.set_basic_auth("hello", "bad");
  2810. auto res = cli.Get(path);
  2811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2812. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2813. }
  2814. {
  2815. cli.set_basic_auth("bad", "world");
  2816. auto res = cli.Get(path);
  2817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2818. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2819. }
  2820. }
  2821. #ifdef CPPHTTPLIB_SSL_ENABLED
  2822. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2823. auto host = "httpbingo.org";
  2824. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2825. auto paths = std::vector<std::string>{
  2826. "/digest-auth/auth/hello/world/MD5",
  2827. "/digest-auth/auth/hello/world/SHA-256",
  2828. };
  2829. auto port = 443;
  2830. SSLClient cli(host, port);
  2831. {
  2832. auto res = cli.Get(unauth_path);
  2833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2834. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2835. }
  2836. {
  2837. cli.set_digest_auth("hello", "world");
  2838. for (const auto &path : paths) {
  2839. auto res = cli.Get(path.c_str());
  2840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2841. auto body = remove_whitespace(res->body);
  2842. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2843. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2844. EXPECT_EQ(StatusCode::OK_200, res->status);
  2845. }
  2846. cli.set_digest_auth("hello", "bad");
  2847. for (const auto &path : paths) {
  2848. auto res = cli.Get(path.c_str());
  2849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2850. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2851. }
  2852. }
  2853. }
  2854. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2855. // comma-separated list of challenges, and each challenge may itself carry a
  2856. // comma-separated auth-param list, so a server can legally offer Basic
  2857. // before Digest, either as two field lines or packed into one. Runs one 401
  2858. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2859. // value() joins them in receipt order) and checks that the retry carries a
  2860. // well-formed Digest Authorization header naming expected_realm.
  2861. static void
  2862. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2863. const std::string &expected_realm) {
  2864. std::atomic<int> hits{0};
  2865. Server svr;
  2866. svr.Get("/x", [&](const Request &req, Response &res) {
  2867. if (++hits == 1) {
  2868. res.status = StatusCode::Unauthorized_401;
  2869. for (const auto &challenge : challenges) {
  2870. res.set_header("WWW-Authenticate", challenge);
  2871. }
  2872. } else {
  2873. auto authorization = req.get_header_value("Authorization");
  2874. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2875. EXPECT_NE(std::string::npos,
  2876. authorization.find("realm=\"" + expected_realm + "\""));
  2877. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2878. res.set_content("ok", "text/plain");
  2879. }
  2880. });
  2881. auto port = svr.bind_to_any_port(HOST);
  2882. std::thread t([&]() { svr.listen_after_bind(); });
  2883. auto se = detail::scope_exit([&] {
  2884. svr.stop();
  2885. t.join();
  2886. });
  2887. svr.wait_until_ready();
  2888. Client cli(HOST, port);
  2889. cli.set_digest_auth("hello", "world");
  2890. auto res = cli.Get("/x");
  2891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2892. EXPECT_EQ(2, hits.load());
  2893. }
  2894. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2895. static const char *kDigestChallenge =
  2896. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2897. "algorithm=MD5";
  2898. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2899. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2900. "testrealm");
  2901. }
  2902. // Same challenge list with the schemes in the opposite order, to make sure
  2903. // the fix above didn't just special-case "Basic first".
  2904. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2905. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2906. "testrealm");
  2907. }
  2908. // A comma inside a quoted auth-param value must not be mistaken for the
  2909. // separator between two challenges (or two auth-params).
  2910. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2911. run_digest_challenge_list_test(
  2912. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2913. "algorithm=MD5"},
  2914. "test,realm");
  2915. }
  2916. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2917. // make_digest_authentication_header() dereferences both unconditionally, so
  2918. // a server sending a challenge missing either one must not be treated as
  2919. // usable -- doing so used to crash the client with std::out_of_range.
  2920. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2921. Server svr;
  2922. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2923. res.status = StatusCode::Unauthorized_401;
  2924. res.set_header("WWW-Authenticate", challenge);
  2925. });
  2926. auto port = svr.bind_to_any_port(HOST);
  2927. std::thread t([&]() { svr.listen_after_bind(); });
  2928. auto se = detail::scope_exit([&] {
  2929. svr.stop();
  2930. t.join();
  2931. });
  2932. svr.wait_until_ready();
  2933. Client cli(HOST, port);
  2934. cli.set_digest_auth("hello", "world");
  2935. auto res = cli.Get("/x");
  2936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2937. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2938. }
  2939. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2940. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2941. }
  2942. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2943. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2944. }
  2945. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2946. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2947. }
  2948. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  2949. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  2950. // when storing the values, so the header builder has to re-escape them (and
  2951. // keep algorithm a bare token); otherwise the value breaks out of its
  2952. // quoted-string and injects extra auth-params into the client's Authorization.
  2953. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  2954. std::atomic<int> hits{0};
  2955. std::string authorization;
  2956. Server svr;
  2957. svr.Get("/x", [&](const Request &req, Response &res) {
  2958. if (++hits == 1) {
  2959. res.status = StatusCode::Unauthorized_401;
  2960. // On the wire the quotes embedded in the values are backslash-escaped.
  2961. res.set_header("WWW-Authenticate",
  2962. "Digest realm=\"testrealm\", "
  2963. "nonce=\"n\\\"; injected=\\\"x\", "
  2964. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  2965. } else {
  2966. authorization = req.get_header_value("Authorization");
  2967. res.set_content("ok", "text/plain");
  2968. }
  2969. });
  2970. auto port = svr.bind_to_any_port(HOST);
  2971. std::thread t([&]() { svr.listen_after_bind(); });
  2972. auto se = detail::scope_exit([&] {
  2973. svr.stop();
  2974. t.join();
  2975. });
  2976. svr.wait_until_ready();
  2977. Client cli(HOST, port);
  2978. cli.set_digest_auth("hello", "world");
  2979. auto res = cli.Get("/x");
  2980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2981. EXPECT_EQ(2, hits.load());
  2982. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2983. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  2984. // inside its quoted-string rather than starting an "injected" auth-param.
  2985. EXPECT_NE(std::string::npos,
  2986. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  2987. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  2988. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  2989. }
  2990. #endif
  2991. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2992. auto host = "google.com";
  2993. auto another_host = "example.com";
  2994. auto wrong_ip = "0.0.0.0";
  2995. #ifdef CPPHTTPLIB_SSL_ENABLED
  2996. SSLClient cli(host);
  2997. #else
  2998. Client cli(host);
  2999. #endif
  3000. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3001. auto res = cli.Get("/");
  3002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3003. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3004. }
  3005. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3006. auto host = "google.com";
  3007. auto wrong_ip = "0.0.0.0";
  3008. #ifdef CPPHTTPLIB_SSL_ENABLED
  3009. SSLClient cli(host);
  3010. #else
  3011. Client cli(host);
  3012. #endif
  3013. cli.set_hostname_addr_map({{host, wrong_ip}});
  3014. auto res = cli.Get("/");
  3015. ASSERT_TRUE(!res);
  3016. EXPECT_EQ(Error::Connection, res.error());
  3017. }
  3018. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3019. // A mapped value that is not an IP literal must be resolved. "localhost"
  3020. // resolves from the hosts file, so this test needs no external DNS.
  3021. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3022. auto host = "target.invalid";
  3023. Server svr;
  3024. std::string received_host;
  3025. svr.Get("/hi", [&](const Request &req, Response &res) {
  3026. received_host = req.get_header_value("Host");
  3027. res.set_content("Hello World!", "text/plain");
  3028. });
  3029. auto port = svr.bind_to_any_port(HOST);
  3030. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3031. auto se = detail::scope_exit([&] {
  3032. svr.stop();
  3033. thread.join();
  3034. ASSERT_FALSE(svr.is_running());
  3035. });
  3036. svr.wait_until_ready();
  3037. Client cli(host, port);
  3038. cli.set_hostname_addr_map({{host, HOST}});
  3039. auto res = cli.Get("/hi");
  3040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3041. EXPECT_EQ(StatusCode::OK_200, res->status);
  3042. // The mapping only redirects the connection; the identity stays host_.
  3043. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3044. }
  3045. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3046. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3047. auto host = "target.invalid";
  3048. Server svr;
  3049. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3050. res.set_content("Hello World!", "text/plain");
  3051. });
  3052. auto port = svr.bind_to_any_port("127.0.0.1");
  3053. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3054. auto se = detail::scope_exit([&] {
  3055. svr.stop();
  3056. thread.join();
  3057. ASSERT_FALSE(svr.is_running());
  3058. });
  3059. svr.wait_until_ready();
  3060. Client cli(host, port);
  3061. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3062. auto res = cli.Get("/hi");
  3063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3064. EXPECT_EQ(StatusCode::OK_200, res->status);
  3065. }
  3066. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3067. // An empty mapped value must leave host_ as the connection target. Without
  3068. // that guard the empty value would become the host argument, getaddrinfo
  3069. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3070. // loopback - silently connecting somewhere the caller never asked for.
  3071. // The server listens on loopback, so such a fallback would succeed and is
  3072. // therefore observable as a failure of this test.
  3073. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3074. Server svr;
  3075. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3076. res.set_content("Hello World!", "text/plain");
  3077. });
  3078. auto port = svr.bind_to_any_port(HOST);
  3079. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3080. auto se = detail::scope_exit([&] {
  3081. svr.stop();
  3082. thread.join();
  3083. ASSERT_FALSE(svr.is_running());
  3084. });
  3085. svr.wait_until_ready();
  3086. Client cli(blackhole, port);
  3087. cli.set_hostname_addr_map({{blackhole, ""}});
  3088. cli.set_connection_timeout(1);
  3089. auto res = cli.Get("/hi");
  3090. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3091. }
  3092. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3093. auto host = "httpbingo.org";
  3094. auto path = std::string{"/absolute-redirect/3"};
  3095. #ifdef CPPHTTPLIB_SSL_ENABLED
  3096. SSLClient cli(host);
  3097. #else
  3098. Client cli(host);
  3099. #endif
  3100. cli.set_follow_location(true);
  3101. auto res = cli.Get(path);
  3102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3103. EXPECT_EQ(StatusCode::OK_200, res->status);
  3104. }
  3105. TEST(RedirectTest, Redirect_Online) {
  3106. auto host = "httpbingo.org";
  3107. auto path = std::string{"/redirect/3"};
  3108. #ifdef CPPHTTPLIB_SSL_ENABLED
  3109. SSLClient cli(host);
  3110. #else
  3111. Client cli(host);
  3112. #endif
  3113. cli.set_follow_location(true);
  3114. auto res = cli.Get(path);
  3115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3116. EXPECT_EQ(StatusCode::OK_200, res->status);
  3117. }
  3118. TEST(RelativeRedirectTest, Redirect_Online) {
  3119. auto host = "httpbingo.org";
  3120. auto path = std::string{"/relative-redirect/3"};
  3121. #ifdef CPPHTTPLIB_SSL_ENABLED
  3122. SSLClient cli(host);
  3123. #else
  3124. Client cli(host);
  3125. #endif
  3126. cli.set_follow_location(true);
  3127. auto res = cli.Get(path);
  3128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3129. EXPECT_EQ(StatusCode::OK_200, res->status);
  3130. }
  3131. TEST(TooManyRedirectTest, Redirect_Online) {
  3132. auto host = "httpbingo.org";
  3133. auto path = std::string{"/redirect/21"};
  3134. #ifdef CPPHTTPLIB_SSL_ENABLED
  3135. SSLClient cli(host);
  3136. #else
  3137. Client cli(host);
  3138. #endif
  3139. cli.set_follow_location(true);
  3140. auto res = cli.Get(path);
  3141. ASSERT_TRUE(!res);
  3142. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3143. }
  3144. #ifdef CPPHTTPLIB_SSL_ENABLED
  3145. TEST(YahooRedirectTest, Redirect_Online) {
  3146. Client cli("yahoo.com");
  3147. auto res = cli.Get("/");
  3148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3149. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3150. cli.set_follow_location(true);
  3151. res = cli.Get("/");
  3152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3153. EXPECT_EQ(StatusCode::OK_200, res->status);
  3154. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3155. }
  3156. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3157. #define REDIR_HOST "httpbingo.org"
  3158. #define REDIR_PATH "/redirect-to"
  3159. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3160. SSLClient cli(REDIR_HOST);
  3161. cli.set_follow_location(true);
  3162. auto res =
  3163. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3165. EXPECT_EQ(StatusCode::OK_200, res->status);
  3166. }
  3167. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3168. SSLClient cli(REDIR_HOST);
  3169. cli.set_follow_location(true);
  3170. Params params;
  3171. params.emplace("url", "http://example.com");
  3172. params.emplace("status_code", "302");
  3173. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3175. EXPECT_EQ(StatusCode::OK_200, res->status);
  3176. }
  3177. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3178. SSLClient cli(REDIR_HOST);
  3179. cli.set_follow_location(true);
  3180. Params params;
  3181. params.emplace("url", "http://example.com");
  3182. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3184. EXPECT_EQ(StatusCode::OK_200, res->status);
  3185. }
  3186. TEST(UrlWithSpace, Redirect_Online) {
  3187. SSLClient cli("edge.forgecdn.net");
  3188. cli.set_follow_location(true);
  3189. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3191. EXPECT_EQ(StatusCode::OK_200, res->status);
  3192. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3193. }
  3194. #endif
  3195. #if !defined(_WIN32) && !defined(_WIN64)
  3196. TEST(ReceiveSignals, Signal) {
  3197. auto setupSignalHandlers = []() {
  3198. struct sigaction act;
  3199. sigemptyset(&act.sa_mask);
  3200. act.sa_flags = SA_SIGINFO;
  3201. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3202. switch (sig) {
  3203. case SIGINT:
  3204. default: break;
  3205. }
  3206. };
  3207. ::sigaction(SIGINT, &act, nullptr);
  3208. };
  3209. Server svr;
  3210. int port = 0;
  3211. auto thread = std::thread([&]() {
  3212. setupSignalHandlers();
  3213. port = svr.bind_to_any_port(HOST);
  3214. svr.listen_after_bind();
  3215. });
  3216. auto se = detail::scope_exit([&] {
  3217. svr.stop();
  3218. thread.join();
  3219. ASSERT_FALSE(svr.is_running());
  3220. });
  3221. svr.wait_until_ready();
  3222. ASSERT_TRUE(svr.is_running());
  3223. pthread_kill(thread.native_handle(), SIGINT);
  3224. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3225. ASSERT_TRUE(svr.is_running());
  3226. }
  3227. #endif
  3228. TEST(RedirectToDifferentPort, Redirect) {
  3229. Server svr1;
  3230. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3231. res.set_content("Hello World!", "text/plain");
  3232. });
  3233. int svr1_port = 0;
  3234. auto thread1 = std::thread([&]() {
  3235. svr1_port = svr1.bind_to_any_port(HOST);
  3236. svr1.listen_after_bind();
  3237. });
  3238. Server svr2;
  3239. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3240. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3241. });
  3242. int svr2_port = 0;
  3243. auto thread2 = std::thread([&]() {
  3244. svr2_port = svr2.bind_to_any_port(HOST);
  3245. svr2.listen_after_bind();
  3246. });
  3247. auto se = detail::scope_exit([&] {
  3248. svr2.stop();
  3249. thread2.join();
  3250. svr1.stop();
  3251. thread1.join();
  3252. ASSERT_FALSE(svr2.is_running());
  3253. ASSERT_FALSE(svr1.is_running());
  3254. });
  3255. svr1.wait_until_ready();
  3256. svr2.wait_until_ready();
  3257. Client cli("localhost", svr2_port);
  3258. cli.set_follow_location(true);
  3259. auto res = cli.Get("/2");
  3260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3261. EXPECT_EQ(StatusCode::OK_200, res->status);
  3262. EXPECT_EQ("Hello World!", res->body);
  3263. }
  3264. // GET /redir on one server redirects to /target on another port, so the
  3265. // client follows it with a new client.
  3266. static Result
  3267. GetThroughRedirectToDifferentPort(Server::Handler target,
  3268. const std::function<void(Client &)> &setup,
  3269. const Headers &headers = Headers()) {
  3270. Server target_svr;
  3271. target_svr.Get("/target", target);
  3272. int target_port = 0;
  3273. auto target_thread = std::thread([&]() {
  3274. target_port = target_svr.bind_to_any_port(HOST);
  3275. target_svr.listen_after_bind();
  3276. });
  3277. Server origin_svr;
  3278. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3279. res.set_redirect(
  3280. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3281. });
  3282. int origin_port = 0;
  3283. auto origin_thread = std::thread([&]() {
  3284. origin_port = origin_svr.bind_to_any_port(HOST);
  3285. origin_svr.listen_after_bind();
  3286. });
  3287. auto se = detail::scope_exit([&] {
  3288. origin_svr.stop();
  3289. origin_thread.join();
  3290. target_svr.stop();
  3291. target_thread.join();
  3292. });
  3293. target_svr.wait_until_ready();
  3294. origin_svr.wait_until_ready();
  3295. Client cli("localhost", origin_port);
  3296. cli.set_follow_location(true);
  3297. setup(cli);
  3298. return cli.Get("/redir", headers);
  3299. }
  3300. static void
  3301. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3302. std::string captured_authorization;
  3303. auto result = GetThroughRedirectToDifferentPort(
  3304. [&](const Request &req, Response &res) {
  3305. captured_authorization = req.get_header_value("Authorization");
  3306. res.set_content("OK", "text/plain");
  3307. },
  3308. set_auth);
  3309. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3310. EXPECT_EQ(StatusCode::OK_200, result->status);
  3311. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3312. EXPECT_TRUE(captured_authorization.empty());
  3313. }
  3314. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3315. TestDoNotForwardCredentialsOnRedirect(
  3316. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3317. }
  3318. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3319. TestDoNotForwardCredentialsOnRedirect(
  3320. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3321. }
  3322. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3323. std::string captured_cookie;
  3324. auto result = GetThroughRedirectToDifferentPort(
  3325. [&](const Request &req, Response &res) {
  3326. captured_cookie = req.get_header_value("Cookie");
  3327. res.set_content("OK", "text/plain");
  3328. },
  3329. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3330. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3331. EXPECT_EQ(StatusCode::OK_200, result->status);
  3332. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3333. EXPECT_TRUE(captured_cookie.empty());
  3334. }
  3335. TEST(RedirectToSamePort, ForwardCookie) {
  3336. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3337. // header so that ordinary session flows keep working.
  3338. Server svr;
  3339. std::string captured_cookie;
  3340. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3341. res.set_redirect("/target", 302);
  3342. });
  3343. svr.Get("/target", [&](const Request &req, Response &res) {
  3344. captured_cookie = req.get_header_value("Cookie");
  3345. res.set_content("OK", "text/plain");
  3346. });
  3347. auto port = svr.bind_to_any_port(HOST);
  3348. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3349. auto se = detail::scope_exit([&] {
  3350. svr.stop();
  3351. thread.join();
  3352. ASSERT_FALSE(svr.is_running());
  3353. });
  3354. svr.wait_until_ready();
  3355. Client cli(HOST, port);
  3356. cli.set_follow_location(true);
  3357. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3358. auto res = cli.Get("/redir", headers);
  3359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3360. EXPECT_EQ(StatusCode::OK_200, res->status);
  3361. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3362. }
  3363. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3364. std::string authorization;
  3365. std::string trace_id;
  3366. auto result = GetThroughRedirectToDifferentPort(
  3367. [&](const Request &req, Response &res) {
  3368. authorization = req.get_header_value("Authorization");
  3369. trace_id = req.get_header_value("X-Trace-Id");
  3370. res.set_content("OK", "text/plain");
  3371. },
  3372. [](Client &cli) {
  3373. cli.set_default_headers(
  3374. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3375. });
  3376. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3377. EXPECT_EQ(StatusCode::OK_200, result->status);
  3378. // Like a header given with the request, a default one goes along unless it
  3379. // carries credentials (RFC 9110 15.4).
  3380. EXPECT_TRUE(authorization.empty());
  3381. EXPECT_EQ("42", trace_id);
  3382. }
  3383. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3384. auto result = GetThroughRedirectToDifferentPort(
  3385. [](const Request &, Response &res) {
  3386. res.set_content(std::string(2048, 'x'), "text/plain");
  3387. },
  3388. [](Client &cli) { cli.set_payload_max_length(1024); });
  3389. EXPECT_FALSE(result);
  3390. }
  3391. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3392. auto result = GetThroughRedirectToDifferentPort(
  3393. [](const Request &req, Response &res) {
  3394. // Answer after a second, or once the client gives up.
  3395. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3396. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3397. }
  3398. res.set_content("late", "text/plain");
  3399. },
  3400. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3401. ASSERT_FALSE(result);
  3402. EXPECT_EQ(Error::Read, result.error());
  3403. }
  3404. #ifdef CPPHTTPLIB_SSL_ENABLED
  3405. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3406. auto result = GetThroughRedirectToDifferentPort(
  3407. [](const Request &, Response &res) {
  3408. res.status = StatusCode::Unauthorized_401;
  3409. res.set_header("WWW-Authenticate",
  3410. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3411. },
  3412. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3413. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3414. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3415. }
  3416. #endif
  3417. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3418. Server svr;
  3419. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3420. // Port number that overflows int — should not crash
  3421. res.set_redirect("http://localhost:99999999999999999999/target");
  3422. });
  3423. auto port = svr.bind_to_any_port(HOST);
  3424. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3425. auto se = detail::scope_exit([&] {
  3426. svr.stop();
  3427. thread.join();
  3428. ASSERT_FALSE(svr.is_running());
  3429. });
  3430. svr.wait_until_ready();
  3431. Client cli(HOST, port);
  3432. cli.set_follow_location(true);
  3433. auto res = cli.Get("/redir");
  3434. // Should fail gracefully, not crash (no valid response due to bad port)
  3435. EXPECT_FALSE(res);
  3436. }
  3437. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3438. Server svr;
  3439. auto port = svr.bind_to_any_port(HOST);
  3440. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3441. // The server's own port followed by junk must not be followed
  3442. res.set_redirect("http://" + std::string(HOST) + ":" +
  3443. std::to_string(port) + "junk/target");
  3444. });
  3445. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3446. res.set_content("target", "text/plain");
  3447. });
  3448. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3449. auto se = detail::scope_exit([&] {
  3450. svr.stop();
  3451. thread.join();
  3452. ASSERT_FALSE(svr.is_running());
  3453. });
  3454. svr.wait_until_ready();
  3455. Client cli(HOST, port);
  3456. cli.set_follow_location(true);
  3457. auto res = cli.Get("/redir");
  3458. EXPECT_FALSE(res);
  3459. }
  3460. TEST(RedirectFromPageWithContent, Redirect) {
  3461. Server svr;
  3462. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3463. res.set_content("___", "text/plain");
  3464. res.set_redirect("/2");
  3465. });
  3466. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3467. res.set_content("Hello World!", "text/plain");
  3468. });
  3469. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3470. auto se = detail::scope_exit([&] {
  3471. svr.stop();
  3472. th.join();
  3473. ASSERT_FALSE(svr.is_running());
  3474. });
  3475. svr.wait_until_ready();
  3476. {
  3477. Client cli("localhost", PORT);
  3478. cli.set_follow_location(true);
  3479. std::string body;
  3480. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3481. body.append(data, data_length);
  3482. return true;
  3483. });
  3484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3485. EXPECT_EQ(StatusCode::OK_200, res->status);
  3486. EXPECT_EQ("Hello World!", body);
  3487. }
  3488. {
  3489. Client cli("localhost", PORT);
  3490. std::string body;
  3491. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3492. body.append(data, data_length);
  3493. return true;
  3494. });
  3495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3496. EXPECT_EQ(StatusCode::Found_302, res->status);
  3497. EXPECT_EQ("___", body);
  3498. }
  3499. }
  3500. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3501. Server svr;
  3502. auto port_str = std::to_string(PORT);
  3503. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3504. auto expected_host = "[::1]:" + port_str;
  3505. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3506. res.set_content("___", "text/plain");
  3507. // res.set_redirect("/2");
  3508. res.set_redirect(redirect_url);
  3509. });
  3510. svr.Get("/2", [&](const Request &req, Response &res) {
  3511. auto host_header = req.headers.find("Host");
  3512. ASSERT_TRUE(host_header != req.headers.end());
  3513. EXPECT_EQ(expected_host, host_header->second);
  3514. res.set_content("Hello World!", "text/plain");
  3515. });
  3516. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3517. auto se = detail::scope_exit([&] {
  3518. svr.stop();
  3519. th.join();
  3520. ASSERT_FALSE(svr.is_running());
  3521. });
  3522. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3523. // actually starts anything, so the condition !svr.is_running() will
  3524. // always remain true, and the loop never stops.
  3525. // This basically counts how many milliseconds have passed since the
  3526. // call to svr.listen(), and if after 5 seconds nothing started yet
  3527. // aborts the test.
  3528. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3529. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3530. ASSERT_LT(milliseconds, 5000U);
  3531. }
  3532. {
  3533. Client cli("::1", PORT);
  3534. cli.set_follow_location(true);
  3535. std::string body;
  3536. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3537. body.append(data, data_length);
  3538. return true;
  3539. });
  3540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3541. EXPECT_EQ(StatusCode::OK_200, res->status);
  3542. EXPECT_EQ("Hello World!", body);
  3543. }
  3544. {
  3545. Client cli("::1", PORT);
  3546. std::string body;
  3547. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3548. body.append(data, data_length);
  3549. return true;
  3550. });
  3551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3552. EXPECT_EQ(StatusCode::Found_302, res->status);
  3553. EXPECT_EQ("___", body);
  3554. }
  3555. }
  3556. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3557. Server svr;
  3558. svr.Get("/foo", [](const Request &req, Response &res) {
  3559. auto a = req.params.find("a");
  3560. if (a != req.params.end()) {
  3561. res.set_content((*a).second, "text/plain");
  3562. res.status = StatusCode::OK_200;
  3563. } else {
  3564. res.status = StatusCode::BadRequest_400;
  3565. }
  3566. });
  3567. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3568. auto se = detail::scope_exit([&] {
  3569. svr.stop();
  3570. thread.join();
  3571. ASSERT_FALSE(svr.is_running());
  3572. });
  3573. svr.wait_until_ready();
  3574. {
  3575. Client cli(HOST, PORT);
  3576. cli.set_path_encode(false);
  3577. auto res = cli.Get("/foo?a=explicitly+encoded");
  3578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3579. EXPECT_EQ(StatusCode::OK_200, res->status);
  3580. // This expects it back with a space, as the `+` won't have been
  3581. // url-encoded, and server-side the params get decoded turning `+`
  3582. // into spaces.
  3583. EXPECT_EQ("explicitly encoded", res->body);
  3584. }
  3585. }
  3586. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3587. // When path encoding is disabled the client must transmit the supplied
  3588. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3589. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3590. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3591. // than a space (0x20). Assert on the raw wire target to catch this.
  3592. Server svr;
  3593. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3594. svr.Get("/foo", [&](const Request &req, Response &res) {
  3595. EXPECT_EQ(expected_target, req.target);
  3596. res.status = StatusCode::OK_200;
  3597. });
  3598. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3599. auto se = detail::scope_exit([&] {
  3600. svr.stop();
  3601. thread.join();
  3602. ASSERT_FALSE(svr.is_running());
  3603. });
  3604. svr.wait_until_ready();
  3605. {
  3606. Client cli(HOST, PORT);
  3607. cli.set_path_encode(false);
  3608. auto res = cli.Get(expected_target.c_str());
  3609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3610. EXPECT_EQ(StatusCode::OK_200, res->status);
  3611. }
  3612. }
  3613. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3614. // `open_stream()` used to skip the path encoding that the buffered send
  3615. // path applies, so the same `path` produced different bytes in the request
  3616. // line depending on which API was used. Assert the two agree.
  3617. Server svr;
  3618. std::string target;
  3619. svr.Get(".*", [&](const Request &req, Response &res) {
  3620. target = req.target;
  3621. res.status = StatusCode::OK_200;
  3622. });
  3623. auto port = svr.bind_to_any_port(HOST);
  3624. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3625. auto se = detail::scope_exit([&] {
  3626. svr.stop();
  3627. thread.join();
  3628. ASSERT_FALSE(svr.is_running());
  3629. });
  3630. svr.wait_until_ready();
  3631. struct {
  3632. const char *path;
  3633. const char *expected;
  3634. } cases[] = {
  3635. {"/a b?x=1", "/a%20b?x=1"},
  3636. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3637. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3638. };
  3639. for (const auto &c : cases) {
  3640. Client cli(HOST, port);
  3641. target.clear();
  3642. auto res = cli.Get(c.path);
  3643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3644. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3645. auto buffered_target = target;
  3646. target.clear();
  3647. auto handle = cli.open_stream("GET", c.path);
  3648. EXPECT_TRUE(handle.is_valid())
  3649. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3650. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3651. }
  3652. }
  3653. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3654. // The `set_path_encode(false)` contract — transmit the supplied target
  3655. // verbatim — must hold for the streaming API too.
  3656. Server svr;
  3657. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3658. std::string target;
  3659. svr.Get("/foo", [&](const Request &req, Response &res) {
  3660. target = req.target;
  3661. res.status = StatusCode::OK_200;
  3662. });
  3663. auto port = svr.bind_to_any_port(HOST);
  3664. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3665. auto se = detail::scope_exit([&] {
  3666. svr.stop();
  3667. thread.join();
  3668. ASSERT_FALSE(svr.is_running());
  3669. });
  3670. svr.wait_until_ready();
  3671. {
  3672. Client cli(HOST, port);
  3673. cli.set_path_encode(false);
  3674. auto handle = cli.open_stream("GET", expected_target);
  3675. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3676. EXPECT_EQ(expected_target, target);
  3677. }
  3678. }
  3679. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3680. // With path encoding enabled a CR/LF in the target is percent-encoded
  3681. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3682. // write_request_line still backstops `set_path_encode(false)`, which is
  3683. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3684. Server svr;
  3685. // Captured before routing: the decoded path contains a newline, which a
  3686. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3687. std::string target;
  3688. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3689. target = req.target;
  3690. res.status = StatusCode::OK_200;
  3691. return Server::HandlerResponse::Handled;
  3692. });
  3693. auto port = svr.bind_to_any_port(HOST);
  3694. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3695. auto se = detail::scope_exit([&] {
  3696. svr.stop();
  3697. thread.join();
  3698. ASSERT_FALSE(svr.is_running());
  3699. });
  3700. svr.wait_until_ready();
  3701. {
  3702. Client cli(HOST, port);
  3703. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3704. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3705. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3706. }
  3707. }
  3708. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3709. // Every control character is percent-encoded, not just CR/LF, so the target
  3710. // passes the request-target check in write_request_line.
  3711. Server svr;
  3712. std::string target;
  3713. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3714. target = req.target;
  3715. res.status = StatusCode::OK_200;
  3716. return Server::HandlerResponse::Handled;
  3717. });
  3718. auto port = svr.bind_to_any_port(HOST);
  3719. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3720. auto se = detail::scope_exit([&] {
  3721. svr.stop();
  3722. thread.join();
  3723. ASSERT_FALSE(svr.is_running());
  3724. });
  3725. svr.wait_until_ready();
  3726. {
  3727. Client cli(HOST, port);
  3728. auto res = cli.Get("/a\tb\x1b\x7f");
  3729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3730. EXPECT_EQ("/a%09b%1B%7F", target);
  3731. }
  3732. }
  3733. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3734. // Nothing may reach the wire: a raw CR/LF target would split the request
  3735. // line and inject headers.
  3736. Server svr;
  3737. // Pre-routing so that "not called" means nothing reached the server at all,
  3738. // rather than merely failing to match a handler pattern.
  3739. auto handler_called = false;
  3740. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3741. handler_called = true;
  3742. res.status = StatusCode::OK_200;
  3743. return Server::HandlerResponse::Handled;
  3744. });
  3745. auto port = svr.bind_to_any_port(HOST);
  3746. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3747. auto se = detail::scope_exit([&] {
  3748. svr.stop();
  3749. thread.join();
  3750. ASSERT_FALSE(svr.is_running());
  3751. });
  3752. svr.wait_until_ready();
  3753. {
  3754. Client cli(HOST, port);
  3755. cli.set_path_encode(false);
  3756. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3757. EXPECT_FALSE(handle.is_valid());
  3758. EXPECT_EQ(Error::Write, handle.error);
  3759. EXPECT_FALSE(handler_called);
  3760. }
  3761. }
  3762. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3763. // Which of the two branches runs is decided by whether the query component
  3764. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3765. // an empty query and must still fall back to building one from
  3766. // `req.params`, while a non-empty query must win over `req.params`.
  3767. Server svr;
  3768. std::string target;
  3769. svr.Get("/foo", [&](const Request &req, Response &res) {
  3770. target = req.target;
  3771. res.status = StatusCode::OK_200;
  3772. });
  3773. auto port = svr.bind_to_any_port(HOST);
  3774. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3775. auto se = detail::scope_exit([&] {
  3776. svr.stop();
  3777. thread.join();
  3778. ASSERT_FALSE(svr.is_running());
  3779. });
  3780. svr.wait_until_ready();
  3781. {
  3782. // Trailing `?` -> empty query component -> `req.params` is used.
  3783. Client cli(HOST, port);
  3784. Request req;
  3785. req.method = "GET";
  3786. req.path = "/foo?";
  3787. req.params.emplace("a", "1");
  3788. target.clear();
  3789. auto res = cli.send(req);
  3790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3791. EXPECT_EQ("/foo?a=1", target);
  3792. }
  3793. {
  3794. // Non-empty query in `req.path` -> `req.params` is not appended.
  3795. Client cli(HOST, port);
  3796. Request req;
  3797. req.method = "GET";
  3798. req.path = "/foo?b=2";
  3799. req.params.emplace("a", "1");
  3800. target.clear();
  3801. auto res = cli.send(req);
  3802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3803. EXPECT_EQ("/foo?b=2", target);
  3804. }
  3805. }
  3806. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3807. Server svr;
  3808. svr.Get("/", [](const Request &req, Response &) {
  3809. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3810. });
  3811. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3812. auto se = detail::scope_exit([&] {
  3813. svr.stop();
  3814. thread.join();
  3815. ASSERT_FALSE(svr.is_running());
  3816. });
  3817. svr.wait_until_ready();
  3818. {
  3819. Client cli(HOST, PORT);
  3820. cli.set_path_encode(false);
  3821. auto res = cli.Get("/?something=%0A");
  3822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3823. EXPECT_EQ(StatusCode::OK_200, res->status);
  3824. }
  3825. }
  3826. TEST(BindServerTest, BindDualStack) {
  3827. Server svr;
  3828. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3829. res.set_content("Hello World!", "text/plain");
  3830. });
  3831. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3832. auto se = detail::scope_exit([&] {
  3833. svr.stop();
  3834. thread.join();
  3835. ASSERT_FALSE(svr.is_running());
  3836. });
  3837. svr.wait_until_ready();
  3838. {
  3839. Client cli("127.0.0.1", PORT);
  3840. auto res = cli.Get("/1");
  3841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3842. EXPECT_EQ(StatusCode::OK_200, res->status);
  3843. EXPECT_EQ("Hello World!", res->body);
  3844. }
  3845. {
  3846. Client cli("::1", PORT);
  3847. auto res = cli.Get("/1");
  3848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3849. EXPECT_EQ(StatusCode::OK_200, res->status);
  3850. EXPECT_EQ("Hello World!", res->body);
  3851. }
  3852. }
  3853. TEST(BindServerTest, BindAndListenSeparately) {
  3854. Server svr;
  3855. int port = svr.bind_to_any_port("0.0.0.0");
  3856. ASSERT_TRUE(svr.is_valid());
  3857. ASSERT_TRUE(port > 0);
  3858. svr.stop();
  3859. }
  3860. // Reports whether anything is still listening on a loopback port. A plain
  3861. // connect() is used instead of a Client request because a socket left bound by
  3862. // mistake accepts the connection into its backlog and never answers, which
  3863. // would hang the test instead of failing it.
  3864. static bool is_loopback_port_accepting(int port) {
  3865. sockaddr_in addr{};
  3866. addr.sin_family = AF_INET;
  3867. addr.sin_port = htons(static_cast<uint16_t>(port));
  3868. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3869. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3870. EXPECT_NE(sock, INVALID_SOCKET);
  3871. if (sock == INVALID_SOCKET) { return false; }
  3872. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3873. static_cast<socklen_t>(sizeof(addr)));
  3874. detail::close_socket(sock);
  3875. return ret == 0;
  3876. }
  3877. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3878. Server svr;
  3879. auto port = svr.bind_to_any_port("127.0.0.1");
  3880. ASSERT_TRUE(port > 0);
  3881. svr.stop();
  3882. // bind_to_any_port() already called listen(2), so until stop() closed the
  3883. // descriptor the port kept accepting connections into the backlog. ASSERT
  3884. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3885. // below blocks forever in the accept loop.
  3886. ASSERT_FALSE(is_loopback_port_accepting(port));
  3887. // Nothing is left to accept on, so listen_after_bind() must report failure
  3888. // instead of returning success without ever serving.
  3889. EXPECT_FALSE(svr.listen_after_bind());
  3890. // The failed listen marks the server decommissioned, so a waiter returns
  3891. // instead of spinning forever.
  3892. svr.wait_until_ready();
  3893. }
  3894. #ifdef CPPHTTPLIB_SSL_ENABLED
  3895. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3896. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3897. CLIENT_CA_CERT_DIR);
  3898. int port = svr.bind_to_any_port("0.0.0.0");
  3899. ASSERT_TRUE(svr.is_valid());
  3900. ASSERT_TRUE(port > 0);
  3901. svr.stop();
  3902. }
  3903. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3904. // or a rejected CustomRoute() registration would not stop the server binding.
  3905. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3906. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3907. CLIENT_CA_CERT_DIR);
  3908. ASSERT_TRUE(svr.is_valid());
  3909. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3910. EXPECT_FALSE(svr.is_valid());
  3911. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3912. }
  3913. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3914. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3915. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3916. int port = svr.bind_to_any_port("0.0.0.0");
  3917. ASSERT_TRUE(svr.is_valid());
  3918. ASSERT_TRUE(port > 0);
  3919. svr.stop();
  3920. }
  3921. TEST(BindServerTest, UpdateCertsPem) {
  3922. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3923. int port = svr.bind_to_any_port("0.0.0.0");
  3924. ASSERT_TRUE(svr.is_valid());
  3925. ASSERT_TRUE(port > 0);
  3926. // Read PEM files
  3927. std::string cert_pem, key_pem, ca_pem;
  3928. read_file(SERVER_CERT_FILE, cert_pem);
  3929. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3930. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3931. // Update server certificates using PEM API
  3932. ASSERT_TRUE(
  3933. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3934. ASSERT_TRUE(svr.is_valid());
  3935. svr.stop();
  3936. }
  3937. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3938. // Start server with client CA (enables client auth)
  3939. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3940. ASSERT_TRUE(svr.is_valid());
  3941. bool handler_called = false;
  3942. svr.Get("/test", [&](const Request &req, Response &res) {
  3943. handler_called = true;
  3944. // Verify client certificate is present
  3945. auto cert = req.peer_cert();
  3946. EXPECT_TRUE(static_cast<bool>(cert));
  3947. res.set_content("ok", "text/plain");
  3948. });
  3949. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3950. auto se = detail::scope_exit([&] {
  3951. svr.stop();
  3952. t.join();
  3953. ASSERT_FALSE(svr.is_running());
  3954. });
  3955. svr.wait_until_ready();
  3956. // Read PEM files
  3957. std::string cert_pem, key_pem, ca_pem;
  3958. read_file(SERVER_CERT_FILE, cert_pem);
  3959. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3960. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3961. // Update server certificates and client CA using PEM API while server running
  3962. ASSERT_TRUE(
  3963. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3964. // Connect with client certificate
  3965. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3966. cli.enable_server_certificate_verification(false);
  3967. cli.set_connection_timeout(30);
  3968. auto res = cli.Get("/test");
  3969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3970. ASSERT_EQ(StatusCode::OK_200, res->status);
  3971. ASSERT_TRUE(handler_called);
  3972. EXPECT_EQ("ok", res->body);
  3973. }
  3974. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  3975. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3976. ASSERT_TRUE(svr.is_valid());
  3977. svr.Get("/test", [](const Request &, Response &res) {
  3978. res.set_content("ok", "text/plain");
  3979. });
  3980. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3981. auto se = detail::scope_exit([&] {
  3982. svr.stop();
  3983. t.join();
  3984. ASSERT_FALSE(svr.is_running());
  3985. });
  3986. svr.wait_until_ready();
  3987. // A connection that sends no ClientHello keeps its handshake in progress,
  3988. // once the server has had a moment to start it.
  3989. auto error = Error::Success;
  3990. auto sock = detail::create_client_socket(
  3991. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  3992. /*connection_timeout_sec=*/5, 0,
  3993. /*read_timeout_sec=*/5, 0,
  3994. /*write_timeout_sec=*/5, 0, std::string(), error);
  3995. ASSERT_NE(INVALID_SOCKET, sock);
  3996. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  3997. std::string cert_pem, key_pem;
  3998. read_file(SERVER_CERT_FILE, cert_pem);
  3999. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4000. auto update = std::async(std::launch::async, [&]() {
  4001. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4002. });
  4003. EXPECT_EQ(std::future_status::timeout,
  4004. update.wait_for(std::chrono::milliseconds(200)));
  4005. detail::close_socket(sock);
  4006. EXPECT_TRUE(update.get());
  4007. SSLClient cli(HOST, PORT);
  4008. cli.enable_server_certificate_verification(false);
  4009. auto res = cli.Get("/test");
  4010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4011. EXPECT_EQ(StatusCode::OK_200, res->status);
  4012. }
  4013. #endif
  4014. TEST(ErrorHandlerTest, ContentLength) {
  4015. Server svr;
  4016. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4017. res.status = StatusCode::OK_200;
  4018. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4019. "text/html"); // <= Content-Length still 13
  4020. });
  4021. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4022. res.set_content("Hello World!\n", "text/plain");
  4023. res.status = 524;
  4024. });
  4025. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4026. auto se = detail::scope_exit([&] {
  4027. svr.stop();
  4028. thread.join();
  4029. ASSERT_FALSE(svr.is_running());
  4030. });
  4031. svr.wait_until_ready();
  4032. {
  4033. Client cli(HOST, PORT);
  4034. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4036. EXPECT_EQ(StatusCode::OK_200, res->status);
  4037. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4038. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4039. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4040. }
  4041. }
  4042. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4043. TEST(ExceptionTest, WithoutExceptionHandler) {
  4044. Server svr;
  4045. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4046. throw std::runtime_error("exception...");
  4047. });
  4048. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4049. throw std::runtime_error("exception\r\n...");
  4050. });
  4051. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4052. auto se = detail::scope_exit([&] {
  4053. svr.stop();
  4054. listen_thread.join();
  4055. ASSERT_FALSE(svr.is_running());
  4056. });
  4057. svr.wait_until_ready();
  4058. Client cli("localhost", PORT);
  4059. {
  4060. auto res = cli.Get("/exception");
  4061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4062. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4063. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4064. }
  4065. {
  4066. auto res = cli.Get("/unknown");
  4067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4068. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4069. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4070. }
  4071. }
  4072. TEST(ExceptionTest, WithExceptionHandler) {
  4073. Server svr;
  4074. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4075. std::exception_ptr ep) {
  4076. EXPECT_FALSE(ep == nullptr);
  4077. try {
  4078. std::rethrow_exception(ep);
  4079. } catch (std::exception &e) {
  4080. EXPECT_EQ("abc", std::string(e.what()));
  4081. } catch (...) {}
  4082. res.status = StatusCode::InternalServerError_500;
  4083. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4084. "text/html"); // <= Content-Length still 13 at this point
  4085. });
  4086. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4087. res.set_content("Hello World!\n", "text/plain");
  4088. throw std::runtime_error("abc");
  4089. });
  4090. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4091. auto se = detail::scope_exit([&] {
  4092. svr.stop();
  4093. thread.join();
  4094. ASSERT_FALSE(svr.is_running());
  4095. });
  4096. svr.wait_until_ready();
  4097. for (size_t i = 0; i < 10; i++) {
  4098. Client cli(HOST, PORT);
  4099. for (size_t j = 0; j < 100; j++) {
  4100. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4102. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4103. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4104. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4105. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4106. }
  4107. cli.set_keep_alive(true);
  4108. for (size_t j = 0; j < 100; j++) {
  4109. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4111. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4112. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4113. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4114. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4115. }
  4116. }
  4117. }
  4118. TEST(ExceptionTest, AndErrorHandler) {
  4119. Server svr;
  4120. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4121. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4122. });
  4123. svr.set_exception_handler(
  4124. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4125. EXPECT_FALSE(ep == nullptr);
  4126. try {
  4127. std::rethrow_exception(ep);
  4128. } catch (std::exception &e) {
  4129. res.set_content(e.what(), "text/html");
  4130. } catch (...) {}
  4131. res.status = StatusCode::InternalServerError_500;
  4132. });
  4133. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4134. throw std::runtime_error("EXCEPTION");
  4135. });
  4136. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4137. res.set_content("ERROR", "text/html");
  4138. res.status = StatusCode::InternalServerError_500;
  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. Client cli(HOST, PORT);
  4148. {
  4149. auto res = cli.Get("/exception");
  4150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4151. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4152. EXPECT_EQ("EXCEPTION", res->body);
  4153. }
  4154. {
  4155. auto res = cli.Get("/error");
  4156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4157. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4158. EXPECT_EQ("ERROR", res->body);
  4159. }
  4160. {
  4161. auto res = cli.Get("/invalid");
  4162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4163. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4164. EXPECT_EQ("NOT_FOUND", res->body);
  4165. }
  4166. }
  4167. #endif
  4168. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4169. // process_request() wraps only routing() in a try/catch, so an exception from
  4170. // any other user callback used to unwind into the task queue - which does not
  4171. // catch - and terminate the process. Each test below runs the server on a
  4172. // single worker thread: a guard that catches the exception but still loses the
  4173. // thread would otherwise be hidden by a spare worker serving the follow-up
  4174. // request. Note that a regression here aborts the whole test binary rather
  4175. // than failing one test.
  4176. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4177. Server svr;
  4178. svr.new_task_queue = [] { return new ThreadPool(1); };
  4179. std::atomic<int> reported{0};
  4180. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4181. if (err == Error::UserCallbackException) { reported++; }
  4182. });
  4183. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4184. res.set_content_provider(
  4185. 1024, "text/plain",
  4186. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4187. sink.write("hello", 5);
  4188. throw std::runtime_error("from the content provider");
  4189. });
  4190. });
  4191. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4192. res.set_content("ok", "text/plain");
  4193. });
  4194. auto port = svr.bind_to_any_port(HOST);
  4195. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4196. auto se = detail::scope_exit([&] {
  4197. svr.stop();
  4198. listen_thread.join();
  4199. ASSERT_FALSE(svr.is_running());
  4200. });
  4201. svr.wait_until_ready();
  4202. {
  4203. Client cli(HOST, port);
  4204. cli.set_read_timeout(5, 0);
  4205. EXPECT_FALSE(cli.Get("/throw"));
  4206. }
  4207. EXPECT_TRUE(svr.is_running());
  4208. EXPECT_EQ(1, reported.load());
  4209. // A request on a fresh connection is still served.
  4210. {
  4211. Client cli(HOST, port);
  4212. auto res = cli.Get("/ok");
  4213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4214. EXPECT_EQ(StatusCode::OK_200, res->status);
  4215. EXPECT_EQ("ok", res->body);
  4216. }
  4217. }
  4218. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4219. Server svr;
  4220. svr.new_task_queue = [] { return new ThreadPool(1); };
  4221. std::atomic<bool> should_throw{true};
  4222. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4223. res.set_content("hi", "text/plain");
  4224. });
  4225. svr.set_post_routing_handler(
  4226. [&](const Request & /*req*/, Response & /*res*/) {
  4227. if (should_throw) {
  4228. throw std::runtime_error("from the post-routing handler");
  4229. }
  4230. });
  4231. auto port = svr.bind_to_any_port(HOST);
  4232. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4233. auto se = detail::scope_exit([&] {
  4234. svr.stop();
  4235. listen_thread.join();
  4236. ASSERT_FALSE(svr.is_running());
  4237. });
  4238. svr.wait_until_ready();
  4239. {
  4240. Client cli(HOST, port);
  4241. cli.set_read_timeout(5, 0);
  4242. EXPECT_FALSE(cli.Get("/hi"));
  4243. }
  4244. EXPECT_TRUE(svr.is_running());
  4245. should_throw = false;
  4246. {
  4247. Client cli(HOST, port);
  4248. auto res = cli.Get("/hi");
  4249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4250. EXPECT_EQ(StatusCode::OK_200, res->status);
  4251. EXPECT_EQ("hi", res->body);
  4252. }
  4253. }
  4254. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4255. // The guard reports the caught exception through the error logger, which is
  4256. // a user callback too. A logger that throws has to be contained as well, or
  4257. // the process would terminate from inside the catch.
  4258. Server svr;
  4259. svr.new_task_queue = [] { return new ThreadPool(1); };
  4260. std::atomic<int> reported{0};
  4261. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4262. if (err == Error::UserCallbackException) {
  4263. reported++;
  4264. throw std::runtime_error("from the error logger");
  4265. }
  4266. });
  4267. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4268. res.set_content_provider(
  4269. 1024, "text/plain",
  4270. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4271. sink.write("hello", 5);
  4272. throw std::runtime_error("from the content provider");
  4273. });
  4274. });
  4275. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4276. res.set_content("ok", "text/plain");
  4277. });
  4278. auto port = svr.bind_to_any_port(HOST);
  4279. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4280. auto se = detail::scope_exit([&] {
  4281. svr.stop();
  4282. listen_thread.join();
  4283. ASSERT_FALSE(svr.is_running());
  4284. });
  4285. svr.wait_until_ready();
  4286. {
  4287. Client cli(HOST, port);
  4288. cli.set_read_timeout(5, 0);
  4289. EXPECT_FALSE(cli.Get("/throw"));
  4290. }
  4291. EXPECT_TRUE(svr.is_running());
  4292. EXPECT_EQ(1, reported.load());
  4293. {
  4294. Client cli(HOST, port);
  4295. auto res = cli.Get("/ok");
  4296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4297. EXPECT_EQ(StatusCode::OK_200, res->status);
  4298. EXPECT_EQ("ok", res->body);
  4299. }
  4300. }
  4301. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4302. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4303. // so the exception unwinds through the ws::WebSocket object on its way to
  4304. // the guard. None of the HTTP cases above cross that.
  4305. Server svr;
  4306. svr.new_task_queue = [] { return new ThreadPool(1); };
  4307. std::atomic<int> reported{0};
  4308. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4309. if (err == Error::UserCallbackException) { reported++; }
  4310. });
  4311. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4312. throw std::runtime_error("from the WebSocket handler");
  4313. });
  4314. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4315. res.set_content("ok", "text/plain");
  4316. });
  4317. auto port = svr.bind_to_any_port(HOST);
  4318. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4319. auto se = detail::scope_exit([&] {
  4320. svr.stop();
  4321. listen_thread.join();
  4322. ASSERT_FALSE(svr.is_running());
  4323. });
  4324. svr.wait_until_ready();
  4325. {
  4326. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4327. "/ws");
  4328. auto res = client.connect();
  4329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4330. // The server dropped the connection instead of dying.
  4331. std::string msg;
  4332. EXPECT_FALSE(client.read(msg));
  4333. client.close();
  4334. }
  4335. EXPECT_TRUE(svr.is_running());
  4336. EXPECT_EQ(1, reported.load());
  4337. {
  4338. Client cli(HOST, port);
  4339. auto res = cli.Get("/ok");
  4340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4341. EXPECT_EQ(StatusCode::OK_200, res->status);
  4342. EXPECT_EQ("ok", res->body);
  4343. }
  4344. }
  4345. #ifdef CPPHTTPLIB_SSL_ENABLED
  4346. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4347. // SSLServer::process_and_close_socket() is a separate overload with its own
  4348. // guard, so it is exercised on its own.
  4349. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4350. ASSERT_TRUE(svr.is_valid());
  4351. svr.new_task_queue = [] { return new ThreadPool(1); };
  4352. std::atomic<int> reported{0};
  4353. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4354. if (err == Error::UserCallbackException) { reported++; }
  4355. });
  4356. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4357. res.set_content_provider(
  4358. 1024, "text/plain",
  4359. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4360. sink.write("hello", 5);
  4361. throw std::runtime_error("from the content provider");
  4362. });
  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. SSLClient cli(HOST, port);
  4377. cli.enable_server_certificate_verification(false);
  4378. cli.set_read_timeout(5, 0);
  4379. EXPECT_FALSE(cli.Get("/throw"));
  4380. }
  4381. EXPECT_TRUE(svr.is_running());
  4382. EXPECT_EQ(1, reported.load());
  4383. {
  4384. SSLClient cli(HOST, port);
  4385. cli.enable_server_certificate_verification(false);
  4386. auto res = cli.Get("/ok");
  4387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4388. EXPECT_EQ(StatusCode::OK_200, res->status);
  4389. EXPECT_EQ("ok", res->body);
  4390. }
  4391. }
  4392. #endif
  4393. #endif
  4394. TEST(NoContentTest, ContentLength) {
  4395. Server svr;
  4396. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4397. res.status = StatusCode::NoContent_204;
  4398. });
  4399. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4400. auto se = detail::scope_exit([&] {
  4401. svr.stop();
  4402. thread.join();
  4403. ASSERT_FALSE(svr.is_running());
  4404. });
  4405. svr.wait_until_ready();
  4406. {
  4407. Client cli(HOST, PORT);
  4408. auto res = cli.Get("/hi");
  4409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4410. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4411. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4412. }
  4413. }
  4414. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4415. #ifdef CPPHTTPLIB_SSL_ENABLED
  4416. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4417. ASSERT_TRUE(svr.is_valid());
  4418. #else
  4419. Server svr;
  4420. #endif
  4421. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4422. if (req.path == "/routing_handler") {
  4423. res.set_header("PRE_ROUTING", "on");
  4424. res.set_content("Routing Handler", "text/plain");
  4425. return httplib::Server::HandlerResponse::Handled;
  4426. }
  4427. return httplib::Server::HandlerResponse::Unhandled;
  4428. });
  4429. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4430. res.set_content("Error", "text/html");
  4431. });
  4432. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4433. if (req.path == "/routing_handler") {
  4434. res.set_header("POST_ROUTING", "on");
  4435. }
  4436. });
  4437. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4438. res.set_content("Hello World!\n", "text/plain");
  4439. });
  4440. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4441. auto se = detail::scope_exit([&] {
  4442. svr.stop();
  4443. thread.join();
  4444. ASSERT_FALSE(svr.is_running());
  4445. });
  4446. svr.wait_until_ready();
  4447. {
  4448. #ifdef CPPHTTPLIB_SSL_ENABLED
  4449. SSLClient cli(HOST, PORT);
  4450. cli.enable_server_certificate_verification(false);
  4451. #else
  4452. Client cli(HOST, PORT);
  4453. #endif
  4454. auto res = cli.Get("/routing_handler");
  4455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4456. EXPECT_EQ(StatusCode::OK_200, res->status);
  4457. EXPECT_EQ("Routing Handler", res->body);
  4458. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4459. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4460. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4461. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4462. }
  4463. {
  4464. #ifdef CPPHTTPLIB_SSL_ENABLED
  4465. SSLClient cli(HOST, PORT);
  4466. cli.enable_server_certificate_verification(false);
  4467. #else
  4468. Client cli(HOST, PORT);
  4469. #endif
  4470. auto res = cli.Get("/hi");
  4471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4472. EXPECT_EQ(StatusCode::OK_200, res->status);
  4473. EXPECT_EQ("Hello World!\n", res->body);
  4474. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4475. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4476. }
  4477. {
  4478. #ifdef CPPHTTPLIB_SSL_ENABLED
  4479. SSLClient cli(HOST, PORT);
  4480. cli.enable_server_certificate_verification(false);
  4481. #else
  4482. Client cli(HOST, PORT);
  4483. #endif
  4484. auto res = cli.Get("/aaa");
  4485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4486. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4487. EXPECT_EQ("Error", res->body);
  4488. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4489. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4490. }
  4491. }
  4492. TEST(RequestHandlerTest, PreRequestHandler) {
  4493. auto route_path = "/user/:user";
  4494. Server svr;
  4495. svr.Get("/hi", [](const Request &, Response &res) {
  4496. res.set_content("hi", "text/plain");
  4497. });
  4498. svr.Get(route_path, [](const Request &req, Response &res) {
  4499. res.set_content(req.path_params.at("user"), "text/plain");
  4500. });
  4501. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4502. if (req.matched_route == route_path) {
  4503. auto user = req.path_params.at("user");
  4504. if (user != "john") {
  4505. res.status = StatusCode::Forbidden_403;
  4506. res.set_content("error", "text/html");
  4507. return Server::HandlerResponse::Handled;
  4508. }
  4509. }
  4510. return Server::HandlerResponse::Unhandled;
  4511. });
  4512. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4513. auto se = detail::scope_exit([&] {
  4514. svr.stop();
  4515. thread.join();
  4516. ASSERT_FALSE(svr.is_running());
  4517. });
  4518. svr.wait_until_ready();
  4519. Client cli(HOST, PORT);
  4520. {
  4521. auto res = cli.Get("/hi");
  4522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4523. EXPECT_EQ(StatusCode::OK_200, res->status);
  4524. EXPECT_EQ("hi", res->body);
  4525. }
  4526. {
  4527. auto res = cli.Get("/user/john");
  4528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4529. EXPECT_EQ(StatusCode::OK_200, res->status);
  4530. EXPECT_EQ("john", res->body);
  4531. }
  4532. {
  4533. auto res = cli.Get("/user/invalid-user");
  4534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4535. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4536. EXPECT_EQ("error", res->body);
  4537. }
  4538. }
  4539. // The pre-request handler must run before the request body is read, so a
  4540. // rejected request never forces the server to buffer a (potentially large)
  4541. // body. Here the posted body is larger than the payload limit: if the body
  4542. // were read first the server would answer 413, but because the pre-request
  4543. // handler runs first it answers 403 and the body is never read.
  4544. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4545. Server svr;
  4546. svr.set_payload_max_length(8);
  4547. auto handler_ran = false;
  4548. svr.Post("/reject", [&](const Request &req, Response &res) {
  4549. handler_ran = true;
  4550. res.set_content(req.body, "text/plain");
  4551. });
  4552. svr.Post("/accept", [](const Request &req, Response &res) {
  4553. res.set_content(req.body, "text/plain");
  4554. });
  4555. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4556. if (req.matched_route == "/reject") {
  4557. res.status = StatusCode::Forbidden_403;
  4558. res.set_content("denied", "text/plain");
  4559. return Server::HandlerResponse::Handled;
  4560. }
  4561. return Server::HandlerResponse::Unhandled;
  4562. });
  4563. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4564. auto se = detail::scope_exit([&] {
  4565. svr.stop();
  4566. thread.join();
  4567. ASSERT_FALSE(svr.is_running());
  4568. });
  4569. svr.wait_until_ready();
  4570. Client cli(HOST, PORT);
  4571. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4572. // rejects with 403 before the body is read, so 413 is never reached.
  4573. {
  4574. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4576. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4577. EXPECT_EQ("denied", res->body);
  4578. EXPECT_FALSE(handler_ran);
  4579. }
  4580. // An approved route still reads the body and enforces the payload limit.
  4581. {
  4582. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4584. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4585. }
  4586. }
  4587. TEST(UserDataTest, BasicOperations) {
  4588. httplib::UserData ud;
  4589. // Initially empty
  4590. EXPECT_FALSE(ud.has("key"));
  4591. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4592. // set and get
  4593. ud.set("key", 42);
  4594. EXPECT_TRUE(ud.has("key"));
  4595. auto *p = ud.get<int>("key");
  4596. ASSERT_NE(nullptr, p);
  4597. EXPECT_EQ(42, *p);
  4598. // Type mismatch → nullptr
  4599. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4600. // Overwrite with different type
  4601. ud.set("key", std::string("hello"));
  4602. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4603. auto *s = ud.get<std::string>("key");
  4604. ASSERT_NE(nullptr, s);
  4605. EXPECT_EQ("hello", *s);
  4606. // erase
  4607. ud.erase("key");
  4608. EXPECT_FALSE(ud.has("key"));
  4609. // clear
  4610. ud.set("a", 1);
  4611. ud.set("b", 2);
  4612. ud.clear();
  4613. EXPECT_FALSE(ud.has("a"));
  4614. EXPECT_FALSE(ud.has("b"));
  4615. }
  4616. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4617. struct AuthCtx {
  4618. std::string user_id;
  4619. };
  4620. Server svr;
  4621. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4622. res.user_data.set("auth", AuthCtx{"alice"});
  4623. return Server::HandlerResponse::Unhandled;
  4624. });
  4625. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4626. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4627. ASSERT_NE(nullptr, ctx);
  4628. res.set_content("Hello " + ctx->user_id, "text/plain");
  4629. });
  4630. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4631. auto se = detail::scope_exit([&] {
  4632. svr.stop();
  4633. thread.join();
  4634. ASSERT_FALSE(svr.is_running());
  4635. });
  4636. svr.wait_until_ready();
  4637. Client cli(HOST, PORT);
  4638. auto res = cli.Get("/me");
  4639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4640. EXPECT_EQ(StatusCode::OK_200, res->status);
  4641. EXPECT_EQ("Hello alice", res->body);
  4642. }
  4643. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4644. struct RoleCtx {
  4645. std::string role;
  4646. };
  4647. Server svr;
  4648. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4649. res.user_data.set("role", RoleCtx{"admin"});
  4650. return Server::HandlerResponse::Unhandled;
  4651. });
  4652. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4653. auto *ctx = res.user_data.get<RoleCtx>("role");
  4654. ASSERT_NE(nullptr, ctx);
  4655. res.set_content(ctx->role, "text/plain");
  4656. });
  4657. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4658. auto se = detail::scope_exit([&] {
  4659. svr.stop();
  4660. thread.join();
  4661. ASSERT_FALSE(svr.is_running());
  4662. });
  4663. svr.wait_until_ready();
  4664. Client cli(HOST, PORT);
  4665. auto res = cli.Get("/role");
  4666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4667. EXPECT_EQ(StatusCode::OK_200, res->status);
  4668. EXPECT_EQ("admin", res->body);
  4669. }
  4670. TEST(InvalidFormatTest, StatusCode) {
  4671. Server svr;
  4672. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4673. res.set_content("Hello World!\n", "text/plain");
  4674. res.status = 9999; // Status should be a three-digit code...
  4675. });
  4676. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4677. auto se = detail::scope_exit([&] {
  4678. svr.stop();
  4679. thread.join();
  4680. ASSERT_FALSE(svr.is_running());
  4681. });
  4682. svr.wait_until_ready();
  4683. {
  4684. Client cli(HOST, PORT);
  4685. auto res = cli.Get("/hi");
  4686. ASSERT_FALSE(res);
  4687. }
  4688. }
  4689. TEST(URLFragmentTest, WithFragment) {
  4690. Server svr;
  4691. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4692. EXPECT_TRUE(req.target == "/hi");
  4693. });
  4694. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4695. auto se = detail::scope_exit([&] {
  4696. svr.stop();
  4697. thread.join();
  4698. ASSERT_FALSE(svr.is_running());
  4699. });
  4700. svr.wait_until_ready();
  4701. {
  4702. Client cli(HOST, PORT);
  4703. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4704. EXPECT_TRUE(res);
  4705. EXPECT_EQ(StatusCode::OK_200, res->status);
  4706. res = cli.Get("/hi%23key1=val1=key2=val2");
  4707. EXPECT_TRUE(res);
  4708. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4709. }
  4710. }
  4711. TEST(HeaderWriter, SetHeaderWriter) {
  4712. Server svr;
  4713. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4714. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4715. return detail::write_headers(strm, hdrs);
  4716. });
  4717. svr.Get("/hi", [](const Request &req, Response &res) {
  4718. auto it = req.headers.find("CustomClientHeader");
  4719. EXPECT_TRUE(it != req.headers.end());
  4720. EXPECT_EQ(it->second, "CustomClientValue");
  4721. res.set_content("Hello World!\n", "text/plain");
  4722. });
  4723. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4724. auto se = detail::scope_exit([&] {
  4725. svr.stop();
  4726. thread.join();
  4727. ASSERT_FALSE(svr.is_running());
  4728. });
  4729. svr.wait_until_ready();
  4730. {
  4731. Client cli(HOST, PORT);
  4732. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4733. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4734. return detail::write_headers(strm, hdrs);
  4735. });
  4736. auto res = cli.Get("/hi");
  4737. EXPECT_TRUE(res);
  4738. EXPECT_EQ(StatusCode::OK_200, res->status);
  4739. auto it = res->headers.find("CustomServerHeader");
  4740. EXPECT_TRUE(it != res->headers.end());
  4741. EXPECT_EQ(it->second, "CustomServerValue");
  4742. }
  4743. }
  4744. class ServerTest : public ::testing::Test {
  4745. protected:
  4746. ServerTest()
  4747. : cli_(HOST, PORT)
  4748. #ifdef CPPHTTPLIB_SSL_ENABLED
  4749. ,
  4750. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4751. #endif
  4752. {
  4753. #ifdef CPPHTTPLIB_SSL_ENABLED
  4754. cli_.enable_server_certificate_verification(false);
  4755. #endif
  4756. // Allow LARGE_DATA (100MB) responses
  4757. cli_.set_payload_max_length(200 * 1024 * 1024);
  4758. }
  4759. virtual void SetUp() {
  4760. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4761. svr_.set_payload_max_length(200 * 1024 * 1024);
  4762. svr_.set_mount_point("/", "./www");
  4763. svr_.set_mount_point("/mount", "./www2");
  4764. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4765. svr_.Get("/hi",
  4766. [&](const Request & /*req*/, Response &res) {
  4767. res.set_content("Hello World!", "text/plain");
  4768. })
  4769. .Get("/file_content",
  4770. [&](const Request & /*req*/, Response &res) {
  4771. res.set_file_content("./www/dir/test.html");
  4772. })
  4773. .Get("/file_content_with_content_type",
  4774. [&](const Request & /*req*/, Response &res) {
  4775. res.set_file_content("./www/file", "text/plain");
  4776. })
  4777. .Get("/invalid_file_content",
  4778. [&](const Request & /*req*/, Response &res) {
  4779. res.set_file_content("./www/dir/invalid_file_path");
  4780. })
  4781. .Get("/http_response_splitting",
  4782. [&](const Request & /*req*/, Response &res) {
  4783. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4784. EXPECT_EQ(0U, res.headers.size());
  4785. EXPECT_FALSE(res.has_header("a"));
  4786. res.set_header("a", "1\nSet-Cookie: a=1");
  4787. EXPECT_EQ(0U, res.headers.size());
  4788. EXPECT_FALSE(res.has_header("a"));
  4789. res.set_header("a", "1\rSet-Cookie: a=1");
  4790. EXPECT_EQ(0U, res.headers.size());
  4791. EXPECT_FALSE(res.has_header("a"));
  4792. res.set_header("a\r\nb", "0");
  4793. EXPECT_EQ(0U, res.headers.size());
  4794. EXPECT_FALSE(res.has_header("a"));
  4795. res.set_header("a\rb", "0");
  4796. EXPECT_EQ(0U, res.headers.size());
  4797. EXPECT_FALSE(res.has_header("a"));
  4798. res.set_header("a\nb", "0");
  4799. EXPECT_EQ(0U, res.headers.size());
  4800. EXPECT_FALSE(res.has_header("a"));
  4801. res.set_redirect("1\r\nSet-Cookie: a=1");
  4802. EXPECT_EQ(0U, res.headers.size());
  4803. EXPECT_FALSE(res.has_header("Location"));
  4804. })
  4805. .Get("/slow",
  4806. [&](const Request & /*req*/, Response &res) {
  4807. std::this_thread::sleep_for(std::chrono::seconds(4));
  4808. res.set_content("slow", "text/plain");
  4809. })
  4810. #if 0
  4811. .Post("/slowpost",
  4812. [&](const Request & /*req*/, Response &res) {
  4813. std::this_thread::sleep_for(std::chrono::seconds(2));
  4814. res.set_content("slow", "text/plain");
  4815. })
  4816. #endif
  4817. .Get("/remote_addr",
  4818. [&](const Request &req, Response &res) {
  4819. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4820. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4821. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4822. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4823. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4824. #endif
  4825. res.set_content(req.remote_addr, "text/plain");
  4826. })
  4827. .Get("/local_addr",
  4828. [&](const Request &req, Response &res) {
  4829. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4830. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4831. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4832. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4833. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4834. #endif
  4835. auto local_addr = req.local_addr;
  4836. auto local_port = std::to_string(req.local_port);
  4837. res.set_content(local_addr.append(":").append(local_port),
  4838. "text/plain");
  4839. })
  4840. .Get("/endwith%",
  4841. [&](const Request & /*req*/, Response &res) {
  4842. res.set_content("Hello World!", "text/plain");
  4843. })
  4844. .Get("/a\\+\\+b",
  4845. [&](const Request &req, Response &res) {
  4846. ASSERT_TRUE(req.has_param("a +b"));
  4847. auto val = req.get_param_value("a +b");
  4848. res.set_content(val, "text/plain");
  4849. })
  4850. .Get("/", [&](const Request & /*req*/,
  4851. Response &res) { res.set_redirect("/hi"); })
  4852. .Post("/1",
  4853. [](const Request & /*req*/, Response &res) {
  4854. res.set_redirect("/2", StatusCode::SeeOther_303);
  4855. })
  4856. .Get("/2",
  4857. [](const Request & /*req*/, Response &res) {
  4858. res.set_content("redirected.", "text/plain");
  4859. res.status = StatusCode::OK_200;
  4860. })
  4861. .Post("/person",
  4862. [&](const Request &req, Response &res) {
  4863. if (req.has_param("name") && req.has_param("note")) {
  4864. persons_[req.get_param_value("name")] =
  4865. req.get_param_value("note");
  4866. } else {
  4867. res.status = StatusCode::BadRequest_400;
  4868. }
  4869. })
  4870. .Put("/person",
  4871. [&](const Request &req, Response &res) {
  4872. if (req.has_param("name") && req.has_param("note")) {
  4873. persons_[req.get_param_value("name")] =
  4874. req.get_param_value("note");
  4875. } else {
  4876. res.status = StatusCode::BadRequest_400;
  4877. }
  4878. })
  4879. .Get("/person/(.*)",
  4880. [&](const Request &req, Response &res) {
  4881. string name = req.matches[1];
  4882. if (persons_.find(name) != persons_.end()) {
  4883. auto note = persons_[name];
  4884. res.set_content(note, "text/plain");
  4885. } else {
  4886. res.status = StatusCode::NotFound_404;
  4887. }
  4888. })
  4889. .Delete("/person",
  4890. [&](const Request &req, Response &res) {
  4891. if (req.has_param("name")) {
  4892. string name = req.get_param_value("name");
  4893. if (persons_.find(name) != persons_.end()) {
  4894. persons_.erase(name);
  4895. res.set_content("DELETED", "text/plain");
  4896. } else {
  4897. res.status = StatusCode::NotFound_404;
  4898. }
  4899. } else {
  4900. res.status = StatusCode::BadRequest_400;
  4901. }
  4902. })
  4903. .Post("/x-www-form-urlencoded-json",
  4904. [&](const Request &req, Response &res) {
  4905. auto json = req.get_param_value("json");
  4906. ASSERT_EQ(JSON_DATA, json);
  4907. res.set_content(json, "appliation/json");
  4908. res.status = StatusCode::OK_200;
  4909. })
  4910. .Get("/streamed-chunked",
  4911. [&](const Request & /*req*/, Response &res) {
  4912. res.set_chunked_content_provider(
  4913. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4914. sink.os << "123";
  4915. sink.os << "456";
  4916. sink.os << "789";
  4917. sink.done();
  4918. return true;
  4919. });
  4920. })
  4921. .Get("/streamed-chunked-with-prohibited-trailer",
  4922. [&](const Request & /*req*/, Response &res) {
  4923. auto i = new int(0);
  4924. // Declare both a prohibited trailer (Content-Length) and an
  4925. // allowed one
  4926. res.set_header("Trailer", "Content-Length, X-Allowed");
  4927. res.set_chunked_content_provider(
  4928. "text/plain",
  4929. [i](size_t /*offset*/, DataSink &sink) {
  4930. switch (*i) {
  4931. case 0: sink.os << "123"; break;
  4932. case 1: sink.os << "456"; break;
  4933. case 2: sink.os << "789"; break;
  4934. case 3: {
  4935. sink.done_with_trailer(
  4936. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4937. } break;
  4938. }
  4939. (*i)++;
  4940. return true;
  4941. },
  4942. [i](bool success) {
  4943. EXPECT_TRUE(success);
  4944. delete i;
  4945. });
  4946. })
  4947. .Get("/streamed-chunked2",
  4948. [&](const Request & /*req*/, Response &res) {
  4949. auto i = new int(0);
  4950. res.set_chunked_content_provider(
  4951. "text/plain",
  4952. [i](size_t /*offset*/, DataSink &sink) {
  4953. switch (*i) {
  4954. case 0: sink.os << "123"; break;
  4955. case 1: sink.os << "456"; break;
  4956. case 2: sink.os << "789"; break;
  4957. case 3: sink.done(); break;
  4958. }
  4959. (*i)++;
  4960. return true;
  4961. },
  4962. [i](bool success) {
  4963. EXPECT_TRUE(success);
  4964. delete i;
  4965. });
  4966. })
  4967. .Get("/streamed-chunked-with-trailer",
  4968. [&](const Request & /*req*/, Response &res) {
  4969. auto i = new int(0);
  4970. res.set_header("Trailer", "Dummy1, Dummy2");
  4971. res.set_chunked_content_provider(
  4972. "text/plain",
  4973. [i](size_t /*offset*/, DataSink &sink) {
  4974. switch (*i) {
  4975. case 0: sink.os << "123"; break;
  4976. case 1: sink.os << "456"; break;
  4977. case 2: sink.os << "789"; break;
  4978. case 3: {
  4979. sink.done_with_trailer(
  4980. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4981. } break;
  4982. }
  4983. (*i)++;
  4984. return true;
  4985. },
  4986. [i](bool success) {
  4987. EXPECT_TRUE(success);
  4988. delete i;
  4989. });
  4990. })
  4991. .Get("/streamed",
  4992. [&](const Request & /*req*/, Response &res) {
  4993. res.set_content_provider(
  4994. 6, "text/plain",
  4995. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4996. sink.os << (offset < 3 ? "a" : "b");
  4997. return true;
  4998. });
  4999. })
  5000. .Get("/streamed-without-length",
  5001. [&](const Request & /*req*/, Response &res) {
  5002. auto data = new std::string("abcdefg");
  5003. res.set_content_provider(
  5004. "text/plain",
  5005. [data](size_t offset, DataSink &sink) {
  5006. if (offset < data->size()) {
  5007. sink.os << data->substr(offset);
  5008. }
  5009. sink.done();
  5010. return true;
  5011. },
  5012. [data](bool success) {
  5013. EXPECT_TRUE(success);
  5014. delete data;
  5015. });
  5016. })
  5017. .Get("/streamed-with-range",
  5018. [&](const Request &req, Response &res) {
  5019. auto data = new std::string("abcdefg");
  5020. // An explicit status keeps the server from picking the 206 it
  5021. // would otherwise choose for a ranged request, so the response
  5022. // is not a partial representation.
  5023. auto status = req.get_param_value("status");
  5024. if (status == "200") {
  5025. res.status = StatusCode::OK_200;
  5026. } else if (status == "403") {
  5027. res.status = StatusCode::Forbidden_403;
  5028. }
  5029. res.set_content_provider(
  5030. data->size(), "text/plain",
  5031. [data](size_t offset, size_t length, DataSink &sink) {
  5032. size_t DATA_CHUNK_SIZE = 4;
  5033. const auto &d = *data;
  5034. auto out_len =
  5035. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5036. auto ret =
  5037. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5038. EXPECT_TRUE(ret);
  5039. return true;
  5040. },
  5041. [data, &req](bool success) {
  5042. EXPECT_EQ(success, !req.has_param("error"));
  5043. delete data;
  5044. });
  5045. })
  5046. .Get("/streamed-cancel",
  5047. [&](const Request & /*req*/, Response &res) {
  5048. res.set_content_provider(
  5049. size_t(-1), "text/plain",
  5050. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5051. sink.os << "data_chunk";
  5052. return true;
  5053. });
  5054. })
  5055. .Get("/regex-with-delimiter",
  5056. [&](const Request &req, Response & /*res*/) {
  5057. ASSERT_TRUE(req.has_param("key"));
  5058. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5059. })
  5060. .Get("/with-range",
  5061. [&](const Request & /*req*/, Response &res) {
  5062. res.set_content("abcdefg", "text/plain");
  5063. })
  5064. .Get("/test-start-time",
  5065. [&](const Request &req, Response & /*res*/) {
  5066. EXPECT_NE(req.start_time_,
  5067. std::chrono::steady_clock::time_point::min());
  5068. })
  5069. .Get("/with-range-customized-response",
  5070. [&](const Request & /*req*/, Response &res) {
  5071. res.status = StatusCode::BadRequest_400;
  5072. res.set_content(JSON_DATA, "application/json");
  5073. })
  5074. .Post("/chunked",
  5075. [&](const Request &req, Response & /*res*/) {
  5076. EXPECT_EQ(req.body, "dechunked post body");
  5077. })
  5078. .Post("/large-chunked",
  5079. [&](const Request &req, Response & /*res*/) {
  5080. std::string expected(6 * 30 * 1024u, 'a');
  5081. EXPECT_EQ(req.body, expected);
  5082. })
  5083. .Post("/multipart",
  5084. [&](const Request &req, Response & /*res*/) {
  5085. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5086. req.form.get_field_count("text2") +
  5087. req.form.get_field_count("file3") +
  5088. req.form.get_field_count("file4"));
  5089. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5090. req.form.get_file_count("file2"));
  5091. ASSERT_TRUE(!req.form.has_file("???"));
  5092. ASSERT_TRUE(!req.form.has_field("???"));
  5093. ASSERT_TRUE(req.body.empty());
  5094. {
  5095. const auto &text = req.form.get_field("text1");
  5096. EXPECT_EQ("text default", text);
  5097. }
  5098. {
  5099. const auto &text = req.form.get_field("text2");
  5100. EXPECT_EQ("aωb", text);
  5101. }
  5102. {
  5103. const auto &file = req.form.get_file("file1");
  5104. EXPECT_EQ("hello.txt", file.filename);
  5105. EXPECT_EQ("text/plain", file.content_type);
  5106. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5107. }
  5108. {
  5109. const auto &file = req.form.get_file("file2");
  5110. EXPECT_EQ("world.json", file.filename);
  5111. EXPECT_EQ("application/json", file.content_type);
  5112. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5113. }
  5114. {
  5115. const auto &text = req.form.get_field("file3");
  5116. EXPECT_EQ(0u, text.size());
  5117. }
  5118. {
  5119. const auto &text = req.form.get_field("file4");
  5120. EXPECT_EQ(0u, text.size());
  5121. }
  5122. })
  5123. .Post("/multipart/multi_file_values",
  5124. [&](const Request &req, Response & /*res*/) {
  5125. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5126. req.form.get_field_count("multi_text1"));
  5127. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5128. ASSERT_TRUE(!req.form.has_file("???"));
  5129. ASSERT_TRUE(!req.form.has_field("???"));
  5130. ASSERT_TRUE(req.body.empty());
  5131. {
  5132. const auto &text = req.form.get_field("text");
  5133. EXPECT_EQ("default text", text);
  5134. }
  5135. {
  5136. const auto &text1_values = req.form.get_fields("multi_text1");
  5137. EXPECT_EQ(2u, text1_values.size());
  5138. EXPECT_EQ("aaaaa", text1_values[0]);
  5139. EXPECT_EQ("bbbbb", text1_values[1]);
  5140. }
  5141. {
  5142. const auto &file1_values = req.form.get_files("multi_file1");
  5143. EXPECT_EQ(2u, file1_values.size());
  5144. auto file1 = file1_values[0];
  5145. EXPECT_EQ(file1.filename, "hello.txt");
  5146. EXPECT_EQ(file1.content_type, "text/plain");
  5147. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5148. auto file2 = file1_values[1];
  5149. EXPECT_EQ(file2.filename, "world.json");
  5150. EXPECT_EQ(file2.content_type, "application/json");
  5151. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5152. }
  5153. })
  5154. .Post("/empty",
  5155. [&](const Request &req, Response &res) {
  5156. EXPECT_EQ(req.body, "");
  5157. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5158. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5159. res.set_content("empty", "text/plain");
  5160. })
  5161. .Post("/empty-no-content-type",
  5162. [&](const Request &req, Response &res) {
  5163. EXPECT_EQ(req.body, "");
  5164. EXPECT_FALSE(req.has_header("Content-Type"));
  5165. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5166. res.set_content("empty-no-content-type", "text/plain");
  5167. })
  5168. .Post("/path-only",
  5169. [&](const Request &req, Response &res) {
  5170. EXPECT_EQ(req.body, "");
  5171. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5172. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5173. res.set_content("path-only", "text/plain");
  5174. })
  5175. .Post("/path-headers-only",
  5176. [&](const Request &req, Response &res) {
  5177. EXPECT_EQ(req.body, "");
  5178. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5179. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5180. EXPECT_EQ("world", req.get_header_value("hello"));
  5181. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5182. res.set_content("path-headers-only", "text/plain");
  5183. })
  5184. .Post("/post-large",
  5185. [&](const Request &req, Response &res) {
  5186. EXPECT_EQ(req.body, LARGE_DATA);
  5187. res.set_content(req.body, "text/plain");
  5188. })
  5189. .Post("/post-loopback",
  5190. [&](const Request &, Response &res,
  5191. ContentReader const &content_reader) {
  5192. std::string body;
  5193. content_reader([&](const char *data, size_t data_length) {
  5194. body.append(data, data_length);
  5195. return true;
  5196. });
  5197. res.set_content(body, "text/plain");
  5198. })
  5199. .Put("/put-loopback",
  5200. [&](const Request &, Response &res,
  5201. ContentReader const &content_reader) {
  5202. std::string body;
  5203. content_reader([&](const char *data, size_t data_length) {
  5204. body.append(data, data_length);
  5205. return true;
  5206. });
  5207. res.set_content(body, "text/plain");
  5208. })
  5209. .Patch("/patch-loopback",
  5210. [&](const Request &, Response &res,
  5211. ContentReader const &content_reader) {
  5212. std::string body;
  5213. content_reader([&](const char *data, size_t data_length) {
  5214. body.append(data, data_length);
  5215. return true;
  5216. });
  5217. res.set_content(body, "text/plain");
  5218. })
  5219. .Put("/empty-no-content-type",
  5220. [&](const Request &req, Response &res) {
  5221. EXPECT_EQ(req.body, "");
  5222. EXPECT_FALSE(req.has_header("Content-Type"));
  5223. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5224. res.set_content("empty-no-content-type", "text/plain");
  5225. })
  5226. .Put("/put",
  5227. [&](const Request &req, Response &res) {
  5228. EXPECT_EQ(req.body, "PUT");
  5229. res.set_content(req.body, "text/plain");
  5230. })
  5231. .Put("/put-large",
  5232. [&](const Request &req, Response &res) {
  5233. EXPECT_EQ(req.body, LARGE_DATA);
  5234. res.set_content(req.body, "text/plain");
  5235. })
  5236. .Patch("/patch",
  5237. [&](const Request &req, Response &res) {
  5238. EXPECT_EQ(req.body, "PATCH");
  5239. res.set_content(req.body, "text/plain");
  5240. })
  5241. .Delete("/delete",
  5242. [&](const Request & /*req*/, Response &res) {
  5243. res.set_content("DELETE", "text/plain");
  5244. })
  5245. .Delete("/delete-body",
  5246. [&](const Request &req, Response &res) {
  5247. EXPECT_EQ(req.body, "content");
  5248. res.set_content(req.body, "text/plain");
  5249. })
  5250. .Options(R"(\*)",
  5251. [&](const Request & /*req*/, Response &res) {
  5252. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5253. })
  5254. .CustomRoute("PROPFIND", "/dav/:id",
  5255. [&](const Request &req, Response &res) {
  5256. res.set_header("x-body-size",
  5257. std::to_string(req.body.size()));
  5258. res.set_header("x-matched-route", req.matched_route);
  5259. res.set_header("x-dav-id", req.path_params.at("id"));
  5260. res.status = StatusCode::MultiStatus_207;
  5261. res.set_content(req.body, "application/xml");
  5262. })
  5263. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5264. [&](const Request &req, Response &res) {
  5265. res.set_header("x-dav-match", req.matches[1]);
  5266. res.status = StatusCode::MultiStatus_207;
  5267. })
  5268. .CustomRoute("MKCOL", "/dav-mkcol",
  5269. [&](const Request &req, Response &res) {
  5270. EXPECT_TRUE(req.body.empty());
  5271. res.status = StatusCode::Created_201;
  5272. })
  5273. .CustomRoute(
  5274. "REPORT", "/dav-report",
  5275. [&](const Request & /*req*/, Response &res,
  5276. const ContentReader &content_reader) {
  5277. std::string body;
  5278. content_reader([&](const char *data, size_t data_length) {
  5279. body.append(data, data_length);
  5280. return true;
  5281. });
  5282. res.set_header("x-body-size", std::to_string(body.size()));
  5283. res.status = StatusCode::MultiStatus_207;
  5284. res.set_content(body, "application/xml");
  5285. })
  5286. .Get("/request-target",
  5287. [&](const Request &req, Response & /*res*/) {
  5288. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5289. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5290. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5291. })
  5292. .Get("/long-query-value",
  5293. [&](const Request &req, Response & /*res*/) {
  5294. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5295. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5296. })
  5297. .Get("/too-long-query-value",
  5298. [&](const Request &req, Response & /*res*/) {
  5299. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5300. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5301. })
  5302. .Get("/array-param",
  5303. [&](const Request &req, Response & /*res*/) {
  5304. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5305. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5306. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5307. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5308. })
  5309. .Get("/array-param-values",
  5310. [&](const Request &req, Response & /*res*/) {
  5311. auto values = req.get_param_values("array");
  5312. EXPECT_EQ(3u, values.size());
  5313. EXPECT_EQ("value1", values[0]);
  5314. EXPECT_EQ("value2", values[1]);
  5315. EXPECT_EQ("value3", values[2]);
  5316. auto empty = req.get_param_values("nonexistent");
  5317. EXPECT_TRUE(empty.empty());
  5318. })
  5319. .Post("/validate-no-multiple-headers",
  5320. [&](const Request &req, Response & /*res*/) {
  5321. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5322. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5323. })
  5324. .Post("/content_receiver",
  5325. [&](const Request &req, Response &res,
  5326. const ContentReader &content_reader) {
  5327. if (req.is_multipart_form_data()) {
  5328. std::vector<FormData> items;
  5329. content_reader(
  5330. [&](const FormData &file) {
  5331. items.push_back(file);
  5332. return true;
  5333. },
  5334. [&](const char *data, size_t data_length) {
  5335. items.back().content.append(data, data_length);
  5336. return true;
  5337. });
  5338. EXPECT_EQ(5u, items.size());
  5339. {
  5340. const auto &file = get_file_value(items, "text1");
  5341. EXPECT_TRUE(file.filename.empty());
  5342. EXPECT_EQ("text default", file.content);
  5343. }
  5344. {
  5345. const auto &file = get_file_value(items, "text2");
  5346. EXPECT_TRUE(file.filename.empty());
  5347. EXPECT_EQ("aωb", file.content);
  5348. }
  5349. {
  5350. const auto &file = get_file_value(items, "file1");
  5351. EXPECT_EQ("hello.txt", file.filename);
  5352. EXPECT_EQ("text/plain", file.content_type);
  5353. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5354. }
  5355. {
  5356. const auto &file = get_file_value(items, "file2");
  5357. EXPECT_EQ("world.json", file.filename);
  5358. EXPECT_EQ("application/json", file.content_type);
  5359. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5360. }
  5361. {
  5362. const auto &file = get_file_value(items, "file3");
  5363. EXPECT_TRUE(file.filename.empty());
  5364. EXPECT_EQ("application/octet-stream", file.content_type);
  5365. EXPECT_EQ(0u, file.content.size());
  5366. }
  5367. } else {
  5368. std::string body;
  5369. content_reader([&](const char *data, size_t data_length) {
  5370. EXPECT_EQ(7U, data_length);
  5371. body.append(data, data_length);
  5372. return true;
  5373. });
  5374. EXPECT_EQ(body, "content");
  5375. res.set_content(body, "text/plain");
  5376. }
  5377. })
  5378. .Put("/content_receiver",
  5379. [&](const Request & /*req*/, Response &res,
  5380. const ContentReader &content_reader) {
  5381. std::string body;
  5382. content_reader([&](const char *data, size_t data_length) {
  5383. body.append(data, data_length);
  5384. return true;
  5385. });
  5386. EXPECT_EQ(body, "content");
  5387. res.set_content(body, "text/plain");
  5388. })
  5389. .Patch("/content_receiver",
  5390. [&](const Request & /*req*/, Response &res,
  5391. const ContentReader &content_reader) {
  5392. std::string body;
  5393. content_reader([&](const char *data, size_t data_length) {
  5394. body.append(data, data_length);
  5395. return true;
  5396. });
  5397. EXPECT_EQ(body, "content");
  5398. res.set_content(body, "text/plain");
  5399. })
  5400. .Post("/query-string-and-body",
  5401. [&](const Request &req, Response & /*res*/) {
  5402. ASSERT_TRUE(req.has_param("key"));
  5403. EXPECT_EQ(req.get_param_value("key"), "value");
  5404. EXPECT_EQ(req.body, "content");
  5405. })
  5406. .Get("/last-request",
  5407. [&](const Request &req, Response & /*res*/) {
  5408. EXPECT_EQ("close", req.get_header_value("Connection"));
  5409. })
  5410. .Get(R"(/redirect/(\d+))",
  5411. [&](const Request &req, Response &res) {
  5412. auto num = std::stoi(req.matches[1]) + 1;
  5413. std::string url = "/redirect/" + std::to_string(num);
  5414. res.set_redirect(url);
  5415. })
  5416. .Post("/binary",
  5417. [&](const Request &req, Response &res) {
  5418. EXPECT_EQ(4U, req.body.size());
  5419. EXPECT_EQ("application/octet-stream",
  5420. req.get_header_value("Content-Type"));
  5421. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5422. res.set_content(req.body, "application/octet-stream");
  5423. })
  5424. .Put("/binary",
  5425. [&](const Request &req, Response &res) {
  5426. EXPECT_EQ(4U, req.body.size());
  5427. EXPECT_EQ("application/octet-stream",
  5428. req.get_header_value("Content-Type"));
  5429. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5430. res.set_content(req.body, "application/octet-stream");
  5431. })
  5432. .Patch("/binary",
  5433. [&](const Request &req, Response &res) {
  5434. EXPECT_EQ(4U, req.body.size());
  5435. EXPECT_EQ("application/octet-stream",
  5436. req.get_header_value("Content-Type"));
  5437. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5438. res.set_content(req.body, "application/octet-stream");
  5439. })
  5440. .Delete("/binary",
  5441. [&](const Request &req, Response &res) {
  5442. EXPECT_EQ(4U, req.body.size());
  5443. EXPECT_EQ("application/octet-stream",
  5444. req.get_header_value("Content-Type"));
  5445. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5446. res.set_content(req.body, "application/octet-stream");
  5447. })
  5448. .Get("/issue1772",
  5449. [&](const Request & /*req*/, Response &res) {
  5450. res.status = 401;
  5451. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5452. })
  5453. .Delete("/issue609",
  5454. [](const httplib::Request &, httplib::Response &res,
  5455. const httplib::ContentReader &) {
  5456. res.set_content("ok", "text/plain");
  5457. })
  5458. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5459. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5460. .Get("/compress",
  5461. [&](const Request & /*req*/, Response &res) {
  5462. res.set_content(
  5463. "12345678901234567890123456789012345678901234567890123456789"
  5464. "01234567890123456789012345678901234567890",
  5465. "text/plain");
  5466. })
  5467. .Get("/compress-with-charset",
  5468. [&](const Request & /*req*/, Response &res) {
  5469. res.set_content(
  5470. "12345678901234567890123456789012345678901234567890123456789"
  5471. "01234567890123456789012345678901234567890",
  5472. "application/json; charset=utf-8");
  5473. })
  5474. .Get("/nocompress",
  5475. [&](const Request & /*req*/, Response &res) {
  5476. res.set_content(
  5477. "12345678901234567890123456789012345678901234567890123456789"
  5478. "01234567890123456789012345678901234567890",
  5479. "application/octet-stream");
  5480. })
  5481. .Post("/compress-multipart",
  5482. [&](const Request &req, Response & /*res*/) {
  5483. EXPECT_EQ(2u, req.form.fields.size());
  5484. ASSERT_TRUE(!req.form.has_field("???"));
  5485. {
  5486. const auto &text = req.form.get_field("key1");
  5487. EXPECT_EQ("test", text);
  5488. }
  5489. {
  5490. const auto &text = req.form.get_field("key2");
  5491. EXPECT_EQ("--abcdefg123", text);
  5492. }
  5493. })
  5494. #endif
  5495. ;
  5496. persons_["john"] = "programmer";
  5497. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5498. svr_.wait_until_ready();
  5499. }
  5500. virtual void TearDown() {
  5501. svr_.stop();
  5502. if (!request_threads_.empty()) {
  5503. std::this_thread::sleep_for(std::chrono::seconds(1));
  5504. for (auto &t : request_threads_) {
  5505. t.join();
  5506. }
  5507. }
  5508. t_.join();
  5509. }
  5510. map<string, string> persons_;
  5511. #ifdef CPPHTTPLIB_SSL_ENABLED
  5512. SSLClient cli_;
  5513. SSLServer svr_;
  5514. #else
  5515. Client cli_;
  5516. Server svr_;
  5517. #endif
  5518. thread t_;
  5519. std::vector<thread> request_threads_;
  5520. };
  5521. TEST_F(ServerTest, GetMethod200) {
  5522. auto res = cli_.Get("/hi");
  5523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5524. EXPECT_EQ("HTTP/1.1", res->version);
  5525. EXPECT_EQ(StatusCode::OK_200, res->status);
  5526. EXPECT_EQ("OK", res->reason);
  5527. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5528. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5529. EXPECT_EQ("Hello World!", res->body);
  5530. }
  5531. TEST_F(ServerTest, GetEmptyFile) {
  5532. auto res = cli_.Get("/empty_file");
  5533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5534. EXPECT_EQ(StatusCode::OK_200, res->status);
  5535. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5536. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5537. EXPECT_EQ("", res->body);
  5538. }
  5539. TEST_F(ServerTest, GetFileContent) {
  5540. auto res = cli_.Get("/file_content");
  5541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5542. EXPECT_EQ(StatusCode::OK_200, res->status);
  5543. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5544. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5545. EXPECT_EQ("test.html", res->body);
  5546. }
  5547. TEST_F(ServerTest, GetFileContentWithRange) {
  5548. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5550. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5551. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5552. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5553. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5554. EXPECT_EQ("est", res->body);
  5555. }
  5556. TEST_F(ServerTest, GetFileContentWithContentType) {
  5557. auto res = cli_.Get("/file_content_with_content_type");
  5558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5559. EXPECT_EQ(StatusCode::OK_200, res->status);
  5560. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5561. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5562. EXPECT_EQ("file\n", res->body);
  5563. }
  5564. TEST_F(ServerTest, GetInvalidFileContent) {
  5565. auto res = cli_.Get("/invalid_file_content");
  5566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5567. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5568. }
  5569. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5570. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5572. EXPECT_EQ("HTTP/1.1", res->version);
  5573. EXPECT_EQ(StatusCode::OK_200, res->status);
  5574. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5575. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5576. EXPECT_EQ("Hello World!", res->body);
  5577. }
  5578. TEST_F(ServerTest, GetMethod302) {
  5579. auto res = cli_.Get("/");
  5580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5581. EXPECT_EQ(StatusCode::Found_302, res->status);
  5582. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5583. }
  5584. TEST_F(ServerTest, GetMethod302Redirect) {
  5585. cli_.set_follow_location(true);
  5586. auto res = cli_.Get("/");
  5587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5588. EXPECT_EQ(StatusCode::OK_200, res->status);
  5589. EXPECT_EQ("Hello World!", res->body);
  5590. EXPECT_EQ("/hi", res->location);
  5591. }
  5592. TEST_F(ServerTest, GetMethod404) {
  5593. auto res = cli_.Get("/invalid");
  5594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5595. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5596. }
  5597. TEST_F(ServerTest, HeadMethod200) {
  5598. auto res = cli_.Head("/hi");
  5599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5600. EXPECT_EQ(StatusCode::OK_200, res->status);
  5601. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5602. EXPECT_TRUE(res->body.empty());
  5603. }
  5604. TEST_F(ServerTest, HeadMethod200Static) {
  5605. auto res = cli_.Head("/mount/dir/index.html");
  5606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5607. EXPECT_EQ(StatusCode::OK_200, res->status);
  5608. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5609. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5610. EXPECT_TRUE(res->body.empty());
  5611. }
  5612. TEST_F(ServerTest, HeadMethod404) {
  5613. auto res = cli_.Head("/invalid");
  5614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5615. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5616. EXPECT_TRUE(res->body.empty());
  5617. }
  5618. TEST_F(ServerTest, GetMethodPersonJohn) {
  5619. auto res = cli_.Get("/person/john");
  5620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5621. EXPECT_EQ(StatusCode::OK_200, res->status);
  5622. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5623. EXPECT_EQ("programmer", res->body);
  5624. }
  5625. TEST_F(ServerTest, PostMethod1) {
  5626. auto res = cli_.Get("/person/john1");
  5627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5628. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5629. res = cli_.Post("/person", "name=john1&note=coder",
  5630. "application/x-www-form-urlencoded");
  5631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5632. ASSERT_EQ(StatusCode::OK_200, res->status);
  5633. res = cli_.Get("/person/john1");
  5634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5635. ASSERT_EQ(StatusCode::OK_200, res->status);
  5636. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5637. ASSERT_EQ("coder", res->body);
  5638. }
  5639. TEST_F(ServerTest, PostMethod2) {
  5640. auto res = cli_.Get("/person/john2");
  5641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5642. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5643. Params params;
  5644. params.emplace("name", "john2");
  5645. params.emplace("note", "coder");
  5646. res = cli_.Post("/person", params);
  5647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5648. ASSERT_EQ(StatusCode::OK_200, res->status);
  5649. res = cli_.Get("/person/john2");
  5650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5651. ASSERT_EQ(StatusCode::OK_200, res->status);
  5652. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5653. ASSERT_EQ("coder", res->body);
  5654. }
  5655. TEST_F(ServerTest, PutMethod3) {
  5656. auto res = cli_.Get("/person/john3");
  5657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5658. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5659. Params params;
  5660. params.emplace("name", "john3");
  5661. params.emplace("note", "coder");
  5662. res = cli_.Put("/person", params);
  5663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5664. ASSERT_EQ(StatusCode::OK_200, res->status);
  5665. res = cli_.Get("/person/john3");
  5666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5667. ASSERT_EQ(StatusCode::OK_200, res->status);
  5668. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5669. ASSERT_EQ("coder", res->body);
  5670. }
  5671. TEST_F(ServerTest, DeleteMethod1) {
  5672. auto res = cli_.Get("/person/john4");
  5673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5674. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5675. Params params;
  5676. params.emplace("name", "john4");
  5677. params.emplace("note", "coder");
  5678. res = cli_.Post("/person", params);
  5679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5680. ASSERT_EQ(StatusCode::OK_200, res->status);
  5681. res = cli_.Get("/person/john4");
  5682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5683. ASSERT_EQ(StatusCode::OK_200, res->status);
  5684. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5685. ASSERT_EQ("coder", res->body);
  5686. Params delete_params;
  5687. delete_params.emplace("name", "john4");
  5688. res = cli_.Delete("/person", delete_params);
  5689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5690. ASSERT_EQ(StatusCode::OK_200, res->status);
  5691. ASSERT_EQ("DELETED", res->body);
  5692. res = cli_.Get("/person/john4");
  5693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5694. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5695. }
  5696. TEST_F(ServerTest, DeleteMethod2) {
  5697. auto res = cli_.Get("/person/john5");
  5698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5699. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5700. Params params;
  5701. params.emplace("name", "john5");
  5702. params.emplace("note", "developer");
  5703. res = cli_.Post("/person", params);
  5704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5705. ASSERT_EQ(StatusCode::OK_200, res->status);
  5706. res = cli_.Get("/person/john5");
  5707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5708. ASSERT_EQ(StatusCode::OK_200, res->status);
  5709. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5710. ASSERT_EQ("developer", res->body);
  5711. Params delete_params;
  5712. delete_params.emplace("name", "john5");
  5713. Headers headers;
  5714. headers.emplace("Custom-Header", "test-value");
  5715. res = cli_.Delete("/person", headers, delete_params);
  5716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5717. ASSERT_EQ(StatusCode::OK_200, res->status);
  5718. ASSERT_EQ("DELETED", res->body);
  5719. res = cli_.Get("/person/john5");
  5720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5721. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5722. }
  5723. TEST_F(ServerTest, DeleteMethod3) {
  5724. auto res = cli_.Get("/person/john6");
  5725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5726. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5727. Params params;
  5728. params.emplace("name", "john6");
  5729. params.emplace("note", "tester");
  5730. res = cli_.Post("/person", params);
  5731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5732. ASSERT_EQ(StatusCode::OK_200, res->status);
  5733. res = cli_.Get("/person/john6");
  5734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5735. ASSERT_EQ(StatusCode::OK_200, res->status);
  5736. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5737. ASSERT_EQ("tester", res->body);
  5738. Params delete_params;
  5739. delete_params.emplace("name", "john6");
  5740. Headers headers;
  5741. headers.emplace("Custom-Header", "test-value");
  5742. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5744. ASSERT_EQ(StatusCode::OK_200, res->status);
  5745. ASSERT_EQ("DELETED", res->body);
  5746. res = cli_.Get("/person/john6");
  5747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5748. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5749. }
  5750. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5751. Params params;
  5752. params.emplace("json", JSON_DATA);
  5753. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5755. ASSERT_EQ(StatusCode::OK_200, res->status);
  5756. ASSERT_EQ(JSON_DATA, res->body);
  5757. }
  5758. TEST_F(ServerTest, PostEmptyContent) {
  5759. auto res = cli_.Post("/empty", "", "text/plain");
  5760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5761. ASSERT_EQ(StatusCode::OK_200, res->status);
  5762. ASSERT_EQ("empty", res->body);
  5763. }
  5764. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5765. auto res = cli_.Post("/empty-no-content-type");
  5766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5767. ASSERT_EQ(StatusCode::OK_200, res->status);
  5768. ASSERT_EQ("empty-no-content-type", res->body);
  5769. }
  5770. TEST_F(ServerTest, PostPathOnly) {
  5771. auto res = cli_.Post("/path-only");
  5772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5773. ASSERT_EQ(StatusCode::OK_200, res->status);
  5774. ASSERT_EQ("path-only", res->body);
  5775. }
  5776. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5777. auto res = cli_.Post("/path-headers-only",
  5778. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5780. ASSERT_EQ(StatusCode::OK_200, res->status);
  5781. ASSERT_EQ("path-headers-only", res->body);
  5782. }
  5783. TEST_F(ServerTest, PostLarge) {
  5784. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5786. ASSERT_EQ(StatusCode::OK_200, res->status);
  5787. EXPECT_EQ(LARGE_DATA, res->body);
  5788. }
  5789. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5790. auto res = cli_.Put("/empty-no-content-type");
  5791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5792. ASSERT_EQ(StatusCode::OK_200, res->status);
  5793. ASSERT_EQ("empty-no-content-type", res->body);
  5794. }
  5795. TEST_F(ServerTest, GetMethodDir) {
  5796. auto res = cli_.Get("/dir/");
  5797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5798. EXPECT_EQ(StatusCode::OK_200, res->status);
  5799. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5800. auto body = R"(<html>
  5801. <head>
  5802. </head>
  5803. <body>
  5804. <a href="/dir/test.html">Test</a>
  5805. <a href="/hi">hi</a>
  5806. </body>
  5807. </html>
  5808. )";
  5809. EXPECT_EQ(body, res->body);
  5810. }
  5811. TEST_F(ServerTest, GetMethodDirTest) {
  5812. auto res = cli_.Get("/dir/test.html");
  5813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5814. EXPECT_EQ(StatusCode::OK_200, res->status);
  5815. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5816. EXPECT_EQ("test.html", res->body);
  5817. }
  5818. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5819. auto res = cli_.Get("/dir/../dir/test.html");
  5820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5821. EXPECT_EQ(StatusCode::OK_200, res->status);
  5822. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5823. EXPECT_EQ("test.html", res->body);
  5824. }
  5825. TEST_F(ServerTest, GetMethodInvalidPath) {
  5826. auto res = cli_.Get("/dir/../test.html");
  5827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5828. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5829. }
  5830. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5831. auto res = cli_.Get("/../www/dir/test.html");
  5832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5833. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5834. }
  5835. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5836. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5838. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5839. }
  5840. TEST_F(ServerTest, GetMethodDirMountTest) {
  5841. auto res = cli_.Get("/mount/dir/test.html");
  5842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5843. EXPECT_EQ(StatusCode::OK_200, res->status);
  5844. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5845. EXPECT_EQ("test.html", res->body);
  5846. }
  5847. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5848. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5850. EXPECT_EQ(StatusCode::OK_200, res->status);
  5851. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5852. EXPECT_EQ("test.html", res->body);
  5853. }
  5854. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5855. auto res = cli_.Get("/mount/dir/../test.html");
  5856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5857. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5858. }
  5859. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5860. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5862. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5863. }
  5864. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5865. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5867. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5868. }
  5869. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5870. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5872. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5873. }
  5874. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5875. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5877. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5878. }
  5879. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  5880. auto res = cli_.Get("/mount/dir");
  5881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5882. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5883. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5884. }
  5885. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  5886. auto res = cli_.Get("//dir");
  5887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5888. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5889. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5890. }
  5891. TEST_F(ServerTest, PostMethod303) {
  5892. auto res = cli_.Post("/1", "body", "text/plain");
  5893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5894. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5895. EXPECT_EQ("/2", res->get_header_value("Location"));
  5896. }
  5897. TEST_F(ServerTest, PostMethod303Redirect) {
  5898. cli_.set_follow_location(true);
  5899. auto res = cli_.Post("/1", "body", "text/plain");
  5900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5901. EXPECT_EQ(StatusCode::OK_200, res->status);
  5902. EXPECT_EQ("redirected.", res->body);
  5903. EXPECT_EQ("/2", res->location);
  5904. }
  5905. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5906. auto res = cli_.Get("/dir/test.abcde");
  5907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5908. EXPECT_EQ(StatusCode::OK_200, res->status);
  5909. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5910. EXPECT_EQ("abcde", res->body);
  5911. }
  5912. TEST_F(ServerTest, StaticFileRange) {
  5913. auto res =
  5914. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5916. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5917. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5918. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5919. EXPECT_EQ(true, res->has_header("Content-Range"));
  5920. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5921. EXPECT_EQ(std::string("cd"), res->body);
  5922. }
  5923. TEST_F(ServerTest, StaticFileRanges) {
  5924. auto res = cli_.Get("/dir/test.abcde",
  5925. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5927. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5928. EXPECT_TRUE(
  5929. res->get_header_value("Content-Type")
  5930. .find(
  5931. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5932. 0);
  5933. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5934. }
  5935. TEST_F(ServerTest, StaticFileRangeHead) {
  5936. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5938. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5939. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5940. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5941. EXPECT_EQ(true, res->has_header("Content-Range"));
  5942. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5943. }
  5944. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5945. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5947. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5948. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5949. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5950. EXPECT_EQ(true, res->has_header("Content-Range"));
  5951. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5952. res->get_header_value("Content-Range"));
  5953. EXPECT_EQ("LAST\n", res->body);
  5954. }
  5955. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5956. auto res =
  5957. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5959. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5960. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5961. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5962. EXPECT_EQ(true, res->has_header("Content-Range"));
  5963. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5964. }
  5965. TEST_F(ServerTest, StaticFileBigFile) {
  5966. auto res = cli_.Get("/dir/1MB.txt");
  5967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5968. EXPECT_EQ(StatusCode::OK_200, res->status);
  5969. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5970. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5971. }
  5972. TEST_F(ServerTest, InvalidBaseDirMount) {
  5973. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5974. }
  5975. TEST_F(ServerTest, Binary) {
  5976. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5977. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5978. "application/octet-stream");
  5979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5980. ASSERT_EQ(StatusCode::OK_200, res->status);
  5981. ASSERT_EQ(4U, res->body.size());
  5982. res = cli_.Put("/binary", binary.data(), binary.size(),
  5983. "application/octet-stream");
  5984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5985. ASSERT_EQ(StatusCode::OK_200, res->status);
  5986. ASSERT_EQ(4U, res->body.size());
  5987. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5988. "application/octet-stream");
  5989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5990. ASSERT_EQ(StatusCode::OK_200, res->status);
  5991. ASSERT_EQ(4U, res->body.size());
  5992. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5993. "application/octet-stream");
  5994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5995. ASSERT_EQ(StatusCode::OK_200, res->status);
  5996. ASSERT_EQ(4U, res->body.size());
  5997. }
  5998. TEST_F(ServerTest, BinaryString) {
  5999. auto binary = std::string("\x00\x01\x02\x03", 4);
  6000. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6002. ASSERT_EQ(StatusCode::OK_200, res->status);
  6003. ASSERT_EQ(4U, res->body.size());
  6004. res = cli_.Put("/binary", binary, "application/octet-stream");
  6005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6006. ASSERT_EQ(StatusCode::OK_200, res->status);
  6007. ASSERT_EQ(4U, res->body.size());
  6008. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6010. ASSERT_EQ(StatusCode::OK_200, res->status);
  6011. ASSERT_EQ(4U, res->body.size());
  6012. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6014. ASSERT_EQ(StatusCode::OK_200, res->status);
  6015. ASSERT_EQ(4U, res->body.size());
  6016. }
  6017. TEST_F(ServerTest, EmptyRequest) {
  6018. auto res = cli_.Get("");
  6019. ASSERT_TRUE(!res);
  6020. EXPECT_EQ(Error::Connection, res.error());
  6021. }
  6022. TEST_F(ServerTest, LongRequest) {
  6023. std::string request;
  6024. for (size_t i = 0; i < 545; i++) {
  6025. request += "/TooLongRequest";
  6026. }
  6027. request += "OK";
  6028. auto res = cli_.Get(request.c_str());
  6029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6030. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6031. }
  6032. TEST_F(ServerTest, TooLongRequest) {
  6033. std::string request;
  6034. for (size_t i = 0; i < 546; i++) {
  6035. request += "/TooLongRequest";
  6036. }
  6037. request += "_NG";
  6038. auto start = std::chrono::high_resolution_clock::now();
  6039. cli_.set_keep_alive(true);
  6040. auto res = cli_.Get(request.c_str());
  6041. auto end = std::chrono::high_resolution_clock::now();
  6042. auto elapsed =
  6043. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6044. .count();
  6045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6046. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6047. EXPECT_LE(elapsed, 1000);
  6048. EXPECT_EQ("close", res->get_header_value("Connection"));
  6049. EXPECT_FALSE(cli_.is_socket_open());
  6050. }
  6051. TEST_F(ServerTest, AlmostTooLongRequest) {
  6052. // test for #2046 - URI length check shouldn't include other content on req
  6053. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6054. // leading /, space, HTTP/1.1)
  6055. std::string request =
  6056. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6057. auto res = cli_.Get(request.c_str());
  6058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6059. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6060. }
  6061. TEST_F(ServerTest, LongHeader) {
  6062. Request req;
  6063. req.method = "GET";
  6064. req.path = "/hi";
  6065. std::string host_and_port;
  6066. host_and_port += HOST;
  6067. host_and_port += ":";
  6068. host_and_port += std::to_string(PORT);
  6069. req.headers.emplace("Host", host_and_port.c_str());
  6070. req.headers.emplace("Accept", "*/*");
  6071. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6072. req.headers.emplace(
  6073. "Header-Name",
  6074. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6075. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6076. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6077. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6078. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6079. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6080. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6081. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6082. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6083. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6084. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6085. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6086. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6087. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6088. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6089. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6090. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6091. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6092. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6093. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6094. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6095. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6096. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6097. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6098. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6099. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6100. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6101. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6102. "@@@@@@@@@@@@@@@@");
  6103. auto res = std::make_shared<Response>();
  6104. auto error = Error::Success;
  6105. auto ret = cli_.send(req, *res, error);
  6106. ASSERT_TRUE(ret);
  6107. EXPECT_EQ(StatusCode::OK_200, res->status);
  6108. }
  6109. TEST_F(ServerTest, LongQueryValue) {
  6110. auto start = std::chrono::high_resolution_clock::now();
  6111. cli_.set_keep_alive(true);
  6112. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6113. auto end = std::chrono::high_resolution_clock::now();
  6114. auto elapsed =
  6115. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6116. .count();
  6117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6118. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6119. EXPECT_LE(elapsed, 1000);
  6120. EXPECT_EQ("close", res->get_header_value("Connection"));
  6121. EXPECT_FALSE(cli_.is_socket_open());
  6122. }
  6123. TEST_F(ServerTest, TooLongQueryValue) {
  6124. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6125. ASSERT_FALSE(res);
  6126. EXPECT_EQ(Error::Read, res.error());
  6127. }
  6128. TEST_F(ServerTest, TooLongHeader) {
  6129. Request req;
  6130. req.method = "GET";
  6131. req.path = "/hi";
  6132. std::string host_and_port;
  6133. host_and_port += HOST;
  6134. host_and_port += ":";
  6135. host_and_port += std::to_string(PORT);
  6136. req.headers.emplace("Host", host_and_port.c_str());
  6137. req.headers.emplace("Accept", "*/*");
  6138. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6139. req.headers.emplace(
  6140. "Header-Name",
  6141. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6142. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6143. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6144. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6145. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6146. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6147. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6148. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6149. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6150. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6151. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6152. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6153. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6154. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6155. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6156. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6157. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6158. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6159. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6160. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6161. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6162. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6163. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6164. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6165. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6166. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6167. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6168. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6169. "@@@@@@@@@@@@@@@@@");
  6170. auto res = std::make_shared<Response>();
  6171. auto error = Error::Success;
  6172. auto ret = cli_.send(req, *res, error);
  6173. ASSERT_TRUE(ret);
  6174. EXPECT_EQ(StatusCode::OK_200, res->status);
  6175. }
  6176. TEST_F(ServerTest, HeaderCountAtLimit) {
  6177. // Test with headers just under the 100 limit
  6178. httplib::Headers headers;
  6179. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6180. // This should keep us just under the 100 header limit
  6181. for (int i = 0; i < 95; i++) {
  6182. std::string name = "X-Test-Header-" + std::to_string(i);
  6183. std::string value = "value" + std::to_string(i);
  6184. headers.emplace(name, value);
  6185. }
  6186. // This should work fine as we're under the limit
  6187. auto res = cli_.Get("/hi", headers);
  6188. EXPECT_TRUE(res);
  6189. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6190. }
  6191. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6192. // Test with many headers to exceed the 100 limit
  6193. httplib::Headers headers;
  6194. // Add 150 headers to definitely exceed the 100 limit
  6195. for (int i = 0; i < 150; i++) {
  6196. std::string name = "X-Test-Header-" + std::to_string(i);
  6197. std::string value = "value" + std::to_string(i);
  6198. headers.emplace(name, value);
  6199. }
  6200. // This should fail due to exceeding header count limit
  6201. cli_.set_keep_alive(true);
  6202. auto res = cli_.Get("/hi", headers);
  6203. // The server should respond with 400 Bad Request
  6204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6205. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6206. EXPECT_EQ("close", res->get_header_value("Connection"));
  6207. EXPECT_FALSE(cli_.is_socket_open());
  6208. }
  6209. TEST_F(ServerTest, PercentEncoding) {
  6210. auto res = cli_.Get("/e%6edwith%");
  6211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6212. EXPECT_EQ(StatusCode::OK_200, res->status);
  6213. }
  6214. TEST_F(ServerTest, PercentEncodingUnicode) {
  6215. auto res = cli_.Get("/e%u006edwith%");
  6216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6217. EXPECT_EQ(StatusCode::OK_200, res->status);
  6218. }
  6219. TEST_F(ServerTest, InvalidPercentEncoding) {
  6220. auto res = cli_.Get("/%endwith%");
  6221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6222. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6223. }
  6224. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6225. auto res = cli_.Get("/%uendwith%");
  6226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6227. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6228. }
  6229. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6230. auto res = cli_.Get("/hello?aaa=bbb%");
  6231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6232. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6233. }
  6234. TEST_F(ServerTest, PlusSignEncoding) {
  6235. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6237. EXPECT_EQ(StatusCode::OK_200, res->status);
  6238. EXPECT_EQ("a +b", res->body);
  6239. }
  6240. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6241. // This test simulates a potential DoS attack using many headers
  6242. // to verify our security fix prevents memory exhaustion
  6243. httplib::Headers attack_headers;
  6244. // Attempt to add many headers like an attacker would (200 headers to far
  6245. // exceed limit)
  6246. for (int i = 0; i < 200; i++) {
  6247. std::string name = "X-Attack-Header-" + std::to_string(i);
  6248. std::string value = "attack_payload_" + std::to_string(i);
  6249. attack_headers.emplace(name, value);
  6250. }
  6251. // Try to POST with excessive headers
  6252. cli_.set_keep_alive(true);
  6253. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6254. // Should either fail or return 400 Bad Request due to security limit
  6255. if (res) {
  6256. // If we get a response, it should be 400 Bad Request
  6257. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6258. EXPECT_EQ("close", res->get_header_value("Connection"));
  6259. }
  6260. EXPECT_FALSE(cli_.is_socket_open());
  6261. }
  6262. TEST_F(ServerTest, MultipartFormData) {
  6263. UploadFormDataItems items = {
  6264. {"text1", "text default", "", ""},
  6265. {"text2", "aωb", "", ""},
  6266. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6267. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6268. {"file3", "", "", "application/octet-stream"},
  6269. {"file4", "", "", " application/json tmp-string "}};
  6270. auto res = cli_.Post("/multipart", items);
  6271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6272. EXPECT_EQ(StatusCode::OK_200, res->status);
  6273. }
  6274. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6275. UploadFormDataItems items = {
  6276. {"text", "default text", "", ""},
  6277. {"multi_text1", "aaaaa", "", ""},
  6278. {"multi_text1", "bbbbb", "", ""},
  6279. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6280. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6281. "application/json"},
  6282. };
  6283. auto res = cli_.Post("/multipart/multi_file_values", items);
  6284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6285. EXPECT_EQ(StatusCode::OK_200, res->status);
  6286. }
  6287. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6288. auto res = cli_.Get("/hi");
  6289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6290. EXPECT_EQ(StatusCode::OK_200, res->status);
  6291. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6292. EXPECT_EQ("Hello World!", res->body);
  6293. }
  6294. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6295. Request req;
  6296. req.method = "POST";
  6297. req.path = "/chunked";
  6298. std::string host_and_port;
  6299. host_and_port += HOST;
  6300. host_and_port += ":";
  6301. host_and_port += std::to_string(PORT);
  6302. req.headers.emplace("Host", host_and_port.c_str());
  6303. req.headers.emplace("Accept", "*/*");
  6304. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6305. req.headers.emplace("Content-Type", "text/plain");
  6306. req.headers.emplace("Content-Length", "0");
  6307. req.headers.emplace(
  6308. "Transfer-Encoding",
  6309. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6310. // Client does not chunk, so make a chunked body manually.
  6311. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6312. auto res = std::make_shared<Response>();
  6313. auto error = Error::Success;
  6314. auto ret = cli_.send(req, *res, error);
  6315. ASSERT_TRUE(ret);
  6316. EXPECT_EQ(StatusCode::OK_200, res->status);
  6317. }
  6318. template <typename ClientT>
  6319. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6320. int expected_status) {
  6321. Request req;
  6322. req.method = "POST";
  6323. req.path = "/chunked";
  6324. std::string host_and_port;
  6325. host_and_port += HOST;
  6326. host_and_port += ":";
  6327. host_and_port += std::to_string(PORT);
  6328. req.headers.emplace("Host", host_and_port.c_str());
  6329. req.headers.emplace("Content-Length", "0");
  6330. req.headers.emplace("Transfer-Encoding", "chunked");
  6331. req.body = body;
  6332. auto res = std::make_shared<Response>();
  6333. auto error = Error::Success;
  6334. ASSERT_TRUE(cli.send(req, *res, error));
  6335. EXPECT_EQ(expected_status, res->status);
  6336. }
  6337. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6338. // rather than treat them as valid lengths.
  6339. template <typename ClientT>
  6340. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6341. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6342. }
  6343. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6344. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6345. }
  6346. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6347. expect_chunked_body_rejected(
  6348. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6349. }
  6350. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6351. // chunk-size line carries no CR, LF or other control character ahead of its
  6352. // terminator. Such a line must be refused rather than read as extension text.
  6353. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6354. expect_chunked_body_rejected(
  6355. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6356. }
  6357. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6358. expect_chunked_body_rejected(
  6359. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6360. }
  6361. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6362. expect_chunked_body_rejected(
  6363. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6364. }
  6365. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6366. // The literal stays split: a hex escape consumes every hex digit that
  6367. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6368. expect_chunked_body_rejected(
  6369. cli_, "4;a\x01"
  6370. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6371. }
  6372. TEST_F(ServerTest, AcceptsChunkExtension) {
  6373. expect_chunked_body_status(cli_,
  6374. "4;name=value\r\ndech\r\n"
  6375. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6376. "0;last\r\n\r\n",
  6377. StatusCode::OK_200);
  6378. }
  6379. TEST_F(ServerTest, GetStreamed2) {
  6380. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6382. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6383. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6384. EXPECT_EQ(true, res->has_header("Content-Range"));
  6385. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6386. EXPECT_EQ(std::string("ab"), res->body);
  6387. }
  6388. TEST_F(ServerTest, GetStreamed) {
  6389. auto res = cli_.Get("/streamed");
  6390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6391. EXPECT_EQ(StatusCode::OK_200, res->status);
  6392. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6393. EXPECT_EQ(std::string("aaabbb"), res->body);
  6394. }
  6395. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6396. auto res = cli_.Get("/streamed-without-length",
  6397. Headers{make_range_header({{0, -1}})});
  6398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6399. EXPECT_EQ(StatusCode::OK_200, res->status);
  6400. EXPECT_EQ(false, res->has_header("Content-Length"));
  6401. EXPECT_EQ(false, res->has_header("Content-Range"));
  6402. EXPECT_EQ(std::string("abcdefg"), res->body);
  6403. }
  6404. TEST_F(ServerTest, GetStreamedWithRange1) {
  6405. auto res =
  6406. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6408. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6409. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6410. EXPECT_EQ(true, res->has_header("Content-Range"));
  6411. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6412. EXPECT_EQ(std::string("def"), res->body);
  6413. }
  6414. TEST_F(ServerTest, GetStreamedWithRange2) {
  6415. auto res =
  6416. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6418. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6419. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6420. EXPECT_EQ(true, res->has_header("Content-Range"));
  6421. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6422. EXPECT_EQ(std::string("bcdefg"), res->body);
  6423. }
  6424. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6425. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6427. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6428. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6429. EXPECT_EQ(true, res->has_header("Content-Range"));
  6430. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6431. EXPECT_EQ(std::string("efg"), res->body);
  6432. }
  6433. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6434. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6435. // the entire representation.
  6436. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6437. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6439. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6440. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6441. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6442. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6443. }
  6444. }
  6445. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6446. auto res =
  6447. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6449. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6450. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6451. EXPECT_EQ(false, res->has_header("Content-Range"));
  6452. EXPECT_EQ(0U, res->body.size());
  6453. }
  6454. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6455. // Only a 206 is served as a partial representation. Under any other status
  6456. // `apply_ranges()` reported the full content length, so the body must match
  6457. // that header, and the content provider must never be asked for an offset
  6458. // outside the representation.
  6459. auto check = [&](int status, const char *range) {
  6460. auto path =
  6461. std::string("/streamed-with-range?status=") + std::to_string(status);
  6462. auto ctx = path + " Range: " + range;
  6463. auto res = cli_.Get(path, Headers{{"Range", range}});
  6464. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6465. EXPECT_EQ(status, res->status) << ctx;
  6466. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6467. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6468. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6469. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6470. };
  6471. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6472. check(403, "bytes=3-5");
  6473. // The offset is far past the representation.
  6474. check(403, "bytes=100000-100200");
  6475. // `first_pos` is still -1 here, and the bounds asserts in
  6476. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6477. check(403, "bytes=-3");
  6478. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6479. // multipart branch would have written one that is empty.
  6480. check(403, "bytes=1-2, 4-5");
  6481. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6482. // covers the whole representation.
  6483. check(200, "bytes=3-5");
  6484. check(200, "bytes=1-2, 4-5");
  6485. }
  6486. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6487. auto res =
  6488. cli_.Get("/streamed-with-range",
  6489. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6490. "92233720368547758079223372036854775807"}});
  6491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6492. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6493. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6494. EXPECT_EQ(false, res->has_header("Content-Range"));
  6495. EXPECT_EQ(0U, res->body.size());
  6496. }
  6497. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6498. auto res = cli_.Get(
  6499. "/with-range",
  6500. Headers{{"Range",
  6501. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6502. {"Accept-Encoding", ""}});
  6503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6504. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6505. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6506. EXPECT_EQ(true, res->has_header("Content-Range"));
  6507. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6508. EXPECT_EQ(std::string("abcdefg"), res->body);
  6509. }
  6510. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6511. auto res = cli_.Get("/with-range", Headers{
  6512. {"Range", "bytes=0-"},
  6513. {"Accept-Encoding", ""},
  6514. });
  6515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6516. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6517. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6518. EXPECT_EQ(true, res->has_header("Content-Range"));
  6519. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6520. EXPECT_EQ(std::string("abcdefg"), res->body);
  6521. }
  6522. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6523. auto res = cli_.Get("/streamed-with-range",
  6524. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6526. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6527. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6528. EXPECT_EQ(false, res->has_header("Content-Range"));
  6529. EXPECT_EQ(267U, res->body.size());
  6530. // Check that both range contents are present
  6531. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6532. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6533. // Check that Content-Range headers are present for both ranges
  6534. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6535. std::string::npos);
  6536. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6537. std::string::npos);
  6538. }
  6539. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6540. Ranges ranges;
  6541. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6542. ranges.emplace_back(0, -1);
  6543. }
  6544. auto res = cli_.Get("/streamed-with-range?error",
  6545. Headers{{make_range_header(ranges)}});
  6546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6547. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6548. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6549. EXPECT_EQ(false, res->has_header("Content-Range"));
  6550. EXPECT_EQ(0U, res->body.size());
  6551. }
  6552. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6553. auto res = cli_.Get("/streamed-with-range",
  6554. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6556. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6557. EXPECT_EQ(5U, res->body.size());
  6558. // Check that overlapping ranges are coalesced into a single range
  6559. EXPECT_EQ("bcdef", res->body);
  6560. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6561. // Should be single range, not multipart
  6562. EXPECT_TRUE(res->has_header("Content-Range"));
  6563. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6564. }
  6565. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6566. auto res = cli_.Get("/streamed-with-range",
  6567. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6569. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6570. EXPECT_EQ(268U, res->body.size());
  6571. // Check that both range contents are present
  6572. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6573. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6574. // Check that Content-Range headers are present for both ranges
  6575. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6576. std::string::npos);
  6577. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6578. std::string::npos);
  6579. }
  6580. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6581. auto res = cli_.Get("/streamed-with-range",
  6582. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6584. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6585. EXPECT_EQ(269U, res->body.size());
  6586. // Check that both duplicate range contents are present
  6587. size_t first_abc = res->body.find("abc\r\n");
  6588. EXPECT_TRUE(first_abc != std::string::npos);
  6589. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6590. EXPECT_TRUE(second_abc != std::string::npos);
  6591. // Check that Content-Range headers are present for both ranges
  6592. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6593. EXPECT_TRUE(first_range != std::string::npos);
  6594. size_t second_range =
  6595. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6596. EXPECT_TRUE(second_range != std::string::npos);
  6597. }
  6598. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6599. auto res =
  6600. cli_.Get("/streamed-with-range?error",
  6601. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6603. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6604. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6605. EXPECT_EQ(false, res->has_header("Content-Range"));
  6606. EXPECT_EQ(0U, res->body.size());
  6607. }
  6608. TEST_F(ServerTest, GetStreamedEndless) {
  6609. uint64_t offset = 0;
  6610. auto res = cli_.Get("/streamed-cancel",
  6611. [&](const char * /*data*/, uint64_t data_length) {
  6612. if (offset < 100) {
  6613. offset += data_length;
  6614. return true;
  6615. }
  6616. return false;
  6617. });
  6618. ASSERT_TRUE(!res);
  6619. EXPECT_EQ(Error::Canceled, res.error());
  6620. }
  6621. TEST_F(ServerTest, ClientStop) {
  6622. std::atomic_size_t count{4};
  6623. std::vector<std::thread> threads;
  6624. for (auto i = count.load(); i != 0; --i) {
  6625. threads.emplace_back([&]() {
  6626. auto res = cli_.Get("/streamed-cancel",
  6627. [&](const char *, uint64_t) { return true; });
  6628. --count;
  6629. ASSERT_TRUE(!res);
  6630. EXPECT_TRUE(res.error() == Error::Canceled ||
  6631. res.error() == Error::Read || res.error() == Error::Write);
  6632. });
  6633. }
  6634. std::this_thread::sleep_for(std::chrono::seconds(2));
  6635. while (count != 0) {
  6636. cli_.stop();
  6637. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6638. }
  6639. for (auto &t : threads) {
  6640. t.join();
  6641. }
  6642. }
  6643. TEST_F(ServerTest, GetWithRange1) {
  6644. auto res = cli_.Get("/with-range", Headers{
  6645. make_range_header({{3, 5}}),
  6646. {"Accept-Encoding", ""},
  6647. });
  6648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6649. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6650. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6651. EXPECT_EQ(true, res->has_header("Content-Range"));
  6652. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6653. EXPECT_EQ(std::string("def"), res->body);
  6654. }
  6655. TEST_F(ServerTest, GetWithRange2) {
  6656. auto res = cli_.Get("/with-range", Headers{
  6657. make_range_header({{1, -1}}),
  6658. {"Accept-Encoding", ""},
  6659. });
  6660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6661. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6662. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6663. EXPECT_EQ(true, res->has_header("Content-Range"));
  6664. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6665. EXPECT_EQ(std::string("bcdefg"), res->body);
  6666. }
  6667. TEST_F(ServerTest, GetWithRange3) {
  6668. auto res = cli_.Get("/with-range", Headers{
  6669. make_range_header({{0, 0}}),
  6670. {"Accept-Encoding", ""},
  6671. });
  6672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6673. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6674. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6675. EXPECT_EQ(true, res->has_header("Content-Range"));
  6676. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6677. EXPECT_EQ(std::string("a"), res->body);
  6678. }
  6679. TEST_F(ServerTest, GetWithRange4) {
  6680. auto res = cli_.Get("/with-range", Headers{
  6681. make_range_header({{-1, 2}}),
  6682. {"Accept-Encoding", ""},
  6683. });
  6684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6685. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6686. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6687. EXPECT_EQ(true, res->has_header("Content-Range"));
  6688. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6689. EXPECT_EQ(std::string("fg"), res->body);
  6690. }
  6691. TEST_F(ServerTest, GetWithRange5) {
  6692. auto res = cli_.Get("/with-range", Headers{
  6693. make_range_header({{0, 5}}),
  6694. {"Accept-Encoding", ""},
  6695. });
  6696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6697. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6698. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6699. EXPECT_EQ(true, res->has_header("Content-Range"));
  6700. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6701. EXPECT_EQ(std::string("abcdef"), res->body);
  6702. }
  6703. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6704. auto res =
  6705. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6707. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6708. }
  6709. TEST_F(ServerTest, GetWithRangeMultipart) {
  6710. auto res =
  6711. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6713. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6714. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6715. EXPECT_EQ(false, res->has_header("Content-Range"));
  6716. EXPECT_EQ(267U, res->body.size());
  6717. }
  6718. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6719. auto res = cli_.Get("/with-range",
  6720. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6722. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6723. }
  6724. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6725. auto res = cli_.Get("/with-range-customized-response",
  6726. Headers{{make_range_header({{1, 2}})}});
  6727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6728. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6729. EXPECT_EQ(true, res->has_header("Content-Length"));
  6730. EXPECT_EQ(false, res->has_header("Content-Range"));
  6731. EXPECT_EQ(JSON_DATA, res->body);
  6732. }
  6733. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6734. auto res = cli_.Get("/with-range-customized-response",
  6735. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6737. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6738. EXPECT_EQ(true, res->has_header("Content-Length"));
  6739. EXPECT_EQ(false, res->has_header("Content-Range"));
  6740. EXPECT_EQ(JSON_DATA, res->body);
  6741. }
  6742. TEST_F(ServerTest, Issue1772) {
  6743. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6745. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6746. }
  6747. TEST_F(ServerTest, Issue609) {
  6748. auto res = cli_.Delete("/issue609");
  6749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6750. EXPECT_EQ(StatusCode::OK_200, res->status);
  6751. EXPECT_EQ(std::string("ok"), res->body);
  6752. }
  6753. TEST_F(ServerTest, GetStreamedChunked) {
  6754. auto res = cli_.Get("/streamed-chunked");
  6755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6756. EXPECT_EQ(StatusCode::OK_200, res->status);
  6757. EXPECT_EQ(std::string("123456789"), res->body);
  6758. }
  6759. TEST_F(ServerTest, GetStreamedChunked2) {
  6760. auto res = cli_.Get("/streamed-chunked2");
  6761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6762. EXPECT_EQ(StatusCode::OK_200, res->status);
  6763. EXPECT_EQ(std::string("123456789"), res->body);
  6764. }
  6765. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6766. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6768. EXPECT_EQ(StatusCode::OK_200, res->status);
  6769. EXPECT_EQ(std::string("123456789"), res->body);
  6770. EXPECT_TRUE(res->has_header("Trailer"));
  6771. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6772. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6773. // Trailers are now stored separately from headers (security fix)
  6774. EXPECT_EQ(2U, res->trailers.size());
  6775. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6776. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6777. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6778. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6779. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6780. // Verify trailers are NOT in headers (security verification)
  6781. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6782. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6783. }
  6784. TEST_F(ServerTest, LargeChunkedPost) {
  6785. Request req;
  6786. req.method = "POST";
  6787. req.path = "/large-chunked";
  6788. std::string host_and_port;
  6789. host_and_port += HOST;
  6790. host_and_port += ":";
  6791. host_and_port += std::to_string(PORT);
  6792. req.headers.emplace("Host", host_and_port.c_str());
  6793. req.headers.emplace("Accept", "*/*");
  6794. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6795. req.headers.emplace("Content-Type", "text/plain");
  6796. req.headers.emplace("Content-Length", "0");
  6797. req.headers.emplace("Transfer-Encoding", "chunked");
  6798. std::string long_string(30 * 1024u, 'a');
  6799. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6800. // Attempt to make a large enough post to exceed OS buffers, to test that
  6801. // the server handles short reads if the full chunk data isn't available.
  6802. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6803. auto res = std::make_shared<Response>();
  6804. auto error = Error::Success;
  6805. auto ret = cli_.send(req, *res, error);
  6806. ASSERT_TRUE(ret);
  6807. EXPECT_EQ(StatusCode::OK_200, res->status);
  6808. }
  6809. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6810. auto res = cli_.Get("/remote_addr");
  6811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6812. EXPECT_EQ(StatusCode::OK_200, res->status);
  6813. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6814. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6815. }
  6816. TEST_F(ServerTest, GetMethodLocalAddr) {
  6817. auto res = cli_.Get("/local_addr");
  6818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6819. EXPECT_EQ(StatusCode::OK_200, res->status);
  6820. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6821. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6822. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6823. }
  6824. TEST_F(ServerTest, HTTPResponseSplitting) {
  6825. auto res = cli_.Get("/http_response_splitting");
  6826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6827. EXPECT_EQ(StatusCode::OK_200, res->status);
  6828. }
  6829. TEST_F(ServerTest, SlowRequest) {
  6830. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6831. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6832. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6833. }
  6834. #if 0
  6835. TEST_F(ServerTest, SlowPost) {
  6836. char buffer[64 * 1024];
  6837. memset(buffer, 0x42, sizeof(buffer));
  6838. auto res = cli_.Post(
  6839. "/slowpost", 64 * 1024 * 1024,
  6840. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6841. auto ret = sink.write(buffer, sizeof(buffer));
  6842. EXPECT_TRUE(ret);
  6843. return true;
  6844. },
  6845. "text/plain");
  6846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6847. EXPECT_EQ(StatusCode::OK_200, res->status);
  6848. }
  6849. TEST_F(ServerTest, SlowPostFail) {
  6850. char buffer[64 * 1024];
  6851. memset(buffer, 0x42, sizeof(buffer));
  6852. cli_.set_write_timeout(std::chrono::seconds(0));
  6853. auto res = cli_.Post(
  6854. "/slowpost", 64 * 1024 * 1024,
  6855. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6856. sink.write(buffer, sizeof(buffer));
  6857. return true;
  6858. },
  6859. "text/plain");
  6860. ASSERT_TRUE(!res);
  6861. EXPECT_EQ(Error::Write, res.error());
  6862. }
  6863. #endif
  6864. TEST_F(ServerTest, Put) {
  6865. auto res = cli_.Put("/put", "PUT", "text/plain");
  6866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6867. EXPECT_EQ(StatusCode::OK_200, res->status);
  6868. EXPECT_EQ("PUT", res->body);
  6869. }
  6870. TEST_F(ServerTest, PutWithContentProvider) {
  6871. auto res = cli_.Put(
  6872. "/put", 3,
  6873. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6874. sink.os << "PUT";
  6875. return true;
  6876. },
  6877. "text/plain");
  6878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6879. EXPECT_EQ(StatusCode::OK_200, res->status);
  6880. EXPECT_EQ("PUT", res->body);
  6881. }
  6882. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6883. auto res = cli_.Post(
  6884. "/post", 42,
  6885. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6886. return false;
  6887. },
  6888. "text/plain");
  6889. ASSERT_TRUE(!res);
  6890. EXPECT_EQ(Error::Canceled, res.error());
  6891. }
  6892. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6893. auto res = cli_.Put(
  6894. "/put",
  6895. [](size_t /*offset*/, DataSink &sink) {
  6896. sink.os << "PUT";
  6897. sink.done();
  6898. return true;
  6899. },
  6900. "text/plain");
  6901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6902. EXPECT_EQ(StatusCode::OK_200, res->status);
  6903. EXPECT_EQ("PUT", res->body);
  6904. }
  6905. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6906. auto res = cli_.Post(
  6907. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6908. "text/plain");
  6909. ASSERT_TRUE(!res);
  6910. EXPECT_EQ(Error::Canceled, res.error());
  6911. }
  6912. TEST_F(ServerTest, PostLoopBack) {
  6913. std::string body;
  6914. auto res = cli_.Post(
  6915. "/post-loopback", 9,
  6916. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6917. EXPECT_EQ(9u, length);
  6918. sink.write("123", 3);
  6919. sink.write("456", 3);
  6920. sink.write("789", 3);
  6921. return true;
  6922. },
  6923. "text/plain",
  6924. [&body](const char *data, size_t data_length) {
  6925. body.append(data, data_length);
  6926. return true;
  6927. });
  6928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6929. EXPECT_EQ(StatusCode::OK_200, res->status);
  6930. EXPECT_EQ("123456789", body);
  6931. }
  6932. TEST_F(ServerTest, PutLoopBack) {
  6933. std::string body;
  6934. auto res = cli_.Put(
  6935. "/put-loopback", 9,
  6936. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6937. EXPECT_EQ(9u, length);
  6938. sink.write("123", 3);
  6939. sink.write("456", 3);
  6940. sink.write("789", 3);
  6941. return true;
  6942. },
  6943. "text/plain",
  6944. [&body](const char *data, size_t data_length) {
  6945. body.append(data, data_length);
  6946. return true;
  6947. });
  6948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6949. EXPECT_EQ(StatusCode::OK_200, res->status);
  6950. EXPECT_EQ("123456789", body);
  6951. }
  6952. TEST_F(ServerTest, PatchLoopBack) {
  6953. std::string body;
  6954. auto res = cli_.Patch(
  6955. "/patch-loopback", 9,
  6956. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6957. EXPECT_EQ(9u, length);
  6958. sink.write("123", 3);
  6959. sink.write("456", 3);
  6960. sink.write("789", 3);
  6961. return true;
  6962. },
  6963. "text/plain",
  6964. [&body](const char *data, size_t data_length) {
  6965. body.append(data, data_length);
  6966. return true;
  6967. });
  6968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6969. EXPECT_EQ(StatusCode::OK_200, res->status);
  6970. EXPECT_EQ("123456789", body);
  6971. }
  6972. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6973. std::string body;
  6974. auto res = cli_.Post(
  6975. "/post-loopback",
  6976. [](size_t /*offset*/, DataSink &sink) {
  6977. sink.write("123", 3);
  6978. sink.write("456", 3);
  6979. sink.write("789", 3);
  6980. sink.done();
  6981. return true;
  6982. },
  6983. "text/plain",
  6984. [&body](const char *data, size_t data_length) {
  6985. body.append(data, data_length);
  6986. return true;
  6987. });
  6988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6989. EXPECT_EQ(StatusCode::OK_200, res->status);
  6990. EXPECT_EQ("123456789", body);
  6991. }
  6992. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6993. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6994. cli_.set_compress(true);
  6995. auto res = cli_.Put(
  6996. "/put", 3,
  6997. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6998. sink.os << "PUT";
  6999. return true;
  7000. },
  7001. "text/plain");
  7002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7003. EXPECT_EQ(StatusCode::OK_200, res->status);
  7004. EXPECT_EQ("PUT", res->body);
  7005. }
  7006. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7007. cli_.set_compress(true);
  7008. auto res = cli_.Post(
  7009. "/post", 42,
  7010. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7011. return false;
  7012. },
  7013. "text/plain");
  7014. ASSERT_TRUE(!res);
  7015. EXPECT_EQ(Error::Canceled, res.error());
  7016. }
  7017. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7018. cli_.set_compress(true);
  7019. auto res = cli_.Put(
  7020. "/put",
  7021. [](size_t /*offset*/, DataSink &sink) {
  7022. sink.os << "PUT";
  7023. sink.done();
  7024. return true;
  7025. },
  7026. "text/plain");
  7027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7028. EXPECT_EQ(StatusCode::OK_200, res->status);
  7029. EXPECT_EQ("PUT", res->body);
  7030. }
  7031. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7032. cli_.set_compress(true);
  7033. auto res = cli_.Post(
  7034. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7035. "text/plain");
  7036. ASSERT_TRUE(!res);
  7037. EXPECT_EQ(Error::Canceled, res.error());
  7038. }
  7039. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7040. cli_.set_compress(true);
  7041. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7043. EXPECT_EQ(StatusCode::OK_200, res->status);
  7044. EXPECT_EQ(LARGE_DATA, res->body);
  7045. }
  7046. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7047. #ifdef CPPHTTPLIB_SSL_ENABLED
  7048. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7049. Client cli(s.c_str());
  7050. cli.enable_server_certificate_verification(false);
  7051. #else
  7052. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7053. Client cli(s.c_str());
  7054. #endif
  7055. cli.set_compress(true);
  7056. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7058. EXPECT_EQ(StatusCode::OK_200, res->status);
  7059. EXPECT_EQ(LARGE_DATA, res->body);
  7060. // The compressed size should be less than a 10th of the original. May vary
  7061. // depending on the zlib library.
  7062. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7063. static_cast<uint64_t>(10 * 1024 * 1024));
  7064. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7065. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7066. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7067. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7068. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7069. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7070. #endif
  7071. }
  7072. TEST_F(ServerTest, PutContentWithDeflate) {
  7073. cli_.set_compress(false);
  7074. Headers headers;
  7075. headers.emplace("Content-Encoding", "deflate");
  7076. // PUT in deflate format:
  7077. auto res = cli_.Put("/put", headers,
  7078. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7080. EXPECT_EQ(StatusCode::OK_200, res->status);
  7081. EXPECT_EQ("PUT", res->body);
  7082. }
  7083. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7084. Headers headers;
  7085. headers.emplace("Accept-Encoding", "gzip, deflate");
  7086. auto res = cli_.Get("/streamed-chunked", headers);
  7087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7088. EXPECT_EQ(StatusCode::OK_200, res->status);
  7089. EXPECT_EQ(std::string("123456789"), res->body);
  7090. }
  7091. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7092. Headers headers;
  7093. headers.emplace("Accept-Encoding", "gzip, deflate");
  7094. auto res = cli_.Get("/streamed-chunked2", headers);
  7095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7096. EXPECT_EQ(StatusCode::OK_200, res->status);
  7097. EXPECT_EQ(std::string("123456789"), res->body);
  7098. }
  7099. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7100. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7102. EXPECT_EQ(StatusCode::OK_200, res->status);
  7103. }
  7104. TEST(GzipDecompressor, ChunkedDecompression) {
  7105. std::string data;
  7106. for (size_t i = 0; i < 32 * 1024; ++i) {
  7107. data.push_back(static_cast<char>('a' + i % 26));
  7108. }
  7109. std::string compressed_data;
  7110. {
  7111. httplib::detail::gzip_compressor compressor;
  7112. bool result = compressor.compress(
  7113. data.data(), data.size(),
  7114. /*last=*/true,
  7115. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7116. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7117. compressed_data_size);
  7118. return true;
  7119. });
  7120. ASSERT_TRUE(result);
  7121. }
  7122. std::string decompressed_data;
  7123. {
  7124. httplib::detail::gzip_decompressor decompressor;
  7125. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7126. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7127. size_t chunk_size = 130;
  7128. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7129. chunk_begin += chunk_size) {
  7130. size_t current_chunk_size =
  7131. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7132. bool result = decompressor.decompress(
  7133. compressed_data.data() + chunk_begin, current_chunk_size,
  7134. [&](const char *decompressed_data_chunk,
  7135. size_t decompressed_data_chunk_size) {
  7136. decompressed_data.insert(decompressed_data.size(),
  7137. decompressed_data_chunk,
  7138. decompressed_data_chunk_size);
  7139. return true;
  7140. });
  7141. ASSERT_TRUE(result);
  7142. }
  7143. }
  7144. ASSERT_EQ(data, decompressed_data);
  7145. }
  7146. TEST(GzipDecompressor, DeflateDecompression) {
  7147. std::string original_text = "Raw deflate without gzip";
  7148. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7149. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7150. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7151. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7152. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7153. std::string decompressed_data;
  7154. {
  7155. httplib::detail::gzip_decompressor decompressor;
  7156. bool result = decompressor.decompress(
  7157. compressed_data.data(), compressed_data.size(),
  7158. [&](const char *decompressed_data_chunk,
  7159. size_t decompressed_data_chunk_size) {
  7160. decompressed_data.insert(decompressed_data.size(),
  7161. decompressed_data_chunk,
  7162. decompressed_data_chunk_size);
  7163. return true;
  7164. });
  7165. ASSERT_TRUE(result);
  7166. }
  7167. ASSERT_EQ(original_text, decompressed_data);
  7168. }
  7169. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7170. std::string original_text = "Raw deflate without gzip";
  7171. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7172. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7173. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7174. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7175. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7176. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7177. std::string decompressed_data;
  7178. {
  7179. httplib::detail::gzip_decompressor decompressor;
  7180. bool result = decompressor.decompress(
  7181. compressed_data.data(), compressed_data.size(),
  7182. [&](const char *decompressed_data_chunk,
  7183. size_t decompressed_data_chunk_size) {
  7184. decompressed_data.insert(decompressed_data.size(),
  7185. decompressed_data_chunk,
  7186. decompressed_data_chunk_size);
  7187. return true;
  7188. });
  7189. ASSERT_TRUE(result);
  7190. }
  7191. ASSERT_EQ(original_text, decompressed_data);
  7192. }
  7193. #endif
  7194. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7195. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7196. Headers headers;
  7197. headers.emplace("Accept-Encoding", "br");
  7198. auto res = cli_.Get("/streamed-chunked", headers);
  7199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7200. EXPECT_EQ(StatusCode::OK_200, res->status);
  7201. EXPECT_EQ(std::string("123456789"), res->body);
  7202. }
  7203. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7204. Headers headers;
  7205. headers.emplace("Accept-Encoding", "br");
  7206. auto res = cli_.Get("/streamed-chunked2", headers);
  7207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7208. EXPECT_EQ(StatusCode::OK_200, res->status);
  7209. EXPECT_EQ(std::string("123456789"), res->body);
  7210. }
  7211. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7212. cli_.set_compress(true);
  7213. auto res = cli_.Put(
  7214. "/put", 3,
  7215. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7216. sink.os << "PUT";
  7217. return true;
  7218. },
  7219. "text/plain");
  7220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7221. EXPECT_EQ(StatusCode::OK_200, res->status);
  7222. EXPECT_EQ("PUT", res->body);
  7223. }
  7224. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7225. cli_.set_compress(true);
  7226. auto res = cli_.Put(
  7227. "/put",
  7228. [](size_t /*offset*/, DataSink &sink) {
  7229. sink.os << "PUT";
  7230. sink.done();
  7231. return true;
  7232. },
  7233. "text/plain");
  7234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7235. EXPECT_EQ(StatusCode::OK_200, res->status);
  7236. EXPECT_EQ("PUT", res->body);
  7237. }
  7238. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7239. cli_.set_compress(true);
  7240. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7242. EXPECT_EQ(StatusCode::OK_200, res->status);
  7243. EXPECT_EQ(LARGE_DATA, res->body);
  7244. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7245. }
  7246. #endif
  7247. TEST_F(ServerTest, Patch) {
  7248. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7250. EXPECT_EQ(StatusCode::OK_200, res->status);
  7251. EXPECT_EQ("PATCH", res->body);
  7252. }
  7253. TEST_F(ServerTest, Delete) {
  7254. auto res = cli_.Delete("/delete");
  7255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7256. EXPECT_EQ(StatusCode::OK_200, res->status);
  7257. EXPECT_EQ("DELETE", res->body);
  7258. }
  7259. TEST_F(ServerTest, DeleteContentReceiver) {
  7260. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7262. EXPECT_EQ(StatusCode::OK_200, res->status);
  7263. EXPECT_EQ("content", res->body);
  7264. }
  7265. TEST_F(ServerTest, Options) {
  7266. auto res = cli_.Options("*");
  7267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7268. EXPECT_EQ(StatusCode::OK_200, res->status);
  7269. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7270. EXPECT_TRUE(res->body.empty());
  7271. }
  7272. TEST_F(ServerTest, URL) {
  7273. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7275. EXPECT_EQ(StatusCode::OK_200, res->status);
  7276. }
  7277. TEST_F(ServerTest, ArrayParam) {
  7278. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7280. EXPECT_EQ(StatusCode::OK_200, res->status);
  7281. }
  7282. TEST_F(ServerTest, ArrayParamValues) {
  7283. auto res =
  7284. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7286. EXPECT_EQ(StatusCode::OK_200, res->status);
  7287. }
  7288. TEST_F(ServerTest, NoMultipleHeaders) {
  7289. Headers headers = {{"Content-Length", "5"}};
  7290. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7291. "text/plain");
  7292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7293. EXPECT_EQ(StatusCode::OK_200, res->status);
  7294. }
  7295. TEST_F(ServerTest, PostContentReceiver) {
  7296. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7298. ASSERT_EQ(StatusCode::OK_200, res->status);
  7299. ASSERT_EQ("content", res->body);
  7300. }
  7301. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7302. UploadFormDataItems items = {
  7303. {"text1", "text default", "", ""},
  7304. {"text2", "aωb", "", ""},
  7305. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7306. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7307. {"file3", "", "", "application/octet-stream"},
  7308. };
  7309. auto res = cli_.Post("/content_receiver", items);
  7310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7311. EXPECT_EQ(StatusCode::OK_200, res->status);
  7312. }
  7313. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7314. UploadFormDataItems items = {
  7315. {"text1", "text default", "", ""},
  7316. {"text2", "aωb", "", ""},
  7317. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7318. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7319. {"file3", "", "", "application/octet-stream"},
  7320. };
  7321. auto boundary = std::string("+++++");
  7322. std::string body;
  7323. for (const auto &item : items) {
  7324. body += "--" + boundary + "\r\n";
  7325. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7326. if (!item.filename.empty()) {
  7327. body += "; filename=\"" + item.filename + "\"";
  7328. }
  7329. body += "\r\n";
  7330. if (!item.content_type.empty()) {
  7331. body += "Content-Type: " + item.content_type + "\r\n";
  7332. }
  7333. body += "\r\n";
  7334. body += item.content + "\r\n";
  7335. }
  7336. body += "--" + boundary + "--\r\n";
  7337. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7338. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7340. EXPECT_EQ(StatusCode::OK_200, res->status);
  7341. }
  7342. TEST(MultipartFormDataTest, FieldEscaping) {
  7343. Server svr;
  7344. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7345. const ContentReader &content_reader) {
  7346. ASSERT_TRUE(req.is_multipart_form_data());
  7347. std::vector<FormData> received;
  7348. content_reader(
  7349. [&](const FormData &file) {
  7350. received.push_back(file);
  7351. return true;
  7352. },
  7353. [&](const char *data, size_t data_length) {
  7354. received.back().content.append(data, data_length);
  7355. return true;
  7356. });
  7357. // '"', CR and LF in names and filenames are escaped following the
  7358. // WHATWG HTML standard, so each part still parses as a single part
  7359. // with no injected headers. Content types get CR/LF escaped too,
  7360. // while '"' (legal there, e.g. quoted charset) is preserved.
  7361. ASSERT_EQ(4U, received.size());
  7362. EXPECT_EQ("na%22me", received[0].name);
  7363. EXPECT_EQ("quoted name", received[0].content);
  7364. EXPECT_EQ("file", received[1].name);
  7365. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7366. received[1].filename);
  7367. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7368. EXPECT_EQ("injected", received[1].content);
  7369. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7370. EXPECT_EQ("my%22file.txt", received[2].filename);
  7371. EXPECT_EQ("cr lf name", received[2].content);
  7372. EXPECT_EQ("typed", received[3].name);
  7373. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7374. received[3].content_type);
  7375. EXPECT_EQ("typed content", received[3].content);
  7376. });
  7377. auto port = svr.bind_to_any_port("localhost");
  7378. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7379. auto se = detail::scope_exit([&] {
  7380. svr.stop();
  7381. t.join();
  7382. ASSERT_FALSE(svr.is_running());
  7383. });
  7384. svr.wait_until_ready();
  7385. Client cli("localhost", port);
  7386. UploadFormDataItems items = {
  7387. {"na\"me", "quoted name", "", ""},
  7388. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7389. "application/octet-stream"},
  7390. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7391. {"typed", "typed content", "",
  7392. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7393. };
  7394. auto res = cli.Post("/post", items);
  7395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7396. EXPECT_EQ(StatusCode::OK_200, res->status);
  7397. }
  7398. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7399. const UploadFormDataItems items = {
  7400. {"name1", "Content 1", "", ""},
  7401. {"name2", "Content 2", "file2.txt", "text/plain"},
  7402. };
  7403. Server svr;
  7404. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7405. const ContentReader &content_reader) {
  7406. ASSERT_TRUE(req.is_multipart_form_data());
  7407. std::vector<FormData> received;
  7408. content_reader(
  7409. [&](const FormData &file) {
  7410. received.push_back(file);
  7411. return true;
  7412. },
  7413. [&](const char *data, size_t data_length) {
  7414. received.back().content.append(data, data_length);
  7415. return true;
  7416. });
  7417. ASSERT_EQ(2U, received.size());
  7418. EXPECT_EQ("name1", received[0].name);
  7419. EXPECT_EQ("Content 1", received[0].content);
  7420. EXPECT_EQ("name2", received[1].name);
  7421. EXPECT_EQ("Content 2", received[1].content);
  7422. EXPECT_EQ("file2.txt", received[1].filename);
  7423. EXPECT_EQ("text/plain", received[1].content_type);
  7424. });
  7425. auto port = svr.bind_to_any_port("localhost");
  7426. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7427. auto se = detail::scope_exit([&] {
  7428. svr.stop();
  7429. t.join();
  7430. ASSERT_FALSE(svr.is_running());
  7431. });
  7432. svr.wait_until_ready();
  7433. Client cli("localhost", port);
  7434. // Whole-body serialization with a generated boundary
  7435. {
  7436. MultipartFormDataWriter writer;
  7437. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7438. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7439. writer.content_type());
  7440. auto body = writer.serialize(items);
  7441. EXPECT_EQ(body.size(), writer.content_length(items));
  7442. auto res = cli.Post("/post", body, writer.content_type());
  7443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7444. EXPECT_EQ(StatusCode::OK_200, res->status);
  7445. }
  7446. // Per-part framing with a custom boundary via a content provider
  7447. {
  7448. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7449. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7450. MultipartFormDataWriter writer("custom-boundary_123");
  7451. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7452. std::string body;
  7453. for (const auto &item : items) {
  7454. body += writer.item_begin(item);
  7455. body += item.content;
  7456. body += MultipartFormDataWriter::item_end();
  7457. }
  7458. body += writer.finish();
  7459. EXPECT_EQ(body.size(), writer.content_length(items));
  7460. auto res = cli.Post(
  7461. "/post", body.size(),
  7462. [&](size_t offset, size_t length, DataSink &sink) {
  7463. sink.write(body.data() + offset, length);
  7464. return true;
  7465. },
  7466. writer.content_type());
  7467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7468. EXPECT_EQ(StatusCode::OK_200, res->status);
  7469. }
  7470. }
  7471. TEST_F(ServerTest, PostContentReceiverGzip) {
  7472. cli_.set_compress(true);
  7473. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7475. ASSERT_EQ(StatusCode::OK_200, res->status);
  7476. ASSERT_EQ("content", res->body);
  7477. }
  7478. TEST_F(ServerTest, PutContentReceiver) {
  7479. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7481. ASSERT_EQ(StatusCode::OK_200, res->status);
  7482. ASSERT_EQ("content", res->body);
  7483. }
  7484. TEST_F(ServerTest, PatchContentReceiver) {
  7485. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7487. ASSERT_EQ(StatusCode::OK_200, res->status);
  7488. ASSERT_EQ("content", res->body);
  7489. }
  7490. template <typename ClientType>
  7491. void TestWithHeadersAndContentReceiver(
  7492. ClientType &cli,
  7493. std::function<Result(ClientType &, const std::string &, const Headers &,
  7494. const std::string &, const std::string &,
  7495. ContentReceiver, DownloadProgress)>
  7496. request_func) {
  7497. Headers headers;
  7498. headers.emplace("X-Custom-Header", "test-value");
  7499. std::string received_body;
  7500. auto res = request_func(
  7501. cli, "/content_receiver", headers, "content", "application/json",
  7502. [&](const char *data, size_t data_length) {
  7503. received_body.append(data, data_length);
  7504. return true;
  7505. },
  7506. nullptr);
  7507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7508. EXPECT_EQ(StatusCode::OK_200, res->status);
  7509. EXPECT_EQ("content", received_body);
  7510. }
  7511. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7512. #ifdef CPPHTTPLIB_SSL_ENABLED
  7513. using ClientT = SSLClient;
  7514. #else
  7515. using ClientT = Client;
  7516. #endif
  7517. TestWithHeadersAndContentReceiver<ClientT>(
  7518. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7519. const std::string &body, const std::string &content_type,
  7520. ContentReceiver receiver, DownloadProgress progress) {
  7521. return cli.Post(path, headers, body, content_type, receiver, progress);
  7522. });
  7523. }
  7524. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7525. #ifdef CPPHTTPLIB_SSL_ENABLED
  7526. using ClientT = SSLClient;
  7527. #else
  7528. using ClientT = Client;
  7529. #endif
  7530. TestWithHeadersAndContentReceiver<ClientT>(
  7531. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7532. const std::string &body, const std::string &content_type,
  7533. ContentReceiver receiver, DownloadProgress progress) {
  7534. return cli.Put(path, headers, body, content_type, receiver, progress);
  7535. });
  7536. }
  7537. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7538. #ifdef CPPHTTPLIB_SSL_ENABLED
  7539. using ClientT = SSLClient;
  7540. #else
  7541. using ClientT = Client;
  7542. #endif
  7543. TestWithHeadersAndContentReceiver<ClientT>(
  7544. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7545. const std::string &body, const std::string &content_type,
  7546. ContentReceiver receiver, DownloadProgress progress) {
  7547. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7548. });
  7549. }
  7550. template <typename ClientType>
  7551. void TestWithHeadersAndContentReceiverWithProgress(
  7552. ClientType &cli,
  7553. std::function<Result(ClientType &, const std::string &, const Headers &,
  7554. const std::string &, const std::string &,
  7555. ContentReceiver, DownloadProgress)>
  7556. request_func) {
  7557. Headers headers;
  7558. headers.emplace("X-Test-Header", "progress-test");
  7559. std::string received_body;
  7560. auto progress_called = false;
  7561. auto res = request_func(
  7562. cli, "/content_receiver", headers, "content", "text/plain",
  7563. [&](const char *data, size_t data_length) {
  7564. received_body.append(data, data_length);
  7565. return true;
  7566. },
  7567. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7568. progress_called = true;
  7569. return true;
  7570. });
  7571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7572. EXPECT_EQ(StatusCode::OK_200, res->status);
  7573. EXPECT_EQ("content", received_body);
  7574. EXPECT_TRUE(progress_called);
  7575. }
  7576. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7577. #ifdef CPPHTTPLIB_SSL_ENABLED
  7578. using ClientT = SSLClient;
  7579. #else
  7580. using ClientT = Client;
  7581. #endif
  7582. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7583. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7584. const std::string &body, const std::string &content_type,
  7585. ContentReceiver receiver, DownloadProgress progress) {
  7586. return cli.Post(path, headers, body, content_type, receiver, progress);
  7587. });
  7588. }
  7589. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7590. #ifdef CPPHTTPLIB_SSL_ENABLED
  7591. using ClientT = SSLClient;
  7592. #else
  7593. using ClientT = Client;
  7594. #endif
  7595. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7596. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7597. const std::string &body, const std::string &content_type,
  7598. ContentReceiver receiver, DownloadProgress progress) {
  7599. return cli.Put(path, headers, body, content_type, receiver, progress);
  7600. });
  7601. }
  7602. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7603. #ifdef CPPHTTPLIB_SSL_ENABLED
  7604. using ClientT = SSLClient;
  7605. #else
  7606. using ClientT = Client;
  7607. #endif
  7608. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7609. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7610. const std::string &body, const std::string &content_type,
  7611. ContentReceiver receiver, DownloadProgress progress) {
  7612. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7613. });
  7614. }
  7615. template <typename ClientType>
  7616. void TestWithHeadersAndContentReceiverError(
  7617. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7618. const Headers &, const std::string &,
  7619. const std::string &, ContentReceiver)>
  7620. request_func) {
  7621. Headers headers;
  7622. headers.emplace("X-Error-Test", "true");
  7623. std::string received_body;
  7624. auto receiver_failed = false;
  7625. auto res =
  7626. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7627. [&](const char *data, size_t data_length) {
  7628. received_body.append(data, data_length);
  7629. receiver_failed = true;
  7630. return false;
  7631. });
  7632. ASSERT_FALSE(res);
  7633. EXPECT_TRUE(receiver_failed);
  7634. }
  7635. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7636. #ifdef CPPHTTPLIB_SSL_ENABLED
  7637. using ClientT = SSLClient;
  7638. #else
  7639. using ClientT = Client;
  7640. #endif
  7641. TestWithHeadersAndContentReceiverError<ClientT>(
  7642. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7643. const std::string &body, const std::string &content_type,
  7644. ContentReceiver receiver) {
  7645. return cli.Post(path, headers, body, content_type, receiver);
  7646. });
  7647. }
  7648. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7649. #ifdef CPPHTTPLIB_SSL_ENABLED
  7650. using ClientT = SSLClient;
  7651. #else
  7652. using ClientT = Client;
  7653. #endif
  7654. TestWithHeadersAndContentReceiverError<ClientT>(
  7655. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7656. const std::string &body, const std::string &content_type,
  7657. ContentReceiver receiver) {
  7658. return cli.Put(path, headers, body, content_type, receiver);
  7659. });
  7660. }
  7661. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7662. #ifdef CPPHTTPLIB_SSL_ENABLED
  7663. using ClientT = SSLClient;
  7664. #else
  7665. using ClientT = Client;
  7666. #endif
  7667. TestWithHeadersAndContentReceiverError<ClientT>(
  7668. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7669. const std::string &body, const std::string &content_type,
  7670. ContentReceiver receiver) {
  7671. return cli.Patch(path, headers, body, content_type, receiver);
  7672. });
  7673. }
  7674. TEST_F(ServerTest, PostQueryStringAndBody) {
  7675. auto res =
  7676. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7678. ASSERT_EQ(StatusCode::OK_200, res->status);
  7679. }
  7680. TEST_F(ServerTest, HTTP2Magic) {
  7681. Request req;
  7682. req.method = "PRI";
  7683. req.path = "*";
  7684. req.body = "SM";
  7685. auto res = std::make_shared<Response>();
  7686. auto error = Error::Success;
  7687. auto ret = cli_.send(req, *res, error);
  7688. ASSERT_TRUE(ret);
  7689. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7690. }
  7691. TEST_F(ServerTest, KeepAlive) {
  7692. auto res = cli_.Get("/hi");
  7693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7694. EXPECT_EQ(StatusCode::OK_200, res->status);
  7695. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7696. EXPECT_EQ("Hello World!", res->body);
  7697. res = cli_.Get("/hi");
  7698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7699. EXPECT_EQ(StatusCode::OK_200, res->status);
  7700. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7701. EXPECT_EQ("Hello World!", res->body);
  7702. res = cli_.Get("/hi");
  7703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7704. EXPECT_EQ(StatusCode::OK_200, res->status);
  7705. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7706. EXPECT_EQ("Hello World!", res->body);
  7707. res = cli_.Get("/not-exist");
  7708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7709. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7710. res = cli_.Post("/empty", "", "text/plain");
  7711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7712. EXPECT_EQ(StatusCode::OK_200, res->status);
  7713. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7714. EXPECT_EQ("empty", res->body);
  7715. EXPECT_EQ("close", res->get_header_value("Connection"));
  7716. res = cli_.Post(
  7717. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7718. "text/plain");
  7719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7720. EXPECT_EQ(StatusCode::OK_200, res->status);
  7721. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7722. EXPECT_EQ("empty", res->body);
  7723. cli_.set_keep_alive(false);
  7724. res = cli_.Get("/last-request");
  7725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7726. EXPECT_EQ(StatusCode::OK_200, res->status);
  7727. EXPECT_EQ("close", res->get_header_value("Connection"));
  7728. }
  7729. TEST_F(ServerTest, TooManyRedirect) {
  7730. cli_.set_follow_location(true);
  7731. auto res = cli_.Get("/redirect/0");
  7732. ASSERT_TRUE(!res);
  7733. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7734. }
  7735. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7736. Request req;
  7737. req.method = "FOOBAR";
  7738. req.path = "/hi";
  7739. cli_.set_keep_alive(true);
  7740. auto res = cli_.send(req);
  7741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7742. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7743. EXPECT_EQ("close", res->get_header_value("Connection"));
  7744. EXPECT_FALSE(cli_.is_socket_open());
  7745. }
  7746. TEST_F(ServerTest, CustomRouteReadsBody) {
  7747. const std::string xml =
  7748. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7749. Request req;
  7750. req.method = "PROPFIND";
  7751. req.path = "/dav/dir";
  7752. req.set_header("Depth", "1");
  7753. req.body = xml;
  7754. auto res = cli_.send(req);
  7755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7756. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7757. EXPECT_EQ(xml, res->body);
  7758. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7759. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7760. }
  7761. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7762. Request req;
  7763. req.method = "PROPFIND";
  7764. req.path = "/dav/42";
  7765. auto res = cli_.send(req);
  7766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7767. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7768. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7769. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7770. }
  7771. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7772. Request req;
  7773. req.method = "PROPFIND";
  7774. req.path = "/dav-re/123";
  7775. auto res = cli_.send(req);
  7776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7777. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7778. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7779. }
  7780. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7781. Request req;
  7782. req.method = "MKCOL";
  7783. req.path = "/dav-mkcol";
  7784. auto res = cli_.send(req);
  7785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7786. EXPECT_EQ(StatusCode::Created_201, res->status);
  7787. }
  7788. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7789. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7790. Request req;
  7791. req.method = "REPORT";
  7792. req.path = "/dav-report";
  7793. req.body = xml;
  7794. auto res = cli_.send(req);
  7795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7796. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7797. EXPECT_EQ(xml, res->body);
  7798. }
  7799. // A content reader route must fire even when the request carries no body,
  7800. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7801. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7802. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7803. Request req;
  7804. req.method = "REPORT";
  7805. req.path = "/dav-report";
  7806. auto res = cli_.send(req);
  7807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7808. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7809. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7810. }
  7811. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7812. Request req;
  7813. req.method = "PROPFIND";
  7814. req.path = "/not-dav";
  7815. auto res = cli_.send(req);
  7816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7817. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7818. }
  7819. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7820. Request req;
  7821. req.method = "UNLOCK";
  7822. req.path = "/dav/dir";
  7823. cli_.set_keep_alive(true);
  7824. auto res = cli_.send(req);
  7825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7826. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7827. EXPECT_EQ("close", res->get_header_value("Connection"));
  7828. EXPECT_FALSE(cli_.is_socket_open());
  7829. }
  7830. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7831. // The mount point serves this path, but only for GET and HEAD.
  7832. auto get_res = cli_.Get("/dir/index.html");
  7833. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7834. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7835. Request req;
  7836. req.method = "PROPFIND";
  7837. req.path = "/dir/index.html";
  7838. auto res = cli_.send(req);
  7839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7840. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7841. }
  7842. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7843. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7844. cli_.set_keep_alive(true);
  7845. for (auto i = 0; i < 2; i++) {
  7846. Request req;
  7847. req.method = "PROPFIND";
  7848. req.path = "/dav/dir";
  7849. req.body = xml;
  7850. auto res = cli_.send(req);
  7851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7852. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7853. EXPECT_EQ(xml, res->body);
  7854. EXPECT_TRUE(cli_.is_socket_open());
  7855. }
  7856. // A built-in method must still be served on the same connection.
  7857. cli_.set_keep_alive(false);
  7858. auto res = cli_.Get("/hi");
  7859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7860. EXPECT_EQ(StatusCode::OK_200, res->status);
  7861. EXPECT_EQ("close", res->get_header_value("Connection"));
  7862. }
  7863. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7864. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7865. Request req;
  7866. req.method = "PROPFIND";
  7867. req.path = "/dav/dir";
  7868. req.set_header("Expect", "100-continue");
  7869. req.body = xml;
  7870. auto res = cli_.send(req);
  7871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7872. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7873. EXPECT_EQ(xml, res->body);
  7874. }
  7875. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7876. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7877. TEST_F(ServerTest, Gzip) {
  7878. Headers headers;
  7879. headers.emplace("Accept-Encoding", "gzip, deflate");
  7880. auto res = cli_.Get("/compress", headers);
  7881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7882. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7883. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7884. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7885. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7886. "7890123456789012345678901234567890",
  7887. res->body);
  7888. EXPECT_EQ(StatusCode::OK_200, res->status);
  7889. }
  7890. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7891. Headers headers;
  7892. headers.emplace("Accept-Encoding", "gzip, deflate");
  7893. auto res = cli_.Get("/compress-with-charset", headers);
  7894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7895. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7896. EXPECT_EQ("application/json; charset=utf-8",
  7897. res->get_header_value("Content-Type"));
  7898. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7899. "7890123456789012345678901234567890",
  7900. res->body);
  7901. EXPECT_EQ(StatusCode::OK_200, res->status);
  7902. }
  7903. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7904. Headers headers;
  7905. headers.emplace("Accept-Encoding", "");
  7906. auto res = cli_.Get("/compress", headers);
  7907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7908. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7909. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7910. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7911. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7912. "7890123456789012345678901234567890",
  7913. res->body);
  7914. EXPECT_EQ(StatusCode::OK_200, res->status);
  7915. }
  7916. TEST_F(ServerTest, GzipWithContentReceiver) {
  7917. Headers headers;
  7918. headers.emplace("Accept-Encoding", "gzip, deflate");
  7919. std::string body;
  7920. auto res = cli_.Get("/compress", headers,
  7921. [&](const char *data, uint64_t data_length) {
  7922. EXPECT_EQ(100U, data_length);
  7923. body.append(data, data_length);
  7924. return true;
  7925. });
  7926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7927. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7928. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7929. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7930. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7931. "7890123456789012345678901234567890",
  7932. body);
  7933. EXPECT_EQ(StatusCode::OK_200, res->status);
  7934. }
  7935. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7936. Headers headers;
  7937. headers.emplace("Accept-Encoding", "gzip, deflate");
  7938. cli_.set_decompress(false);
  7939. auto res = cli_.Get("/compress", headers);
  7940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7941. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7942. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7943. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7944. EXPECT_EQ(33U, res->body.size());
  7945. EXPECT_EQ(StatusCode::OK_200, res->status);
  7946. }
  7947. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7948. Headers headers;
  7949. headers.emplace("Accept-Encoding", "");
  7950. std::string body;
  7951. auto res = cli_.Get("/compress", headers,
  7952. [&](const char *data, uint64_t data_length) {
  7953. EXPECT_EQ(100U, data_length);
  7954. body.append(data, data_length);
  7955. return true;
  7956. });
  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. body);
  7964. EXPECT_EQ(StatusCode::OK_200, res->status);
  7965. }
  7966. TEST_F(ServerTest, NoGzip) {
  7967. Headers headers;
  7968. headers.emplace("Accept-Encoding", "gzip, deflate");
  7969. auto res = cli_.Get("/nocompress", headers);
  7970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7971. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7972. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7973. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7974. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7975. "7890123456789012345678901234567890",
  7976. res->body);
  7977. EXPECT_EQ(StatusCode::OK_200, res->status);
  7978. }
  7979. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7980. Headers headers;
  7981. headers.emplace("Accept-Encoding", "gzip, deflate");
  7982. std::string body;
  7983. auto res = cli_.Get("/nocompress", headers,
  7984. [&](const char *data, uint64_t data_length) {
  7985. EXPECT_EQ(100U, data_length);
  7986. body.append(data, data_length);
  7987. return true;
  7988. });
  7989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7990. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7991. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7992. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7993. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7994. "7890123456789012345678901234567890",
  7995. body);
  7996. EXPECT_EQ(StatusCode::OK_200, res->status);
  7997. }
  7998. TEST_F(ServerTest, MultipartFormDataGzip) {
  7999. UploadFormDataItems items = {
  8000. {"key1", "test", "", ""},
  8001. {"key2", "--abcdefg123", "", ""},
  8002. };
  8003. cli_.set_compress(true);
  8004. auto res = cli_.Post("/compress-multipart", items);
  8005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8006. EXPECT_EQ(StatusCode::OK_200, res->status);
  8007. }
  8008. #endif
  8009. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8010. // Static file compression is opt-in, so these run their own server rather than
  8011. // flipping it on for the shared ServerTest fixture, which would silently
  8012. // rewrite what every other static file test is asserting.
  8013. class StaticFileCompressionTest : public ::testing::Test {
  8014. protected:
  8015. void TearDown() override {
  8016. if (t_.joinable()) {
  8017. svr_.stop();
  8018. t_.join();
  8019. }
  8020. }
  8021. int start(const std::function<void(Server &)> &configure = nullptr) {
  8022. // Serves the same tree as a directory of build-time compressed assets
  8023. // would be served: the mount point names the coding the files are already
  8024. // stored in. Registered before "/" so it is the one that matches.
  8025. svr_.set_mount_point("/pre-encoded", "./www",
  8026. {{"Content-Encoding", "gzip"}});
  8027. svr_.set_mount_point("/", "./www");
  8028. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8029. res.set_file_content("./www/dir/index.html", "text/html");
  8030. });
  8031. svr_.Get("/pre-encoded-file-content",
  8032. [](const Request & /*req*/, Response &res) {
  8033. res.set_header("Content-Encoding", "gzip");
  8034. res.set_file_content("./www/dir/index.html", "text/html");
  8035. });
  8036. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8037. res.set_content_provider(
  8038. 6, "text/plain",
  8039. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8040. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8041. return true;
  8042. });
  8043. });
  8044. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8045. res.set_content_provider(
  8046. 1000, "text/plain",
  8047. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8048. if (offset < 100) {
  8049. std::string data(100, 'A');
  8050. sink.write(data.data(), data.size());
  8051. return true;
  8052. }
  8053. std::this_thread::sleep_for(std::chrono::seconds(2));
  8054. std::string data(900, 'B');
  8055. sink.write(data.data(), data.size());
  8056. return true;
  8057. });
  8058. });
  8059. if (configure) { configure(svr_); }
  8060. auto port = svr_.bind_to_any_port(HOST);
  8061. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8062. svr_.wait_until_ready();
  8063. return port;
  8064. }
  8065. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8066. // Every file under ./www except 1MB.txt is smaller than the default
  8067. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8068. // it out of the way.
  8069. static void enable_without_floor(Server &svr) {
  8070. svr.set_static_file_compression(true);
  8071. svr.set_static_file_compression_min_length(0);
  8072. }
  8073. Server svr_;
  8074. std::thread t_;
  8075. };
  8076. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8077. auto port = start();
  8078. Client cli(HOST, port);
  8079. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8081. EXPECT_EQ(StatusCode::OK_200, res->status);
  8082. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8083. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8084. EXPECT_EQ(1048576U, res->body.size());
  8085. }
  8086. TEST_F(StaticFileCompressionTest, MountPoint) {
  8087. auto port = start(enable);
  8088. Client cli(HOST, port);
  8089. cli.set_decompress(false);
  8090. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8092. EXPECT_EQ(StatusCode::OK_200, res->status);
  8093. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8094. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8095. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8096. // The response stays self-delimiting: a length, not a chunked body.
  8097. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8098. EXPECT_EQ(std::to_string(res->body.size()),
  8099. res->get_header_value("Content-Length"));
  8100. EXPECT_LT(res->body.size(), 1048576U);
  8101. EXPECT_FALSE(res->body.empty());
  8102. }
  8103. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8104. auto port = start(enable);
  8105. Client cli(HOST, port);
  8106. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8108. EXPECT_EQ(StatusCode::OK_200, res->status);
  8109. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8110. EXPECT_EQ(1048576U, res->body.size());
  8111. }
  8112. TEST_F(StaticFileCompressionTest, FileContent) {
  8113. auto port = start(enable_without_floor);
  8114. Client cli(HOST, port);
  8115. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8117. EXPECT_EQ(StatusCode::OK_200, res->status);
  8118. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8119. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8120. EXPECT_EQ(104U, res->body.size());
  8121. }
  8122. // A handler that serves an already-encoded file names the coding itself. The
  8123. // file-backed path decided its coding from Accept-Encoding and the content
  8124. // type alone, so it compressed the stored bytes a second time and appended a
  8125. // second Content-Encoding field line.
  8126. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8127. auto port = start(enable_without_floor);
  8128. Client cli(HOST, port);
  8129. cli.set_decompress(false);
  8130. auto res = cli.Get("/pre-encoded-file-content",
  8131. Headers{{"Accept-Encoding", "gzip"}});
  8132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8133. EXPECT_EQ(StatusCode::OK_200, res->status);
  8134. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8135. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8136. // Vary belongs to a coding the server chose, and it chose none here.
  8137. EXPECT_FALSE(res->has_header("Vary"));
  8138. // The file travels exactly as it is stored on disk.
  8139. EXPECT_EQ(104U, res->body.size());
  8140. }
  8141. // The 1MB file clears the default floor, so this one runs the configuration a
  8142. // deployment would actually have.
  8143. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8144. auto port = start(enable);
  8145. Client cli(HOST, port);
  8146. cli.set_decompress(false);
  8147. auto res =
  8148. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8150. EXPECT_EQ(StatusCode::OK_200, res->status);
  8151. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8152. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8153. EXPECT_FALSE(res->has_header("Vary"));
  8154. EXPECT_EQ(1048576U, res->body.size());
  8155. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8156. }
  8157. TEST_F(StaticFileCompressionTest, Head) {
  8158. auto port = start(enable);
  8159. Client cli(HOST, port);
  8160. cli.set_decompress(false);
  8161. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8162. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8163. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8165. EXPECT_EQ(StatusCode::OK_200, res->status);
  8166. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8167. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8168. // HEAD still reports the size a GET would return.
  8169. EXPECT_EQ(get->get_header_value("Content-Length"),
  8170. res->get_header_value("Content-Length"));
  8171. EXPECT_TRUE(res->body.empty());
  8172. }
  8173. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8174. auto port = start(enable);
  8175. Client cli(HOST, port);
  8176. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8177. {"Accept-Encoding", "gzip"}});
  8178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8179. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8180. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8181. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8182. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8183. EXPECT_EQ("cd", res->body);
  8184. }
  8185. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8186. auto port = start(enable);
  8187. Client cli(HOST, port);
  8188. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8190. EXPECT_EQ(StatusCode::OK_200, res->status);
  8191. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8192. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8193. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8194. }
  8195. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8196. auto port = start(enable);
  8197. Client cli(HOST, port);
  8198. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8200. EXPECT_EQ(StatusCode::OK_200, res->status);
  8201. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8202. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8203. EXPECT_TRUE(res->body.empty());
  8204. }
  8205. TEST_F(StaticFileCompressionTest, MinLength) {
  8206. auto port = start(enable);
  8207. Client cli(HOST, port);
  8208. // 104 bytes, well under the default floor. Compressing it would add the
  8209. // gzip header and trailer to a body that already fits in one packet.
  8210. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8212. EXPECT_EQ(StatusCode::OK_200, res->status);
  8213. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8214. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8215. }
  8216. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8217. auto port = start([](Server &svr) {
  8218. svr.set_static_file_compression(true);
  8219. svr.set_static_file_compression_min_length(1);
  8220. });
  8221. Client cli(HOST, port);
  8222. cli.set_decompress(false);
  8223. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8225. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8226. // A 9-byte file comes back larger than it went in, because gzip's header and
  8227. // trailer outweigh anything deflate can save. That is the end of the range
  8228. // the floor exists to keep out.
  8229. EXPECT_GT(res->body.size(), 9U);
  8230. }
  8231. TEST_F(StaticFileCompressionTest, MaxLength) {
  8232. auto port = start([](Server &svr) {
  8233. svr.set_static_file_compression(true);
  8234. svr.set_static_file_compression_min_length(0);
  8235. svr.set_static_file_compression_max_length(1024);
  8236. });
  8237. Client cli(HOST, port);
  8238. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8239. // defines `small` as a macro on Windows.
  8240. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8241. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8242. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8243. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8244. // Under it: compressed.
  8245. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8246. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8247. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8248. }
  8249. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8250. auto port = start(enable_without_floor);
  8251. Client cli(HOST, port);
  8252. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8253. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8254. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8255. auto identity_etag = identity->get_header_value("ETag");
  8256. ASSERT_FALSE(identity_etag.empty());
  8257. auto gzipped =
  8258. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8259. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8260. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8261. auto gzip_etag = gzipped->get_header_value("ETag");
  8262. ASSERT_FALSE(gzip_etag.empty());
  8263. // Two representations, two validators.
  8264. EXPECT_NE(identity_etag, gzip_etag);
  8265. // Each one revalidates against the request that would produce it...
  8266. auto fresh =
  8267. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8268. {"If-None-Match", gzip_etag}});
  8269. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8270. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8271. auto fresh_identity =
  8272. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8273. {"If-None-Match", identity_etag}});
  8274. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8275. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8276. // ...and not against the other representation.
  8277. auto crossed =
  8278. cli.Get("/dir/index.html",
  8279. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8280. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8281. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8282. }
  8283. // The opt-in covers responses the server reads off disk itself. A caller's own
  8284. // known-length provider keeps its Content-Length and, more importantly, keeps
  8285. // delivering incrementally: routing it through a compressor would hold every
  8286. // write back until zlib's window filled.
  8287. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8288. auto port = start(enable);
  8289. Client cli(HOST, port);
  8290. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8292. EXPECT_EQ(StatusCode::OK_200, res->status);
  8293. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8294. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8295. EXPECT_EQ("aaabbb", res->body);
  8296. }
  8297. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8298. auto port = start(enable);
  8299. Client cli(HOST, port);
  8300. cli.set_read_timeout(1, 0);
  8301. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8302. Headers{{"Accept-Encoding", "gzip"}});
  8303. ASSERT_TRUE(handle.is_valid());
  8304. // The provider writes 100 bytes and then stalls for longer than the read
  8305. // timeout. Those first bytes have to arrive anyway: run the response through
  8306. // a compressor and zlib holds them until its window fills, so the read would
  8307. // come back empty instead.
  8308. char buf[256];
  8309. auto n = handle.read(buf, sizeof(buf));
  8310. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8311. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8312. }
  8313. #endif
  8314. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8315. TEST_F(ServerTest, Brotli) {
  8316. Headers headers;
  8317. headers.emplace("Accept-Encoding", "br");
  8318. auto res = cli_.Get("/compress", headers);
  8319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8320. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8321. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8322. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8323. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8324. "7890123456789012345678901234567890",
  8325. res->body);
  8326. EXPECT_EQ(StatusCode::OK_200, res->status);
  8327. }
  8328. #endif
  8329. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8330. TEST_F(ServerTest, Zstd) {
  8331. Headers headers;
  8332. headers.emplace("Accept-Encoding", "zstd");
  8333. auto res = cli_.Get("/compress", headers);
  8334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8335. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8336. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8337. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8338. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8339. "7890123456789012345678901234567890",
  8340. res->body);
  8341. EXPECT_EQ(StatusCode::OK_200, res->status);
  8342. }
  8343. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8344. Headers headers;
  8345. headers.emplace("Accept-Encoding", "");
  8346. auto res = cli_.Get("/compress", headers);
  8347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8348. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8349. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8350. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8351. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8352. "7890123456789012345678901234567890",
  8353. res->body);
  8354. EXPECT_EQ(StatusCode::OK_200, res->status);
  8355. }
  8356. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8357. Headers headers;
  8358. headers.emplace("Accept-Encoding", "zstd");
  8359. std::string body;
  8360. auto res = cli_.Get("/compress", headers,
  8361. [&](const char *data, uint64_t data_length) {
  8362. EXPECT_EQ(100U, data_length);
  8363. body.append(data, data_length);
  8364. return true;
  8365. });
  8366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8367. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8368. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8369. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8370. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8371. "7890123456789012345678901234567890",
  8372. body);
  8373. EXPECT_EQ(StatusCode::OK_200, res->status);
  8374. }
  8375. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8376. Headers headers;
  8377. headers.emplace("Accept-Encoding", "zstd");
  8378. cli_.set_decompress(false);
  8379. auto res = cli_.Get("/compress", headers);
  8380. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8381. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8382. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8383. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  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(StatusCode::OK_200, res->status);
  8389. ASSERT_EQ(26U, res->body.size());
  8390. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8391. 0);
  8392. }
  8393. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8394. Headers headers;
  8395. headers.emplace("Accept-Encoding", "");
  8396. std::string body;
  8397. auto res = cli_.Get("/compress", headers,
  8398. [&](const char *data, uint64_t data_length) {
  8399. EXPECT_EQ(100U, data_length);
  8400. body.append(data, data_length);
  8401. return true;
  8402. });
  8403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8404. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8405. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8406. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8407. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8408. "7890123456789012345678901234567890",
  8409. body);
  8410. EXPECT_EQ(StatusCode::OK_200, res->status);
  8411. }
  8412. TEST_F(ServerTest, NoZstd) {
  8413. Headers headers;
  8414. headers.emplace("Accept-Encoding", "zstd");
  8415. auto res = cli_.Get("/nocompress", headers);
  8416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8417. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8418. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8419. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8420. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8421. "7890123456789012345678901234567890",
  8422. res->body);
  8423. EXPECT_EQ(StatusCode::OK_200, res->status);
  8424. }
  8425. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8426. Headers headers;
  8427. headers.emplace("Accept-Encoding", "zstd");
  8428. std::string body;
  8429. auto res = cli_.Get("/nocompress", headers,
  8430. [&](const char *data, uint64_t data_length) {
  8431. EXPECT_EQ(100U, data_length);
  8432. body.append(data, data_length);
  8433. return true;
  8434. });
  8435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8436. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8437. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8438. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8439. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8440. "7890123456789012345678901234567890",
  8441. body);
  8442. EXPECT_EQ(StatusCode::OK_200, res->status);
  8443. }
  8444. // TODO: How to enable zstd ??
  8445. TEST_F(ServerTest, MultipartFormDataZstd) {
  8446. UploadFormDataItems items = {
  8447. {"key1", "test", "", ""},
  8448. {"key2", "--abcdefg123", "", ""},
  8449. };
  8450. Headers headers;
  8451. headers.emplace("Accept-Encoding", "zstd");
  8452. cli_.set_compress(true);
  8453. auto res = cli_.Post("/compress-multipart", headers, items);
  8454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8455. EXPECT_EQ(StatusCode::OK_200, res->status);
  8456. }
  8457. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8458. Headers headers;
  8459. headers.emplace("Accept-Encoding", "zstd");
  8460. cli_.set_compress(true);
  8461. auto res = cli_.Put(
  8462. "/put", headers, 3,
  8463. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8464. sink.os << "PUT";
  8465. return true;
  8466. },
  8467. "text/plain");
  8468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8469. EXPECT_EQ(StatusCode::OK_200, res->status);
  8470. EXPECT_EQ("PUT", res->body);
  8471. }
  8472. // Pre-compression logging tests
  8473. TEST_F(ServerTest, PreCompressionLogging) {
  8474. // Test data for compression (matches the actual /compress endpoint content)
  8475. const std::string test_content =
  8476. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8477. "3456789012345678901234567890";
  8478. // Variables to capture logging data
  8479. std::string pre_compression_body;
  8480. std::string pre_compression_content_type;
  8481. std::string pre_compression_content_encoding;
  8482. std::string post_compression_body;
  8483. std::string post_compression_content_type;
  8484. std::string post_compression_content_encoding;
  8485. // Set up pre-compression logger
  8486. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8487. const Response &res) {
  8488. pre_compression_body = res.body;
  8489. pre_compression_content_type = res.get_header_value("Content-Type");
  8490. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8491. });
  8492. // Set up post-compression logger
  8493. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8494. post_compression_body = res.body;
  8495. post_compression_content_type = res.get_header_value("Content-Type");
  8496. post_compression_content_encoding =
  8497. res.get_header_value("Content-Encoding");
  8498. });
  8499. // Test with gzip compression
  8500. Headers headers;
  8501. headers.emplace("Accept-Encoding", "gzip");
  8502. auto res = cli_.Get("/compress", headers);
  8503. // Verify response was compressed
  8504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8505. EXPECT_EQ(StatusCode::OK_200, res->status);
  8506. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8507. // Verify pre-compression logger captured uncompressed content
  8508. EXPECT_EQ(test_content, pre_compression_body);
  8509. EXPECT_EQ("text/plain", pre_compression_content_type);
  8510. EXPECT_TRUE(pre_compression_content_encoding
  8511. .empty()); // No encoding header before compression
  8512. // Verify post-compression logger captured compressed content
  8513. EXPECT_NE(test_content,
  8514. post_compression_body); // Should be different after compression
  8515. EXPECT_EQ("text/plain", post_compression_content_type);
  8516. EXPECT_EQ("gzip", post_compression_content_encoding);
  8517. // Verify compressed content is smaller
  8518. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8519. }
  8520. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8521. const std::string test_content =
  8522. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8523. "3456789012345678901234567890";
  8524. std::string pre_compression_body;
  8525. std::string post_compression_body;
  8526. svr_.set_pre_compression_logger(
  8527. [&](const Request & /*req*/, const Response &res) {
  8528. pre_compression_body = res.body;
  8529. });
  8530. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8531. post_compression_body = res.body;
  8532. });
  8533. Headers headers;
  8534. headers.emplace("Accept-Encoding", "br");
  8535. auto res = cli_.Get("/compress", headers);
  8536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8537. EXPECT_EQ(StatusCode::OK_200, res->status);
  8538. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8539. // Verify pre-compression content is uncompressed
  8540. EXPECT_EQ(test_content, pre_compression_body);
  8541. // Verify post-compression content is compressed
  8542. EXPECT_NE(test_content, post_compression_body);
  8543. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8544. }
  8545. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8546. const std::string test_content =
  8547. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8548. "3456789012345678901234567890";
  8549. std::string pre_compression_body;
  8550. std::string post_compression_body;
  8551. svr_.set_pre_compression_logger(
  8552. [&](const Request & /*req*/, const Response &res) {
  8553. pre_compression_body = res.body;
  8554. });
  8555. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8556. post_compression_body = res.body;
  8557. });
  8558. // Request without compression (use /nocompress endpoint)
  8559. Headers headers;
  8560. auto res = cli_.Get("/nocompress", headers);
  8561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8562. EXPECT_EQ(StatusCode::OK_200, res->status);
  8563. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8564. // Pre-compression logger should not be called when no compression is applied
  8565. EXPECT_TRUE(
  8566. pre_compression_body.empty()); // Pre-compression logger not called
  8567. EXPECT_EQ(
  8568. test_content,
  8569. post_compression_body); // Post-compression logger captures final content
  8570. }
  8571. TEST_F(ServerTest, LoggerSeesContentLength) {
  8572. size_t logged_content_length = 0;
  8573. std::string logged_content_length_header;
  8574. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8575. logged_content_length = res.content_length_;
  8576. logged_content_length_header = res.get_header_value("Content-Length");
  8577. });
  8578. auto res = cli_.Get("/nocompress");
  8579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8580. EXPECT_EQ(StatusCode::OK_200, res->status);
  8581. EXPECT_EQ(res->body.size(), logged_content_length);
  8582. EXPECT_EQ(std::to_string(logged_content_length),
  8583. logged_content_length_header);
  8584. }
  8585. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8586. const std::string test_content =
  8587. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8588. "3456789012345678901234567890";
  8589. std::string pre_compression_body;
  8590. bool pre_logger_called = false;
  8591. // Set only pre-compression logger
  8592. svr_.set_pre_compression_logger(
  8593. [&](const Request & /*req*/, const Response &res) {
  8594. pre_compression_body = res.body;
  8595. pre_logger_called = true;
  8596. });
  8597. Headers headers;
  8598. headers.emplace("Accept-Encoding", "gzip");
  8599. auto res = cli_.Get("/compress", headers);
  8600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8601. EXPECT_EQ(StatusCode::OK_200, res->status);
  8602. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8603. // Verify pre-compression logger was called
  8604. EXPECT_TRUE(pre_logger_called);
  8605. EXPECT_EQ(test_content, pre_compression_body);
  8606. }
  8607. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8608. {
  8609. // Test with Expect: 100-continue header - success case
  8610. // Server returns 100 Continue, client sends body, server returns 200 OK
  8611. Request req;
  8612. req.method = "POST";
  8613. req.path = "/post-large";
  8614. req.set_header("Expect", "100-continue");
  8615. req.body = LARGE_DATA;
  8616. Response res;
  8617. auto error = Error::Success;
  8618. cli_.set_keep_alive(true);
  8619. auto ret = cli_.send(req, res, error);
  8620. EXPECT_TRUE(ret);
  8621. EXPECT_EQ(StatusCode::OK_200, res.status);
  8622. EXPECT_EQ(LARGE_DATA, res.body);
  8623. }
  8624. {
  8625. // Test with Expect: 100-continue header - error case
  8626. // Client should not send the body when server returns an error
  8627. Request req;
  8628. req.method = "POST";
  8629. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8630. req.set_header("Expect", "100-continue");
  8631. req.body = LARGE_DATA;
  8632. Response res;
  8633. auto error = Error::Success;
  8634. auto start = std::chrono::high_resolution_clock::now();
  8635. cli_.set_keep_alive(true);
  8636. auto ret = cli_.send(req, res, error);
  8637. auto end = std::chrono::high_resolution_clock::now();
  8638. auto elapsed =
  8639. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8640. .count();
  8641. // With Expect: 100-continue, request completes successfully but with error
  8642. EXPECT_TRUE(ret);
  8643. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8644. EXPECT_EQ("close", res.get_header_value("Connection"));
  8645. EXPECT_FALSE(cli_.is_socket_open());
  8646. EXPECT_LE(elapsed, 2000);
  8647. }
  8648. {
  8649. // Send an extra GET request to ensure error recovery without hanging
  8650. Request req;
  8651. req.method = "GET";
  8652. req.path = "/hi";
  8653. auto start = std::chrono::high_resolution_clock::now();
  8654. auto res = cli_.send(req);
  8655. auto end = std::chrono::high_resolution_clock::now();
  8656. auto elapsed =
  8657. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8658. .count();
  8659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8660. EXPECT_EQ(StatusCode::OK_200, res->status);
  8661. EXPECT_EQ("Hello World!", res->body);
  8662. EXPECT_LE(elapsed, 500);
  8663. }
  8664. }
  8665. TEST(ZstdDecompressor, ChunkedDecompression) {
  8666. std::string data;
  8667. for (size_t i = 0; i < 32 * 1024; ++i) {
  8668. data.push_back(static_cast<char>('a' + i % 26));
  8669. }
  8670. std::string compressed_data;
  8671. {
  8672. httplib::detail::zstd_compressor compressor;
  8673. bool result = compressor.compress(
  8674. data.data(), data.size(),
  8675. /*last=*/true,
  8676. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8677. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8678. compressed_data_size);
  8679. return true;
  8680. });
  8681. ASSERT_TRUE(result);
  8682. }
  8683. std::string decompressed_data;
  8684. {
  8685. httplib::detail::zstd_decompressor decompressor;
  8686. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8687. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8688. size_t chunk_size = 130;
  8689. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8690. chunk_begin += chunk_size) {
  8691. size_t current_chunk_size =
  8692. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8693. bool result = decompressor.decompress(
  8694. compressed_data.data() + chunk_begin, current_chunk_size,
  8695. [&](const char *decompressed_data_chunk,
  8696. size_t decompressed_data_chunk_size) {
  8697. decompressed_data.insert(decompressed_data.size(),
  8698. decompressed_data_chunk,
  8699. decompressed_data_chunk_size);
  8700. return true;
  8701. });
  8702. ASSERT_TRUE(result);
  8703. }
  8704. }
  8705. ASSERT_EQ(data, decompressed_data);
  8706. }
  8707. TEST(ZstdDecompressor, Decompress) {
  8708. std::string original_text = "Compressed with ZSTD";
  8709. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8710. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8711. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8712. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8713. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8714. std::string decompressed_data;
  8715. {
  8716. httplib::detail::zstd_decompressor decompressor;
  8717. bool result = decompressor.decompress(
  8718. compressed_data.data(), compressed_data.size(),
  8719. [&](const char *decompressed_data_chunk,
  8720. size_t decompressed_data_chunk_size) {
  8721. decompressed_data.insert(decompressed_data.size(),
  8722. decompressed_data_chunk,
  8723. decompressed_data_chunk_size);
  8724. return true;
  8725. });
  8726. ASSERT_TRUE(result);
  8727. }
  8728. ASSERT_EQ(original_text, decompressed_data);
  8729. }
  8730. #endif
  8731. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8732. // separate chunks so that the server sees each part in its own read(). Used to
  8733. // place a read boundary at a specific offset of a request body.
  8734. static bool send_request_in_parts(time_t read_timeout_sec,
  8735. const std::vector<std::string> &parts,
  8736. std::string *resp = nullptr,
  8737. int port = PORT) {
  8738. auto error = Error::Success;
  8739. auto client_sock = detail::create_client_socket(
  8740. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8741. /*connection_timeout_sec=*/5, 0,
  8742. /*read_timeout_sec=*/5, 0,
  8743. /*write_timeout_sec=*/5, 0, std::string(), error);
  8744. if (client_sock == INVALID_SOCKET) { return false; }
  8745. auto ret = detail::process_client_socket(
  8746. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8747. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8748. for (size_t i = 0; i < parts.size(); i++) {
  8749. const auto &part = parts[i];
  8750. if (part.size() !=
  8751. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8752. return false;
  8753. }
  8754. if (i + 1 < parts.size()) {
  8755. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8756. }
  8757. }
  8758. char buf[512];
  8759. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8760. while (line_reader.getline()) {
  8761. if (resp) { *resp += line_reader.ptr(); }
  8762. }
  8763. return true;
  8764. });
  8765. detail::close_socket(client_sock);
  8766. return ret;
  8767. }
  8768. // Sends a raw request to a server listening at HOST:PORT.
  8769. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8770. std::string *resp = nullptr, int port = PORT) {
  8771. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8772. }
  8773. #ifdef CPPHTTPLIB_SSL_ENABLED
  8774. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  8775. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8776. ASSERT_TRUE(svr.is_valid());
  8777. svr.set_read_timeout(1, 0);
  8778. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8779. auto se = detail::scope_exit([&] {
  8780. svr.stop();
  8781. t.join();
  8782. ASSERT_FALSE(svr.is_running());
  8783. });
  8784. svr.wait_until_ready();
  8785. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  8786. // keeps each wait well within the read timeout. The server gives up a
  8787. // second in, so the bytes sent after that fail.
  8788. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  8789. parts.resize(26, std::string(1, '\0'));
  8790. EXPECT_FALSE(send_request_in_parts(5, parts));
  8791. }
  8792. #endif
  8793. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8794. Server svr;
  8795. std::string header_value;
  8796. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8797. header_value = req.get_header_value("foo");
  8798. res.set_content("ok", "text/plain");
  8799. });
  8800. thread t = thread([&] { svr.listen(HOST, PORT); });
  8801. auto se = detail::scope_exit([&] {
  8802. svr.stop();
  8803. t.join();
  8804. ASSERT_FALSE(svr.is_running());
  8805. });
  8806. svr.wait_until_ready();
  8807. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8808. // like characters are not treated the same - use vertical tab and escape.
  8809. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8810. "foo: \t \v bar \x1B\t \r\n"
  8811. "Connection: close\r\n"
  8812. "\r\n";
  8813. std::string res;
  8814. ASSERT_TRUE(send_request(5, req, &res));
  8815. EXPECT_EQ(header_value, "");
  8816. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8817. }
  8818. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8819. Server svr;
  8820. std::string received;
  8821. svr.Get("/order", [&](const Request &req, Response &res) {
  8822. received = entries_to_string(req.headers);
  8823. res.set_content("ok", "text/plain");
  8824. });
  8825. auto port = svr.bind_to_any_port(HOST);
  8826. thread t = thread([&] { svr.listen_after_bind(); });
  8827. auto se = detail::scope_exit([&] {
  8828. svr.stop();
  8829. t.join();
  8830. ASSERT_FALSE(svr.is_running());
  8831. });
  8832. svr.wait_until_ready();
  8833. const std::string req = "GET /order HTTP/1.1\r\n"
  8834. "X-First: 1\r\n"
  8835. "X-Dup: a\r\n"
  8836. "X-Second: 2\r\n"
  8837. "X-Dup: b\r\n"
  8838. "Connection: close\r\n"
  8839. "\r\n";
  8840. std::string res;
  8841. ASSERT_TRUE(send_request(5, req, &res, port));
  8842. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8843. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  8844. }
  8845. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8846. Server svr;
  8847. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8848. res.set_header("Set-Cookie", "first=1");
  8849. res.set_header("X-Between", "y");
  8850. res.set_header("Set-Cookie", "second=2");
  8851. res.set_content("ok", "text/plain");
  8852. });
  8853. auto port = svr.bind_to_any_port(HOST);
  8854. thread t = thread([&] { svr.listen_after_bind(); });
  8855. auto se = detail::scope_exit([&] {
  8856. svr.stop();
  8857. t.join();
  8858. ASSERT_FALSE(svr.is_running());
  8859. });
  8860. svr.wait_until_ready();
  8861. Client cli(HOST, port);
  8862. auto res = cli.Get("/cookies");
  8863. ASSERT_TRUE(res);
  8864. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8865. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8866. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8867. }
  8868. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8869. Server svr;
  8870. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8871. auto i = new int(0);
  8872. res.set_header("Trailer", "X-Safe, X-Reflected");
  8873. res.set_chunked_content_provider(
  8874. "text/plain",
  8875. [i](size_t /*offset*/, DataSink &sink) {
  8876. if (*i == 0) {
  8877. sink.os << "body";
  8878. } else {
  8879. Headers trailer;
  8880. // A valid trailer that must survive.
  8881. trailer.emplace("X-Safe", "safe");
  8882. // Attacker-controlled value carrying CR/LF (response splitting).
  8883. trailer.emplace("X-Reflected",
  8884. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8885. // Attacker-controlled name carrying CR/LF.
  8886. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8887. sink.done_with_trailer(trailer);
  8888. }
  8889. (*i)++;
  8890. return true;
  8891. },
  8892. [i](bool /*success*/) { delete i; });
  8893. });
  8894. thread t = thread([&] { svr.listen(HOST, PORT); });
  8895. auto se = detail::scope_exit([&] {
  8896. svr.stop();
  8897. t.join();
  8898. ASSERT_FALSE(svr.is_running());
  8899. });
  8900. svr.wait_until_ready();
  8901. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8902. "Host: " + HOST +
  8903. "\r\n"
  8904. "Connection: close\r\n"
  8905. "\r\n";
  8906. std::string res;
  8907. ASSERT_TRUE(send_request(5, req, &res));
  8908. // The injected fields must not appear anywhere in the raw response.
  8909. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8910. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8911. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8912. // Invalid trailers are dropped entirely, matching set_header().
  8913. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8914. // The valid trailer still passes through.
  8915. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8916. }
  8917. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8918. Server svr;
  8919. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8920. // res.headers is a public field an application can populate directly,
  8921. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8922. // A valid header that must survive.
  8923. res.headers.emplace("X-Safe", "safe");
  8924. // Attacker-controlled value carrying CR/LF (response splitting).
  8925. res.headers.emplace("X-Reflected",
  8926. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8927. // Attacker-controlled name carrying CR/LF.
  8928. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8929. res.set_content("body", "text/plain");
  8930. });
  8931. thread t = thread([&] { svr.listen(HOST, PORT); });
  8932. auto se = detail::scope_exit([&] {
  8933. svr.stop();
  8934. t.join();
  8935. ASSERT_FALSE(svr.is_running());
  8936. });
  8937. svr.wait_until_ready();
  8938. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8939. "Host: " + HOST +
  8940. "\r\n"
  8941. "Connection: close\r\n"
  8942. "\r\n";
  8943. std::string res;
  8944. ASSERT_TRUE(send_request(5, req, &res));
  8945. // The injected fields must not appear anywhere in the raw response.
  8946. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8947. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8948. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8949. // Invalid headers are dropped entirely, matching set_header().
  8950. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8951. // The valid header still passes through.
  8952. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8953. }
  8954. // Forward declaration: in split builds split.py strips `inline` and moves the
  8955. // definition into httplib.cc, so detail::write_request_line is not visible from
  8956. // the public httplib.h. Re-declaring it here lets the tests link against the
  8957. // symbol in both header-only and split builds.
  8958. namespace httplib {
  8959. namespace detail {
  8960. ssize_t write_request_line(Stream &strm, const std::string &method,
  8961. const std::string &path);
  8962. } // namespace detail
  8963. } // namespace httplib
  8964. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  8965. // A well-formed target is written verbatim.
  8966. {
  8967. detail::BufferStream strm;
  8968. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8969. EXPECT_GT(n, 0);
  8970. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8971. }
  8972. // A target carrying CR/LF, SP or other control octets must be rejected
  8973. // before anything reaches the wire, otherwise it splits the request line and
  8974. // injects a header or a whole request.
  8975. const std::string evil_targets[] = {
  8976. "/a\r\nInjected: pwned",
  8977. "/a\rInjected",
  8978. "/a\nInjected",
  8979. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8980. "/a b",
  8981. "/a\tb",
  8982. "/a\x7f",
  8983. };
  8984. for (const auto &evil : evil_targets) {
  8985. detail::BufferStream strm;
  8986. auto n = detail::write_request_line(strm, "GET", evil);
  8987. EXPECT_LT(n, 0);
  8988. EXPECT_TRUE(strm.get_buffer().empty());
  8989. }
  8990. }
  8991. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8992. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  8993. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  8994. // target reaches write_request. The client must fail cleanly with
  8995. // Error::Write instead of putting a request-line-less, header-injecting
  8996. // request on the wire.
  8997. Server svr;
  8998. svr.Get("/a", [](const Request &, Response &res) {
  8999. res.set_content("ok", "text/plain");
  9000. });
  9001. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9002. auto se = detail::scope_exit([&] {
  9003. svr.stop();
  9004. thread.join();
  9005. ASSERT_FALSE(svr.is_running());
  9006. });
  9007. svr.wait_until_ready();
  9008. {
  9009. Client cli(HOST, PORT);
  9010. cli.set_path_encode(false);
  9011. // The request is rejected before anything is written, so the connection
  9012. // stays silent and the subsequent response read would otherwise block for
  9013. // the full default read timeout. Shorten it -- the assertion is on the
  9014. // error, not the timeout.
  9015. cli.set_read_timeout(1, 0);
  9016. auto res = cli.Get("/a\r\nInjected: pwned");
  9017. EXPECT_FALSE(res);
  9018. EXPECT_EQ(Error::Write, res.error());
  9019. }
  9020. }
  9021. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9022. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9023. // including extension methods.
  9024. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9025. for (const auto &method : good_methods) {
  9026. detail::BufferStream strm;
  9027. auto n = detail::write_request_line(strm, method, "/");
  9028. EXPECT_GT(n, 0);
  9029. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9030. }
  9031. // A method carrying CR/LF would split the request line and smuggle a whole
  9032. // request ahead of the real one. A space or an empty method corrupts the
  9033. // request line. All must be rejected before anything reaches the wire.
  9034. const std::string evil_methods[] = {
  9035. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9036. "GET\r\nInjected: pwned",
  9037. "GET\r",
  9038. "GET\n",
  9039. "GE T",
  9040. "",
  9041. };
  9042. for (const auto &evil : evil_methods) {
  9043. detail::BufferStream strm;
  9044. auto n = detail::write_request_line(strm, evil, "/");
  9045. EXPECT_LT(n, 0);
  9046. EXPECT_TRUE(strm.get_buffer().empty());
  9047. }
  9048. }
  9049. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9050. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9051. // through Client::send must fail with Error::Write and no request, neither
  9052. // the smuggled one nor the real one, may reach the server.
  9053. Server svr;
  9054. std::atomic<int> request_count(0);
  9055. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9056. request_count++;
  9057. res.status = StatusCode::OK_200;
  9058. return Server::HandlerResponse::Handled;
  9059. });
  9060. auto port = svr.bind_to_any_port(HOST);
  9061. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9062. auto se = detail::scope_exit([&] {
  9063. svr.stop();
  9064. thread.join();
  9065. ASSERT_FALSE(svr.is_running());
  9066. });
  9067. svr.wait_until_ready();
  9068. {
  9069. Client cli(HOST, port);
  9070. const std::string evil_methods[] = {
  9071. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9072. "GE T",
  9073. "",
  9074. };
  9075. for (const auto &evil : evil_methods) {
  9076. Request req;
  9077. req.method = evil;
  9078. req.path = "/";
  9079. auto res = cli.send(req);
  9080. EXPECT_FALSE(res);
  9081. EXPECT_EQ(Error::Write, res.error());
  9082. }
  9083. auto handle =
  9084. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9085. EXPECT_FALSE(handle.is_valid());
  9086. EXPECT_EQ(Error::Write, handle.error);
  9087. // A valid request on the same client still goes through.
  9088. auto res = cli.Get("/");
  9089. ASSERT_TRUE(res);
  9090. EXPECT_EQ(StatusCode::OK_200, res->status);
  9091. }
  9092. EXPECT_EQ(1, request_count.load());
  9093. }
  9094. // Sends a raw request and verifies that there isn't a crash or exception.
  9095. static void test_raw_request(const std::string &req,
  9096. std::string *out = nullptr) {
  9097. Server svr;
  9098. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9099. res.set_content("ok", "text/plain");
  9100. });
  9101. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9102. res.set_content("ok", "text/plain");
  9103. });
  9104. svr.Get("/header_field_value_check",
  9105. [&](const Request & /*req*/, Response &res) {
  9106. res.set_content("ok", "text/plain");
  9107. });
  9108. svr.CustomRoute("PROPFIND", "/dav",
  9109. [&](const Request & /*req*/, Response &res) {
  9110. res.status = StatusCode::MultiStatus_207;
  9111. });
  9112. // Server read timeout must be longer than the client read timeout for the
  9113. // bug to reproduce, probably to force the server to process a request
  9114. // without a trailing blank line.
  9115. const time_t client_read_timeout_sec = 1;
  9116. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9117. bool listen_thread_ok = false;
  9118. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9119. auto se = detail::scope_exit([&] {
  9120. svr.stop();
  9121. t.join();
  9122. ASSERT_FALSE(svr.is_running());
  9123. EXPECT_TRUE(listen_thread_ok);
  9124. });
  9125. svr.wait_until_ready();
  9126. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9127. }
  9128. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9129. // A certain header line causes an exception if the header property is parsed
  9130. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9131. test_raw_request(
  9132. "GET /hi HTTP/1.1\r\n"
  9133. " : "
  9134. " "
  9135. " ");
  9136. }
  9137. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9138. // A certain header line causes an exception if the header property *name* is
  9139. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9140. // greedy matcher and requires backtracking when there are a lot of ":"
  9141. // characters.
  9142. // This occurs with libc++ but not libstdc++.
  9143. test_raw_request(
  9144. "GET /hi HTTP/1.1\r\n"
  9145. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9146. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9147. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9148. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9149. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9150. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9151. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9152. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9153. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9154. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9155. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9156. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9157. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9158. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9159. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9160. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9161. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9162. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9163. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9164. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9165. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9166. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9167. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9168. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9169. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9170. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9171. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9172. "&&&%%%");
  9173. }
  9174. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9175. // Make sure this doesn't crash the server.
  9176. // In a previous version of the header line regex, the "\r" rendered the line
  9177. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9178. // a new position where the leading white space ended and the field value
  9179. // began.
  9180. // The crash occurs with libc++ but not libstdc++.
  9181. test_raw_request("GET /hi HTTP/1.1\r\n"
  9182. "a:" +
  9183. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9184. "\r\n"
  9185. "\r\n");
  9186. }
  9187. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9188. std::string out;
  9189. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9190. "Content-Type: text/plain\r\n"
  9191. "Transfer-Encoding: chunked\r\n"
  9192. "\r\n"
  9193. "nothex\r\n",
  9194. &out);
  9195. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9196. }
  9197. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9198. std::string out;
  9199. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9200. "Content-Type: text/plain\r\n"
  9201. "Transfer-Encoding: chunked\r\n"
  9202. "\r\n"
  9203. "3\r\n"
  9204. "xyz\r\n"
  9205. "NaN\r\n",
  9206. &out);
  9207. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9208. }
  9209. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9210. std::string out;
  9211. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9212. "Content-Type: text/plain\r\n"
  9213. "Transfer-Encoding: chunked\r\n"
  9214. "\r\n"
  9215. // Length is too large for 64 bits.
  9216. "1ffffffffffffffff\r\n"
  9217. "xyz\r\n",
  9218. &out);
  9219. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9220. }
  9221. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9222. test_raw_request("GET /hi HTTP/1.1\r\n"
  9223. "Content-Type: text/plain\r\n\r");
  9224. }
  9225. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9226. std::string out;
  9227. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9228. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9229. }
  9230. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9231. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9232. std::string out;
  9233. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9234. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9235. }
  9236. }
  9237. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9238. std::string out;
  9239. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9240. "Connection: close\r\n\r\n",
  9241. &out);
  9242. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9243. }
  9244. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9245. Server svr;
  9246. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9247. EXPECT_TRUE(!req.remote_addr.empty());
  9248. });
  9249. thread t = thread([&] { svr.listen(HOST, PORT); });
  9250. auto se = detail::scope_exit([&] {
  9251. svr.stop();
  9252. t.join();
  9253. ASSERT_FALSE(svr.is_running());
  9254. });
  9255. svr.wait_until_ready();
  9256. // Send an invalid request line to trigger Bad Request
  9257. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9258. std::string out;
  9259. ASSERT_TRUE(send_request(5, bad_req, &out));
  9260. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9261. }
  9262. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9263. // answered right away rather than blocking on a read that waits for EOF.
  9264. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9265. std::string out;
  9266. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9267. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9268. }
  9269. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9270. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9271. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9272. for (const auto *method : methods) {
  9273. Server svr;
  9274. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9275. EXPECT_FALSE(svr.is_valid()) << method;
  9276. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9277. }
  9278. }
  9279. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9280. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9281. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9282. for (const auto *method : methods) {
  9283. Server svr;
  9284. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9285. EXPECT_FALSE(svr.is_valid()) << method;
  9286. }
  9287. }
  9288. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9289. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9290. "COPY", "MOVE", "LOCK",
  9291. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9292. Server svr;
  9293. for (const auto *method : methods) {
  9294. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9295. }
  9296. EXPECT_TRUE(svr.is_valid());
  9297. }
  9298. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9299. Server svr;
  9300. svr.CustomRoute("POST", "/x",
  9301. [](const Request &, Response &, const ContentReader &) {});
  9302. EXPECT_FALSE(svr.is_valid());
  9303. }
  9304. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9305. Server svr;
  9306. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9307. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9308. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9309. EXPECT_FALSE(svr.is_valid());
  9310. }
  9311. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9312. Server svr;
  9313. auto captured = Error::Success;
  9314. svr.set_error_logger(
  9315. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9316. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9317. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9318. }
  9319. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9320. std::string out;
  9321. std::string request(
  9322. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9323. test_raw_request(request, &out);
  9324. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9325. }
  9326. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9327. std::string out;
  9328. std::string request(
  9329. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9330. test_raw_request(request, &out);
  9331. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9332. }
  9333. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9334. std::string out;
  9335. std::string request(
  9336. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9337. test_raw_request(request, &out);
  9338. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9339. }
  9340. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9341. std::string out;
  9342. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9343. "Test: \r\n\r\n",
  9344. &out);
  9345. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9346. }
  9347. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9348. Server svr;
  9349. std::string x_custom;
  9350. std::string cookie;
  9351. std::string xff;
  9352. std::string x_unicode;
  9353. std::string x_iis;
  9354. svr.Get("/check", [&](const Request &req, Response &res) {
  9355. x_custom = req.get_header_value("X-Custom");
  9356. cookie = req.get_header_value("Cookie");
  9357. xff = req.get_header_value("X-Forwarded-For");
  9358. x_unicode = req.get_header_value("X-Unicode");
  9359. x_iis = req.get_header_value("X-IIS");
  9360. res.set_content("ok", "text/plain");
  9361. });
  9362. thread t = thread([&] { svr.listen(HOST, PORT); });
  9363. auto se = detail::scope_exit([&] {
  9364. svr.stop();
  9365. t.join();
  9366. ASSERT_FALSE(svr.is_running());
  9367. });
  9368. svr.wait_until_ready();
  9369. const std::string req = "GET /check HTTP/1.1\r\n"
  9370. "Host: localhost\r\n"
  9371. "X-Custom: a%0D%0AInjected: b\r\n"
  9372. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9373. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9374. "X-Unicode: %E3%81%82\r\n"
  9375. "X-IIS: %u00E9\r\n"
  9376. "Connection: close\r\n"
  9377. "\r\n";
  9378. std::string res;
  9379. ASSERT_TRUE(send_request(5, req, &res));
  9380. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9381. // Every value must be returned verbatim (wire form), with no decoding.
  9382. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9383. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9384. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9385. EXPECT_EQ("%E3%81%82", x_unicode);
  9386. EXPECT_EQ("%u00E9", x_iis);
  9387. }
  9388. // Applications that previously relied on automatic percent-decoding can
  9389. // reproduce the old behavior by explicitly calling decode_path_component()
  9390. // or, for RFC 3986 conformance, decode_uri_component().
  9391. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9392. Server svr;
  9393. std::string decoded;
  9394. svr.Get("/check", [&](const Request &req, Response &res) {
  9395. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9396. res.set_content("ok", "text/plain");
  9397. });
  9398. thread t = thread([&] { svr.listen(HOST, PORT); });
  9399. auto se = detail::scope_exit([&] {
  9400. svr.stop();
  9401. t.join();
  9402. ASSERT_FALSE(svr.is_running());
  9403. });
  9404. svr.wait_until_ready();
  9405. const std::string req = "GET /check HTTP/1.1\r\n"
  9406. "Host: localhost\r\n"
  9407. "X-Custom: hello%20world\r\n"
  9408. "Connection: close\r\n"
  9409. "\r\n";
  9410. std::string res;
  9411. ASSERT_TRUE(send_request(5, req, &res));
  9412. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9413. EXPECT_EQ("hello world", decoded);
  9414. }
  9415. // Regression test for #2033. Browsers send Referer values that include
  9416. // percent-encoded characters such as %0A inside the URL. Decoding the
  9417. // header value would either trip the post-decode CR/LF/NUL guard (the
  9418. // original bug, returning 400) or, after that guard was relaxed, silently
  9419. // store a literal LF — both unacceptable. The wire form must round-trip.
  9420. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9421. Server svr;
  9422. std::string referer;
  9423. svr.Get("/check", [&](const Request &req, Response &res) {
  9424. referer = req.get_header_value("Referer");
  9425. res.set_content("ok", "text/plain");
  9426. });
  9427. thread t = thread([&] { svr.listen(HOST, PORT); });
  9428. auto se = detail::scope_exit([&] {
  9429. svr.stop();
  9430. t.join();
  9431. ASSERT_FALSE(svr.is_running());
  9432. });
  9433. svr.wait_until_ready();
  9434. const std::string req = "GET /check HTTP/1.1\r\n"
  9435. "Host: localhost\r\n"
  9436. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9437. "Connection: close\r\n"
  9438. "\r\n";
  9439. std::string res;
  9440. ASSERT_TRUE(send_request(5, req, &res));
  9441. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9442. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9443. }
  9444. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9445. Server svr;
  9446. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9447. res.set_header("Cache-Control", "no-cache");
  9448. res.set_chunked_content_provider(
  9449. "text/event-stream", [](size_t offset, DataSink &sink) {
  9450. std::string s = "data:";
  9451. s += std::to_string(offset);
  9452. s += "\n\n";
  9453. auto ret = sink.write(s.data(), s.size());
  9454. EXPECT_TRUE(ret);
  9455. std::this_thread::sleep_for(std::chrono::seconds(1));
  9456. return true;
  9457. });
  9458. });
  9459. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9460. svr.wait_until_ready();
  9461. Client client(HOST, PORT);
  9462. const Headers headers = {{"Accept", "text/event-stream"}};
  9463. auto get_thread = std::thread([&client, &headers]() {
  9464. auto res = client.Get(
  9465. "/events", headers,
  9466. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9467. });
  9468. auto se = detail::scope_exit([&] {
  9469. svr.stop();
  9470. get_thread.join();
  9471. listen_thread.join();
  9472. ASSERT_FALSE(svr.is_running());
  9473. });
  9474. // Give GET time to get a few messages.
  9475. std::this_thread::sleep_for(std::chrono::seconds(2));
  9476. }
  9477. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9478. httplib::Server svr;
  9479. svr.Post("/hi",
  9480. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9481. res.status = StatusCode::OK_200;
  9482. });
  9483. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9484. svr.wait_until_ready();
  9485. Client cli(HOST, PORT);
  9486. auto res = cli.Post("/hi", "data", "text/plain");
  9487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9488. EXPECT_EQ(StatusCode::OK_200, res->status);
  9489. svr.stop();
  9490. thread.join();
  9491. ASSERT_FALSE(svr.is_running());
  9492. res = cli.Post("/hi", "data", "text/plain");
  9493. ASSERT_FALSE(res);
  9494. }
  9495. TEST(ServerStopTest, ListenFailure) {
  9496. Server svr;
  9497. auto t = thread([&]() {
  9498. auto ret = svr.listen("????", PORT);
  9499. EXPECT_FALSE(ret);
  9500. });
  9501. svr.wait_until_ready();
  9502. svr.stop();
  9503. t.join();
  9504. }
  9505. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9506. TEST(ServerStopTest, Decommision) {
  9507. Server svr;
  9508. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9509. for (int i = 0; i < 4; i++) {
  9510. auto is_even = !(i % 2);
  9511. std::thread t{[&] {
  9512. try {
  9513. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9514. if (is_even) {
  9515. throw std::runtime_error("Some thing that happens to go wrong.");
  9516. }
  9517. svr.listen(HOST, PORT);
  9518. } catch (...) { svr.decommission(); }
  9519. }};
  9520. svr.wait_until_ready();
  9521. // Server is up
  9522. {
  9523. Client cli(HOST, PORT);
  9524. auto res = cli.Get("/hi");
  9525. if (is_even) {
  9526. EXPECT_FALSE(res);
  9527. } else {
  9528. EXPECT_TRUE(res);
  9529. EXPECT_EQ("hi...", res->body);
  9530. }
  9531. }
  9532. svr.stop();
  9533. t.join();
  9534. // Server is down...
  9535. {
  9536. Client cli(HOST, PORT);
  9537. auto res = cli.Get("/hi");
  9538. EXPECT_FALSE(res);
  9539. }
  9540. }
  9541. }
  9542. #endif
  9543. // Helper function for string body upload progress tests
  9544. template <typename SetupHandler, typename ClientCall>
  9545. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9546. ClientCall &&client_call,
  9547. const string &body) {
  9548. Server svr;
  9549. setup_handler(svr);
  9550. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9551. auto se = detail::scope_exit([&] {
  9552. svr.stop();
  9553. t.join();
  9554. });
  9555. svr.wait_until_ready();
  9556. Client cli(HOST, PORT);
  9557. vector<uint64_t> progress_values;
  9558. bool progress_called = false;
  9559. auto res =
  9560. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9561. progress_values.push_back(current);
  9562. progress_called = true;
  9563. return true;
  9564. });
  9565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9566. EXPECT_EQ(200, res->status);
  9567. EXPECT_TRUE(progress_called);
  9568. }
  9569. TEST(UploadProgressTest, PostStringBodyBasic) {
  9570. TestStringBodyUploadProgress(
  9571. [](Server &svr) {
  9572. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9573. res.set_content("received", "text/plain");
  9574. });
  9575. },
  9576. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9577. return cli.Post("/test", body, "text/plain", progress_callback);
  9578. },
  9579. "test data for upload progress");
  9580. }
  9581. TEST(UploadProgressTest, PutStringBodyBasic) {
  9582. TestStringBodyUploadProgress(
  9583. [](Server &svr) {
  9584. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9585. res.set_content("put received", "text/plain");
  9586. });
  9587. },
  9588. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9589. return cli.Put("/test", body, "text/plain", progress_callback);
  9590. },
  9591. "put test data for upload progress");
  9592. }
  9593. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9594. TestStringBodyUploadProgress(
  9595. [](Server &svr) {
  9596. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9597. res.set_content("patch received", "text/plain");
  9598. });
  9599. },
  9600. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9601. return cli.Patch("/test", body, "text/plain", progress_callback);
  9602. },
  9603. "patch test data for upload progress");
  9604. }
  9605. // Helper function for content provider upload progress tests
  9606. template <typename SetupHandler, typename ClientCall>
  9607. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9608. ClientCall &&client_call) {
  9609. Server svr;
  9610. setup_handler(svr);
  9611. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9612. auto se = detail::scope_exit([&] {
  9613. svr.stop();
  9614. t.join();
  9615. });
  9616. svr.wait_until_ready();
  9617. Client cli(HOST, PORT);
  9618. vector<uint64_t> progress_values;
  9619. auto res =
  9620. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9621. progress_values.push_back(current);
  9622. return true;
  9623. });
  9624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9625. EXPECT_EQ(200, res->status);
  9626. EXPECT_FALSE(progress_values.empty());
  9627. }
  9628. TEST(UploadProgressTest, PostContentProviderProgress) {
  9629. TestContentProviderUploadProgress(
  9630. [](Server &svr) {
  9631. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9632. res.set_content("provider received", "text/plain");
  9633. });
  9634. },
  9635. [](Client &cli, UploadProgress progress_callback) {
  9636. return cli.Post(
  9637. "/test", 10,
  9638. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9639. sink.os << "test data";
  9640. return true;
  9641. },
  9642. "text/plain", progress_callback);
  9643. });
  9644. }
  9645. // Helper function for multipart upload progress tests
  9646. template <typename SetupHandler, typename ClientCall>
  9647. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9648. ClientCall &&client_call,
  9649. const string &endpoint) {
  9650. Server svr;
  9651. setup_handler(svr);
  9652. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9653. auto se = detail::scope_exit([&] {
  9654. svr.stop();
  9655. t.join();
  9656. });
  9657. svr.wait_until_ready();
  9658. Client cli(HOST, PORT);
  9659. vector<uint64_t> progress_values;
  9660. UploadFormDataItems items = {
  9661. {"field1", "value1", "", ""},
  9662. {"field2", "longer value for progress tracking test", "", ""},
  9663. {"file1", "file content data for upload progress", "test.txt",
  9664. "text/plain"}};
  9665. auto res = client_call(cli, endpoint, items,
  9666. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9667. progress_values.push_back(current);
  9668. return true;
  9669. });
  9670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9671. EXPECT_EQ(200, res->status);
  9672. EXPECT_FALSE(progress_values.empty());
  9673. }
  9674. TEST(UploadProgressTest, PostMultipartProgress) {
  9675. TestMultipartUploadProgress(
  9676. [](Server &svr) {
  9677. svr.Post("/multipart", [](const Request &req, Response &res) {
  9678. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9679. res.set_content("multipart received", "text/plain");
  9680. });
  9681. },
  9682. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9683. UploadProgress progress_callback) {
  9684. return cli.Post(endpoint, items, progress_callback);
  9685. },
  9686. "/multipart");
  9687. }
  9688. // Helper function for basic download progress tests
  9689. template <typename SetupHandler, typename ClientCall>
  9690. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9691. ClientCall &&client_call, const string &endpoint,
  9692. size_t expected_content_size) {
  9693. Server svr;
  9694. setup_handler(svr);
  9695. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9696. auto se = detail::scope_exit([&] {
  9697. svr.stop();
  9698. t.join();
  9699. });
  9700. svr.wait_until_ready();
  9701. Client cli(HOST, PORT);
  9702. vector<uint64_t> progress_values;
  9703. auto res = client_call(cli, endpoint,
  9704. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9705. progress_values.push_back(current);
  9706. return true;
  9707. });
  9708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9709. EXPECT_EQ(200, res->status);
  9710. EXPECT_FALSE(progress_values.empty());
  9711. EXPECT_EQ(expected_content_size, res->body.size());
  9712. }
  9713. TEST(DownloadProgressTest, GetBasic) {
  9714. TestBasicDownloadProgress(
  9715. [](Server &svr) {
  9716. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9717. string content(1000, 'D');
  9718. res.set_content(content, "text/plain");
  9719. });
  9720. },
  9721. [](Client &cli, const string &endpoint,
  9722. DownloadProgress progress_callback) {
  9723. return cli.Get(endpoint, progress_callback);
  9724. },
  9725. "/download", 1000u);
  9726. }
  9727. // Helper function for content receiver download progress tests
  9728. template <typename SetupHandler, typename ClientCall>
  9729. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9730. ClientCall &&client_call,
  9731. const string &endpoint,
  9732. size_t expected_content_size) {
  9733. Server svr;
  9734. setup_handler(svr);
  9735. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9736. auto se = detail::scope_exit([&] {
  9737. svr.stop();
  9738. t.join();
  9739. });
  9740. svr.wait_until_ready();
  9741. Client cli(HOST, PORT);
  9742. vector<uint64_t> progress_values;
  9743. string received_body;
  9744. auto res = client_call(
  9745. cli, endpoint,
  9746. [&](const char *data, size_t data_length) -> bool {
  9747. received_body.append(data, data_length);
  9748. return true;
  9749. },
  9750. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9751. progress_values.push_back(current);
  9752. return true;
  9753. });
  9754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9755. EXPECT_EQ(200, res->status);
  9756. EXPECT_FALSE(progress_values.empty());
  9757. EXPECT_EQ(expected_content_size, received_body.size());
  9758. EXPECT_TRUE(res->body.empty());
  9759. }
  9760. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9761. TestContentReceiverDownloadProgress(
  9762. [](Server &svr) {
  9763. svr.Get("/download-receiver",
  9764. [](const Request & /*req*/, Response &res) {
  9765. string content(2000, 'R');
  9766. res.set_content(content, "text/plain");
  9767. });
  9768. },
  9769. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9770. DownloadProgress progress_callback) {
  9771. return cli.Get(endpoint, content_receiver, progress_callback);
  9772. },
  9773. "/download-receiver", 2000u);
  9774. }
  9775. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9776. // A provider reaching a pass with nothing to hand over - an empty buffer
  9777. // popped off a queue, say - must not be taken to mean the body is finished.
  9778. // It used to end the loop with the terminating chunk unwritten while the
  9779. // server still considered the response complete, so the peer waited for an
  9780. // end that never arrived.
  9781. Server svr;
  9782. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9783. auto step = std::make_shared<int>(0);
  9784. res.set_chunked_content_provider("text/plain",
  9785. [step](size_t /*offset*/, DataSink &sink) {
  9786. switch ((*step)++) {
  9787. case 0: sink.write("", 0); break;
  9788. case 1: sink.write("hello", 5); break;
  9789. default: sink.done(); break;
  9790. }
  9791. return true;
  9792. });
  9793. });
  9794. auto port = svr.bind_to_any_port(HOST);
  9795. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9796. auto listen_se = detail::scope_exit([&] {
  9797. svr.stop();
  9798. listen_thread.join();
  9799. ASSERT_FALSE(svr.is_running());
  9800. });
  9801. svr.wait_until_ready();
  9802. Client cli(HOST, port);
  9803. // Without the fix the body is never terminated, so bound the wait rather
  9804. // than letting the test hang on the default read timeout.
  9805. cli.set_read_timeout(5, 0);
  9806. auto res = cli.Get("/stream");
  9807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9808. EXPECT_EQ(StatusCode::OK_200, res->status);
  9809. EXPECT_EQ("hello", res->body);
  9810. }
  9811. TEST(StreamingTest, NoContentLengthStreaming) {
  9812. Server svr;
  9813. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9814. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9815. if (offset < 6) {
  9816. sink.os << (offset < 3 ? "a" : "b");
  9817. } else {
  9818. sink.done();
  9819. }
  9820. return true;
  9821. });
  9822. });
  9823. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9824. auto listen_se = detail::scope_exit([&] {
  9825. svr.stop();
  9826. listen_thread.join();
  9827. ASSERT_FALSE(svr.is_running());
  9828. });
  9829. svr.wait_until_ready();
  9830. Client client(HOST, PORT);
  9831. auto get_thread = std::thread([&client]() {
  9832. std::string s;
  9833. auto res =
  9834. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9835. s += std::string(data, len);
  9836. return true;
  9837. });
  9838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9839. EXPECT_EQ(StatusCode::OK_200, res->status);
  9840. EXPECT_EQ("aaabbb", s);
  9841. });
  9842. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9843. // Give GET time to get a few messages.
  9844. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9845. }
  9846. TEST(MountTest, Unmount) {
  9847. Server svr;
  9848. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9849. auto se = detail::scope_exit([&] {
  9850. svr.stop();
  9851. listen_thread.join();
  9852. ASSERT_FALSE(svr.is_running());
  9853. });
  9854. svr.wait_until_ready();
  9855. Client cli("localhost", PORT);
  9856. svr.set_mount_point("/mount2", "./www2");
  9857. auto res = cli.Get("/");
  9858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9859. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9860. res = cli.Get("/mount2/dir/test.html");
  9861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9862. EXPECT_EQ(StatusCode::OK_200, res->status);
  9863. svr.set_mount_point("/", "./www");
  9864. res = cli.Get("/dir/");
  9865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9866. EXPECT_EQ(StatusCode::OK_200, res->status);
  9867. svr.remove_mount_point("/");
  9868. res = cli.Get("/dir/");
  9869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9870. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9871. svr.remove_mount_point("/mount2");
  9872. res = cli.Get("/mount2/dir/test.html");
  9873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9874. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9875. }
  9876. TEST(MountTest, PathSegmentBoundary) {
  9877. Server svr;
  9878. svr.set_mount_point("/mount2", "./www2");
  9879. svr.set_mount_point("/", "./www");
  9880. auto port = svr.bind_to_any_port(HOST);
  9881. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9882. auto se = detail::scope_exit([&] {
  9883. svr.stop();
  9884. listen_thread.join();
  9885. ASSERT_FALSE(svr.is_running());
  9886. });
  9887. svr.wait_until_ready();
  9888. Client cli(HOST, port);
  9889. auto res = cli.Get("/mount2/dir/test.html");
  9890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9891. EXPECT_EQ(StatusCode::OK_200, res->status);
  9892. // "/mount2" must not match part-way through a path segment.
  9893. res = cli.Get("/mount2dir/test.html");
  9894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9895. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9896. // A mount point ending in '/' keeps matching every path below it.
  9897. res = cli.Get("/dir/test.html");
  9898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9899. EXPECT_EQ(StatusCode::OK_200, res->status);
  9900. }
  9901. TEST(MountTest, Redicect) {
  9902. Server svr;
  9903. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9904. auto se = detail::scope_exit([&] {
  9905. svr.stop();
  9906. listen_thread.join();
  9907. ASSERT_FALSE(svr.is_running());
  9908. });
  9909. svr.set_mount_point("/", "./www");
  9910. svr.wait_until_ready();
  9911. Client cli("localhost", PORT);
  9912. auto res = cli.Get("/dir/");
  9913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9914. EXPECT_EQ(StatusCode::OK_200, res->status);
  9915. res = cli.Get("/dir");
  9916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9917. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9918. res = cli.Get("/file");
  9919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9920. EXPECT_EQ(StatusCode::OK_200, res->status);
  9921. res = cli.Get("/file/");
  9922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9923. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9924. cli.set_follow_location(true);
  9925. res = cli.Get("/dir");
  9926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9927. EXPECT_EQ(StatusCode::OK_200, res->status);
  9928. }
  9929. TEST(MountTest, MultibytesPathName) {
  9930. Server svr;
  9931. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9932. auto se = detail::scope_exit([&] {
  9933. svr.stop();
  9934. listen_thread.join();
  9935. ASSERT_FALSE(svr.is_running());
  9936. });
  9937. svr.set_mount_point("/", "./www");
  9938. svr.wait_until_ready();
  9939. Client cli("localhost", PORT);
  9940. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  9941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9942. EXPECT_EQ(StatusCode::OK_200, res->status);
  9943. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  9944. }
  9945. #ifdef _WIN32
  9946. // Issue #2435: mmap::open() must succeed even when another handle holds
  9947. // the file open for writing (e.g. an active log file).
  9948. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  9949. const char *path = "mmap_concurrent_writer_test.txt";
  9950. const char *content = "hello";
  9951. {
  9952. std::ofstream f(path, std::ios::binary);
  9953. f.write(content, static_cast<std::streamsize>(strlen(content)));
  9954. }
  9955. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  9956. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  9957. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  9958. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  9959. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  9960. detail::mmap m(path);
  9961. ASSERT_TRUE(m.is_open());
  9962. EXPECT_EQ(strlen(content), m.size());
  9963. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  9964. }
  9965. #endif
  9966. #ifndef _WIN32
  9967. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  9968. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  9969. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  9970. TEST(MmapTest, FailedMappingIsNotOpen) {
  9971. const char *path = "./mmap_failed_mapping_test_dir";
  9972. ASSERT_EQ(0, ::mkdir(path, 0755));
  9973. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  9974. detail::mmap m(path);
  9975. EXPECT_FALSE(m.is_open());
  9976. EXPECT_EQ(0U, m.size());
  9977. EXPECT_NE(static_cast<const void *>(m.data()),
  9978. static_cast<const void *>(MAP_FAILED));
  9979. }
  9980. #endif
  9981. TEST(KeepAliveTest, ReadTimeout) {
  9982. Server svr;
  9983. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9984. std::this_thread::sleep_for(std::chrono::seconds(2));
  9985. res.set_content("a", "text/plain");
  9986. });
  9987. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9988. res.set_content("b", "text/plain");
  9989. });
  9990. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9991. auto se = detail::scope_exit([&] {
  9992. svr.stop();
  9993. listen_thread.join();
  9994. ASSERT_FALSE(svr.is_running());
  9995. });
  9996. svr.wait_until_ready();
  9997. Client cli("localhost", PORT);
  9998. cli.set_keep_alive(true);
  9999. cli.set_read_timeout(std::chrono::seconds(1));
  10000. auto resa = cli.Get("/a");
  10001. ASSERT_FALSE(resa);
  10002. EXPECT_EQ(Error::Read, resa.error());
  10003. auto resb = cli.Get("/b");
  10004. ASSERT_TRUE(resb);
  10005. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10006. EXPECT_EQ("b", resb->body);
  10007. }
  10008. TEST(KeepAliveTest, MaxCount) {
  10009. size_t keep_alive_max_count = 3;
  10010. Server svr;
  10011. svr.set_keep_alive_max_count(keep_alive_max_count);
  10012. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10013. res.set_content("Hello World!", "text/plain");
  10014. });
  10015. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10016. auto se = detail::scope_exit([&] {
  10017. svr.stop();
  10018. listen_thread.join();
  10019. ASSERT_FALSE(svr.is_running());
  10020. });
  10021. svr.wait_until_ready();
  10022. Client cli(HOST, PORT);
  10023. cli.set_keep_alive(true);
  10024. for (size_t i = 0; i < 5; i++) {
  10025. auto result = cli.Get("/hi");
  10026. ASSERT_TRUE(result);
  10027. EXPECT_EQ(StatusCode::OK_200, result->status);
  10028. if (i == keep_alive_max_count - 1) {
  10029. EXPECT_EQ("close", result->get_header_value("Connection"));
  10030. } else {
  10031. EXPECT_FALSE(result->has_header("Connection"));
  10032. }
  10033. }
  10034. }
  10035. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10036. // can pull the next one into the server's buffer. The server must serve it
  10037. // without waiting for the socket to become readable again. The keep-alive
  10038. // timeout outlasts the client's read timeout, so a request left waiting for it
  10039. // shows up as a missing response.
  10040. static void serve_pipelining_routes(Server &svr,
  10041. const std::function<void(int)> &client) {
  10042. svr.set_keep_alive_timeout(5);
  10043. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10044. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10045. });
  10046. svr.Post("/echo", [](const Request &req, Response &res) {
  10047. res.set_content("echo " + req.body, "text/plain");
  10048. });
  10049. auto port = svr.bind_to_any_port(HOST);
  10050. thread t = thread([&] { svr.listen_after_bind(); });
  10051. auto se = detail::scope_exit([&] {
  10052. svr.stop();
  10053. t.join();
  10054. });
  10055. svr.wait_until_ready();
  10056. client(port);
  10057. }
  10058. static std::string
  10059. send_pipelined_requests(const std::vector<std::string> &parts) {
  10060. Server svr;
  10061. std::string res;
  10062. serve_pipelining_routes(svr, [&](int port) {
  10063. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10064. });
  10065. return res;
  10066. }
  10067. static void expect_in_order(const std::string &res,
  10068. const std::vector<std::string> &bodies) {
  10069. size_t pos = 0;
  10070. for (const auto &body : bodies) {
  10071. pos = res.find(body, pos);
  10072. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10073. pos += body.size();
  10074. }
  10075. }
  10076. TEST(KeepAliveTest, PipelinedRequests) {
  10077. auto res = send_pipelined_requests(
  10078. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10079. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10080. "Content-Length: 4\r\n\r\nbody"
  10081. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10082. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10083. }
  10084. // The second request starts in the server's buffer and ends on the socket.
  10085. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10086. auto res =
  10087. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10088. "GET /hi/2 HTTP/1.1\r\nHo",
  10089. "st: localhost\r\nConnection: close\r\n\r\n"});
  10090. expect_in_order(res, {"hi 1", "hi 2"});
  10091. }
  10092. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10093. // CRLF after a body does not turn into a 400 for the next request.
  10094. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10095. auto res = send_pipelined_requests(
  10096. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10097. "Content-Length: 4\r\n\r\nbody\r\n"
  10098. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10099. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10100. expect_in_order(res, {"echo body", "hi 2"});
  10101. }
  10102. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10103. // must not be served as the next request.
  10104. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10105. auto res = send_pipelined_requests(
  10106. {"INVALID REQUEST LINE\r\n\r\n"
  10107. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10108. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10109. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10110. }
  10111. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10112. // Over TLS, the next request is held by the TLS library as already decrypted
  10113. // data rather than on the socket.
  10114. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10115. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10116. std::string res;
  10117. serve_pipelining_routes(svr, [&](int port) {
  10118. auto error = Error::Success;
  10119. auto sock = detail::create_client_socket(
  10120. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  10121. /*connection_timeout_sec=*/5, 0,
  10122. /*read_timeout_sec=*/2, 0,
  10123. /*write_timeout_sec=*/5, 0, std::string(), error);
  10124. ASSERT_NE(INVALID_SOCKET, sock);
  10125. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  10126. auto ctx = SSL_CTX_new(TLS_client_method());
  10127. auto ssl = SSL_new(ctx);
  10128. auto ssl_se = detail::scope_exit([&] {
  10129. SSL_free(ssl);
  10130. SSL_CTX_free(ctx);
  10131. });
  10132. SSL_set_fd(ssl, static_cast<int>(sock));
  10133. ASSERT_EQ(1, SSL_connect(ssl));
  10134. // One write, so all three requests arrive in one TLS record
  10135. const std::string req =
  10136. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10137. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10138. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
  10139. ASSERT_EQ(static_cast<int>(req.size()),
  10140. SSL_write(ssl, req.data(), static_cast<int>(req.size())));
  10141. char buf[512];
  10142. int n;
  10143. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  10144. res.append(buf, static_cast<size_t>(n));
  10145. }
  10146. });
  10147. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10148. }
  10149. #endif
  10150. TEST(KeepAliveTest, Issue1041) {
  10151. Server svr;
  10152. svr.set_keep_alive_timeout(3);
  10153. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10154. res.set_content("Hello World!", "text/plain");
  10155. });
  10156. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10157. auto se = detail::scope_exit([&] {
  10158. svr.stop();
  10159. listen_thread.join();
  10160. ASSERT_FALSE(svr.is_running());
  10161. });
  10162. svr.wait_until_ready();
  10163. Client cli(HOST, PORT);
  10164. cli.set_keep_alive(true);
  10165. auto result = cli.Get("/hi");
  10166. ASSERT_TRUE(result);
  10167. EXPECT_EQ(StatusCode::OK_200, result->status);
  10168. std::this_thread::sleep_for(std::chrono::seconds(5));
  10169. result = cli.Get("/hi");
  10170. ASSERT_TRUE(result);
  10171. EXPECT_EQ(StatusCode::OK_200, result->status);
  10172. }
  10173. TEST(KeepAliveTest, Issue1959) {
  10174. Server svr;
  10175. svr.set_keep_alive_timeout(5);
  10176. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10177. res.set_content("a", "text/plain");
  10178. });
  10179. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10180. auto se = detail::scope_exit([&] {
  10181. if (!svr.is_running()) return;
  10182. svr.stop();
  10183. listen_thread.join();
  10184. ASSERT_FALSE(svr.is_running());
  10185. });
  10186. svr.wait_until_ready();
  10187. Client cli("localhost", PORT);
  10188. cli.set_keep_alive(true);
  10189. using namespace std::chrono;
  10190. auto start = steady_clock::now();
  10191. cli.Get("/a");
  10192. svr.stop();
  10193. listen_thread.join();
  10194. auto end = steady_clock::now();
  10195. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10196. EXPECT_LT(elapsed, 5000);
  10197. }
  10198. #ifdef CPPHTTPLIB_SSL_ENABLED
  10199. TEST(KeepAliveTest, SSLClientReconnection) {
  10200. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10201. ASSERT_TRUE(svr.is_valid());
  10202. svr.set_keep_alive_timeout(1);
  10203. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10204. res.set_content("Hello World!", "text/plain");
  10205. });
  10206. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10207. auto se = detail::scope_exit([&] {
  10208. svr.stop();
  10209. listen_thread.join();
  10210. ASSERT_FALSE(svr.is_running());
  10211. });
  10212. svr.wait_until_ready();
  10213. SSLClient cli(HOST, PORT);
  10214. cli.enable_server_certificate_verification(false);
  10215. cli.set_keep_alive(true);
  10216. auto result = cli.Get("/hi");
  10217. ASSERT_TRUE(result);
  10218. EXPECT_EQ(StatusCode::OK_200, result->status);
  10219. result = cli.Get("/hi");
  10220. ASSERT_TRUE(result);
  10221. EXPECT_EQ(StatusCode::OK_200, result->status);
  10222. std::this_thread::sleep_for(std::chrono::seconds(2));
  10223. // Recoonect
  10224. result = cli.Get("/hi");
  10225. ASSERT_TRUE(result);
  10226. EXPECT_EQ(StatusCode::OK_200, result->status);
  10227. result = cli.Get("/hi");
  10228. ASSERT_TRUE(result);
  10229. EXPECT_EQ(StatusCode::OK_200, result->status);
  10230. }
  10231. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10232. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10233. ASSERT_TRUE(svr.is_valid());
  10234. svr.set_keep_alive_timeout(1);
  10235. std::string content = "reconnect";
  10236. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10237. res.set_content("Hello World!", "text/plain");
  10238. });
  10239. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10240. auto se = detail::scope_exit([&] {
  10241. svr.stop();
  10242. listen_thread.join();
  10243. ASSERT_FALSE(svr.is_running());
  10244. });
  10245. svr.wait_until_ready();
  10246. SSLClient cli(HOST, PORT);
  10247. cli.enable_server_certificate_verification(false);
  10248. cli.set_keep_alive(true);
  10249. auto result = cli.Post(
  10250. "/hi", content.size(),
  10251. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10252. sink.write(content.c_str(), content.size());
  10253. return true;
  10254. },
  10255. "text/plain");
  10256. ASSERT_TRUE(result);
  10257. EXPECT_EQ(200, result->status);
  10258. std::this_thread::sleep_for(std::chrono::seconds(2));
  10259. // Recoonect
  10260. result = cli.Post(
  10261. "/hi", content.size(),
  10262. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10263. sink.write(content.c_str(), content.size());
  10264. return true;
  10265. },
  10266. "text/plain");
  10267. ASSERT_TRUE(result);
  10268. EXPECT_EQ(200, result->status);
  10269. result = cli.Post(
  10270. "/hi", content.size(),
  10271. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10272. sink.write(content.c_str(), content.size());
  10273. return true;
  10274. },
  10275. "text/plain");
  10276. ASSERT_TRUE(result);
  10277. EXPECT_EQ(200, result->status);
  10278. }
  10279. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10280. using namespace httplib::tls;
  10281. {
  10282. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10283. ASSERT_TRUE(svr.is_valid());
  10284. svr.Get("/sni", [&](const Request &req, Response &res) {
  10285. std::string expected = req.sni();
  10286. EXPECT_EQ(expected, req.get_param_value("expected"));
  10287. res.set_content("ok", "text/plain");
  10288. });
  10289. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10290. auto se = detail::scope_exit([&] {
  10291. svr.stop();
  10292. listen_thread.join();
  10293. ASSERT_FALSE(svr.is_running());
  10294. });
  10295. svr.wait_until_ready();
  10296. {
  10297. SSLClient cli("localhost", PORT);
  10298. cli.enable_server_certificate_verification(false);
  10299. auto res = cli.Get("/sni?expected=localhost");
  10300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10301. }
  10302. {
  10303. SSLClient cli("::1", PORT);
  10304. cli.enable_server_certificate_verification(false);
  10305. auto res = cli.Get("/sni?expected=");
  10306. // NOTE: This may fail if the server is listening on IPv4 only
  10307. // (e.g., when localhost resolves to 127.0.0.1 only)
  10308. if (res) {
  10309. EXPECT_EQ(StatusCode::OK_200, res->status);
  10310. } else {
  10311. EXPECT_EQ(Error::Connection, res.error());
  10312. }
  10313. }
  10314. }
  10315. }
  10316. #endif
  10317. TEST(ClientProblemDetectionTest, ContentProvider) {
  10318. Server svr;
  10319. size_t content_length = 1024 * 1024;
  10320. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10321. res.set_content_provider(
  10322. content_length, "text/plain",
  10323. [&](size_t offset, size_t length, DataSink &sink) {
  10324. auto out_len = std::min(length, static_cast<size_t>(1024));
  10325. std::string out(out_len, '@');
  10326. sink.write(out.data(), out_len);
  10327. return offset < 4096;
  10328. },
  10329. [](bool success) { ASSERT_FALSE(success); });
  10330. });
  10331. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10332. res.set_content_provider(
  10333. 0, "text/plain",
  10334. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10335. EXPECT_TRUE(false);
  10336. return true;
  10337. },
  10338. [](bool success) { ASSERT_FALSE(success); });
  10339. });
  10340. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10341. auto se = detail::scope_exit([&] {
  10342. svr.stop();
  10343. listen_thread.join();
  10344. ASSERT_FALSE(svr.is_running());
  10345. });
  10346. svr.wait_until_ready();
  10347. Client cli("localhost", PORT);
  10348. {
  10349. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10350. size_t /*data_length*/) { return false; });
  10351. ASSERT_FALSE(res);
  10352. }
  10353. {
  10354. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10355. size_t /*data_length*/) { return false; });
  10356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10357. }
  10358. }
  10359. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10360. // A provider that reports success without writing anything and without
  10361. // calling done() used to be handed the same offset and length again on every
  10362. // pass, so it spun for as long as the peer stayed connected.
  10363. Server svr;
  10364. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10365. res.set_content("ok", "text/plain");
  10366. });
  10367. auto port = svr.bind_to_any_port(HOST);
  10368. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10369. auto se = detail::scope_exit([&] {
  10370. svr.stop();
  10371. listen_thread.join();
  10372. ASSERT_FALSE(svr.is_running());
  10373. });
  10374. svr.wait_until_ready();
  10375. std::atomic<int> call_count{0};
  10376. Client cli(HOST, port);
  10377. auto res = cli.Post(
  10378. "/", 1024,
  10379. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10380. // Give up after enough passes to show the spin, so that losing the
  10381. // check below fails this test instead of hanging it.
  10382. return ++call_count < 100;
  10383. },
  10384. "text/plain");
  10385. ASSERT_FALSE(res);
  10386. EXPECT_EQ(Error::Write, res.error());
  10387. EXPECT_EQ(1, call_count.load());
  10388. }
  10389. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10390. // A writer only has to assign `write`. The other three used to be left as
  10391. // empty std::functions, so a provider calling one threw
  10392. // std::bad_function_call out of the thread running it and took the whole
  10393. // process down.
  10394. DataSink sink;
  10395. std::string written;
  10396. sink.write = [&](const char *data, size_t data_len) {
  10397. written.append(data, data_len);
  10398. return true;
  10399. };
  10400. EXPECT_TRUE(sink.is_writable());
  10401. sink.done();
  10402. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10403. EXPECT_TRUE(written.empty());
  10404. }
  10405. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10406. // A sink that cannot carry trailers still has to finish.
  10407. DataSink sink;
  10408. auto done_count = 0;
  10409. sink.done = [&]() { done_count++; };
  10410. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10411. EXPECT_EQ(1, done_count);
  10412. }
  10413. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10414. Server svr;
  10415. const std::string body(4096, 'x');
  10416. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10417. res.set_content_provider(body.size(), "text/plain",
  10418. [&](size_t offset, size_t length, DataSink &sink) {
  10419. sink.write(body.data() + offset, length);
  10420. sink.done();
  10421. return true;
  10422. });
  10423. });
  10424. auto port = svr.bind_to_any_port(HOST);
  10425. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10426. auto se = detail::scope_exit([&] {
  10427. svr.stop();
  10428. listen_thread.join();
  10429. ASSERT_FALSE(svr.is_running());
  10430. });
  10431. svr.wait_until_ready();
  10432. Client cli(HOST, port);
  10433. auto res = cli.Get("/");
  10434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10435. EXPECT_EQ(StatusCode::OK_200, res->status);
  10436. EXPECT_EQ(body, res->body);
  10437. }
  10438. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10439. Server svr;
  10440. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10441. res.set_content_provider(
  10442. 1024, "text/plain",
  10443. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10444. sink.write("hello", 5);
  10445. sink.done(); // short of the 1024 bytes the response promised
  10446. return true;
  10447. });
  10448. });
  10449. auto port = svr.bind_to_any_port(HOST);
  10450. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10451. auto se = detail::scope_exit([&] {
  10452. svr.stop();
  10453. listen_thread.join();
  10454. ASSERT_FALSE(svr.is_running());
  10455. });
  10456. svr.wait_until_ready();
  10457. Client cli(HOST, port);
  10458. cli.set_read_timeout(5, 0);
  10459. // The response is short of its Content-Length, so the client cannot read a
  10460. // complete body. What matters is that this returns at all: a no-op done()
  10461. // would leave the writer looping over a provider that never makes progress.
  10462. auto res = cli.Get("/");
  10463. EXPECT_FALSE(res);
  10464. }
  10465. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10466. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10467. // The compressed path builds the whole body before connecting, so this
  10468. // fails client-side and never reaches a server.
  10469. Client cli(HOST, PORT);
  10470. cli.set_compress(true);
  10471. auto res = cli.Post(
  10472. "/", 1024,
  10473. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10474. sink.write("hello", 5);
  10475. sink.done(); // short of the 1024 bytes the request announced
  10476. return true;
  10477. },
  10478. "text/plain");
  10479. ASSERT_FALSE(res);
  10480. EXPECT_EQ(Error::Write, res.error());
  10481. }
  10482. #endif
  10483. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  10484. Server svr;
  10485. svr.set_error_handler([](Request const &, Response &res) -> void {
  10486. res.set_chunked_content_provider(
  10487. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10488. sink.os << "hello";
  10489. sink.os << "world";
  10490. sink.done();
  10491. return true;
  10492. });
  10493. });
  10494. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10495. auto se = detail::scope_exit([&] {
  10496. svr.stop();
  10497. listen_thread.join();
  10498. ASSERT_FALSE(svr.is_running());
  10499. });
  10500. svr.wait_until_ready();
  10501. Client cli("localhost", PORT);
  10502. auto res = cli.Get("/");
  10503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10504. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10505. EXPECT_EQ("helloworld", res->body);
  10506. }
  10507. // A body set after a content provider must replace it, not be sent through it.
  10508. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  10509. Server svr;
  10510. svr.set_mount_point("/", "./www");
  10511. svr.set_file_request_handler([](const Request &req, Response &res) {
  10512. if (req.path == "/dir/test.html") {
  10513. res.status = StatusCode::Forbidden_403;
  10514. res.set_content(std::string(5000, 'D'), "text/plain");
  10515. } else if (req.path == "/file") {
  10516. res.status = StatusCode::Forbidden_403;
  10517. res.body = "Denied";
  10518. }
  10519. });
  10520. auto port = svr.bind_to_any_port(HOST);
  10521. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10522. auto se = detail::scope_exit([&] {
  10523. svr.stop();
  10524. t.join();
  10525. ASSERT_FALSE(svr.is_running());
  10526. });
  10527. svr.wait_until_ready();
  10528. Client cli(HOST, port);
  10529. {
  10530. auto res = cli.Get("/dir/test.html");
  10531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10532. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10533. EXPECT_EQ(std::string(5000, 'D'), res->body);
  10534. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  10535. }
  10536. {
  10537. auto res = cli.Get("/file");
  10538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10539. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10540. EXPECT_EQ("Denied", res->body);
  10541. }
  10542. {
  10543. auto res = cli.Get("/dir/index.html");
  10544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10545. EXPECT_EQ(StatusCode::OK_200, res->status);
  10546. EXPECT_EQ(0U, res->body.find("<html>"));
  10547. }
  10548. }
  10549. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  10550. Server svr;
  10551. std::vector<bool> released;
  10552. std::mutex released_mutex;
  10553. auto releaser = [&](bool success) {
  10554. std::lock_guard<std::mutex> guard(released_mutex);
  10555. released.push_back(success);
  10556. };
  10557. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  10558. return sink.write(&"hello"[offset], length);
  10559. };
  10560. svr.Get("/sized", [&](const Request &, Response &res) {
  10561. res.status = StatusCode::NotFound_404;
  10562. res.set_content_provider(5, "text/plain", provider, releaser);
  10563. });
  10564. svr.Get("/chunked", [&](const Request &, Response &res) {
  10565. res.status = StatusCode::ServiceUnavailable_503;
  10566. res.set_chunked_content_provider(
  10567. "text/plain",
  10568. [](size_t, DataSink &sink) {
  10569. sink.os << "chunk";
  10570. sink.done();
  10571. return true;
  10572. },
  10573. releaser);
  10574. });
  10575. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  10576. res.set_content_provider(5, "text/plain", provider, releaser);
  10577. throw std::runtime_error("after the provider");
  10578. });
  10579. svr.set_error_handler([](const Request &req, Response &res) {
  10580. // Leave the exception handler's content to it.
  10581. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  10582. res.set_content(std::string(1000, 'E'), "text/html");
  10583. return Server::HandlerResponse::Handled;
  10584. });
  10585. svr.set_exception_handler(
  10586. [](const Request &, Response &res, std::exception_ptr) {
  10587. res.status = StatusCode::InternalServerError_500;
  10588. res.set_content(std::string(1000, 'X'), "text/html");
  10589. });
  10590. auto port = svr.bind_to_any_port(HOST);
  10591. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10592. auto se = detail::scope_exit([&] {
  10593. svr.stop();
  10594. t.join();
  10595. ASSERT_FALSE(svr.is_running());
  10596. });
  10597. svr.wait_until_ready();
  10598. Client cli(HOST, port);
  10599. {
  10600. auto res = cli.Get("/sized");
  10601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10602. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10603. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10604. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  10605. }
  10606. {
  10607. auto res = cli.Get("/chunked");
  10608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10609. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  10610. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10611. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  10612. }
  10613. {
  10614. auto res = cli.Get("/throw");
  10615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10616. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  10617. EXPECT_EQ(std::string(1000, 'X'), res->body);
  10618. }
  10619. std::lock_guard<std::mutex> guard(released_mutex);
  10620. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  10621. }
  10622. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  10623. Server svr;
  10624. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  10625. return sink.write(&"abc"[offset], length);
  10626. };
  10627. svr.Get("/file-then-body", [](const Request &, Response &res) {
  10628. res.set_file_content("./www/dir/test.html");
  10629. res.set_content("body", "text/plain");
  10630. });
  10631. svr.Get("/body-then-file", [](const Request &, Response &res) {
  10632. res.set_content(std::string(100, 'B'), "text/plain");
  10633. res.set_file_content("./www/dir/test.html");
  10634. });
  10635. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  10636. res.set_content(std::string(100, 'B'), "text/plain");
  10637. res.set_content_provider(3, "text/plain", abc);
  10638. });
  10639. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  10640. res.set_content_provider(3, "text/plain", abc);
  10641. res.set_content(std::string(100, 'B'), "text/plain");
  10642. });
  10643. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  10644. res.set_content_provider(3, "text/plain", abc);
  10645. res.body = "direct";
  10646. });
  10647. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  10648. res.set_file_content("./www/dir/test.html");
  10649. res.body = "direct";
  10650. });
  10651. auto port = svr.bind_to_any_port(HOST);
  10652. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10653. auto se = detail::scope_exit([&] {
  10654. svr.stop();
  10655. t.join();
  10656. ASSERT_FALSE(svr.is_running());
  10657. });
  10658. svr.wait_until_ready();
  10659. Client cli(HOST, port);
  10660. auto expect_body = [&](const char *path, const std::string &body) {
  10661. // Uncompressed, so Content-Length can be compared with the body.
  10662. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  10663. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  10664. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10665. EXPECT_EQ(body, res->body) << path;
  10666. EXPECT_EQ(std::to_string(body.size()),
  10667. res->get_header_value("Content-Length"))
  10668. << path;
  10669. };
  10670. expect_body("/file-then-body", "body");
  10671. expect_body("/body-then-file", "test.html");
  10672. expect_body("/body-then-provider", "abc");
  10673. expect_body("/provider-then-body", std::string(100, 'B'));
  10674. expect_body("/provider-then-direct-body", "direct");
  10675. expect_body("/file-then-direct-body", "direct");
  10676. // Ranges are checked against the body, not the dropped provider.
  10677. {
  10678. auto res = cli.Get("/provider-then-direct-body",
  10679. Headers{{make_range_header({{1, 2}})}});
  10680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10681. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10682. EXPECT_EQ("ir", res->body);
  10683. }
  10684. {
  10685. auto res = cli.Get("/file-then-direct-body",
  10686. Headers{{make_range_header({{7, 8}})}});
  10687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10688. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  10689. }
  10690. }
  10691. // Forward declaration (see the base64_encode note).
  10692. namespace httplib {
  10693. namespace detail {
  10694. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  10695. const std::string &content_type,
  10696. EncodingType encoding);
  10697. } // namespace detail
  10698. } // namespace httplib
  10699. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  10700. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  10701. ASSERT_TRUE(mm->is_open());
  10702. Response res;
  10703. detail::set_file_content_provider(res, mm, "text/html",
  10704. detail::EncodingType::None);
  10705. std::string out;
  10706. DataSink sink;
  10707. sink.write = [&](const char *d, size_t l) {
  10708. out.append(d, l);
  10709. return true;
  10710. };
  10711. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  10712. EXPECT_EQ("test.html", out);
  10713. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  10714. EXPECT_EQ("test.html", out);
  10715. }
  10716. TEST(LongPollingTest, ClientCloseDetection) {
  10717. Server svr;
  10718. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10719. res.set_chunked_content_provider(
  10720. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10721. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10722. sink.os << "hello";
  10723. auto count = 10;
  10724. while (count > 0 && sink.is_writable()) {
  10725. this_thread::sleep_for(chrono::milliseconds(10));
  10726. count--;
  10727. }
  10728. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  10729. return true;
  10730. });
  10731. });
  10732. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10733. auto se = detail::scope_exit([&] {
  10734. svr.stop();
  10735. listen_thread.join();
  10736. ASSERT_FALSE(svr.is_running());
  10737. });
  10738. svr.wait_until_ready();
  10739. Client cli("localhost", PORT);
  10740. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10741. EXPECT_EQ("hello", string(data, data_length));
  10742. return false; // close the socket immediately.
  10743. });
  10744. ASSERT_FALSE(res);
  10745. }
  10746. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  10747. Server svr;
  10748. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10749. res.set_chunked_content_provider(
  10750. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10751. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10752. sink.os << "hello";
  10753. EXPECT_TRUE(sink.os.good());
  10754. // Wait for the client to close the connection
  10755. auto count = 10;
  10756. while (count > 0 && sink.is_writable()) {
  10757. this_thread::sleep_for(chrono::milliseconds(10));
  10758. count--;
  10759. }
  10760. // After client disconnect, write repeatedly until the socket
  10761. // write actually fails (small writes may be absorbed by the
  10762. // kernel buffer)
  10763. std::string chunk(1024, 'x');
  10764. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  10765. sink.os << chunk;
  10766. }
  10767. EXPECT_TRUE(sink.os.fail());
  10768. return true;
  10769. });
  10770. });
  10771. auto port = svr.bind_to_any_port("localhost");
  10772. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10773. auto se = detail::scope_exit([&] {
  10774. svr.stop();
  10775. listen_thread.join();
  10776. ASSERT_FALSE(svr.is_running());
  10777. });
  10778. svr.wait_until_ready();
  10779. Client cli("localhost", port);
  10780. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10781. EXPECT_EQ("hello", string(data, data_length));
  10782. return false; // close the socket immediately.
  10783. });
  10784. ASSERT_FALSE(res);
  10785. }
  10786. TEST(GetWithParametersTest, GetWithParameters) {
  10787. Server svr;
  10788. svr.Get("/", [&](const Request &req, Response &) {
  10789. EXPECT_EQ("world", req.get_param_value("hello"));
  10790. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10791. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10792. });
  10793. svr.Get("/params", [&](const Request &req, Response &) {
  10794. EXPECT_EQ("world", req.get_param_value("hello"));
  10795. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10796. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10797. });
  10798. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10799. EXPECT_EQ("resource-id", req.matches[1]);
  10800. EXPECT_EQ("foo", req.get_param_value("param1"));
  10801. EXPECT_EQ("bar", req.get_param_value("param2"));
  10802. });
  10803. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10804. EXPECT_EQ("user-id", req.path_params.at("id"));
  10805. EXPECT_EQ("foo", req.get_param_value("param1"));
  10806. EXPECT_EQ("bar", req.get_param_value("param2"));
  10807. });
  10808. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10809. auto se = detail::scope_exit([&] {
  10810. svr.stop();
  10811. listen_thread.join();
  10812. ASSERT_FALSE(svr.is_running());
  10813. });
  10814. svr.wait_until_ready();
  10815. {
  10816. Client cli(HOST, PORT);
  10817. Params params;
  10818. params.emplace("hello", "world");
  10819. params.emplace("hello2", "world2");
  10820. params.emplace("hello3", "world3");
  10821. auto res = cli.Get("/", params, Headers{});
  10822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10823. EXPECT_EQ(StatusCode::OK_200, res->status);
  10824. }
  10825. {
  10826. Client cli(HOST, PORT);
  10827. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10829. EXPECT_EQ(StatusCode::OK_200, res->status);
  10830. }
  10831. {
  10832. Client cli(HOST, PORT);
  10833. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  10834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10835. EXPECT_EQ(StatusCode::OK_200, res->status);
  10836. }
  10837. {
  10838. Client cli(HOST, PORT);
  10839. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  10840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10841. EXPECT_EQ(StatusCode::OK_200, res->status);
  10842. }
  10843. }
  10844. TEST(GetWithParametersTest, GetWithParameters2) {
  10845. Server svr;
  10846. svr.Get("/", [&](const Request &req, Response &res) {
  10847. auto text = req.get_param_value("hello");
  10848. res.set_content(text, "text/plain");
  10849. });
  10850. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10851. auto se = detail::scope_exit([&] {
  10852. svr.stop();
  10853. listen_thread.join();
  10854. ASSERT_FALSE(svr.is_running());
  10855. });
  10856. svr.wait_until_ready();
  10857. Client cli("localhost", PORT);
  10858. Params params;
  10859. params.emplace("hello", "world");
  10860. std::string body;
  10861. auto res = cli.Get("/", params, Headers{},
  10862. [&](const char *data, size_t data_length) {
  10863. body.append(data, data_length);
  10864. return true;
  10865. });
  10866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10867. EXPECT_EQ(StatusCode::OK_200, res->status);
  10868. EXPECT_EQ("world", body);
  10869. }
  10870. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  10871. Server svr;
  10872. svr.Get("/search", [&](const Request &req, Response &res) {
  10873. auto q = req.get_param_value("q");
  10874. res.set_content(q, "text/plain");
  10875. });
  10876. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10877. auto se = detail::scope_exit([&] {
  10878. svr.stop();
  10879. listen_thread.join();
  10880. ASSERT_FALSE(svr.is_running());
  10881. });
  10882. svr.wait_until_ready();
  10883. Client cli("localhost", PORT);
  10884. // Verify that Get(path, params) works without requiring Headers argument
  10885. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  10886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10887. EXPECT_EQ(StatusCode::OK_200, res->status);
  10888. EXPECT_EQ("cpp-httplib", res->body);
  10889. }
  10890. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  10891. auto host = "httpbingo.org";
  10892. auto path = std::string{"/range/32"};
  10893. #ifdef CPPHTTPLIB_SSL_ENABLED
  10894. SSLClient cli(host);
  10895. #else
  10896. Client cli(host);
  10897. #endif
  10898. cli.set_default_headers({make_range_header({{1, 10}})});
  10899. cli.set_connection_timeout(5);
  10900. {
  10901. auto res = cli.Get(path);
  10902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10903. EXPECT_EQ("bcdefghijk", res->body);
  10904. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10905. }
  10906. {
  10907. auto res = cli.Get(path);
  10908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10909. EXPECT_EQ("bcdefghijk", res->body);
  10910. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10911. }
  10912. }
  10913. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  10914. Server svr;
  10915. svr.set_default_headers({{"Hello", "World"}});
  10916. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10917. res.set_content("ok", "text/plain");
  10918. });
  10919. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10920. auto se = detail::scope_exit([&] {
  10921. svr.stop();
  10922. listen_thread.join();
  10923. ASSERT_FALSE(svr.is_running());
  10924. });
  10925. svr.wait_until_ready();
  10926. Client cli("localhost", PORT);
  10927. auto res = cli.Get("/");
  10928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10929. EXPECT_EQ(StatusCode::OK_200, res->status);
  10930. EXPECT_EQ("ok", res->body);
  10931. EXPECT_EQ("World", res->get_header_value("Hello"));
  10932. }
  10933. #ifdef CPPHTTPLIB_SSL_ENABLED
  10934. TEST(KeepAliveTest, ReadTimeoutSSL) {
  10935. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10936. ASSERT_TRUE(svr.is_valid());
  10937. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10938. std::this_thread::sleep_for(std::chrono::seconds(2));
  10939. res.set_content("a", "text/plain");
  10940. });
  10941. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10942. res.set_content("b", "text/plain");
  10943. });
  10944. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10945. auto se = detail::scope_exit([&] {
  10946. svr.stop();
  10947. listen_thread.join();
  10948. ASSERT_FALSE(svr.is_running());
  10949. });
  10950. svr.wait_until_ready();
  10951. SSLClient cli("localhost", PORT);
  10952. cli.enable_server_certificate_verification(false);
  10953. cli.set_keep_alive(true);
  10954. cli.set_read_timeout(std::chrono::seconds(1));
  10955. auto resa = cli.Get("/a");
  10956. ASSERT_TRUE(!resa);
  10957. EXPECT_EQ(Error::Read, resa.error());
  10958. auto resb = cli.Get("/b");
  10959. ASSERT_TRUE(resb);
  10960. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10961. EXPECT_EQ("b", resb->body);
  10962. }
  10963. // Closing an idle keep-alive connection sends close_notify and returns. The
  10964. // server must not wait for the client's close_notify: an idle client never
  10965. // sends one, so the worker would be held until the read timeout expires, and
  10966. // stop() would wait for it.
  10967. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  10968. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10969. ASSERT_TRUE(svr.is_valid());
  10970. svr.set_keep_alive_timeout(1);
  10971. svr.set_read_timeout(10, 0);
  10972. svr.Get("/", [](const Request &, Response &res) {
  10973. res.set_content("ok", "text/plain");
  10974. });
  10975. auto port = svr.bind_to_any_port(HOST);
  10976. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10977. auto se = detail::scope_exit([&] {
  10978. if (listen_thread.joinable()) {
  10979. svr.stop();
  10980. listen_thread.join();
  10981. }
  10982. });
  10983. svr.wait_until_ready();
  10984. SSLClient cli(HOST, port);
  10985. cli.enable_server_certificate_verification(false);
  10986. cli.set_keep_alive(true);
  10987. auto res = cli.Get("/");
  10988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10989. EXPECT_EQ(StatusCode::OK_200, res->status);
  10990. // Stay idle past the keep-alive timeout so the server closes the connection.
  10991. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  10992. auto start = std::chrono::steady_clock::now();
  10993. svr.stop();
  10994. listen_thread.join();
  10995. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10996. std::chrono::steady_clock::now() - start)
  10997. .count();
  10998. EXPECT_LT(elapsed, 3000);
  10999. }
  11000. #endif
  11001. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11002. protected:
  11003. ServerTestWithAI_PASSIVE()
  11004. : cli_(HOST, PORT)
  11005. #ifdef CPPHTTPLIB_SSL_ENABLED
  11006. ,
  11007. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11008. #endif
  11009. {
  11010. #ifdef CPPHTTPLIB_SSL_ENABLED
  11011. cli_.enable_server_certificate_verification(false);
  11012. #endif
  11013. }
  11014. virtual void SetUp() {
  11015. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11016. res.set_content("Hello World!", "text/plain");
  11017. });
  11018. t_ = thread(
  11019. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11020. svr_.wait_until_ready();
  11021. }
  11022. virtual void TearDown() {
  11023. svr_.stop();
  11024. t_.join();
  11025. }
  11026. #ifdef CPPHTTPLIB_SSL_ENABLED
  11027. SSLClient cli_;
  11028. SSLServer svr_;
  11029. #else
  11030. Client cli_;
  11031. Server svr_;
  11032. #endif
  11033. thread t_;
  11034. };
  11035. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11036. auto res = cli_.Get("/hi");
  11037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11038. EXPECT_EQ(StatusCode::OK_200, res->status);
  11039. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11040. EXPECT_EQ("Hello World!", res->body);
  11041. }
  11042. class ServerUpDownTest : public ::testing::Test {
  11043. protected:
  11044. ServerUpDownTest() : cli_(HOST, PORT) {}
  11045. virtual void SetUp() {
  11046. t_ = thread([&]() {
  11047. svr_.bind_to_any_port(HOST);
  11048. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11049. ASSERT_TRUE(svr_.listen_after_bind());
  11050. });
  11051. svr_.wait_until_ready();
  11052. }
  11053. virtual void TearDown() {
  11054. svr_.stop();
  11055. t_.join();
  11056. }
  11057. Client cli_;
  11058. Server svr_;
  11059. thread t_;
  11060. };
  11061. TEST_F(ServerUpDownTest, QuickStartStop) {
  11062. // Should not crash, especially when run with
  11063. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11064. }
  11065. class PayloadMaxLengthTest : public ::testing::Test {
  11066. protected:
  11067. PayloadMaxLengthTest()
  11068. : cli_(HOST, PORT)
  11069. #ifdef CPPHTTPLIB_SSL_ENABLED
  11070. ,
  11071. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11072. #endif
  11073. {
  11074. #ifdef CPPHTTPLIB_SSL_ENABLED
  11075. cli_.enable_server_certificate_verification(false);
  11076. #endif
  11077. }
  11078. virtual void SetUp() {
  11079. svr_.set_payload_max_length(8);
  11080. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11081. res.set_content("test", "text/plain");
  11082. });
  11083. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11084. svr_.wait_until_ready();
  11085. }
  11086. virtual void TearDown() {
  11087. svr_.stop();
  11088. t_.join();
  11089. }
  11090. #ifdef CPPHTTPLIB_SSL_ENABLED
  11091. SSLClient cli_;
  11092. SSLServer svr_;
  11093. #else
  11094. Client cli_;
  11095. Server svr_;
  11096. #endif
  11097. thread t_;
  11098. };
  11099. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11100. auto res = cli_.Post("/test", "123456789", "text/plain");
  11101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11102. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11103. res = cli_.Post("/test", "12345678", "text/plain");
  11104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11105. EXPECT_EQ(StatusCode::OK_200, res->status);
  11106. }
  11107. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11108. // Test chunked encoding with payload exceeding the 8-byte limit
  11109. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11110. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11112. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11113. }
  11114. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11115. // Test chunked encoding with payload within the 8-byte limit
  11116. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11117. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11119. EXPECT_EQ(StatusCode::OK_200, res->status);
  11120. }
  11121. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11122. // Test using send_request to send chunked data exceeding payload limit
  11123. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11124. "Host: " +
  11125. std::string(HOST) + ":" + std::to_string(PORT) +
  11126. "\r\n"
  11127. "Transfer-Encoding: chunked\r\n"
  11128. "Connection: close\r\n"
  11129. "\r\n"
  11130. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  11131. "0123456789\r\n"
  11132. "0\r\n" // End chunk
  11133. "\r\n";
  11134. std::string response;
  11135. bool result = send_request(1, chunked_request, &response);
  11136. if (!result) {
  11137. // If send_request fails, it might be because the server closed the
  11138. // connection due to payload limit enforcement, which is acceptable
  11139. SUCCEED()
  11140. << "Server rejected oversized chunked request (connection closed)";
  11141. } else {
  11142. // If we got a response, check if it's an error response or connection was
  11143. // closed early Short response length indicates connection was closed due to
  11144. // payload limit
  11145. if (response.length() <= 10) {
  11146. SUCCEED() << "Server closed connection for oversized chunked request";
  11147. } else {
  11148. // Check for error status codes
  11149. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11150. response.find("Payload Too Large") != std::string::npos ||
  11151. response.find("400") != std::string::npos);
  11152. }
  11153. }
  11154. }
  11155. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  11156. // Test request without Content-Length header exceeding payload limit
  11157. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11158. "Host: " +
  11159. std::string(HOST) + ":" +
  11160. std::to_string(PORT) +
  11161. "\r\n"
  11162. "Connection: close\r\n"
  11163. "\r\n";
  11164. // Add payload exceeding the 8-byte limit
  11165. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  11166. request_without_content_length += large_payload;
  11167. std::string response;
  11168. bool result = send_request(1, request_without_content_length, &response);
  11169. if (!result) {
  11170. // If send_request fails, server likely closed connection due to payload
  11171. // limit
  11172. SUCCEED() << "Server rejected oversized request without Content-Length "
  11173. "(connection closed)";
  11174. } else {
  11175. // Check if server responded with error or closed connection early
  11176. if (response.length() <= 10) {
  11177. SUCCEED() << "Server closed connection for oversized request without "
  11178. "Content-Length";
  11179. } else {
  11180. // Check for error status codes
  11181. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11182. response.find("Payload Too Large") != std::string::npos ||
  11183. response.find("400") != std::string::npos);
  11184. }
  11185. }
  11186. }
  11187. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  11188. // Test request without Content-Length header within payload limit
  11189. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11190. "Host: " +
  11191. std::string(HOST) + ":" +
  11192. std::to_string(PORT) +
  11193. "\r\n"
  11194. "Connection: close\r\n"
  11195. "\r\n";
  11196. // Add payload within the 8-byte limit
  11197. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  11198. request_without_content_length += small_payload;
  11199. std::string response;
  11200. bool result = send_request(1, request_without_content_length, &response);
  11201. // For requests without Content-Length, the server may have different behavior
  11202. // The key is that it should not reject due to payload limit for small
  11203. // payloads
  11204. if (result) {
  11205. // Check for any HTTP response (success or error, but not connection closed)
  11206. if (response.length() > 10) {
  11207. SUCCEED()
  11208. << "Server processed request without Content-Length within limit";
  11209. } else {
  11210. // Short response might indicate connection closed, which is acceptable
  11211. SUCCEED() << "Server closed connection for request without "
  11212. "Content-Length (acceptable behavior)";
  11213. }
  11214. } else {
  11215. // Connection failure might be due to protocol requirements
  11216. SUCCEED() << "Connection issue with request without Content-Length "
  11217. "(environment-specific)";
  11218. }
  11219. }
  11220. class LargePayloadMaxLengthTest : public ::testing::Test {
  11221. protected:
  11222. LargePayloadMaxLengthTest()
  11223. : cli_(HOST, PORT)
  11224. #ifdef CPPHTTPLIB_SSL_ENABLED
  11225. ,
  11226. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11227. #endif
  11228. {
  11229. #ifdef CPPHTTPLIB_SSL_ENABLED
  11230. cli_.enable_server_certificate_verification(false);
  11231. #endif
  11232. }
  11233. virtual void SetUp() {
  11234. // Set 10MB payload limit
  11235. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  11236. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  11237. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11238. res.set_content("Large payload test", "text/plain");
  11239. });
  11240. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11241. svr_.wait_until_ready();
  11242. }
  11243. virtual void TearDown() {
  11244. svr_.stop();
  11245. t_.join();
  11246. }
  11247. #ifdef CPPHTTPLIB_SSL_ENABLED
  11248. SSLClient cli_;
  11249. SSLServer svr_;
  11250. #else
  11251. Client cli_;
  11252. Server svr_;
  11253. #endif
  11254. thread t_;
  11255. };
  11256. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  11257. // Test chunked encoding with payload within 10MB limit
  11258. std::string medium_payload(5 * 1024 * 1024,
  11259. 'A'); // 5MB payload, within 10MB limit
  11260. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  11261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11262. EXPECT_EQ(StatusCode::OK_200, res->status);
  11263. }
  11264. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  11265. // Test chunked encoding with payload exceeding 10MB limit
  11266. std::string large_payload(12 * 1024 * 1024,
  11267. 'B'); // 12MB payload, exceeds 10MB limit
  11268. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  11269. // Server may either return 413 or close the connection
  11270. if (res) {
  11271. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11272. } else {
  11273. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  11274. }
  11275. }
  11276. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  11277. // Test request without Content-Length header within 10MB limit
  11278. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11279. "Host: " +
  11280. std::string(HOST) + ":" +
  11281. std::to_string(PORT) +
  11282. "\r\n"
  11283. "Connection: close\r\n"
  11284. "\r\n";
  11285. // Add 1MB payload (within 10MB limit)
  11286. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  11287. request_without_content_length += medium_payload;
  11288. std::string response;
  11289. bool result = send_request(5, request_without_content_length, &response);
  11290. if (result) {
  11291. // Should get a proper HTTP response for payloads within limit
  11292. if (response.length() > 10) {
  11293. SUCCEED() << "Server processed 1MB request without Content-Length within "
  11294. "10MB limit";
  11295. } else {
  11296. SUCCEED() << "Server closed connection (acceptable behavior for no "
  11297. "Content-Length)";
  11298. }
  11299. } else {
  11300. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  11301. }
  11302. }
  11303. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  11304. // Test request without Content-Length header exceeding 10MB limit
  11305. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11306. "Host: " +
  11307. std::string(HOST) + ":" +
  11308. std::to_string(PORT) +
  11309. "\r\n"
  11310. "Connection: close\r\n"
  11311. "\r\n";
  11312. // Add 12MB payload (exceeds 10MB limit)
  11313. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  11314. request_without_content_length += large_payload;
  11315. std::string response;
  11316. bool result = send_request(10, request_without_content_length, &response);
  11317. if (!result) {
  11318. // Server should close connection due to payload limit
  11319. SUCCEED() << "Server rejected 12MB request without Content-Length "
  11320. "(connection closed)";
  11321. } else {
  11322. // Check for error response
  11323. if (response.length() <= 10) {
  11324. SUCCEED()
  11325. << "Server closed connection for 12MB request exceeding 10MB limit";
  11326. } else {
  11327. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11328. response.find("Payload Too Large") != std::string::npos ||
  11329. response.find("400") != std::string::npos);
  11330. }
  11331. }
  11332. }
  11333. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  11334. Server svr;
  11335. svr.Get("/", [](const Request &, Response &res) {
  11336. // Claims far more than it sends, then drops the connection.
  11337. res.set_content_provider(size_t(1) << 41, "text/plain",
  11338. [](size_t, size_t, DataSink &sink) {
  11339. sink.write("abc", 3);
  11340. return false;
  11341. });
  11342. });
  11343. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11344. auto se = detail::scope_exit([&] {
  11345. svr.stop();
  11346. thread.join();
  11347. ASSERT_FALSE(svr.is_running());
  11348. });
  11349. svr.wait_until_ready();
  11350. Client cli(HOST, PORT);
  11351. cli.set_payload_max_length(0);
  11352. EXPECT_FALSE(cli.Get("/"));
  11353. }
  11354. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11355. // `payload_max_length` is not enforced on decompressed body in ContentReader
  11356. // path.
  11357. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  11358. Server svr;
  11359. const size_t LIMIT = 64 * 1024; // 64KB
  11360. svr.set_payload_max_length(LIMIT);
  11361. size_t total = 0;
  11362. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11363. const ContentReader &content_reader) {
  11364. content_reader([&](const char * /*data*/, size_t len) {
  11365. total += len;
  11366. return true;
  11367. });
  11368. res.status = 200;
  11369. res.set_content("stream_ok", "text/plain");
  11370. });
  11371. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11372. auto se = detail::scope_exit([&] {
  11373. svr.stop();
  11374. thread.join();
  11375. ASSERT_FALSE(svr.is_running());
  11376. });
  11377. svr.wait_until_ready();
  11378. // Prepare 256KB raw data and gzip-compress it
  11379. std::string raw(256 * 1024, 'A');
  11380. std::string gz;
  11381. {
  11382. z_stream zs{};
  11383. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  11384. Z_DEFAULT_STRATEGY);
  11385. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  11386. zs.avail_in = static_cast<uInt>(raw.size());
  11387. char outbuf[4096];
  11388. int ret;
  11389. do {
  11390. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  11391. zs.avail_out = sizeof(outbuf);
  11392. ret = deflate(&zs, Z_FINISH);
  11393. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  11394. } while (ret != Z_STREAM_END);
  11395. deflateEnd(&zs);
  11396. }
  11397. Client cli(HOST, PORT);
  11398. cli.set_connection_timeout(std::chrono::seconds(5));
  11399. Headers headers = {{"Content-Encoding", "gzip"}};
  11400. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  11401. "application/octet-stream");
  11402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11403. // Server must reject oversized decompressed payloads with 413.
  11404. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11405. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11406. EXPECT_LE(total, LIMIT);
  11407. }
  11408. #ifndef CPPHTTPLIB_SSL_ENABLED
  11409. // For a request with neither Content-Length nor Transfer-Encoding, the
  11410. // non-SSL raw-socket fallback in read_content_core() used to hand the
  11411. // compressed wire bytes straight to the ContentReader without ever routing
  11412. // them through the decompressor, so payload_max_length_ only bounded the
  11413. // compressed size on the wire, not the decompressed size.
  11414. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  11415. Server svr;
  11416. const size_t LIMIT = 64 * 1024; // 64KB
  11417. svr.set_payload_max_length(LIMIT);
  11418. size_t total = 0;
  11419. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11420. const ContentReader &content_reader) {
  11421. content_reader([&](const char * /*data*/, size_t len) {
  11422. total += len;
  11423. return true;
  11424. });
  11425. res.status = 200;
  11426. res.set_content("stream_ok", "text/plain");
  11427. });
  11428. auto port = svr.bind_to_any_port(HOST);
  11429. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11430. auto se = detail::scope_exit([&] {
  11431. svr.stop();
  11432. thread.join();
  11433. ASSERT_FALSE(svr.is_running());
  11434. });
  11435. svr.wait_until_ready();
  11436. // Prepare 256KB raw data and gzip-compress it, same payload as the
  11437. // StreamingGzipDecompression test above.
  11438. std::string raw(256 * 1024, 'A');
  11439. std::string gz;
  11440. {
  11441. httplib::detail::gzip_compressor compressor;
  11442. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  11443. [&](const char *chunk, size_t len) {
  11444. gz.append(chunk, len);
  11445. return true;
  11446. });
  11447. ASSERT_TRUE(result);
  11448. }
  11449. // Send the gzip body over raw TCP with neither Content-Length nor
  11450. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  11451. // kicks in.
  11452. std::string req = "POST /stream HTTP/1.1\r\n"
  11453. "Host: " +
  11454. std::string(HOST) + ":" + std::to_string(port) +
  11455. "\r\n"
  11456. "Content-Encoding: gzip\r\n"
  11457. "Connection: close\r\n"
  11458. "\r\n" +
  11459. gz;
  11460. std::string response;
  11461. ASSERT_TRUE(send_request(5, req, &response, port));
  11462. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11463. EXPECT_LE(total, LIMIT);
  11464. }
  11465. #endif
  11466. #endif
  11467. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  11468. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  11469. // the payload must be passed through untouched instead of being rejected.
  11470. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  11471. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11472. Server svr;
  11473. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  11474. res.set_content(body, "image/jpeg");
  11475. res.set_header("Content-Encoding", "UTF-8");
  11476. });
  11477. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  11478. res.set_content(body, "image/jpeg");
  11479. res.set_header("Content-Encoding", "identity");
  11480. });
  11481. svr.Post("/echo", [](const Request &req, Response &res) {
  11482. res.set_content(req.body, "image/jpeg");
  11483. });
  11484. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11485. auto se = detail::scope_exit([&] {
  11486. svr.stop();
  11487. t.join();
  11488. ASSERT_FALSE(svr.is_running());
  11489. });
  11490. svr.wait_until_ready();
  11491. Client cli(HOST, PORT);
  11492. {
  11493. auto res = cli.Get("/image");
  11494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11495. EXPECT_EQ(StatusCode::OK_200, res->status);
  11496. EXPECT_EQ(body, res->body);
  11497. }
  11498. {
  11499. auto res = cli.Get("/identity");
  11500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11501. EXPECT_EQ(StatusCode::OK_200, res->status);
  11502. EXPECT_EQ(body, res->body);
  11503. }
  11504. {
  11505. // The same applies to a request body reaching the server.
  11506. Headers headers = {{"Content-Encoding", "UTF-8"}};
  11507. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  11508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11509. EXPECT_EQ(StatusCode::OK_200, res->status);
  11510. EXPECT_EQ(body, res->body);
  11511. }
  11512. }
  11513. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  11514. // gzip-encoded response even when the build has no zlib support.
  11515. static const char GZIPPED_HELLO_WORLD[] = {
  11516. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  11517. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  11518. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  11519. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  11520. // A content coding is a whole token, not something the field value merely
  11521. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  11522. // as "fibre" look like Brotli, and turned a multi-coding value like
  11523. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  11524. // it was never meant to see.
  11525. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  11526. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11527. Server svr;
  11528. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  11529. res.set_content(body, "image/jpeg");
  11530. res.set_header("Content-Encoding", "fibre");
  11531. });
  11532. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  11533. res.set_content(body, "image/jpeg");
  11534. res.set_header("Content-Encoding", "gzip, br");
  11535. });
  11536. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  11537. res.set_content(body, "image/jpeg");
  11538. res.set_header("Content-Encoding", "x-zstd-ish");
  11539. });
  11540. auto port = svr.bind_to_any_port(HOST);
  11541. thread t = thread([&]() { svr.listen_after_bind(); });
  11542. auto se = detail::scope_exit([&] {
  11543. svr.stop();
  11544. t.join();
  11545. ASSERT_FALSE(svr.is_running());
  11546. });
  11547. svr.wait_until_ready();
  11548. Client cli(HOST, port);
  11549. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  11550. auto res = cli.Get(path);
  11551. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11552. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11553. // Not a coding we recognize, so the payload comes back untouched
  11554. EXPECT_EQ(body, res->body) << path;
  11555. }
  11556. }
  11557. // A content coding cpp-httplib recognizes but was not built with must be
  11558. // reported as such. Handing the still-compressed payload back to the caller
  11559. // would silently corrupt it.
  11560. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  11561. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11562. Server svr;
  11563. // "image/jpeg" keeps the server from applying a content coding of its own,
  11564. // so the hand-crafted Content-Encoding below survives.
  11565. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  11566. res.set_content(gzipped, "image/jpeg");
  11567. res.set_header("Content-Encoding", "gzip");
  11568. });
  11569. // Content codings are case-insensitive (RFC 9110 8.4.1).
  11570. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  11571. res.set_content(gzipped, "image/jpeg");
  11572. res.set_header("Content-Encoding", "GZIP");
  11573. });
  11574. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11575. auto se = detail::scope_exit([&] {
  11576. svr.stop();
  11577. t.join();
  11578. ASSERT_FALSE(svr.is_running());
  11579. });
  11580. svr.wait_until_ready();
  11581. Client cli(HOST, PORT);
  11582. {
  11583. auto res = cli.Get("/gzipped");
  11584. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11586. EXPECT_EQ("Hello World!", res->body);
  11587. #else
  11588. ASSERT_FALSE(res);
  11589. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11590. #endif
  11591. }
  11592. {
  11593. // open_stream() must behave the same way.
  11594. auto handle = cli.open_stream("GET", "/gzipped");
  11595. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11596. ASSERT_TRUE(handle.is_valid());
  11597. std::string received;
  11598. char buf[256];
  11599. ssize_t n;
  11600. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11601. received.append(buf, static_cast<size_t>(n));
  11602. }
  11603. EXPECT_EQ("Hello World!", received);
  11604. #else
  11605. EXPECT_FALSE(handle.is_valid());
  11606. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  11607. #endif
  11608. }
  11609. {
  11610. // A differently-cased coding must not be mistaken for an unknown one, or
  11611. // the body would be handed back still compressed.
  11612. auto res = cli.Get("/gzipped-uppercase");
  11613. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11615. EXPECT_EQ("Hello World!", res->body);
  11616. #else
  11617. ASSERT_FALSE(res);
  11618. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11619. #endif
  11620. }
  11621. }
  11622. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11623. // A handler serving pre-compressed content (e.g. build-time gzipped static
  11624. // assets) sets Content-Encoding itself. The server used to pick a coding from
  11625. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  11626. // body a second time and appending a second Content-Encoding field line, so
  11627. // clients that decode one coding per listed value handed back raw gzip bytes.
  11628. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  11629. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11630. Server svr;
  11631. // text/plain is a compressible type, so only the pre-set Content-Encoding
  11632. // keeps the server from applying a coding of its own.
  11633. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11634. res.set_content(gzipped, "text/plain");
  11635. res.set_header("Content-Encoding", "gzip");
  11636. });
  11637. auto port = svr.bind_to_any_port(HOST);
  11638. thread t = thread([&]() { svr.listen_after_bind(); });
  11639. auto se = detail::scope_exit([&] {
  11640. svr.stop();
  11641. t.join();
  11642. ASSERT_FALSE(svr.is_running());
  11643. });
  11644. svr.wait_until_ready();
  11645. Client cli(HOST, port);
  11646. Headers headers = {{"Accept-Encoding", "gzip"}};
  11647. auto res = cli.Get("/pre-gzipped", headers);
  11648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11649. EXPECT_EQ(StatusCode::OK_200, res->status);
  11650. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11651. EXPECT_EQ("Hello World!", res->body);
  11652. }
  11653. // A chunked provider settles its coding where the headers are written and
  11654. // reuses it at write time. Both ends of that have to hold: a handler's own
  11655. // Content-Encoding suppresses the coding, and a response without one is still
  11656. // compressed as it always was.
  11657. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  11658. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11659. const std::string plain = "Hello World! Hello World! Hello World!";
  11660. Server svr;
  11661. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11662. res.set_header("Content-Encoding", "gzip");
  11663. res.set_chunked_content_provider(
  11664. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  11665. sink.write(gzipped.data(), gzipped.size());
  11666. sink.done();
  11667. return true;
  11668. });
  11669. });
  11670. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  11671. res.set_chunked_content_provider(
  11672. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  11673. sink.write(plain.data(), plain.size());
  11674. sink.done();
  11675. return true;
  11676. });
  11677. });
  11678. auto port = svr.bind_to_any_port(HOST);
  11679. thread t = thread([&]() { svr.listen_after_bind(); });
  11680. auto se = detail::scope_exit([&] {
  11681. svr.stop();
  11682. t.join();
  11683. ASSERT_FALSE(svr.is_running());
  11684. });
  11685. svr.wait_until_ready();
  11686. Client cli(HOST, port);
  11687. Headers headers = {{"Accept-Encoding", "gzip"}};
  11688. {
  11689. auto res = cli.Get("/pre-gzipped", headers);
  11690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11691. EXPECT_EQ(StatusCode::OK_200, res->status);
  11692. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11693. EXPECT_EQ("Hello World!", res->body);
  11694. }
  11695. {
  11696. auto res = cli.Get("/negotiated", headers);
  11697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11698. EXPECT_EQ(StatusCode::OK_200, res->status);
  11699. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  11700. EXPECT_EQ(plain, res->body);
  11701. }
  11702. }
  11703. #endif
  11704. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  11705. // the same message as the comma-joined one, so both have to be read the same
  11706. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  11707. // single gzip coding, and a body the sender says was encoded twice was handed
  11708. // back after one pass, still compressed but presented as decoded.
  11709. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  11710. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11711. Server svr;
  11712. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  11713. res.set_content(body, "image/jpeg");
  11714. res.headers.emplace("Content-Encoding", "gzip");
  11715. res.headers.emplace("Content-Encoding", "gzip");
  11716. });
  11717. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  11718. res.set_content(body, "image/jpeg");
  11719. res.set_header("Content-Encoding", "gzip, gzip");
  11720. });
  11721. auto port = svr.bind_to_any_port(HOST);
  11722. thread t = thread([&]() { svr.listen_after_bind(); });
  11723. auto se = detail::scope_exit([&] {
  11724. svr.stop();
  11725. t.join();
  11726. ASSERT_FALSE(svr.is_running());
  11727. });
  11728. svr.wait_until_ready();
  11729. Client cli(HOST, port);
  11730. // Two codings is not something cpp-httplib decodes, so both representations
  11731. // take the pass-through path rather than one of them being gunzipped once.
  11732. for (const char *path : {"/split", "/joined"}) {
  11733. auto res = cli.Get(path);
  11734. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11735. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11736. EXPECT_EQ(body, res->body) << path;
  11737. }
  11738. }
  11739. // Regression test for DoS vulnerability: a malicious server sending a response
  11740. // without Content-Length header must not cause unbounded memory consumption on
  11741. // the client side. The client should stop reading after a reasonable limit,
  11742. // similar to the server-side set_payload_max_length protection.
  11743. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  11744. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11745. #ifndef _WIN32
  11746. signal(SIGPIPE, SIG_IGN);
  11747. #endif
  11748. auto server_thread = std::thread([] {
  11749. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  11750. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11751. default_socket_options(srv);
  11752. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11753. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11754. sockaddr_in addr{};
  11755. addr.sin_family = AF_INET;
  11756. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11757. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11758. int opt = 1;
  11759. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11760. #ifdef _WIN32
  11761. reinterpret_cast<const char *>(&opt),
  11762. #else
  11763. &opt,
  11764. #endif
  11765. sizeof(opt));
  11766. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11767. ::listen(srv, 1);
  11768. sockaddr_in cli_addr{};
  11769. socklen_t cli_len = sizeof(cli_addr);
  11770. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11771. if (cli != INVALID_SOCKET) {
  11772. char buf[4096];
  11773. ::recv(cli, buf, sizeof(buf), 0);
  11774. // Malicious response: no Content-Length, no chunked encoding
  11775. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11776. "Connection: close\r\n"
  11777. "\r\n";
  11778. ::send(cli,
  11779. #ifdef _WIN32
  11780. static_cast<const char *>(response_header.c_str()),
  11781. static_cast<int>(response_header.size()),
  11782. #else
  11783. response_header.c_str(), response_header.size(),
  11784. #endif
  11785. 0);
  11786. // Send 10MB of data
  11787. std::string chunk(64 * 1024, 'A');
  11788. size_t total_sent = 0;
  11789. while (total_sent < MALICIOUS_DATA_SIZE) {
  11790. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  11791. auto sent = ::send(cli,
  11792. #ifdef _WIN32
  11793. static_cast<const char *>(chunk.c_str()),
  11794. static_cast<int>(to_send),
  11795. #else
  11796. chunk.c_str(), to_send,
  11797. #endif
  11798. 0);
  11799. if (sent <= 0) break;
  11800. total_sent += static_cast<size_t>(sent);
  11801. }
  11802. detail::close_socket(cli);
  11803. }
  11804. detail::close_socket(srv);
  11805. });
  11806. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11807. size_t total_read = 0;
  11808. {
  11809. Client cli("127.0.0.1", PORT + 2);
  11810. cli.set_read_timeout(5, 0);
  11811. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11812. auto stream = cli.open_stream("GET", "/malicious");
  11813. ASSERT_TRUE(stream.is_valid());
  11814. char buffer[64 * 1024];
  11815. ssize_t n;
  11816. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11817. total_read += static_cast<size_t>(n);
  11818. }
  11819. } // StreamHandle and Client destroyed here, closing the socket
  11820. server_thread.join();
  11821. // With set_payload_max_length, the client must stop reading before consuming
  11822. // all 10MB. The read loop should be cut off at or near the configured limit.
  11823. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  11824. << "Client read " << total_read << " bytes, exceeding the configured "
  11825. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  11826. }
  11827. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  11828. // the entire response body without truncation.
  11829. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  11830. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  11831. #ifndef _WIN32
  11832. signal(SIGPIPE, SIG_IGN);
  11833. #endif
  11834. auto server_thread = std::thread([] {
  11835. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11836. default_socket_options(srv);
  11837. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11838. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11839. sockaddr_in addr{};
  11840. addr.sin_family = AF_INET;
  11841. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11842. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11843. int opt = 1;
  11844. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11845. #ifdef _WIN32
  11846. reinterpret_cast<const char *>(&opt),
  11847. #else
  11848. &opt,
  11849. #endif
  11850. sizeof(opt));
  11851. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11852. ::listen(srv, 1);
  11853. sockaddr_in cli_addr{};
  11854. socklen_t cli_len = sizeof(cli_addr);
  11855. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11856. if (cli != INVALID_SOCKET) {
  11857. char buf[4096];
  11858. ::recv(cli, buf, sizeof(buf), 0);
  11859. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11860. "Connection: close\r\n"
  11861. "\r\n";
  11862. ::send(cli,
  11863. #ifdef _WIN32
  11864. static_cast<const char *>(response_header.c_str()),
  11865. static_cast<int>(response_header.size()),
  11866. #else
  11867. response_header.c_str(), response_header.size(),
  11868. #endif
  11869. 0);
  11870. std::string chunk(64 * 1024, 'A');
  11871. size_t total_sent = 0;
  11872. while (total_sent < DATA_SIZE) {
  11873. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11874. auto sent = ::send(cli,
  11875. #ifdef _WIN32
  11876. static_cast<const char *>(chunk.c_str()),
  11877. static_cast<int>(to_send),
  11878. #else
  11879. chunk.c_str(), to_send,
  11880. #endif
  11881. 0);
  11882. if (sent <= 0) break;
  11883. total_sent += static_cast<size_t>(sent);
  11884. }
  11885. #ifdef _WIN32
  11886. ::shutdown(cli, SD_SEND);
  11887. #else
  11888. ::shutdown(cli, SHUT_WR);
  11889. #endif
  11890. // Drain until the client closes its end, ensuring all data is delivered
  11891. char drain[1024];
  11892. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11893. detail::close_socket(cli);
  11894. }
  11895. detail::close_socket(srv);
  11896. });
  11897. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11898. size_t total_read = 0;
  11899. {
  11900. Client cli("127.0.0.1", PORT + 2);
  11901. cli.set_read_timeout(5, 0);
  11902. cli.set_payload_max_length(0); // 0 means no limit
  11903. auto stream = cli.open_stream("GET", "/data");
  11904. ASSERT_TRUE(stream.is_valid());
  11905. char buffer[64 * 1024];
  11906. ssize_t n;
  11907. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11908. total_read += static_cast<size_t>(n);
  11909. }
  11910. }
  11911. server_thread.join();
  11912. EXPECT_EQ(total_read, DATA_SIZE)
  11913. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  11914. << " bytes without truncation, but only read " << total_read << " bytes.";
  11915. }
  11916. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  11917. // enormous Content-Length must not cause the client to pre-allocate a huge
  11918. // response body buffer. The reservation is capped at payload_max_length_, and
  11919. // the read itself fails when the body exceeds the limit.
  11920. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  11921. #ifndef _WIN32
  11922. signal(SIGPIPE, SIG_IGN);
  11923. #endif
  11924. auto server_thread = std::thread([] {
  11925. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11926. default_socket_options(srv);
  11927. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11928. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11929. sockaddr_in addr{};
  11930. addr.sin_family = AF_INET;
  11931. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11932. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11933. int opt = 1;
  11934. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11935. #ifdef _WIN32
  11936. reinterpret_cast<const char *>(&opt),
  11937. #else
  11938. &opt,
  11939. #endif
  11940. sizeof(opt));
  11941. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11942. ::listen(srv, 1);
  11943. sockaddr_in cli_addr{};
  11944. socklen_t cli_len = sizeof(cli_addr);
  11945. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11946. if (cli != INVALID_SOCKET) {
  11947. char buf[4096];
  11948. ::recv(cli, buf, sizeof(buf), 0);
  11949. // Malicious response: claim a 20GB body but send only a tiny payload.
  11950. std::string response = "HTTP/1.1 200 OK\r\n"
  11951. "Content-Length: 20000000000\r\n"
  11952. "\r\n"
  11953. "abc";
  11954. ::send(cli,
  11955. #ifdef _WIN32
  11956. static_cast<const char *>(response.c_str()),
  11957. static_cast<int>(response.size()),
  11958. #else
  11959. response.c_str(), response.size(),
  11960. #endif
  11961. 0);
  11962. detail::close_socket(cli);
  11963. }
  11964. detail::close_socket(srv);
  11965. });
  11966. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11967. {
  11968. Client cli("127.0.0.1", PORT + 2);
  11969. cli.set_read_timeout(5, 0);
  11970. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  11971. // result in a 20GB pre-allocation. The Get() call is expected to fail
  11972. // (server claims more bytes than payload_max_length permits), but it must
  11973. // not exhaust memory before getting there.
  11974. auto res = cli.Get("/malicious");
  11975. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  11976. }
  11977. server_thread.join();
  11978. }
  11979. // Verify that content_receiver bypasses the default payload_max_length,
  11980. // allowing streaming downloads larger than 100MB without requiring an explicit
  11981. // set_payload_max_length call.
  11982. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  11983. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11984. #ifndef _WIN32
  11985. signal(SIGPIPE, SIG_IGN);
  11986. #endif
  11987. auto server_thread = std::thread([] {
  11988. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11989. default_socket_options(srv);
  11990. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11991. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11992. sockaddr_in addr{};
  11993. addr.sin_family = AF_INET;
  11994. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11995. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11996. int opt = 1;
  11997. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11998. #ifdef _WIN32
  11999. reinterpret_cast<const char *>(&opt),
  12000. #else
  12001. &opt,
  12002. #endif
  12003. sizeof(opt));
  12004. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12005. ::listen(srv, 1);
  12006. sockaddr_in cli_addr{};
  12007. socklen_t cli_len = sizeof(cli_addr);
  12008. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12009. if (cli != INVALID_SOCKET) {
  12010. char buf[4096];
  12011. ::recv(cli, buf, sizeof(buf), 0);
  12012. // Response with Content-Length larger than default 100MB limit
  12013. auto content_length = std::to_string(DATA_SIZE);
  12014. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12015. "Content-Length: " +
  12016. content_length +
  12017. "\r\n"
  12018. "Connection: close\r\n"
  12019. "\r\n";
  12020. ::send(cli,
  12021. #ifdef _WIN32
  12022. static_cast<const char *>(response_header.c_str()),
  12023. static_cast<int>(response_header.size()),
  12024. #else
  12025. response_header.c_str(), response_header.size(),
  12026. #endif
  12027. 0);
  12028. std::string chunk(64 * 1024, 'A');
  12029. size_t total_sent = 0;
  12030. while (total_sent < DATA_SIZE) {
  12031. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12032. auto sent = ::send(cli,
  12033. #ifdef _WIN32
  12034. static_cast<const char *>(chunk.c_str()),
  12035. static_cast<int>(to_send),
  12036. #else
  12037. chunk.c_str(), to_send,
  12038. #endif
  12039. 0);
  12040. if (sent <= 0) break;
  12041. total_sent += static_cast<size_t>(sent);
  12042. }
  12043. detail::close_socket(cli);
  12044. }
  12045. detail::close_socket(srv);
  12046. });
  12047. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12048. size_t total_received = 0;
  12049. {
  12050. Client cli("127.0.0.1", PORT + 2);
  12051. cli.set_read_timeout(10, 0);
  12052. // Do NOT call set_payload_max_length — use the default 100MB limit
  12053. auto res =
  12054. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12055. total_received += data_length;
  12056. return true;
  12057. });
  12058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12059. EXPECT_EQ(StatusCode::OK_200, res->status);
  12060. }
  12061. server_thread.join();
  12062. EXPECT_EQ(total_received, DATA_SIZE)
  12063. << "With content_receiver, the client should read all " << DATA_SIZE
  12064. << " bytes despite the default 100MB payload_max_length, but only read "
  12065. << total_received << " bytes.";
  12066. }
  12067. // Verify that an explicit set_payload_max_length smaller than the response is
  12068. // enforced even when a content_receiver is used.
  12069. TEST(ClientVulnerabilityTest,
  12070. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12071. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12072. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12073. #ifndef _WIN32
  12074. signal(SIGPIPE, SIG_IGN);
  12075. #endif
  12076. auto server_thread = std::thread([] {
  12077. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12078. default_socket_options(srv);
  12079. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12080. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12081. sockaddr_in addr{};
  12082. addr.sin_family = AF_INET;
  12083. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12084. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12085. int opt = 1;
  12086. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12087. #ifdef _WIN32
  12088. reinterpret_cast<const char *>(&opt),
  12089. #else
  12090. &opt,
  12091. #endif
  12092. sizeof(opt));
  12093. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12094. ::listen(srv, 1);
  12095. sockaddr_in cli_addr{};
  12096. socklen_t cli_len = sizeof(cli_addr);
  12097. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12098. if (cli != INVALID_SOCKET) {
  12099. char buf[4096];
  12100. ::recv(cli, buf, sizeof(buf), 0);
  12101. auto content_length = std::to_string(DATA_SIZE);
  12102. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12103. "Content-Length: " +
  12104. content_length +
  12105. "\r\n"
  12106. "Connection: close\r\n"
  12107. "\r\n";
  12108. ::send(cli,
  12109. #ifdef _WIN32
  12110. static_cast<const char *>(response_header.c_str()),
  12111. static_cast<int>(response_header.size()),
  12112. #else
  12113. response_header.c_str(), response_header.size(),
  12114. #endif
  12115. 0);
  12116. std::string chunk(64 * 1024, 'A');
  12117. size_t total_sent = 0;
  12118. while (total_sent < DATA_SIZE) {
  12119. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12120. auto sent = ::send(cli,
  12121. #ifdef _WIN32
  12122. static_cast<const char *>(chunk.c_str()),
  12123. static_cast<int>(to_send),
  12124. #else
  12125. chunk.c_str(), to_send,
  12126. #endif
  12127. 0);
  12128. if (sent <= 0) break;
  12129. total_sent += static_cast<size_t>(sent);
  12130. }
  12131. detail::close_socket(cli);
  12132. }
  12133. detail::close_socket(srv);
  12134. });
  12135. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12136. size_t total_received = 0;
  12137. {
  12138. Client cli("127.0.0.1", PORT + 2);
  12139. cli.set_read_timeout(10, 0);
  12140. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  12141. auto res =
  12142. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12143. total_received += data_length;
  12144. return true;
  12145. });
  12146. // Should fail because 200MB exceeds the explicit 150MB limit
  12147. EXPECT_FALSE(res);
  12148. }
  12149. server_thread.join();
  12150. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12151. << "Client with content_receiver should respect the explicit "
  12152. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12153. << total_received << " bytes.";
  12154. }
  12155. // Verify that an explicit set_payload_max_length larger than the response
  12156. // allows the content_receiver to read all data successfully.
  12157. TEST(ClientVulnerabilityTest,
  12158. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  12159. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12160. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  12161. #ifndef _WIN32
  12162. signal(SIGPIPE, SIG_IGN);
  12163. #endif
  12164. auto server_thread = std::thread([] {
  12165. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12166. default_socket_options(srv);
  12167. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12168. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12169. sockaddr_in addr{};
  12170. addr.sin_family = AF_INET;
  12171. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12172. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12173. int opt = 1;
  12174. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12175. #ifdef _WIN32
  12176. reinterpret_cast<const char *>(&opt),
  12177. #else
  12178. &opt,
  12179. #endif
  12180. sizeof(opt));
  12181. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12182. ::listen(srv, 1);
  12183. sockaddr_in cli_addr{};
  12184. socklen_t cli_len = sizeof(cli_addr);
  12185. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12186. if (cli != INVALID_SOCKET) {
  12187. char buf[4096];
  12188. ::recv(cli, buf, sizeof(buf), 0);
  12189. auto content_length = std::to_string(DATA_SIZE);
  12190. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12191. "Content-Length: " +
  12192. content_length +
  12193. "\r\n"
  12194. "Connection: close\r\n"
  12195. "\r\n";
  12196. ::send(cli,
  12197. #ifdef _WIN32
  12198. static_cast<const char *>(response_header.c_str()),
  12199. static_cast<int>(response_header.size()),
  12200. #else
  12201. response_header.c_str(), response_header.size(),
  12202. #endif
  12203. 0);
  12204. std::string chunk(64 * 1024, 'A');
  12205. size_t total_sent = 0;
  12206. while (total_sent < DATA_SIZE) {
  12207. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12208. auto sent = ::send(cli,
  12209. #ifdef _WIN32
  12210. static_cast<const char *>(chunk.c_str()),
  12211. static_cast<int>(to_send),
  12212. #else
  12213. chunk.c_str(), to_send,
  12214. #endif
  12215. 0);
  12216. if (sent <= 0) break;
  12217. total_sent += static_cast<size_t>(sent);
  12218. }
  12219. #ifdef _WIN32
  12220. ::shutdown(cli, SD_SEND);
  12221. #else
  12222. ::shutdown(cli, SHUT_WR);
  12223. #endif
  12224. char drain[1024];
  12225. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12226. detail::close_socket(cli);
  12227. }
  12228. detail::close_socket(srv);
  12229. });
  12230. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12231. size_t total_received = 0;
  12232. {
  12233. Client cli("127.0.0.1", PORT + 2);
  12234. cli.set_read_timeout(10, 0);
  12235. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  12236. auto res =
  12237. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12238. total_received += data_length;
  12239. return true;
  12240. });
  12241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12242. EXPECT_EQ(StatusCode::OK_200, res->status);
  12243. }
  12244. server_thread.join();
  12245. EXPECT_EQ(total_received, DATA_SIZE)
  12246. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  12247. << " bytes (larger than " << DATA_SIZE
  12248. << " bytes response), content_receiver should read all data, but only "
  12249. "read "
  12250. << total_received << " bytes.";
  12251. }
  12252. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  12253. // Regression test for "zip bomb" attack on the client side: a malicious server
  12254. // sends a small gzip-compressed response that decompresses to a huge payload.
  12255. // The client must enforce payload_max_length on the decompressed size.
  12256. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  12257. constexpr size_t DECOMPRESSED_SIZE =
  12258. 10 * 1024 * 1024; // 10MB after decompression
  12259. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12260. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  12261. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  12262. std::string compressed;
  12263. {
  12264. httplib::detail::gzip_compressor compressor;
  12265. bool ok =
  12266. compressor.compress(uncompressed.data(), uncompressed.size(),
  12267. /*last=*/true, [&](const char *buf, size_t len) {
  12268. compressed.append(buf, len);
  12269. return true;
  12270. });
  12271. ASSERT_TRUE(ok);
  12272. }
  12273. // Sanity: compressed data should be much smaller than the decompressed size
  12274. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  12275. #ifndef _WIN32
  12276. signal(SIGPIPE, SIG_IGN);
  12277. #endif
  12278. // Set up the listening socket in the main thread so the server is guaranteed
  12279. // to be ready before the client connects (eliminates race condition).
  12280. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12281. default_socket_options(srv);
  12282. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12283. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12284. sockaddr_in addr{};
  12285. addr.sin_family = AF_INET;
  12286. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  12287. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12288. int opt = 1;
  12289. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12290. #ifdef _WIN32
  12291. reinterpret_cast<const char *>(&opt),
  12292. #else
  12293. &opt,
  12294. #endif
  12295. sizeof(opt));
  12296. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12297. ASSERT_EQ(0, ::listen(srv, 1));
  12298. auto server_thread = std::thread([&compressed, srv] {
  12299. sockaddr_in cli_addr{};
  12300. socklen_t cli_len = sizeof(cli_addr);
  12301. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12302. if (cli != INVALID_SOCKET) {
  12303. // Read the full HTTP request (until \r\n\r\n)
  12304. char buf[4096];
  12305. size_t total = 0;
  12306. while (total < sizeof(buf)) {
  12307. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  12308. if (n <= 0) break;
  12309. total += static_cast<size_t>(n);
  12310. // Check for end of headers
  12311. if (total >= 4) {
  12312. std::string req(buf, total);
  12313. if (req.find("\r\n\r\n") != std::string::npos) break;
  12314. }
  12315. }
  12316. // Malicious response: gzip-compressed body, no Content-Length
  12317. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12318. "Content-Encoding: gzip\r\n"
  12319. "Connection: close\r\n"
  12320. "\r\n";
  12321. ::send(cli,
  12322. #ifdef _WIN32
  12323. static_cast<const char *>(response_header.c_str()),
  12324. static_cast<int>(response_header.size()),
  12325. #else
  12326. response_header.c_str(), response_header.size(),
  12327. #endif
  12328. 0);
  12329. // Send the compressed payload (small on the wire, huge when decompressed)
  12330. size_t total_sent = 0;
  12331. while (total_sent < compressed.size()) {
  12332. auto to_send = std::min(compressed.size() - total_sent,
  12333. static_cast<size_t>(64 * 1024));
  12334. auto sent =
  12335. ::send(cli,
  12336. #ifdef _WIN32
  12337. static_cast<const char *>(compressed.c_str() + total_sent),
  12338. static_cast<int>(to_send),
  12339. #else
  12340. compressed.c_str() + total_sent, to_send,
  12341. #endif
  12342. 0);
  12343. if (sent <= 0) break;
  12344. total_sent += static_cast<size_t>(sent);
  12345. }
  12346. detail::close_socket(cli);
  12347. }
  12348. });
  12349. auto se = detail::scope_exit([&] {
  12350. detail::close_socket(srv);
  12351. server_thread.join();
  12352. });
  12353. size_t total_decompressed = 0;
  12354. {
  12355. Client cli("127.0.0.1", PORT + 3);
  12356. cli.set_read_timeout(5, 0);
  12357. cli.set_decompress(true);
  12358. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12359. auto stream = cli.open_stream("GET", "/zipbomb");
  12360. ASSERT_TRUE(stream.is_valid());
  12361. char buffer[64 * 1024];
  12362. ssize_t n;
  12363. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12364. total_decompressed += static_cast<size_t>(n);
  12365. }
  12366. }
  12367. // The decompressed size must be capped by payload_max_length. Without
  12368. // protection, the client would decompress the full 10MB from a tiny
  12369. // compressed payload, enabling a zip bomb DoS attack.
  12370. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  12371. << "Client decompressed " << total_decompressed
  12372. << " bytes from a gzip response. The decompressed size should be "
  12373. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  12374. }
  12375. #endif
  12376. TEST(HostAndPortPropertiesTest, NoSSL) {
  12377. httplib::Client cli("www.google.com", 1234);
  12378. ASSERT_EQ("www.google.com", cli.host());
  12379. ASSERT_EQ(1234, cli.port());
  12380. }
  12381. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  12382. httplib::Client cli("www.google.com:1234");
  12383. ASSERT_EQ("www.google.com", cli.host());
  12384. ASSERT_EQ(1234, cli.port());
  12385. }
  12386. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  12387. // Port number that overflows int — should not crash, client becomes invalid
  12388. httplib::Client cli("http://www.google.com:99999999999999999999");
  12389. ASSERT_FALSE(cli.is_valid());
  12390. }
  12391. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  12392. // Port 99999 exceeds valid range (1-65535) — should not crash
  12393. httplib::Client cli("http://www.google.com:99999");
  12394. ASSERT_FALSE(cli.is_valid());
  12395. auto res = cli.Get("/");
  12396. EXPECT_FALSE(res);
  12397. EXPECT_EQ(Error::Connection, res.error());
  12398. }
  12399. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  12400. httplib::Client cli("http://www.google.com:80abc");
  12401. ASSERT_FALSE(cli.is_valid());
  12402. }
  12403. #ifdef CPPHTTPLIB_SSL_ENABLED
  12404. TEST(HostAndPortPropertiesTest, SSL) {
  12405. httplib::SSLClient cli("www.google.com");
  12406. ASSERT_EQ("www.google.com", cli.host());
  12407. ASSERT_EQ(443, cli.port());
  12408. }
  12409. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  12410. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  12411. std::string cert;
  12412. read_file(CA_CERT_FILE, cert);
  12413. httplib::SSLClient httplib_client("www.google.com");
  12414. // Load CA store first time
  12415. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12416. // Load CA store second time (update)
  12417. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12418. // Verify client is still valid and can make connections
  12419. httplib_client.enable_server_certificate_verification(true);
  12420. auto res = httplib_client.Get("/");
  12421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12422. // Google may return 200 or 301 depending on various factors
  12423. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  12424. res->status == StatusCode::MovedPermanently_301);
  12425. }
  12426. TEST(SSLClientTest, ServerNameIndication_Online) {
  12427. auto host = "httpbingo.org";
  12428. auto path = std::string{"/get"};
  12429. SSLClient cli(host, 443);
  12430. auto res = cli.Get(path);
  12431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12432. ASSERT_EQ(StatusCode::OK_200, res->status);
  12433. }
  12434. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  12435. // Use a site that will cause SSL verification failure due to self-signed cert
  12436. SSLClient cli("self-signed.badssl.com", 443);
  12437. cli.enable_server_certificate_verification(true);
  12438. auto res = cli.Get("/");
  12439. ASSERT_TRUE(!res);
  12440. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12441. // Verify backend error is captured for SSLServerVerification
  12442. // This occurs when certificate verification fails
  12443. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  12444. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  12445. EXPECT_NE(0UL, res.ssl_backend_error());
  12446. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12447. // For OpenSSL, ssl_error is 0 for verification errors
  12448. EXPECT_EQ(0, res.ssl_error());
  12449. #if !defined(_WIN32) || \
  12450. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12451. // On non-Windows or when Windows Schannel is disabled, the error comes
  12452. // from OpenSSL's verification
  12453. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  12454. res.ssl_backend_error());
  12455. #endif
  12456. #endif
  12457. }
  12458. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  12459. // Use a site where hostname doesn't match the certificate
  12460. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  12461. SSLClient cli("wrong.host.badssl.com", 443);
  12462. cli.enable_server_certificate_verification(true);
  12463. cli.enable_server_hostname_verification(true);
  12464. auto res = cli.Get("/");
  12465. ASSERT_TRUE(!res);
  12466. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  12467. // Verify backend error is captured for hostname verification failure
  12468. EXPECT_NE(0UL, res.ssl_backend_error());
  12469. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12470. // For OpenSSL, ssl_error is 0 for verification errors
  12471. EXPECT_EQ(0, res.ssl_error());
  12472. #if !defined(_WIN32) || \
  12473. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12474. // On non-Windows or when Windows Schannel is disabled, the error comes
  12475. // from OpenSSL's hostname verification
  12476. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  12477. res.ssl_backend_error());
  12478. #endif
  12479. #endif
  12480. }
  12481. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  12482. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12483. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  12484. SSLClient cli("www.google.com", 443);
  12485. cli.enable_server_certificate_verification(true);
  12486. auto res = cli.Get("/");
  12487. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12488. }
  12489. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  12490. SSLClient cli("www.google.com", 443);
  12491. cli.enable_server_certificate_verification(true);
  12492. cli.enable_windows_certificate_verification(false);
  12493. auto res = cli.Get("/");
  12494. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12495. }
  12496. // The server sends an intermediate cross-signed by a root Windows trusts,
  12497. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  12498. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  12499. SSLClient cli("accounts.spotify.com", 443);
  12500. auto res = cli.Get("/");
  12501. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  12502. << " ssl_backend_error=" << res.ssl_backend_error();
  12503. }
  12504. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  12505. // policy status, which no backend reports for a self-signed certificate.
  12506. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  12507. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12508. ASSERT_TRUE(svr.is_valid());
  12509. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12510. auto se = detail::scope_exit([&] {
  12511. svr.stop();
  12512. t.join();
  12513. ASSERT_FALSE(svr.is_running());
  12514. });
  12515. svr.wait_until_ready();
  12516. SSLClient cli("127.0.0.1", PORT);
  12517. cli.set_connection_timeout(30);
  12518. auto res = cli.Get("/");
  12519. ASSERT_FALSE(res);
  12520. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12521. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  12522. }
  12523. #endif
  12524. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  12525. Client cli("https://google.com");
  12526. auto res = cli.Get("/");
  12527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12528. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12529. }
  12530. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  12531. SSLClient cli("google.com");
  12532. cli.set_ca_cert_path(CA_CERT_FILE);
  12533. auto res = cli.Get("/");
  12534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12535. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12536. }
  12537. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  12538. SSLClient cli("google.com");
  12539. cli.enable_server_certificate_verification(true);
  12540. cli.set_ca_cert_path("hello");
  12541. auto res = cli.Get("/");
  12542. ASSERT_TRUE(!res);
  12543. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  12544. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  12545. // should be set
  12546. EXPECT_EQ(0, res.ssl_error());
  12547. // Verify backend error is captured for SSLLoadingCerts
  12548. // This error occurs when loading CA certificates fails
  12549. EXPECT_NE(0UL, res.ssl_backend_error());
  12550. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12551. // OpenSSL specific error codes:
  12552. // > openssl errstr 0x80000002
  12553. // error:80000002:system library::No such file or directory
  12554. // > openssl errstr 0xA000126
  12555. // error:0A000126:SSL routines::unexpected eof while reading
  12556. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  12557. res.ssl_backend_error() == 0xA000126);
  12558. #endif
  12559. }
  12560. TEST(SSLClientTest, ServerCertificateVerification4) {
  12561. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12562. ASSERT_TRUE(svr.is_valid());
  12563. svr.Get("/test", [&](const Request &, Response &res) {
  12564. res.set_content("test", "text/plain");
  12565. svr.stop();
  12566. ASSERT_TRUE(true);
  12567. });
  12568. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12569. auto se = detail::scope_exit([&] {
  12570. t.join();
  12571. ASSERT_FALSE(svr.is_running());
  12572. });
  12573. svr.wait_until_ready();
  12574. SSLClient cli("127.0.0.1", PORT);
  12575. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12576. cli.enable_server_certificate_verification(true);
  12577. cli.set_connection_timeout(30);
  12578. auto res = cli.Get("/test");
  12579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12580. ASSERT_EQ(StatusCode::OK_200, res->status);
  12581. }
  12582. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  12583. std::string cert;
  12584. read_file(CA_CERT_FILE, cert);
  12585. SSLClient cli("google.com");
  12586. cli.load_ca_cert_store(cert.data(), cert.size());
  12587. const auto res = cli.Get("/");
  12588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12589. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12590. }
  12591. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  12592. // clang-format off
  12593. static constexpr char cert[] =
  12594. "GlobalSign Root CA\n"
  12595. "==================\n"
  12596. "-----BEGIN CERTIFICATE-----\n"
  12597. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  12598. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  12599. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  12600. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  12601. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  12602. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  12603. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  12604. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  12605. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  12606. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  12607. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  12608. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  12609. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  12610. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  12611. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  12612. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  12613. "-----END CERTIFICATE-----\n";
  12614. // clang-format on
  12615. SSLClient cli("google.com");
  12616. cli.load_ca_cert_store(cert, sizeof(cert));
  12617. const auto res = cli.Get("/");
  12618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12619. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12620. }
  12621. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  12622. SSLClient cli("www.youtube.com");
  12623. cli.set_ca_cert_path(CA_CERT_FILE);
  12624. cli.enable_server_certificate_verification(true);
  12625. cli.set_follow_location(true);
  12626. auto res = cli.Get("/");
  12627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12628. ASSERT_EQ(StatusCode::OK_200, res->status);
  12629. }
  12630. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  12631. SSLClient cli("wWw.YouTube.Com");
  12632. cli.set_ca_cert_path(CA_CERT_FILE);
  12633. cli.enable_server_certificate_verification(true);
  12634. cli.enable_server_hostname_verification(true);
  12635. cli.set_follow_location(true);
  12636. auto res = cli.Get("/");
  12637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12638. ASSERT_EQ(StatusCode::OK_200, res->status);
  12639. }
  12640. TEST(SSLClientTest, HostNameMatchCase_Online) {
  12641. SSLClient cli("gOoGlE.COm");
  12642. cli.enable_server_certificate_verification(true);
  12643. cli.enable_server_hostname_verification(true);
  12644. cli.set_follow_location(true);
  12645. auto res = cli.Get("/");
  12646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12647. ASSERT_EQ(StatusCode::OK_200, res->status);
  12648. }
  12649. TEST(SSLClientTest, Issue2004_Online) {
  12650. Client client("https://google.com");
  12651. client.set_follow_location(true);
  12652. auto res = client.Get("/");
  12653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12654. ASSERT_EQ(StatusCode::OK_200, res->status);
  12655. auto body = res->body;
  12656. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  12657. }
  12658. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  12659. // Create SSLClient with invalid cert/key to make is_valid() return false
  12660. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  12661. "nonexistent_key.pem");
  12662. // is_valid() should be false due to cert loading failure
  12663. ASSERT_FALSE(cli.is_valid());
  12664. auto res = cli.Get("/");
  12665. ASSERT_FALSE(res);
  12666. EXPECT_EQ(Error::SSLConnection, res.error());
  12667. }
  12668. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  12669. // Test for Issue #2251: SSL error not properly reported when client cert
  12670. // and key paths are swapped or mismatched
  12671. // This simulates the scenario where user accidentally swaps the cert and key
  12672. // files
  12673. // Using client cert file as private key and vice versa (completely wrong)
  12674. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  12675. // Should fail validation due to cert/key mismatch
  12676. ASSERT_FALSE(cli.is_valid());
  12677. // Attempt to make a request should fail with proper error
  12678. auto res = cli.Get("/");
  12679. ASSERT_FALSE(res);
  12680. EXPECT_EQ(Error::SSLConnection, res.error());
  12681. // SSL error should be recorded in the Result object (this is the key fix for
  12682. // Issue #2251)
  12683. auto backend_error = res.ssl_backend_error();
  12684. EXPECT_NE(0u, backend_error);
  12685. }
  12686. // Tests cert/key mismatch detection at the TLS context level
  12687. TEST(TlsApiTest, ClientCertKeyMismatch) {
  12688. // Test that using mismatched cert/key causes connection failure.
  12689. // We verify this at the SSLClient level rather than through internal
  12690. // TLS API functions.
  12691. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  12692. cli.enable_server_certificate_verification(false);
  12693. cli.set_connection_timeout(2);
  12694. // The mismatch should cause a connection or handshake error
  12695. auto res = cli.Get("/test");
  12696. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  12697. // Either way, the request should fail
  12698. EXPECT_FALSE(res);
  12699. }
  12700. #endif
  12701. #if 0
  12702. TEST(SSLClientTest, SetInterfaceWithINET6) {
  12703. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  12704. ASSERT_TRUE(cli != nullptr);
  12705. cli->set_address_family(AF_INET6);
  12706. cli->set_interface("en0");
  12707. auto res = cli->Get("/get");
  12708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12709. ASSERT_EQ(StatusCode::OK_200, res->status);
  12710. }
  12711. #endif
  12712. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  12713. #ifdef CPPHTTPLIB_SSL_ENABLED
  12714. void ClientCertPresent(
  12715. const std::string &client_cert_file,
  12716. const std::string &client_private_key_file,
  12717. const std::string &client_encrypted_private_key_pass = std::string()) {
  12718. using namespace httplib::tls;
  12719. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12720. CLIENT_CA_CERT_DIR);
  12721. ASSERT_TRUE(svr.is_valid());
  12722. svr.Get("/test", [&](const Request &req, Response &res) {
  12723. res.set_content("test", "text/plain");
  12724. auto cert = req.peer_cert();
  12725. ASSERT_TRUE(static_cast<bool>(cert));
  12726. std::string common_name = cert.subject_cn();
  12727. EXPECT_EQ("Common Name", common_name);
  12728. });
  12729. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12730. auto se = detail::scope_exit([&] {
  12731. svr.stop();
  12732. t.join();
  12733. ASSERT_FALSE(svr.is_running());
  12734. });
  12735. svr.wait_until_ready();
  12736. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  12737. client_encrypted_private_key_pass);
  12738. cli.enable_server_certificate_verification(false);
  12739. cli.set_connection_timeout(30);
  12740. auto res = cli.Get("/test");
  12741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12742. ASSERT_EQ(StatusCode::OK_200, res->status);
  12743. }
  12744. TEST(SSLClientServerTest, ClientCertPresent) {
  12745. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12746. }
  12747. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  12748. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12749. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12750. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12751. }
  12752. // PEM memory-based constructor tests (works with all TLS backends)
  12753. void PemMemoryClientCertPresent(
  12754. const std::string &client_cert_file,
  12755. const std::string &client_private_key_file,
  12756. const std::string &client_encrypted_private_key_pass = std::string()) {
  12757. // Read PEM files into memory
  12758. std::string server_cert_pem, server_key_pem;
  12759. std::string client_ca_pem;
  12760. std::string client_cert_pem, client_key_pem;
  12761. read_file(SERVER_CERT_FILE, server_cert_pem);
  12762. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12763. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12764. read_file(client_cert_file, client_cert_pem);
  12765. read_file(client_private_key_file, client_key_pem);
  12766. // Create server with PEM memory
  12767. SSLServer::PemMemory server_pem = {
  12768. server_cert_pem.c_str(),
  12769. server_cert_pem.size(),
  12770. server_key_pem.c_str(),
  12771. server_key_pem.size(),
  12772. client_ca_pem.c_str(),
  12773. client_ca_pem.size(),
  12774. nullptr // no password for server key
  12775. };
  12776. SSLServer svr(server_pem);
  12777. ASSERT_TRUE(svr.is_valid());
  12778. svr.Get("/test", [&](const Request &, Response &res) {
  12779. res.set_content("test", "text/plain");
  12780. });
  12781. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12782. auto se = detail::scope_exit([&] {
  12783. svr.stop();
  12784. t.join();
  12785. ASSERT_FALSE(svr.is_running());
  12786. });
  12787. svr.wait_until_ready();
  12788. // Create client with PEM memory
  12789. const char *password = client_encrypted_private_key_pass.empty()
  12790. ? nullptr
  12791. : client_encrypted_private_key_pass.c_str();
  12792. SSLClient::PemMemory client_pem = {
  12793. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  12794. client_key_pem.size(), password};
  12795. SSLClient cli(HOST, PORT, client_pem);
  12796. cli.enable_server_certificate_verification(false);
  12797. cli.set_connection_timeout(30);
  12798. auto res = cli.Get("/test");
  12799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12800. ASSERT_EQ(StatusCode::OK_200, res->status);
  12801. }
  12802. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  12803. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12804. }
  12805. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  12806. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12807. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12808. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12809. }
  12810. TEST(SSLClientServerTest, ClientCertMissing) {
  12811. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12812. CLIENT_CA_CERT_DIR);
  12813. ASSERT_TRUE(svr.is_valid());
  12814. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  12815. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12816. auto se = detail::scope_exit([&] {
  12817. svr.stop();
  12818. t.join();
  12819. ASSERT_FALSE(svr.is_running());
  12820. });
  12821. svr.wait_until_ready();
  12822. SSLClient cli(HOST, PORT);
  12823. cli.set_connection_timeout(30);
  12824. // cert.pem does not match HOST. Skip the hostname check, which runs before
  12825. // the chain check on Windows, so the result does not depend on the order.
  12826. cli.enable_server_hostname_verification(false);
  12827. auto res = cli.Get("/test");
  12828. ASSERT_TRUE(!res);
  12829. // When client cert is missing and server requires it, connection fails
  12830. // Error type depends on backend implementation
  12831. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12832. res.error() == Error::SSLConnection);
  12833. // Verify backend error is captured
  12834. // Note: This test may have different error codes depending on the exact
  12835. // verification failure
  12836. EXPECT_NE(0UL, res.ssl_backend_error());
  12837. }
  12838. TEST(SSLClientServerTest, TrustDirOptional) {
  12839. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12840. ASSERT_TRUE(svr.is_valid());
  12841. svr.Get("/test", [&](const Request &, Response &res) {
  12842. res.set_content("test", "text/plain");
  12843. });
  12844. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12845. auto se = detail::scope_exit([&] {
  12846. svr.stop();
  12847. t.join();
  12848. ASSERT_FALSE(svr.is_running());
  12849. });
  12850. svr.wait_until_ready();
  12851. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12852. cli.enable_server_certificate_verification(false);
  12853. cli.set_connection_timeout(30);
  12854. auto res = cli.Get("/test");
  12855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12856. ASSERT_EQ(StatusCode::OK_200, res->status);
  12857. }
  12858. TEST(SSLClientServerTest, SSLConnectTimeout) {
  12859. class NoListenSSLServer : public SSLServer {
  12860. public:
  12861. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  12862. const char *client_ca_cert_file_path,
  12863. const char *client_ca_cert_dir_path = nullptr)
  12864. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  12865. client_ca_cert_dir_path),
  12866. stop_(false) {}
  12867. std::atomic_bool stop_;
  12868. private:
  12869. bool process_and_close_socket(socket_t /*sock*/) override {
  12870. // Don't create SSL context
  12871. while (!stop_.load()) {
  12872. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  12873. }
  12874. return true;
  12875. }
  12876. };
  12877. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12878. CLIENT_CA_CERT_FILE);
  12879. ASSERT_TRUE(svr.is_valid());
  12880. svr.Get("/test", [&](const Request &, Response &res) {
  12881. res.set_content("test", "text/plain");
  12882. });
  12883. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12884. auto se = detail::scope_exit([&] {
  12885. svr.stop_ = true;
  12886. svr.stop();
  12887. t.join();
  12888. ASSERT_FALSE(svr.is_running());
  12889. });
  12890. svr.wait_until_ready();
  12891. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12892. cli.enable_server_certificate_verification(false);
  12893. cli.set_connection_timeout(1);
  12894. auto res = cli.Get("/test");
  12895. ASSERT_TRUE(!res);
  12896. EXPECT_EQ(Error::SSLConnection, res.error());
  12897. // Timeout results in WantRead error code (maps to backend-specific value)
  12898. EXPECT_NE(0, res.ssl_error());
  12899. }
  12900. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  12901. // Test SSLServer with client certificate verification using the standard
  12902. // constructor (ContextSetupCallback is tested by backend-specific tests)
  12903. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12904. CLIENT_CA_CERT_DIR);
  12905. ASSERT_TRUE(svr.is_valid());
  12906. svr.Get("/test", [&](const Request &req, Response &res) {
  12907. res.set_content("test", "text/plain");
  12908. auto cert = req.peer_cert();
  12909. ASSERT_TRUE(static_cast<bool>(cert));
  12910. auto common_name = cert.subject_cn();
  12911. EXPECT_EQ("Common Name", common_name);
  12912. });
  12913. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12914. auto se = detail::scope_exit([&] {
  12915. svr.stop();
  12916. t.join();
  12917. ASSERT_FALSE(svr.is_running());
  12918. });
  12919. svr.wait_until_ready();
  12920. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12921. cli.enable_server_certificate_verification(false);
  12922. cli.set_connection_timeout(30);
  12923. auto res = cli.Get("/test");
  12924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12925. ASSERT_EQ(StatusCode::OK_200, res->status);
  12926. }
  12927. // Test verify_hostname for both OpenSSL and MbedTLS backends
  12928. // Verifies that wildcard matching and exact matching work consistently
  12929. TEST(SSLClientServerTest, TlsVerifyHostname) {
  12930. using namespace httplib::tls;
  12931. // We need a running server to test against
  12932. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12933. ASSERT_TRUE(svr.is_valid());
  12934. svr.Get("/test", [](const Request &, Response &res) {
  12935. res.set_content("ok", "text/plain");
  12936. });
  12937. thread t([&]() { svr.listen(HOST, PORT); });
  12938. auto se = detail::scope_exit([&] {
  12939. svr.stop();
  12940. t.join();
  12941. });
  12942. svr.wait_until_ready();
  12943. bool verify_callback_called = false;
  12944. bool verify_result_wrong = false;
  12945. SSLClient cli(HOST, PORT);
  12946. cli.enable_server_certificate_verification(true);
  12947. cli.set_ca_cert_path(CA_CERT_FILE);
  12948. cli.set_connection_timeout(5);
  12949. // Note: Test certificate has CN="Common Name", not "localhost"
  12950. bool verify_result_cn = false;
  12951. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12952. verify_callback_called = true;
  12953. if (!ctx.cert) return false;
  12954. // Test 1: "Common Name" should match (our test server cert CN)
  12955. verify_result_cn = ctx.check_hostname("Common Name");
  12956. // Test 2: wrong hostname should not match
  12957. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  12958. return true; // Accept for the purpose of this test
  12959. });
  12960. auto res = cli.Get("/test");
  12961. // The request may succeed or fail depending on cert configuration
  12962. // but the callback should have been called
  12963. ASSERT_TRUE(verify_callback_called)
  12964. << "Verify callback should have been called";
  12965. // CN="Common Name" should match our test certificate
  12966. //
  12967. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  12968. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  12969. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  12970. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  12971. // <openssl/base.h>, which is included transitively when
  12972. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  12973. #if defined(OPENSSL_IS_BORINGSSL)
  12974. EXPECT_FALSE(verify_result_cn)
  12975. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  12976. #else
  12977. EXPECT_TRUE(verify_result_cn)
  12978. << "verify_hostname should match 'Common Name' (certificate CN)";
  12979. #endif
  12980. // Wrong hostname should not match
  12981. EXPECT_FALSE(verify_result_wrong)
  12982. << "verify_hostname should not match 'wronghost.example.com'";
  12983. }
  12984. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  12985. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  12986. // X509_check_ip behavior and must hold for every backend.
  12987. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  12988. using namespace httplib::tls;
  12989. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  12990. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  12991. ASSERT_TRUE(svr.is_valid());
  12992. svr.Get("/test", [](const Request &, Response &res) {
  12993. res.set_content("ok", "text/plain");
  12994. });
  12995. thread t([&]() { svr.listen(HOST, PORT); });
  12996. auto se = detail::scope_exit([&] {
  12997. svr.stop();
  12998. t.join();
  12999. });
  13000. svr.wait_until_ready();
  13001. bool verify_callback_called = false;
  13002. bool ip_matched_via_cn = true;
  13003. SSLClient cli(HOST, PORT);
  13004. cli.enable_server_certificate_verification(true);
  13005. cli.set_ca_cert_path(CA_CERT_FILE);
  13006. cli.set_connection_timeout(5);
  13007. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13008. verify_callback_called = true;
  13009. if (!ctx.cert) return false;
  13010. // The IP appears only in the CN, so it must NOT be accepted.
  13011. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  13012. return true; // Accept for the purpose of this test
  13013. });
  13014. cli.Get("/test");
  13015. ASSERT_TRUE(verify_callback_called)
  13016. << "Verify callback should have been called";
  13017. EXPECT_FALSE(ip_matched_via_cn)
  13018. << "An IP host must not be authenticated via the certificate CN";
  13019. }
  13020. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  13021. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  13022. using namespace httplib::tls;
  13023. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  13024. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  13025. ASSERT_TRUE(svr.is_valid());
  13026. svr.Get("/test", [](const Request &, Response &res) {
  13027. res.set_content("ok", "text/plain");
  13028. });
  13029. thread t([&]() { svr.listen(HOST, PORT); });
  13030. auto se = detail::scope_exit([&] {
  13031. svr.stop();
  13032. t.join();
  13033. });
  13034. svr.wait_until_ready();
  13035. bool verify_callback_called = false;
  13036. bool san_matched = false;
  13037. bool wrong_ipv6_matched = true;
  13038. bool cn_ipv6_matched = true;
  13039. SSLClient cli(HOST, PORT);
  13040. cli.enable_server_certificate_verification(true);
  13041. cli.set_ca_cert_path(CA_CERT_FILE);
  13042. cli.set_connection_timeout(5);
  13043. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13044. verify_callback_called = true;
  13045. if (!ctx.cert) return false;
  13046. // Matches the IPv6 iPAddress SAN.
  13047. san_matched = ctx.check_hostname("2001:db8::1");
  13048. // A different IPv6 address must not match.
  13049. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  13050. // "::1" lives only in the CN, so it must not be accepted.
  13051. cn_ipv6_matched = ctx.check_hostname("::1");
  13052. return true; // Accept for the purpose of this test
  13053. });
  13054. cli.Get("/test");
  13055. ASSERT_TRUE(verify_callback_called)
  13056. << "Verify callback should have been called";
  13057. EXPECT_TRUE(san_matched)
  13058. << "verify_hostname should match an IPv6 iPAddress SAN";
  13059. EXPECT_FALSE(wrong_ipv6_matched)
  13060. << "verify_hostname should not match a non-matching IPv6 address";
  13061. EXPECT_FALSE(cn_ipv6_matched)
  13062. << "An IPv6 host must not be authenticated via the certificate CN";
  13063. }
  13064. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  13065. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  13066. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  13067. using namespace httplib::tls;
  13068. // SANs: DNS:a.zz, IP:42.46.122.122
  13069. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13070. ASSERT_TRUE(svr.is_valid());
  13071. svr.Get("/test", [](const Request &, Response &res) {
  13072. res.set_content("ok", "text/plain");
  13073. });
  13074. auto port = svr.bind_to_any_port(HOST);
  13075. thread t([&]() { svr.listen_after_bind(); });
  13076. auto se = detail::scope_exit([&] {
  13077. svr.stop();
  13078. t.join();
  13079. });
  13080. svr.wait_until_ready();
  13081. bool verify_callback_called = false;
  13082. bool dns_san_matched = false;
  13083. bool ip_san_matched = false;
  13084. bool ip_matched_via_dns_san = true;
  13085. bool dns_matched_via_ip_san = true;
  13086. SSLClient cli(HOST, port);
  13087. cli.enable_server_certificate_verification(true);
  13088. cli.set_ca_cert_path(CA_CERT_FILE);
  13089. cli.set_connection_timeout(5);
  13090. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13091. verify_callback_called = true;
  13092. if (!ctx.cert) return false;
  13093. dns_san_matched = ctx.check_hostname("a.zz");
  13094. ip_san_matched = ctx.check_hostname("42.46.122.122");
  13095. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  13096. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  13097. return true; // Accept for the purpose of this test
  13098. });
  13099. cli.Get("/test");
  13100. ASSERT_TRUE(verify_callback_called)
  13101. << "Verify callback should have been called";
  13102. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  13103. EXPECT_TRUE(ip_san_matched)
  13104. << "verify_hostname should match an iPAddress SAN";
  13105. EXPECT_FALSE(ip_matched_via_dns_san)
  13106. << "An IP host must not be authenticated via a dNSName SAN";
  13107. EXPECT_FALSE(dns_matched_via_ip_san)
  13108. << "A DNS host must not be authenticated via an iPAddress SAN";
  13109. }
  13110. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  13111. // "www.*.example.test" names one host and not every host under example.test.
  13112. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  13113. using namespace httplib::tls;
  13114. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  13115. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  13116. ASSERT_TRUE(svr.is_valid());
  13117. svr.Get("/test", [](const Request &, Response &res) {
  13118. res.set_content("ok", "text/plain");
  13119. });
  13120. auto port = svr.bind_to_any_port(HOST);
  13121. thread t([&]() { svr.listen_after_bind(); });
  13122. auto se = detail::scope_exit([&] {
  13123. svr.stop();
  13124. t.join();
  13125. });
  13126. svr.wait_until_ready();
  13127. bool verify_callback_called = false;
  13128. bool leftmost_wildcard_matched = false;
  13129. bool wildcard_spanned_labels = true;
  13130. bool inner_wildcard_matched = true;
  13131. SSLClient cli(HOST, port);
  13132. cli.enable_server_certificate_verification(true);
  13133. cli.set_ca_cert_path(CA_CERT_FILE);
  13134. cli.set_connection_timeout(5);
  13135. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13136. verify_callback_called = true;
  13137. if (!ctx.cert) return false;
  13138. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  13139. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  13140. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  13141. return true; // Accept for the purpose of this test
  13142. });
  13143. cli.Get("/test");
  13144. ASSERT_TRUE(verify_callback_called)
  13145. << "Verify callback should have been called";
  13146. EXPECT_TRUE(leftmost_wildcard_matched)
  13147. << "A leftmost wildcard should match a single label";
  13148. EXPECT_FALSE(wildcard_spanned_labels)
  13149. << "A wildcard label must not match more than one label";
  13150. EXPECT_FALSE(inner_wildcard_matched)
  13151. << "A wildcard outside the leftmost label must not be honoured";
  13152. }
  13153. // sans() must report each SAN entry under its own type.
  13154. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  13155. using namespace httplib::tls;
  13156. // SANs: DNS:a.zz, IP:42.46.122.122
  13157. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13158. ASSERT_TRUE(svr.is_valid());
  13159. svr.Get("/test", [](const Request &, Response &res) {
  13160. res.set_content("ok", "text/plain");
  13161. });
  13162. auto port = svr.bind_to_any_port(HOST);
  13163. thread t([&]() { svr.listen_after_bind(); });
  13164. auto se = detail::scope_exit([&] {
  13165. svr.stop();
  13166. t.join();
  13167. });
  13168. svr.wait_until_ready();
  13169. bool verify_callback_called = false;
  13170. std::vector<SanEntry> sans;
  13171. SSLClient cli(HOST, port);
  13172. cli.enable_server_certificate_verification(true);
  13173. cli.set_ca_cert_path(CA_CERT_FILE);
  13174. cli.set_connection_timeout(5);
  13175. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13176. verify_callback_called = true;
  13177. if (!ctx.cert) return false;
  13178. sans = ctx.sans();
  13179. return true; // Accept for the purpose of this test
  13180. });
  13181. cli.Get("/test");
  13182. ASSERT_TRUE(verify_callback_called)
  13183. << "Verify callback should have been called";
  13184. auto has_san = [&](SanType type, const std::string &value) {
  13185. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  13186. return san.type == type && san.value == value;
  13187. });
  13188. };
  13189. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  13190. << "sans() should report the dNSName SAN";
  13191. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  13192. << "sans() should report the iPAddress SAN";
  13193. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  13194. << "sans() must not report the dNSName SAN as an address";
  13195. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  13196. << "sans() must not report the iPAddress SAN as a DNS name";
  13197. }
  13198. #endif
  13199. // mbedTLS-specific callback constructor test
  13200. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  13201. #ifdef CPPHTTPLIB_SSL_ENABLED
  13202. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  13203. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13204. ASSERT_TRUE(svr.is_valid());
  13205. // Set up a handler to verify client certificate is present
  13206. bool client_cert_verified = false;
  13207. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13208. // Verify that client certificate was provided
  13209. client_cert_verified = true;
  13210. res.set_content("success", "text/plain");
  13211. });
  13212. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13213. auto se = detail::scope_exit([&] {
  13214. svr.stop();
  13215. t.join();
  13216. ASSERT_FALSE(svr.is_running());
  13217. });
  13218. svr.wait_until_ready();
  13219. // Client with certificate
  13220. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13221. cli.enable_server_certificate_verification(false);
  13222. cli.set_connection_timeout(30);
  13223. auto res = cli.Get("/test");
  13224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13225. ASSERT_EQ(StatusCode::OK_200, res->status);
  13226. ASSERT_TRUE(client_cert_verified);
  13227. EXPECT_EQ("success", res->body);
  13228. }
  13229. #endif
  13230. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  13231. // backends
  13232. #ifdef CPPHTTPLIB_SSL_ENABLED
  13233. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  13234. using namespace httplib::tls;
  13235. // Test that when client CA cert file is provided,
  13236. // the server properly requests and validates client certificates
  13237. // Create a server with client authentication
  13238. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13239. ASSERT_TRUE(svr.is_valid());
  13240. bool handler_called = false;
  13241. svr.Get("/test", [&](const Request &req, Response &res) {
  13242. handler_called = true;
  13243. // Verify that a client certificate was provided
  13244. auto cert = req.peer_cert();
  13245. ASSERT_TRUE(static_cast<bool>(cert));
  13246. // Get the issuer name
  13247. std::string issuer_str = cert.issuer_name();
  13248. ASSERT_FALSE(issuer_str.empty());
  13249. // The client certificate should be issued by our test CA
  13250. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  13251. res.set_content("authenticated", "text/plain");
  13252. });
  13253. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13254. auto se = detail::scope_exit([&] {
  13255. svr.stop();
  13256. t.join();
  13257. ASSERT_FALSE(svr.is_running());
  13258. });
  13259. svr.wait_until_ready();
  13260. // Connect with a client certificate issued by the CA
  13261. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13262. cli.enable_server_certificate_verification(false);
  13263. cli.set_connection_timeout(30);
  13264. auto res = cli.Get("/test");
  13265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13266. ASSERT_EQ(StatusCode::OK_200, res->status);
  13267. ASSERT_TRUE(handler_called);
  13268. EXPECT_EQ("authenticated", res->body);
  13269. }
  13270. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  13271. using namespace httplib::tls;
  13272. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13273. ASSERT_TRUE(svr.is_valid());
  13274. svr.Get("/test", [](const Request &, Response &res) {
  13275. res.set_content("ok", "text/plain");
  13276. });
  13277. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13278. auto se = detail::scope_exit([&] {
  13279. svr.stop();
  13280. t.join();
  13281. });
  13282. svr.wait_until_ready();
  13283. SSLClient cli(HOST, PORT);
  13284. cli.enable_server_certificate_verification(false);
  13285. cli.set_connection_timeout(30);
  13286. bool cert_checked = false;
  13287. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13288. if (ctx.cert) {
  13289. auto sans = ctx.sans();
  13290. // Test certificate may or may not have SANs - just verify the API
  13291. // works If SANs exist, verify the types are valid
  13292. for (const auto &san : sans) {
  13293. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  13294. san.type == SanType::EMAIL || san.type == SanType::URI ||
  13295. san.type == SanType::OTHER);
  13296. EXPECT_FALSE(san.value.empty());
  13297. }
  13298. cert_checked = true;
  13299. }
  13300. return true;
  13301. });
  13302. auto res = cli.Get("/test");
  13303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13304. EXPECT_TRUE(cert_checked);
  13305. }
  13306. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  13307. using namespace httplib::tls;
  13308. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13309. ASSERT_TRUE(svr.is_valid());
  13310. svr.Get("/test", [](const Request &, Response &res) {
  13311. res.set_content("ok", "text/plain");
  13312. });
  13313. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13314. auto se = detail::scope_exit([&] {
  13315. svr.stop();
  13316. t.join();
  13317. });
  13318. svr.wait_until_ready();
  13319. SSLClient cli(HOST, PORT);
  13320. cli.enable_server_certificate_verification(false);
  13321. cli.set_connection_timeout(30);
  13322. bool validity_checked = false;
  13323. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13324. if (ctx.cert) {
  13325. time_t not_before = 0, not_after = 0;
  13326. bool result = ctx.validity(not_before, not_after);
  13327. EXPECT_TRUE(result);
  13328. // Verify that not_before < now < not_after for a valid cert
  13329. time_t now = time(nullptr);
  13330. EXPECT_LT(not_before, now);
  13331. EXPECT_GT(not_after, now);
  13332. validity_checked = true;
  13333. }
  13334. return true;
  13335. });
  13336. auto res = cli.Get("/test");
  13337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13338. EXPECT_TRUE(validity_checked);
  13339. }
  13340. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  13341. using namespace httplib::tls;
  13342. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13343. ASSERT_TRUE(svr.is_valid());
  13344. svr.Get("/test", [](const Request &, Response &res) {
  13345. res.set_content("ok", "text/plain");
  13346. });
  13347. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13348. auto se = detail::scope_exit([&] {
  13349. svr.stop();
  13350. t.join();
  13351. });
  13352. svr.wait_until_ready();
  13353. SSLClient cli(HOST, PORT);
  13354. cli.enable_server_certificate_verification(false);
  13355. cli.set_connection_timeout(30);
  13356. bool serial_checked = false;
  13357. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13358. if (ctx.cert) {
  13359. std::string serial = ctx.serial();
  13360. EXPECT_FALSE(serial.empty());
  13361. // Serial should be a hex string
  13362. for (char c : serial) {
  13363. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  13364. (c >= 'a' && c <= 'f'));
  13365. }
  13366. serial_checked = true;
  13367. }
  13368. return true;
  13369. });
  13370. auto res = cli.Get("/test");
  13371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13372. EXPECT_TRUE(serial_checked);
  13373. }
  13374. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  13375. // Test 1: Valid CA file - no error should be recorded
  13376. {
  13377. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13378. CLIENT_CA_CERT_FILE);
  13379. ASSERT_TRUE(svr.is_valid());
  13380. // With valid setup, last_ssl_error should be 0
  13381. EXPECT_EQ(0, svr.ssl_last_error());
  13382. }
  13383. // Test 2: Invalid CA file content
  13384. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  13385. {
  13386. // Create a temporary file with completely invalid content
  13387. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  13388. {
  13389. std::ofstream ofs(temp_invalid_ca);
  13390. ofs << "This is not a certificate file at all\n";
  13391. ofs << "Just plain text content\n";
  13392. }
  13393. // Create server with invalid CA file
  13394. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  13395. // Clean up temporary file
  13396. std::remove(temp_invalid_ca);
  13397. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  13398. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  13399. // Note: SSL_CTX_load_verify_locations typically fails first,
  13400. // but our error handling code path is still exercised
  13401. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  13402. }
  13403. }
  13404. TEST(VerifyCallbackTest, VerifyContextFields) {
  13405. using namespace httplib::tls;
  13406. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13407. ASSERT_TRUE(svr.is_valid());
  13408. svr.Get("/test", [](const Request &, Response &res) {
  13409. res.set_content("ok", "text/plain");
  13410. });
  13411. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13412. auto se = detail::scope_exit([&] {
  13413. svr.stop();
  13414. t.join();
  13415. });
  13416. svr.wait_until_ready();
  13417. SSLClient cli(HOST, PORT);
  13418. cli.enable_server_certificate_verification(false);
  13419. cli.set_connection_timeout(30);
  13420. int callback_count = 0;
  13421. bool saw_leaf_cert = false;
  13422. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13423. if (ctx.cert) {
  13424. callback_count++;
  13425. // We should see at least one certificate (the leaf)
  13426. std::string cn = ctx.subject_cn();
  13427. if (!cn.empty()) { saw_leaf_cert = true; }
  13428. // Verify context fields are populated
  13429. EXPECT_NE(ctx.session, nullptr);
  13430. EXPECT_GE(ctx.depth, 0);
  13431. }
  13432. return true;
  13433. });
  13434. auto res = cli.Get("/test");
  13435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13436. EXPECT_GT(callback_count, 0);
  13437. EXPECT_TRUE(saw_leaf_cert);
  13438. }
  13439. // A verifier belongs to the client that set it, not to the thread that set it.
  13440. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  13441. using namespace httplib::tls;
  13442. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13443. ASSERT_TRUE(svr.is_valid());
  13444. svr.Get("/test", [](const Request &, Response &res) {
  13445. res.set_content("ok", "text/plain");
  13446. });
  13447. auto port = svr.bind_to_any_port(HOST);
  13448. thread t([&]() { svr.listen_after_bind(); });
  13449. auto se = detail::scope_exit([&] {
  13450. svr.stop();
  13451. t.join();
  13452. });
  13453. svr.wait_until_ready();
  13454. auto rejecting_calls = 0;
  13455. SSLClient rejecting(HOST, port);
  13456. rejecting.enable_server_certificate_verification(false);
  13457. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  13458. rejecting_calls++;
  13459. return false;
  13460. });
  13461. auto accepting_calls = 0;
  13462. SSLClient accepting(HOST, port);
  13463. accepting.enable_server_certificate_verification(false);
  13464. // Set on another thread than the requests below.
  13465. thread([&]() {
  13466. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  13467. accepting_calls++;
  13468. return true;
  13469. });
  13470. }).join();
  13471. // Requested on another thread than the verifier was set on.
  13472. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  13473. EXPECT_GT(rejecting_calls, 0);
  13474. auto res = accepting.Get("/test");
  13475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13476. EXPECT_GT(accepting_calls, 0);
  13477. }
  13478. // VerifyContext::session is the same handle the other tls:: functions take.
  13479. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  13480. using namespace httplib::tls;
  13481. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13482. ASSERT_TRUE(svr.is_valid());
  13483. svr.Get("/test", [](const Request &, Response &res) {
  13484. res.set_content("ok", "text/plain");
  13485. });
  13486. auto port = svr.bind_to_any_port(HOST);
  13487. thread t([&]() { svr.listen_after_bind(); });
  13488. auto se = detail::scope_exit([&] {
  13489. svr.stop();
  13490. t.join();
  13491. });
  13492. svr.wait_until_ready();
  13493. SSLClient cli(HOST, port);
  13494. cli.enable_server_certificate_verification(false);
  13495. session_t verifier_session = nullptr;
  13496. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  13497. verifier_session = ctx.session;
  13498. return true;
  13499. });
  13500. session_t session_verifier_session = nullptr;
  13501. cli.set_session_verifier([&](session_t session) {
  13502. session_verifier_session = session;
  13503. return SSLVerifierResponse::NoDecisionMade;
  13504. });
  13505. auto res = cli.Get("/test");
  13506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13507. EXPECT_NE(nullptr, verifier_session);
  13508. EXPECT_EQ(session_verifier_session, verifier_session);
  13509. }
  13510. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  13511. using httplib::tls::TlsError;
  13512. // Test that verify_error_to_string returns empty for success
  13513. std::string success_str = TlsError::verify_error_to_string(0);
  13514. EXPECT_TRUE(success_str.empty());
  13515. // Test that verify_error_to_string returns non-empty for error codes
  13516. // Using a common error code (certificate expired)
  13517. std::string error_str =
  13518. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  13519. EXPECT_FALSE(error_str.empty());
  13520. }
  13521. TEST(SessionVerifierTest, CertificateAccepted) {
  13522. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13523. ASSERT_TRUE(svr.is_valid());
  13524. svr.Get("/test", [](const Request &, Response &res) {
  13525. res.set_content("ok", "text/plain");
  13526. });
  13527. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13528. auto se = detail::scope_exit([&] {
  13529. svr.stop();
  13530. t.join();
  13531. });
  13532. svr.wait_until_ready();
  13533. SSLClient cli(HOST, PORT);
  13534. cli.enable_server_certificate_verification(false);
  13535. cli.set_connection_timeout(30);
  13536. bool callback_called = false;
  13537. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13538. EXPECT_NE(session, nullptr);
  13539. callback_called = true;
  13540. return SSLVerifierResponse::CertificateAccepted;
  13541. });
  13542. auto res = cli.Get("/test");
  13543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13544. EXPECT_EQ(200, res->status);
  13545. EXPECT_TRUE(callback_called);
  13546. }
  13547. TEST(SessionVerifierTest, CertificateRejected) {
  13548. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13549. ASSERT_TRUE(svr.is_valid());
  13550. svr.Get("/test", [](const Request &, Response &res) {
  13551. res.set_content("ok", "text/plain");
  13552. });
  13553. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13554. auto se = detail::scope_exit([&] {
  13555. svr.stop();
  13556. t.join();
  13557. });
  13558. svr.wait_until_ready();
  13559. SSLClient cli(HOST, PORT);
  13560. cli.enable_server_certificate_verification(false);
  13561. cli.set_connection_timeout(30);
  13562. bool callback_called = false;
  13563. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13564. EXPECT_NE(session, nullptr);
  13565. callback_called = true;
  13566. return SSLVerifierResponse::CertificateRejected;
  13567. });
  13568. auto res = cli.Get("/test");
  13569. EXPECT_FALSE(res);
  13570. EXPECT_TRUE(callback_called);
  13571. }
  13572. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  13573. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13574. ASSERT_TRUE(svr.is_valid());
  13575. svr.Get("/test", [](const Request &, Response &res) {
  13576. res.set_content("ok", "text/plain");
  13577. });
  13578. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13579. auto se = detail::scope_exit([&] {
  13580. svr.stop();
  13581. t.join();
  13582. });
  13583. svr.wait_until_ready();
  13584. // NoDecisionMade with verification disabled should succeed (no default check)
  13585. SSLClient cli(HOST, PORT);
  13586. cli.enable_server_certificate_verification(false);
  13587. cli.set_connection_timeout(30);
  13588. bool callback_called = false;
  13589. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13590. EXPECT_NE(session, nullptr);
  13591. callback_called = true;
  13592. return SSLVerifierResponse::NoDecisionMade;
  13593. });
  13594. auto res = cli.Get("/test");
  13595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13596. EXPECT_EQ(200, res->status);
  13597. EXPECT_TRUE(callback_called);
  13598. }
  13599. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  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. // NoDecisionMade with verification enabled should fail (self-signed cert).
  13612. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  13613. // so we only check that the request fails, not whether the callback was
  13614. // called.
  13615. SSLClient cli(HOST, PORT);
  13616. cli.enable_server_certificate_verification(true);
  13617. cli.set_connection_timeout(30);
  13618. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13619. EXPECT_NE(session, nullptr);
  13620. return SSLVerifierResponse::NoDecisionMade;
  13621. });
  13622. auto res = cli.Get("/test");
  13623. EXPECT_FALSE(res);
  13624. }
  13625. TEST(SSLClientServerTest, ClientCAListFromPem) {
  13626. // Test SSL server using PemMemory constructor with client CA certificates
  13627. // Read PEM files
  13628. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13629. read_file(SERVER_CERT_FILE, server_cert_pem);
  13630. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13631. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13632. // Create SSLServer with PemMemory constructor including client CA
  13633. SSLServer::PemMemory server_pem = {
  13634. server_cert_pem.c_str(),
  13635. server_cert_pem.size(),
  13636. server_key_pem.c_str(),
  13637. server_key_pem.size(),
  13638. client_ca_pem.c_str(),
  13639. client_ca_pem.size(),
  13640. nullptr // no password for server key
  13641. };
  13642. SSLServer svr(server_pem);
  13643. ASSERT_TRUE(svr.is_valid());
  13644. // No SSL error should be recorded for valid setup
  13645. EXPECT_EQ(0, svr.ssl_last_error());
  13646. // Set up server endpoints
  13647. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  13648. res.set_content("ok", "text/plain");
  13649. });
  13650. // Start server in a thread
  13651. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  13652. svr.wait_until_ready();
  13653. // Connect with client certificate (using constructor with paths)
  13654. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13655. cli.enable_server_certificate_verification(false);
  13656. auto res = cli.Get("/test-pem-ca");
  13657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13658. EXPECT_EQ(200, res->status);
  13659. EXPECT_EQ("ok", res->body);
  13660. svr.stop();
  13661. server_thread.join();
  13662. }
  13663. #endif
  13664. #ifdef _WIN32
  13665. TEST(CleanupTest, WSACleanup) {
  13666. int ret = WSACleanup();
  13667. ASSERT_EQ(0, ret);
  13668. }
  13669. #endif
  13670. #ifndef CPPHTTPLIB_SSL_ENABLED
  13671. TEST(NoSSLSupport, SimpleInterface) {
  13672. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  13673. }
  13674. #endif
  13675. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  13676. TEST(InvalidScheme, SimpleInterface) {
  13677. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  13678. }
  13679. #endif
  13680. TEST(NoScheme, SimpleInterface) {
  13681. Client cli("yahoo.com:80");
  13682. ASSERT_TRUE(cli.is_valid());
  13683. }
  13684. TEST(SendAPI, SimpleInterface_Online) {
  13685. Client cli("http://yahoo.com");
  13686. Request req;
  13687. req.method = "GET";
  13688. req.path = "/";
  13689. auto res = cli.send(req);
  13690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13691. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13692. }
  13693. TEST(SendAPI, WithParamsInRequest) {
  13694. Server svr;
  13695. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  13696. EXPECT_TRUE(req.has_param("test"));
  13697. EXPECT_EQ("test_value", req.get_param_value("test"));
  13698. });
  13699. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13700. auto se = detail::scope_exit([&] {
  13701. svr.stop();
  13702. t.join();
  13703. ASSERT_FALSE(svr.is_running());
  13704. });
  13705. svr.wait_until_ready();
  13706. Client cli(HOST, PORT);
  13707. {
  13708. Request req;
  13709. req.method = "GET";
  13710. req.path = "/";
  13711. req.params.emplace("test", "test_value");
  13712. auto res = cli.send(req);
  13713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13714. }
  13715. {
  13716. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  13717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13718. }
  13719. }
  13720. TEST(ClientImplMethods, GetSocketTest) {
  13721. httplib::Server svr;
  13722. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  13723. res.status = StatusCode::OK_200;
  13724. });
  13725. auto port = svr.bind_to_any_port("127.0.0.1");
  13726. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13727. auto se = detail::scope_exit([&] {
  13728. svr.stop();
  13729. thread.join();
  13730. ASSERT_FALSE(svr.is_running());
  13731. });
  13732. svr.wait_until_ready();
  13733. {
  13734. httplib::Client cli("127.0.0.1", port);
  13735. cli.set_keep_alive(true);
  13736. // Use the behavior of cpp-httplib of opening the connection
  13737. // only when the first request happens. If that changes,
  13738. // this test would be obsolete.
  13739. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  13740. // This also implicitly tests the server. But other tests would fail much
  13741. // earlier than this one to be considered.
  13742. auto res = cli.Get("/");
  13743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13744. EXPECT_EQ(StatusCode::OK_200, res->status);
  13745. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  13746. }
  13747. }
  13748. #ifdef CPPHTTPLIB_SSL_ENABLED
  13749. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  13750. Client cli("http://yahoo.com");
  13751. auto res = cli.Get("/");
  13752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13753. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13754. cli.set_follow_location(true);
  13755. res = cli.Get("/");
  13756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13757. EXPECT_EQ(StatusCode::OK_200, res->status);
  13758. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13759. }
  13760. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  13761. Client cli("https://yahoo.com");
  13762. auto res = cli.Get("/");
  13763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13764. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13765. cli.set_follow_location(true);
  13766. res = cli.Get("/");
  13767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13768. EXPECT_EQ(StatusCode::OK_200, res->status);
  13769. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13770. }
  13771. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  13772. Client cli("https://yahoo.com");
  13773. auto res = cli.Get("/");
  13774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13775. ASSERT_FALSE(!res);
  13776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13777. ASSERT_FALSE(res == nullptr);
  13778. ASSERT_TRUE(res != nullptr);
  13779. EXPECT_EQ(Error::Success, res.error());
  13780. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  13781. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  13782. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13783. cli.set_follow_location(true);
  13784. res = cli.Get("/");
  13785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13786. EXPECT_EQ(Error::Success, res.error());
  13787. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  13788. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  13789. EXPECT_EQ(StatusCode::OK_200, res->status);
  13790. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13791. }
  13792. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13793. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  13794. Client cli("https://cdnjs.cloudflare.com");
  13795. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  13796. Headers{{"Accept-Encoding", "br"}});
  13797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13798. EXPECT_EQ(StatusCode::OK_200, res->status);
  13799. EXPECT_EQ(287630U, res->body.size());
  13800. EXPECT_EQ("application/javascript; charset=utf-8",
  13801. res->get_header_value("Content-Type"));
  13802. }
  13803. #endif
  13804. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  13805. #undef REDIR_HOST // Silence compiler warning
  13806. #define REDIR_HOST "https://httpbingo.org"
  13807. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  13808. Client cli(REDIR_HOST);
  13809. cli.set_follow_location(true);
  13810. auto res =
  13811. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  13812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13813. EXPECT_EQ(StatusCode::OK_200, res->status);
  13814. }
  13815. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  13816. Client cli(REDIR_HOST);
  13817. cli.set_follow_location(true);
  13818. Params params;
  13819. params.emplace("url", "http://example.com");
  13820. params.emplace("status_code", "302");
  13821. auto res = cli.Get(REDIR_PATH, params, Headers{});
  13822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13823. EXPECT_EQ(StatusCode::OK_200, res->status);
  13824. }
  13825. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  13826. Client cli(REDIR_HOST);
  13827. cli.set_follow_location(true);
  13828. Params params;
  13829. params.emplace("url", "http://example.com");
  13830. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  13831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13832. EXPECT_EQ(StatusCode::OK_200, res->status);
  13833. }
  13834. TEST(HttpToHttpsRedirectTest, CertFile) {
  13835. auto ssl_port = PORT + 1;
  13836. Server svr;
  13837. ASSERT_TRUE(svr.is_valid());
  13838. svr.Get("/index", [&](const Request &, Response &res) {
  13839. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13840. "/index");
  13841. svr.stop();
  13842. });
  13843. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13844. ASSERT_TRUE(ssl_svr.is_valid());
  13845. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  13846. res.set_content("test", "text/plain");
  13847. ssl_svr.stop();
  13848. });
  13849. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13850. thread t2 =
  13851. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  13852. auto se = detail::scope_exit([&] {
  13853. t2.join();
  13854. t.join();
  13855. ASSERT_FALSE(svr.is_running());
  13856. });
  13857. svr.wait_until_ready();
  13858. ssl_svr.wait_until_ready();
  13859. Client cli("127.0.0.1", PORT);
  13860. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13861. cli.enable_server_certificate_verification(true);
  13862. cli.set_follow_location(true);
  13863. cli.set_connection_timeout(30);
  13864. auto res = cli.Get("/index");
  13865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13866. ASSERT_EQ(StatusCode::OK_200, res->status);
  13867. }
  13868. TEST(SSLClientRedirectTest, CertFile) {
  13869. auto ssl_port = PORT + 1;
  13870. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13871. ASSERT_TRUE(ssl_svr1.is_valid());
  13872. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13873. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13874. "/index");
  13875. ssl_svr1.stop();
  13876. });
  13877. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13878. ASSERT_TRUE(ssl_svr2.is_valid());
  13879. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13880. res.set_content("test", "text/plain");
  13881. ssl_svr2.stop();
  13882. });
  13883. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13884. thread t2 =
  13885. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13886. auto se = detail::scope_exit([&] {
  13887. t2.join();
  13888. t.join();
  13889. ASSERT_FALSE(ssl_svr1.is_running());
  13890. });
  13891. ssl_svr1.wait_until_ready();
  13892. ssl_svr2.wait_until_ready();
  13893. SSLClient cli("127.0.0.1", PORT);
  13894. std::string cert;
  13895. read_file(SERVER_CERT2_FILE, cert);
  13896. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13897. cli.enable_server_certificate_verification(true);
  13898. cli.set_follow_location(true);
  13899. cli.set_connection_timeout(30);
  13900. auto res = cli.Get("/index");
  13901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13902. ASSERT_EQ(StatusCode::OK_200, res->status);
  13903. }
  13904. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  13905. // another port, so the client follows it with a new client.
  13906. static Result GetThroughTlsRedirectToDifferentPort(
  13907. const std::function<void(SSLClient &)> &setup,
  13908. const char *target_cert = SERVER_CERT2_FILE) {
  13909. auto ssl_port = PORT + 1;
  13910. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13911. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13912. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13913. "/index");
  13914. });
  13915. SSLServer ssl_svr2(target_cert, SERVER_PRIVATE_KEY_FILE);
  13916. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13917. res.set_content("test", "text/plain");
  13918. });
  13919. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  13920. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  13921. auto se = detail::scope_exit([&] {
  13922. ssl_svr2.stop();
  13923. ssl_svr1.stop();
  13924. t2.join();
  13925. t.join();
  13926. });
  13927. ssl_svr1.wait_until_ready();
  13928. ssl_svr2.wait_until_ready();
  13929. SSLClient cli("127.0.0.1", PORT);
  13930. cli.set_follow_location(true);
  13931. cli.set_connection_timeout(30);
  13932. setup(cli);
  13933. return cli.Get("/index");
  13934. }
  13935. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  13936. auto calls = 0;
  13937. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  13938. cli.enable_server_certificate_verification(false);
  13939. // Accept the first server only.
  13940. cli.set_session_verifier([&](tls::session_t) {
  13941. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  13942. : SSLVerifierResponse::CertificateRejected;
  13943. });
  13944. });
  13945. EXPECT_FALSE(res);
  13946. EXPECT_EQ(2, calls);
  13947. }
  13948. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  13949. std::string pinned;
  13950. auto res = GetThroughTlsRedirectToDifferentPort(
  13951. [&](SSLClient &cli) {
  13952. cli.enable_server_certificate_verification(false);
  13953. // Pin the first certificate seen.
  13954. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  13955. if (pinned.empty()) { pinned = ctx.serial(); }
  13956. return ctx.serial() == pinned;
  13957. });
  13958. },
  13959. // A certificate other than the first server's.
  13960. SERVER_CERT_FILE);
  13961. EXPECT_FALSE(res);
  13962. EXPECT_FALSE(pinned.empty());
  13963. }
  13964. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  13965. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  13966. std::string cert;
  13967. read_file(SERVER_CERT2_FILE, cert);
  13968. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13969. });
  13970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13971. EXPECT_EQ(StatusCode::OK_200, res->status);
  13972. }
  13973. #endif
  13974. #ifdef CPPHTTPLIB_SSL_ENABLED
  13975. // Test that set_ca_cert_store() skips system certs (consistent with
  13976. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  13977. // should be trusted - system certs should NOT be loaded.
  13978. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  13979. // Load a specific cert that is NOT a system CA cert
  13980. std::string cert;
  13981. read_file(SERVER_CERT2_FILE, cert);
  13982. SSLClient cli("google.com");
  13983. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13984. cli.enable_server_certificate_verification(true);
  13985. // This should FAIL because:
  13986. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  13987. // 2. System certs should NOT be loaded when custom store is set
  13988. // If system certs WERE loaded, this would succeed
  13989. auto res = cli.Get("/");
  13990. ASSERT_FALSE(res);
  13991. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13992. }
  13993. // Same as above, but through the native store handle path. Regression test:
  13994. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  13995. // merged system certs into the user-provided store.
  13996. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  13997. std::string cert;
  13998. read_file(SERVER_CERT2_FILE, cert);
  13999. SSLClient cli("google.com");
  14000. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14001. cli.enable_server_certificate_verification(true);
  14002. auto res = cli.Get("/");
  14003. ASSERT_FALSE(res);
  14004. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14005. }
  14006. // A custom store set via the native handle must still verify a server whose
  14007. // cert it does contain.
  14008. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  14009. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14010. ASSERT_TRUE(svr.is_valid());
  14011. svr.Get("/test", [&](const Request &, Response &res) {
  14012. res.set_content("test", "text/plain");
  14013. });
  14014. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14015. auto se = detail::scope_exit([&] {
  14016. svr.stop();
  14017. t.join();
  14018. ASSERT_FALSE(svr.is_running());
  14019. });
  14020. svr.wait_until_ready();
  14021. SSLClient cli("127.0.0.1", PORT);
  14022. std::string cert;
  14023. read_file(SERVER_CERT2_FILE, cert);
  14024. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14025. cli.enable_server_certificate_verification(true);
  14026. cli.set_connection_timeout(30);
  14027. auto res = cli.Get("/test");
  14028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14029. ASSERT_EQ(StatusCode::OK_200, res->status);
  14030. }
  14031. // CA certs loaded through the universal Client must be transferred to the
  14032. // client created internally for following an HTTPS redirect. Regression test:
  14033. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  14034. // the CA data for redirect transfer.
  14035. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  14036. auto ssl_port = PORT + 1;
  14037. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14038. ASSERT_TRUE(ssl_svr1.is_valid());
  14039. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14040. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14041. "/index");
  14042. });
  14043. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14044. ASSERT_TRUE(ssl_svr2.is_valid());
  14045. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14046. res.set_content("test", "text/plain");
  14047. });
  14048. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14049. thread t2 =
  14050. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14051. auto se = detail::scope_exit([&] {
  14052. ssl_svr2.stop();
  14053. ssl_svr1.stop();
  14054. t2.join();
  14055. t.join();
  14056. ASSERT_FALSE(ssl_svr1.is_running());
  14057. });
  14058. ssl_svr1.wait_until_ready();
  14059. ssl_svr2.wait_until_ready();
  14060. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14061. std::string cert;
  14062. read_file(SERVER_CERT2_FILE, cert);
  14063. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14064. cli.enable_server_certificate_verification(true);
  14065. cli.set_follow_location(true);
  14066. cli.set_connection_timeout(30);
  14067. auto res = cli.Get("/index");
  14068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14069. ASSERT_EQ(StatusCode::OK_200, res->status);
  14070. }
  14071. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  14072. // so a host signed by a system CA verifies even though a custom CA is set
  14073. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  14074. std::string cert;
  14075. read_file(SERVER_CERT2_FILE, cert);
  14076. SSLClient cli("google.com");
  14077. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14078. cli.enable_system_ca(true);
  14079. cli.enable_server_certificate_verification(true);
  14080. auto res = cli.Get("/");
  14081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14082. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14083. }
  14084. // The custom CA remains effective when combined with the system CA
  14085. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  14086. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14087. ASSERT_TRUE(svr.is_valid());
  14088. svr.Get("/test", [&](const Request &, Response &res) {
  14089. res.set_content("test", "text/plain");
  14090. });
  14091. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14092. auto se = detail::scope_exit([&] {
  14093. svr.stop();
  14094. t.join();
  14095. ASSERT_FALSE(svr.is_running());
  14096. });
  14097. svr.wait_until_ready();
  14098. SSLClient cli("127.0.0.1", PORT);
  14099. std::string cert;
  14100. read_file(SERVER_CERT2_FILE, cert);
  14101. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14102. cli.enable_system_ca(true);
  14103. cli.enable_server_certificate_verification(true);
  14104. cli.set_connection_timeout(30);
  14105. auto res = cli.Get("/test");
  14106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14107. ASSERT_EQ(StatusCode::OK_200, res->status);
  14108. }
  14109. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  14110. // skip chain verification entirely (only the certificate identity was
  14111. // checked), so a server presenting an untrusted certificate with a matching
  14112. // IP SAN was accepted. The chain must be validated for IP hosts too.
  14113. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  14114. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14115. ASSERT_TRUE(svr.is_valid());
  14116. svr.Get("/test", [&](const Request &, Response &res) {
  14117. res.set_content("test", "text/plain");
  14118. });
  14119. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14120. auto se = detail::scope_exit([&] {
  14121. svr.stop();
  14122. t.join();
  14123. ASSERT_FALSE(svr.is_running());
  14124. });
  14125. svr.wait_until_ready();
  14126. SSLClient cli("127.0.0.1", PORT);
  14127. std::string cert;
  14128. // A trusted CA that did not sign the server certificate. The server cert
  14129. // (cert2) carries the matching IP SAN, so only chain validation can reject
  14130. // this connection.
  14131. read_file(CLIENT_CA_CERT_FILE, cert);
  14132. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14133. cli.enable_server_certificate_verification(true);
  14134. cli.set_connection_timeout(30);
  14135. auto res = cli.Get("/test");
  14136. ASSERT_FALSE(res);
  14137. }
  14138. // enable_system_ca(false) prevents system CA loading entirely
  14139. TEST(SSLClientTest, DisableSystemCa_Online) {
  14140. SSLClient cli("google.com");
  14141. cli.enable_system_ca(false);
  14142. cli.enable_server_certificate_verification(true);
  14143. auto res = cli.Get("/");
  14144. ASSERT_FALSE(res);
  14145. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  14146. // itself when the CA chain is empty
  14147. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  14148. res.error() == Error::SSLConnection);
  14149. }
  14150. // The universal Client forwards enable_system_ca()
  14151. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  14152. std::string cert;
  14153. read_file(SERVER_CERT2_FILE, cert);
  14154. Client cli("https://google.com");
  14155. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14156. cli.enable_system_ca(true);
  14157. cli.enable_server_certificate_verification(true);
  14158. auto res = cli.Get("/");
  14159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14160. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14161. }
  14162. // The system CA policy must carry over to the client created internally for
  14163. // following a cross-host HTTPS redirect
  14164. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  14165. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14166. ASSERT_TRUE(svr.is_valid());
  14167. svr.Get("/index", [&](const Request &, Response &res) {
  14168. res.set_redirect("https://www.google.com/");
  14169. });
  14170. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14171. auto se = detail::scope_exit([&] {
  14172. svr.stop();
  14173. t.join();
  14174. ASSERT_FALSE(svr.is_running());
  14175. });
  14176. svr.wait_until_ready();
  14177. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14178. std::string cert;
  14179. read_file(SERVER_CERT2_FILE, cert);
  14180. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14181. cli.enable_system_ca(true);
  14182. cli.enable_server_certificate_verification(true);
  14183. cli.set_follow_location(true);
  14184. cli.set_connection_timeout(30);
  14185. // Receiving any response proves the redirect client completed the TLS
  14186. // handshake with a system-CA-signed host
  14187. auto res = cli.Get("/index");
  14188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14189. }
  14190. TEST(MultipartFormDataTest, LargeData) {
  14191. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14192. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  14193. const ContentReader &content_reader) {
  14194. if (req.is_multipart_form_data()) {
  14195. std::vector<FormData> items;
  14196. content_reader(
  14197. [&](const FormData &file) {
  14198. items.push_back(file);
  14199. return true;
  14200. },
  14201. [&](const char *data, size_t data_length) {
  14202. items.back().content.append(data, data_length);
  14203. return true;
  14204. });
  14205. EXPECT_TRUE(std::string(items[0].name) == "document");
  14206. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14207. EXPECT_TRUE(items[0].filename == "2MB_data");
  14208. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14209. EXPECT_TRUE(items[1].name == "hello");
  14210. EXPECT_TRUE(items[1].content == "world");
  14211. EXPECT_TRUE(items[1].filename == "");
  14212. EXPECT_TRUE(items[1].content_type == "");
  14213. } else {
  14214. std::string body;
  14215. content_reader([&](const char *data, size_t data_length) {
  14216. body.append(data, data_length);
  14217. return true;
  14218. });
  14219. }
  14220. });
  14221. auto port = svr.bind_to_any_port(HOST);
  14222. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14223. auto se = detail::scope_exit([&] {
  14224. svr.stop();
  14225. t.join();
  14226. ASSERT_FALSE(svr.is_running());
  14227. });
  14228. svr.wait_until_ready();
  14229. {
  14230. std::string data(1024 * 1024 * 2, '.');
  14231. std::stringstream buffer;
  14232. buffer << data;
  14233. SSLClient cli(HOST, port);
  14234. cli.enable_server_certificate_verification(false);
  14235. UploadFormDataItems items{
  14236. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14237. {"hello", "world", "", ""},
  14238. };
  14239. auto res = cli.Post("/post", items);
  14240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14241. ASSERT_EQ(StatusCode::OK_200, res->status);
  14242. }
  14243. }
  14244. TEST(MultipartFormDataTest, DataProviderItems) {
  14245. std::random_device seed_gen;
  14246. std::mt19937 random(seed_gen());
  14247. std::string rand1;
  14248. rand1.resize(1000);
  14249. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  14250. std::string rand2;
  14251. rand2.resize(3000);
  14252. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  14253. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14254. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  14255. const ContentReader &content_reader) {
  14256. ASSERT_FALSE(req.is_multipart_form_data());
  14257. std::string body;
  14258. content_reader([&](const char *data, size_t data_length) {
  14259. body.append(data, data_length);
  14260. return true;
  14261. });
  14262. EXPECT_EQ(body, "");
  14263. });
  14264. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  14265. const ContentReader &content_reader) {
  14266. ASSERT_TRUE(req.is_multipart_form_data());
  14267. std::vector<FormData> items;
  14268. content_reader(
  14269. [&](const FormData &file) {
  14270. items.push_back(file);
  14271. return true;
  14272. },
  14273. [&](const char *data, size_t data_length) {
  14274. items.back().content.append(data, data_length);
  14275. return true;
  14276. });
  14277. ASSERT_TRUE(items.size() == 2);
  14278. EXPECT_EQ(std::string(items[0].name), "name1");
  14279. EXPECT_EQ(items[0].content, "Testing123");
  14280. EXPECT_EQ(items[0].filename, "filename1");
  14281. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14282. EXPECT_EQ(items[1].name, "name2");
  14283. EXPECT_EQ(items[1].content, "Testing456");
  14284. EXPECT_EQ(items[1].filename, "");
  14285. EXPECT_EQ(items[1].content_type, "");
  14286. });
  14287. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  14288. const ContentReader &content_reader) {
  14289. ASSERT_TRUE(req.is_multipart_form_data());
  14290. std::vector<FormData> items;
  14291. content_reader(
  14292. [&](const FormData &file) {
  14293. items.push_back(file);
  14294. return true;
  14295. },
  14296. [&](const char *data, size_t data_length) {
  14297. items.back().content.append(data, data_length);
  14298. return true;
  14299. });
  14300. ASSERT_TRUE(items.size() == 2);
  14301. EXPECT_EQ(items[0].name, "name3");
  14302. EXPECT_EQ(items[0].content, rand1);
  14303. EXPECT_EQ(items[0].filename, "filename3");
  14304. EXPECT_EQ(items[0].content_type, "");
  14305. EXPECT_EQ(items[1].name, "name4");
  14306. EXPECT_EQ(items[1].content, rand2);
  14307. EXPECT_EQ(items[1].filename, "filename4");
  14308. EXPECT_EQ(items[1].content_type, "");
  14309. });
  14310. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  14311. const ContentReader &content_reader) {
  14312. ASSERT_TRUE(req.is_multipart_form_data());
  14313. std::vector<FormData> items;
  14314. content_reader(
  14315. [&](const FormData &file) {
  14316. items.push_back(file);
  14317. return true;
  14318. },
  14319. [&](const char *data, size_t data_length) {
  14320. items.back().content.append(data, data_length);
  14321. return true;
  14322. });
  14323. ASSERT_TRUE(items.size() == 4);
  14324. EXPECT_EQ(std::string(items[0].name), "name1");
  14325. EXPECT_EQ(items[0].content, "Testing123");
  14326. EXPECT_EQ(items[0].filename, "filename1");
  14327. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14328. EXPECT_EQ(items[1].name, "name2");
  14329. EXPECT_EQ(items[1].content, "Testing456");
  14330. EXPECT_EQ(items[1].filename, "");
  14331. EXPECT_EQ(items[1].content_type, "");
  14332. EXPECT_EQ(items[2].name, "name3");
  14333. EXPECT_EQ(items[2].content, rand1);
  14334. EXPECT_EQ(items[2].filename, "filename3");
  14335. EXPECT_EQ(items[2].content_type, "");
  14336. EXPECT_EQ(items[3].name, "name4");
  14337. EXPECT_EQ(items[3].content, rand2);
  14338. EXPECT_EQ(items[3].filename, "filename4");
  14339. EXPECT_EQ(items[3].content_type, "");
  14340. });
  14341. auto port = svr.bind_to_any_port("localhost");
  14342. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14343. auto se = detail::scope_exit([&] {
  14344. svr.stop();
  14345. t.join();
  14346. ASSERT_FALSE(svr.is_running());
  14347. });
  14348. svr.wait_until_ready();
  14349. {
  14350. SSLClient cli("localhost", port);
  14351. cli.enable_server_certificate_verification(false);
  14352. UploadFormDataItems items{
  14353. {"name1", "Testing123", "filename1", "application/octet-stream"},
  14354. {"name2", "Testing456", "", ""}, // not a file
  14355. };
  14356. {
  14357. auto res = cli.Post("/post-none", {}, {}, {});
  14358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14359. ASSERT_EQ(StatusCode::OK_200, res->status);
  14360. }
  14361. FormDataProviderItems providers;
  14362. {
  14363. auto res =
  14364. cli.Post("/post-items", {}, items, providers); // empty providers
  14365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14366. ASSERT_EQ(StatusCode::OK_200, res->status);
  14367. }
  14368. providers.push_back({"name3",
  14369. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14370. // test the offset is given correctly at each step
  14371. if (!offset)
  14372. sink.os.write(rand1.data(), 30);
  14373. else if (offset == 30)
  14374. sink.os.write(rand1.data() + 30, 300);
  14375. else if (offset == 330)
  14376. sink.os.write(rand1.data() + 330, 670);
  14377. else if (offset == rand1.size())
  14378. sink.done();
  14379. return true;
  14380. },
  14381. "filename3",
  14382. {}});
  14383. providers.push_back({"name4",
  14384. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14385. // test the offset is given correctly at each step
  14386. if (!offset)
  14387. sink.os.write(rand2.data(), 2000);
  14388. else if (offset == 2000)
  14389. sink.os.write(rand2.data() + 2000, 1);
  14390. else if (offset == 2001)
  14391. sink.os.write(rand2.data() + 2001, 999);
  14392. else if (offset == rand2.size())
  14393. sink.done();
  14394. return true;
  14395. },
  14396. "filename4",
  14397. {}});
  14398. {
  14399. auto res = cli.Post("/post-providers", {}, {}, providers);
  14400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14401. ASSERT_EQ(StatusCode::OK_200, res->status);
  14402. }
  14403. {
  14404. auto res = cli.Post("/post-both", {}, items, providers);
  14405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14406. ASSERT_EQ(StatusCode::OK_200, res->status);
  14407. }
  14408. }
  14409. }
  14410. TEST(MultipartFormDataTest, BadHeader) {
  14411. Server svr;
  14412. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14413. res.set_content("ok", "text/plain");
  14414. });
  14415. thread t = thread([&] { svr.listen(HOST, PORT); });
  14416. auto se = detail::scope_exit([&] {
  14417. svr.stop();
  14418. t.join();
  14419. ASSERT_FALSE(svr.is_running());
  14420. });
  14421. svr.wait_until_ready();
  14422. const std::string body =
  14423. "This is the preamble. It is to be ignored, though it\r\n"
  14424. "is a handy place for composition agents to include an\r\n"
  14425. "explanatory note to non-MIME conformant readers.\r\n"
  14426. "\r\n"
  14427. "\r\n"
  14428. "--simple boundary\r\n"
  14429. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14430. ": BAD...\r\n"
  14431. "\r\n"
  14432. "value1\r\n"
  14433. "--simple boundary\r\n"
  14434. "Content-Disposition: form-data; name=\"field2\"; "
  14435. "filename=\"example.txt\"\r\n"
  14436. "\r\n"
  14437. "value2\r\n"
  14438. "--simple boundary--\r\n"
  14439. "This is the epilogue. It is also to be ignored.\r\n";
  14440. std::string content_type =
  14441. R"(multipart/form-data; boundary="simple boundary")";
  14442. Client cli(HOST, PORT);
  14443. auto res = cli.Post("/post", body, content_type.c_str());
  14444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14445. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14446. }
  14447. TEST(MultipartFormDataTest, WithPreamble) {
  14448. Server svr;
  14449. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14450. res.set_content("ok", "text/plain");
  14451. });
  14452. thread t = thread([&] { svr.listen(HOST, PORT); });
  14453. auto se = detail::scope_exit([&] {
  14454. svr.stop();
  14455. t.join();
  14456. ASSERT_FALSE(svr.is_running());
  14457. });
  14458. svr.wait_until_ready();
  14459. const std::string body =
  14460. "This is the preamble. It is to be ignored, though it\r\n"
  14461. "is a handy place for composition agents to include an\r\n"
  14462. "explanatory note to non-MIME conformant readers.\r\n"
  14463. "\r\n"
  14464. "\r\n"
  14465. "--simple boundary\r\n"
  14466. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14467. "\r\n"
  14468. "value1\r\n"
  14469. "--simple boundary\r\n"
  14470. "Content-Disposition: form-data; name=\"field2\"; "
  14471. "filename=\"example.txt\"\r\n"
  14472. "\r\n"
  14473. "value2\r\n"
  14474. "--simple boundary--\r\n"
  14475. "This is the epilogue. It is also to be ignored.\r\n";
  14476. std::string content_type =
  14477. R"(multipart/form-data; boundary="simple boundary")";
  14478. Client cli(HOST, PORT);
  14479. auto res = cli.Post("/post", body, content_type.c_str());
  14480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14481. EXPECT_EQ(StatusCode::OK_200, res->status);
  14482. }
  14483. TEST(MultipartFormDataTest, PostCustomBoundary) {
  14484. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14485. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  14486. const ContentReader &content_reader) {
  14487. if (req.is_multipart_form_data()) {
  14488. std::vector<FormData> items;
  14489. content_reader(
  14490. [&](const FormData &file) {
  14491. items.push_back(file);
  14492. return true;
  14493. },
  14494. [&](const char *data, size_t data_length) {
  14495. items.back().content.append(data, data_length);
  14496. return true;
  14497. });
  14498. EXPECT_TRUE(std::string(items[0].name) == "document");
  14499. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14500. EXPECT_TRUE(items[0].filename == "2MB_data");
  14501. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14502. EXPECT_TRUE(items[1].name == "hello");
  14503. EXPECT_TRUE(items[1].content == "world");
  14504. EXPECT_TRUE(items[1].filename == "");
  14505. EXPECT_TRUE(items[1].content_type == "");
  14506. } else {
  14507. std::string body;
  14508. content_reader([&](const char *data, size_t data_length) {
  14509. body.append(data, data_length);
  14510. return true;
  14511. });
  14512. }
  14513. });
  14514. auto port = svr.bind_to_any_port("localhost");
  14515. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14516. auto se = detail::scope_exit([&] {
  14517. svr.stop();
  14518. t.join();
  14519. ASSERT_FALSE(svr.is_running());
  14520. });
  14521. svr.wait_until_ready();
  14522. {
  14523. std::string data(1024 * 1024 * 2, '.');
  14524. std::stringstream buffer;
  14525. buffer << data;
  14526. SSLClient cli("localhost", port);
  14527. cli.enable_server_certificate_verification(false);
  14528. UploadFormDataItems items{
  14529. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14530. {"hello", "world", "", ""},
  14531. };
  14532. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  14533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14534. ASSERT_EQ(StatusCode::OK_200, res->status);
  14535. }
  14536. }
  14537. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  14538. std::string data(1024 * 1024 * 2, '&');
  14539. std::stringstream buffer;
  14540. buffer << data;
  14541. Client cli("https://localhost:8080");
  14542. UploadFormDataItems items{
  14543. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14544. {"hello", "world", "", ""},
  14545. };
  14546. for (const char &c : " \t\r\n") {
  14547. auto res =
  14548. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  14549. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14550. ASSERT_FALSE(res);
  14551. }
  14552. }
  14553. TEST(MultipartFormDataTest, PutFormData) {
  14554. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14555. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  14556. const ContentReader &content_reader) {
  14557. if (req.is_multipart_form_data()) {
  14558. std::vector<FormData> items;
  14559. content_reader(
  14560. [&](const FormData &file) {
  14561. items.push_back(file);
  14562. return true;
  14563. },
  14564. [&](const char *data, size_t data_length) {
  14565. items.back().content.append(data, data_length);
  14566. return true;
  14567. });
  14568. EXPECT_TRUE(std::string(items[0].name) == "document");
  14569. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14570. EXPECT_TRUE(items[0].filename == "2MB_data");
  14571. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14572. EXPECT_TRUE(items[1].name == "hello");
  14573. EXPECT_TRUE(items[1].content == "world");
  14574. EXPECT_TRUE(items[1].filename == "");
  14575. EXPECT_TRUE(items[1].content_type == "");
  14576. } else {
  14577. std::string body;
  14578. content_reader([&](const char *data, size_t data_length) {
  14579. body.append(data, data_length);
  14580. return true;
  14581. });
  14582. }
  14583. });
  14584. auto port = svr.bind_to_any_port("localhost");
  14585. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14586. auto se = detail::scope_exit([&] {
  14587. svr.stop();
  14588. t.join();
  14589. ASSERT_FALSE(svr.is_running());
  14590. });
  14591. svr.wait_until_ready();
  14592. {
  14593. std::string data(1024 * 1024 * 2, '&');
  14594. std::stringstream buffer;
  14595. buffer << data;
  14596. SSLClient cli("localhost", port);
  14597. cli.enable_server_certificate_verification(false);
  14598. UploadFormDataItems items{
  14599. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14600. {"hello", "world", "", ""},
  14601. };
  14602. auto res = cli.Put("/put", items);
  14603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14604. ASSERT_EQ(StatusCode::OK_200, res->status);
  14605. }
  14606. }
  14607. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  14608. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14609. svr.Put("/put_customboundary",
  14610. [&](const Request &req, const Response & /*res*/,
  14611. const ContentReader &content_reader) {
  14612. if (req.is_multipart_form_data()) {
  14613. std::vector<FormData> items;
  14614. content_reader(
  14615. [&](const FormData &file) {
  14616. items.push_back(file);
  14617. return true;
  14618. },
  14619. [&](const char *data, size_t data_length) {
  14620. items.back().content.append(data, data_length);
  14621. return true;
  14622. });
  14623. EXPECT_TRUE(std::string(items[0].name) == "document");
  14624. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14625. EXPECT_TRUE(items[0].filename == "2MB_data");
  14626. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14627. EXPECT_TRUE(items[1].name == "hello");
  14628. EXPECT_TRUE(items[1].content == "world");
  14629. EXPECT_TRUE(items[1].filename == "");
  14630. EXPECT_TRUE(items[1].content_type == "");
  14631. } else {
  14632. std::string body;
  14633. content_reader([&](const char *data, size_t data_length) {
  14634. body.append(data, data_length);
  14635. return true;
  14636. });
  14637. }
  14638. });
  14639. auto port = svr.bind_to_any_port("localhost");
  14640. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14641. auto se = detail::scope_exit([&] {
  14642. svr.stop();
  14643. t.join();
  14644. ASSERT_FALSE(svr.is_running());
  14645. });
  14646. svr.wait_until_ready();
  14647. {
  14648. std::string data(1024 * 1024 * 2, '&');
  14649. std::stringstream buffer;
  14650. buffer << data;
  14651. SSLClient cli("localhost", port);
  14652. cli.enable_server_certificate_verification(false);
  14653. UploadFormDataItems items{
  14654. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14655. {"hello", "world", "", ""},
  14656. };
  14657. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  14658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14659. ASSERT_EQ(StatusCode::OK_200, res->status);
  14660. }
  14661. }
  14662. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  14663. std::string data(1024 * 1024 * 2, '&');
  14664. std::stringstream buffer;
  14665. buffer << data;
  14666. Client cli("https://localhost:8080");
  14667. cli.enable_server_certificate_verification(false);
  14668. UploadFormDataItems items{
  14669. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14670. {"hello", "world", "", ""},
  14671. };
  14672. for (const char &c : " \t\r\n") {
  14673. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  14674. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14675. ASSERT_FALSE(res);
  14676. }
  14677. }
  14678. TEST(MultipartFormDataTest, AlternateFilename) {
  14679. auto handled = false;
  14680. Server svr;
  14681. svr.Post("/test", [&](const Request &req, Response &res) {
  14682. ASSERT_EQ(2u, req.form.files.size());
  14683. ASSERT_EQ(1u, req.form.fields.size());
  14684. // Test files
  14685. const auto &file1 = req.form.get_file("file1");
  14686. ASSERT_EQ("file1", file1.name);
  14687. ASSERT_EQ("A.txt", file1.filename);
  14688. ASSERT_EQ("text/plain", file1.content_type);
  14689. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  14690. const auto &file2 = req.form.get_file("file2");
  14691. ASSERT_EQ("file2", file2.name);
  14692. ASSERT_EQ("a.html", file2.filename);
  14693. ASSERT_EQ("text/html", file2.content_type);
  14694. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  14695. file2.content);
  14696. // Test text field
  14697. const auto &text = req.form.get_field("text");
  14698. ASSERT_EQ("text default", text);
  14699. res.set_content("ok", "text/plain");
  14700. handled = true;
  14701. });
  14702. thread t = thread([&] { svr.listen(HOST, PORT); });
  14703. auto se = detail::scope_exit([&] {
  14704. svr.stop();
  14705. t.join();
  14706. ASSERT_FALSE(svr.is_running());
  14707. ASSERT_TRUE(handled);
  14708. });
  14709. svr.wait_until_ready();
  14710. auto req = "POST /test HTTP/1.1\r\n"
  14711. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14712. "Content-Length: 399\r\n"
  14713. "\r\n"
  14714. "----------\r\n"
  14715. "Content-Disposition: form-data; name=\"text\"\r\n"
  14716. "\r\n"
  14717. "text default\r\n"
  14718. "----------\r\n"
  14719. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  14720. "filename=\"a.txt\"; name=\"file1\"\r\n"
  14721. "Content-Type: text/plain\r\n"
  14722. "\r\n"
  14723. "Content of a.txt.\r\n"
  14724. "\r\n"
  14725. "----------\r\n"
  14726. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  14727. "\"a.html\"\r\n"
  14728. "Content-Type: text/html\r\n"
  14729. "\r\n"
  14730. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  14731. "\r\n"
  14732. "------------\r\n";
  14733. ASSERT_TRUE(send_request(1, req));
  14734. }
  14735. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  14736. auto handled = false;
  14737. Server svr;
  14738. svr.Post("/test", [&](const Request &req, Response &res) {
  14739. // Case-insensitive "utf-8''" prefix with a long value
  14740. const auto &file = req.form.get_file("file1");
  14741. ASSERT_EQ("file1", file.name);
  14742. // 8000 chars exercises both the Content-Disposition parser and the
  14743. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  14744. // Prior to the fix, std::regex_match on this header would cause O(N)
  14745. // stack recursion in libstdc++, leading to SIGSEGV.
  14746. std::string expected_filename(8000, 'A');
  14747. ASSERT_EQ(expected_filename, file.filename);
  14748. res.set_content("ok", "text/plain");
  14749. handled = true;
  14750. });
  14751. thread t = thread([&] { svr.listen(HOST, PORT); });
  14752. auto se = detail::scope_exit([&] {
  14753. svr.stop();
  14754. t.join();
  14755. ASSERT_FALSE(svr.is_running());
  14756. ASSERT_TRUE(handled);
  14757. });
  14758. svr.wait_until_ready();
  14759. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  14760. // Regression test for GHSA-qq6v-r583-3h69
  14761. std::string long_filename(8000, 'A');
  14762. std::string body = "----------\r\n"
  14763. "Content-Disposition: form-data; name=\"file1\"; "
  14764. "filename*=\"Utf-8''" +
  14765. long_filename +
  14766. "\"\r\n"
  14767. "\r\n"
  14768. "hello\r\n"
  14769. "------------\r\n";
  14770. auto req = "POST /test HTTP/1.1\r\n"
  14771. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14772. "Content-Length: " +
  14773. std::to_string(body.size()) + "\r\n\r\n" + body;
  14774. ASSERT_TRUE(send_request(1, req));
  14775. }
  14776. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  14777. auto handled = false;
  14778. Server svr;
  14779. svr.Post("/test", [&](const Request &req, Response &) {
  14780. ASSERT_EQ(2u, req.form.fields.size());
  14781. const auto &text1 = req.form.get_field("text1");
  14782. ASSERT_EQ("text1", text1);
  14783. const auto &text2 = req.form.get_field("text2");
  14784. ASSERT_EQ("text2", text2);
  14785. handled = true;
  14786. });
  14787. thread t = thread([&] { svr.listen(HOST, PORT); });
  14788. auto se = detail::scope_exit([&] {
  14789. svr.stop();
  14790. t.join();
  14791. ASSERT_FALSE(svr.is_running());
  14792. ASSERT_TRUE(handled);
  14793. });
  14794. svr.wait_until_ready();
  14795. auto req = "POST /test HTTP/1.1\r\n"
  14796. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14797. "Content-Length: 146\r\n"
  14798. "\r\n----------\r\n"
  14799. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14800. "\r\n"
  14801. "text1"
  14802. "\r\n----------\r\n"
  14803. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14804. "\r\n"
  14805. "text2"
  14806. "\r\n------------";
  14807. std::string response;
  14808. ASSERT_TRUE(send_request(1, req, &response));
  14809. ASSERT_EQ("200", response.substr(9, 3));
  14810. }
  14811. TEST(MultipartFormDataTest, ContentLength) {
  14812. auto handled = false;
  14813. Server svr;
  14814. svr.Post("/test", [&](const Request &req, Response &) {
  14815. ASSERT_EQ(2u, req.form.fields.size());
  14816. const auto &text1 = req.form.get_field("text1");
  14817. ASSERT_EQ("text1", text1);
  14818. const auto &text2 = req.form.get_field("text2");
  14819. ASSERT_EQ("text2", text2);
  14820. handled = true;
  14821. });
  14822. thread t = thread([&] { svr.listen(HOST, PORT); });
  14823. auto se = detail::scope_exit([&] {
  14824. svr.stop();
  14825. t.join();
  14826. ASSERT_FALSE(svr.is_running());
  14827. ASSERT_TRUE(handled);
  14828. });
  14829. svr.wait_until_ready();
  14830. auto req = "POST /test HTTP/1.1\r\n"
  14831. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14832. "Content-Length: 167\r\n"
  14833. "\r\n----------\r\n"
  14834. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14835. "Content-Length: 5\r\n"
  14836. "\r\n"
  14837. "text1"
  14838. "\r\n----------\r\n"
  14839. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14840. "\r\n"
  14841. "text2"
  14842. "\r\n------------\r\n";
  14843. std::string response;
  14844. ASSERT_TRUE(send_request(1, req, &response));
  14845. ASSERT_EQ("200", response.substr(9, 3));
  14846. }
  14847. TEST(MultipartFormDataTest, AccessPartHeaders) {
  14848. auto handled = false;
  14849. Server svr;
  14850. svr.Post("/test", [&](const Request &req, Response &) {
  14851. ASSERT_EQ(2u, req.form.fields.size());
  14852. const auto &text1 = req.form.get_field("text1");
  14853. ASSERT_EQ("text1", text1);
  14854. // TODO: Add header access for text fields if needed
  14855. const auto &text2 = req.form.get_field("text2");
  14856. ASSERT_EQ("text2", text2);
  14857. // TODO: Header access for text fields needs to be implemented
  14858. // auto &headers = it->second.headers;
  14859. // ASSERT_EQ(3U, headers.size());
  14860. // auto custom_header = headers.find("x-whatever");
  14861. // ASSERT_TRUE(custom_header != headers.end());
  14862. // ASSERT_NE("customvalue", custom_header->second);
  14863. // ASSERT_EQ("CustomValue", custom_header->second);
  14864. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  14865. handled = true;
  14866. });
  14867. thread t = thread([&] { svr.listen(HOST, PORT); });
  14868. auto se = detail::scope_exit([&] {
  14869. svr.stop();
  14870. t.join();
  14871. ASSERT_FALSE(svr.is_running());
  14872. ASSERT_TRUE(handled);
  14873. });
  14874. svr.wait_until_ready();
  14875. auto req = "POST /test HTTP/1.1\r\n"
  14876. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14877. "Content-Length: 232\r\n"
  14878. "\r\n----------\r\n"
  14879. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14880. "Content-Length: 5\r\n"
  14881. "X-Test: 1\r\n"
  14882. "\r\n"
  14883. "text1"
  14884. "\r\n----------\r\n"
  14885. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14886. "Content-Type: text/plain\r\n"
  14887. "X-Whatever: CustomValue\r\n"
  14888. "\r\n"
  14889. "text2"
  14890. "\r\n------------\r\n"
  14891. "That should be disregarded. Not even read";
  14892. std::string response;
  14893. ASSERT_TRUE(send_request(1, req, &response));
  14894. ASSERT_EQ("200", response.substr(9, 3));
  14895. }
  14896. TEST(MultipartFormDataTest, LargeHeader) {
  14897. auto handled = false;
  14898. Server svr;
  14899. svr.Post("/test", [&](const Request &req, Response &) {
  14900. ASSERT_EQ(1u, req.form.fields.size());
  14901. const auto &text = req.form.get_field("name1");
  14902. ASSERT_EQ("text1", text);
  14903. handled = true;
  14904. });
  14905. thread t = thread([&] { svr.listen(HOST, PORT); });
  14906. auto se = detail::scope_exit([&] {
  14907. svr.stop();
  14908. t.join();
  14909. ASSERT_FALSE(svr.is_running());
  14910. ASSERT_TRUE(handled);
  14911. });
  14912. svr.wait_until_ready();
  14913. auto boundary = std::string("cpp-httplib-multipart-data");
  14914. std::string content = "--" + boundary +
  14915. "\r\n"
  14916. "Content-Disposition: form-data; name=\"name1\"\r\n"
  14917. "\r\n"
  14918. "text1\r\n"
  14919. "--" +
  14920. boundary + "--\r\n";
  14921. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  14922. "Content-Type: multipart/form-data;boundary=" +
  14923. boundary +
  14924. "\r\n"
  14925. "Content-Length: " +
  14926. std::to_string(content.size()) +
  14927. "\r\n"
  14928. "Dummy-Header: ";
  14929. std::string header_suffix = "\r\n"
  14930. "\r\n";
  14931. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  14932. size_t header_dummy_size =
  14933. read_buff_size -
  14934. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  14935. auto header_dummy = std::string(header_dummy_size, '@');
  14936. auto req = header_prefix + header_dummy + header_suffix + content;
  14937. std::string response;
  14938. ASSERT_TRUE(send_request(1, req, &response));
  14939. ASSERT_EQ("200", response.substr(9, 3));
  14940. }
  14941. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  14942. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  14943. // (not chunked Transfer-Encoding) after the streaming refactor.
  14944. auto handled = false;
  14945. Server svr;
  14946. svr.Post("/upload", [&](const Request &req, Response &res) {
  14947. auto cl_it = req.headers.find("Content-Length");
  14948. EXPECT_TRUE(cl_it != req.headers.end());
  14949. auto te_it = req.headers.find("Transfer-Encoding");
  14950. EXPECT_TRUE(te_it == req.headers.end());
  14951. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  14952. res.set_content("ok", "text/plain");
  14953. handled = true;
  14954. });
  14955. auto port = svr.bind_to_any_port(HOST);
  14956. auto t = thread([&] { svr.listen_after_bind(); });
  14957. auto se = detail::scope_exit([&] {
  14958. svr.stop();
  14959. t.join();
  14960. ASSERT_FALSE(svr.is_running());
  14961. ASSERT_TRUE(handled);
  14962. });
  14963. svr.wait_until_ready();
  14964. UploadFormDataItems items = {
  14965. {"field1", "hello", "", "text/plain"},
  14966. {"file1", "world", "test.txt", "application/octet-stream"},
  14967. };
  14968. Client cli(HOST, port);
  14969. auto res = cli.Post("/upload", {}, items);
  14970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14971. EXPECT_EQ(StatusCode::OK_200, res->status);
  14972. }
  14973. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  14974. // Verify that make_multipart_content_provider coalesces many small segments
  14975. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  14976. constexpr size_t kItemCount = 1000;
  14977. UploadFormDataItems items;
  14978. items.reserve(kItemCount);
  14979. for (size_t i = 0; i < kItemCount; i++) {
  14980. items.push_back(
  14981. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14982. }
  14983. const std::string boundary = "----test-boundary";
  14984. auto content_length = detail::get_multipart_content_length(items, boundary);
  14985. auto provider = detail::make_multipart_content_provider(items, boundary);
  14986. // Drive the provider the same way write_content_with_progress does
  14987. size_t write_count = 0;
  14988. size_t total_bytes = 0;
  14989. DataSink sink;
  14990. size_t offset = 0;
  14991. sink.write = [&](const char *d, size_t l) -> bool {
  14992. (void)d;
  14993. write_count++;
  14994. total_bytes += l;
  14995. offset += l;
  14996. return true;
  14997. };
  14998. sink.is_writable = []() -> bool { return true; };
  14999. while (offset < content_length) {
  15000. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  15001. }
  15002. EXPECT_EQ(content_length, total_bytes);
  15003. // The total number of segments is 3 * kItemCount + 1 = 3001.
  15004. // With buffering into 64KB blocks, write_count should be much smaller.
  15005. auto segment_count = 3 * kItemCount + 1;
  15006. EXPECT_LT(write_count, segment_count / 10);
  15007. }
  15008. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  15009. // Integration test: send many UploadFormDataItems and verify the server
  15010. // receives all of them correctly (#2410).
  15011. constexpr size_t kItemCount = 500;
  15012. auto handled = false;
  15013. Server svr;
  15014. svr.Post("/upload", [&](const Request &req, Response &res) {
  15015. EXPECT_EQ(kItemCount, req.form.fields.size());
  15016. for (size_t i = 0; i < kItemCount; i++) {
  15017. auto key = "field" + std::to_string(i);
  15018. auto val = "value" + std::to_string(i);
  15019. auto it = req.form.fields.find(key);
  15020. if (it != req.form.fields.end()) {
  15021. EXPECT_EQ(val, it->second.content);
  15022. } else {
  15023. ADD_FAILURE() << "Missing field: " << key;
  15024. }
  15025. }
  15026. res.set_content("ok", "text/plain");
  15027. handled = true;
  15028. });
  15029. auto port = svr.bind_to_any_port(HOST);
  15030. auto t = thread([&] { svr.listen_after_bind(); });
  15031. auto se = detail::scope_exit([&] {
  15032. svr.stop();
  15033. t.join();
  15034. ASSERT_FALSE(svr.is_running());
  15035. ASSERT_TRUE(handled);
  15036. });
  15037. svr.wait_until_ready();
  15038. UploadFormDataItems items;
  15039. items.reserve(kItemCount);
  15040. for (size_t i = 0; i < kItemCount; i++) {
  15041. items.push_back(
  15042. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15043. }
  15044. Client cli(HOST, port);
  15045. auto res = cli.Post("/upload", items);
  15046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15047. EXPECT_EQ(StatusCode::OK_200, res->status);
  15048. }
  15049. TEST(MultipartFormDataTest, MakeFileProvider) {
  15050. // Verify make_file_provider sends a file's contents correctly.
  15051. const std::string file_content(4096, 'Z');
  15052. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  15053. {
  15054. std::ofstream ofs(tmp_path, std::ios::binary);
  15055. ofs.write(file_content.data(),
  15056. static_cast<std::streamsize>(file_content.size()));
  15057. }
  15058. auto handled = false;
  15059. Server svr;
  15060. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  15061. const ContentReader &content_reader) {
  15062. ASSERT_TRUE(req.is_multipart_form_data());
  15063. std::vector<FormData> items;
  15064. content_reader(
  15065. [&](const FormData &file) {
  15066. items.push_back(file);
  15067. return true;
  15068. },
  15069. [&](const char *data, size_t data_length) {
  15070. items.back().content.append(data, data_length);
  15071. return true;
  15072. });
  15073. ASSERT_EQ(1u, items.size());
  15074. EXPECT_EQ("myfile", items[0].name);
  15075. EXPECT_EQ("data.bin", items[0].filename);
  15076. EXPECT_EQ("application/octet-stream", items[0].content_type);
  15077. EXPECT_EQ(file_content, items[0].content);
  15078. handled = true;
  15079. });
  15080. auto port = svr.bind_to_any_port(HOST);
  15081. auto t = thread([&] { svr.listen_after_bind(); });
  15082. auto se = detail::scope_exit([&] {
  15083. svr.stop();
  15084. t.join();
  15085. ASSERT_FALSE(svr.is_running());
  15086. ASSERT_TRUE(handled);
  15087. std::remove(tmp_path.c_str());
  15088. });
  15089. svr.wait_until_ready();
  15090. FormDataProviderItems providers;
  15091. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  15092. "application/octet-stream"));
  15093. Client cli(HOST, port);
  15094. auto res = cli.Post("/upload", {}, {}, providers);
  15095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15096. EXPECT_EQ(StatusCode::OK_200, res->status);
  15097. }
  15098. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  15099. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  15100. // (100) headers is rejected with a 400 Bad Request response.
  15101. Server svr;
  15102. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15103. res.set_content("ok", "text/plain");
  15104. });
  15105. thread t = thread([&] { svr.listen(HOST, PORT); });
  15106. auto se = detail::scope_exit([&] {
  15107. svr.stop();
  15108. t.join();
  15109. ASSERT_FALSE(svr.is_running());
  15110. });
  15111. svr.wait_until_ready();
  15112. // Build a multipart part with 101 custom headers (exceeding
  15113. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  15114. std::stringstream body;
  15115. body << "--simpleboundary\r\n"
  15116. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  15117. for (int i = 0; i < 101; i++) {
  15118. body << "X-Custom-Header-" << i << ": value\r\n";
  15119. }
  15120. body << "\r\n"
  15121. << "value1\r\n"
  15122. << "--simpleboundary--\r\n";
  15123. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  15124. Client cli(HOST, PORT);
  15125. auto res = cli.Post("/post", body.str(), content_type.c_str());
  15126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15127. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15128. }
  15129. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  15130. // A body that never contains the declared boundary must not be accumulated
  15131. // while the parser waits for it. Buffering it would also make every read
  15132. // rescan everything seen so far, which is quadratic in the body size.
  15133. Server svr;
  15134. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15135. res.set_content("ok", "text/plain");
  15136. });
  15137. auto port = svr.bind_to_any_port(HOST);
  15138. thread t = thread([&] { svr.listen_after_bind(); });
  15139. auto se = detail::scope_exit([&] {
  15140. svr.stop();
  15141. t.join();
  15142. ASSERT_FALSE(svr.is_running());
  15143. });
  15144. svr.wait_until_ready();
  15145. Client cli(HOST, port);
  15146. cli.set_read_timeout(60, 0);
  15147. cli.set_write_timeout(60, 0);
  15148. // '-' is the worst case: it matches the first character of the boundary, so
  15149. // every position has to be checked against it.
  15150. auto post_dashes = [&](size_t size) {
  15151. const std::string body(size, '-');
  15152. auto start = std::chrono::steady_clock::now();
  15153. auto res =
  15154. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  15155. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  15156. std::chrono::steady_clock::now() - start)
  15157. .count();
  15158. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15159. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  15160. return ms;
  15161. };
  15162. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  15163. // Windows.
  15164. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  15165. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  15166. // Comparing the two sizes rather than checking an absolute duration keeps
  15167. // this meaningful across build types and CI load, both of which move the
  15168. // absolute numbers by more than an order of magnitude. Four times the bytes
  15169. // costs about four times the time when parsing is linear, and about sixteen
  15170. // times when the body is buffered and rescanned.
  15171. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  15172. EXPECT_LT(ms_16mb, ms_4mb * 10)
  15173. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  15174. << "ms, which suggests the body is being buffered and rescanned";
  15175. }
  15176. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  15177. // A boundary can only be followed by CRLF or by "--", so anything else is
  15178. // malformed no matter what comes next. The parser must say so right away
  15179. // instead of buffering the rest of the declared body.
  15180. Server svr;
  15181. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15182. res.set_content("ok", "text/plain");
  15183. });
  15184. auto port = svr.bind_to_any_port(HOST);
  15185. thread t = thread([&] { svr.listen_after_bind(); });
  15186. auto se = detail::scope_exit([&] {
  15187. svr.stop();
  15188. t.join();
  15189. ASSERT_FALSE(svr.is_running());
  15190. });
  15191. svr.wait_until_ready();
  15192. // Announce a 1 MB body but send only the malformed prefix. A parser that
  15193. // buffers instead of failing would still be waiting for the remaining bytes.
  15194. const std::string body = "--zzzz\r\n"
  15195. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15196. "\r\n"
  15197. "text1"
  15198. "\r\n--zzzzXX";
  15199. const std::string req = "POST /post HTTP/1.1\r\n"
  15200. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15201. "Content-Length: 1048576\r\n"
  15202. "\r\n" +
  15203. body;
  15204. std::string response;
  15205. ASSERT_TRUE(send_request(3, req, &response, port));
  15206. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  15207. EXPECT_EQ("400", response.substr(9, 3));
  15208. }
  15209. // Posts a multipart body split into two writes, so that the server sees the
  15210. // split at whatever offset the caller chose, and expects the single "text1"
  15211. // field to come through.
  15212. static void expect_split_multipart_ok(const std::string &body1,
  15213. const std::string &body2) {
  15214. auto handled = false;
  15215. Server svr;
  15216. svr.Post("/post", [&](const Request &req, Response &) {
  15217. EXPECT_EQ(1u, req.form.fields.size());
  15218. EXPECT_EQ("text1", req.form.get_field("text1"));
  15219. handled = true;
  15220. });
  15221. auto port = svr.bind_to_any_port(HOST);
  15222. thread t = thread([&] { svr.listen_after_bind(); });
  15223. auto se = detail::scope_exit([&] {
  15224. svr.stop();
  15225. t.join();
  15226. ASSERT_FALSE(svr.is_running());
  15227. ASSERT_TRUE(handled);
  15228. });
  15229. svr.wait_until_ready();
  15230. // "Connection: close" makes the server close once it has answered, so the
  15231. // response drain ends immediately instead of idling until the read timeout.
  15232. const std::string head =
  15233. "POST /post HTTP/1.1\r\n"
  15234. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15235. "Connection: close\r\n"
  15236. "Content-Length: " +
  15237. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  15238. std::string response;
  15239. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  15240. ASSERT_GE(response.size(), 12u) << "no response";
  15241. EXPECT_EQ("200", response.substr(9, 3));
  15242. }
  15243. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  15244. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  15245. // ignored, including when it does not arrive in the same read as the
  15246. // close-delimiter itself.
  15247. expect_split_multipart_ok("--zzzz\r\n"
  15248. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15249. "\r\n"
  15250. "text1"
  15251. "\r\n--zzzz--",
  15252. "\r\nthis epilogue must be ignored\r\n");
  15253. }
  15254. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  15255. // The initial boundary may be preceded by a preamble of any length and may
  15256. // straddle a read boundary. Discarding data while waiting for it must not
  15257. // throw away a partial boundary sitting at the end of the buffer.
  15258. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  15259. "zz\r\n"
  15260. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15261. "\r\n"
  15262. "text1"
  15263. "\r\n--zzzz--\r\n");
  15264. }
  15265. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  15266. // The received boundary was only checked for being non-empty, so it could be
  15267. // as long as a header is allowed to be. The parser scans the body for
  15268. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  15269. // costs a nearly full comparison at nearly every position, making the
  15270. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  15271. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  15272. Server svr;
  15273. svr.Post("/post", [](const Request &req, Response &res) {
  15274. EXPECT_EQ(1u, req.form.fields.size());
  15275. EXPECT_EQ("text1", req.form.get_field("text1"));
  15276. res.set_content("ok", "text/plain");
  15277. });
  15278. auto port = svr.bind_to_any_port(HOST);
  15279. thread t = thread([&] { svr.listen_after_bind(); });
  15280. auto se = detail::scope_exit([&] {
  15281. svr.stop();
  15282. t.join();
  15283. ASSERT_FALSE(svr.is_running());
  15284. });
  15285. svr.wait_until_ready();
  15286. Client cli(HOST, port);
  15287. auto post_with_boundary_of_length = [&](size_t len) {
  15288. const std::string boundary(len, 'a');
  15289. const std::string body =
  15290. "--" + boundary +
  15291. "\r\n"
  15292. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15293. "\r\n"
  15294. "text1"
  15295. "\r\n--" +
  15296. boundary + "--\r\n";
  15297. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  15298. };
  15299. auto res = post_with_boundary_of_length(70);
  15300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15301. EXPECT_EQ(StatusCode::OK_200, res->status);
  15302. res = post_with_boundary_of_length(71);
  15303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15304. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15305. }
  15306. TEST(MakeFileBodyTest, Basic) {
  15307. const std::string file_content(4096, 'Z');
  15308. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  15309. {
  15310. std::ofstream ofs(tmp_path, std::ios::binary);
  15311. ofs.write(file_content.data(),
  15312. static_cast<std::streamsize>(file_content.size()));
  15313. }
  15314. auto handled = false;
  15315. Server svr;
  15316. svr.Post("/upload", [&](const Request &req, Response &res) {
  15317. EXPECT_EQ(file_content, req.body);
  15318. handled = true;
  15319. res.status = StatusCode::OK_200;
  15320. });
  15321. auto port = svr.bind_to_any_port(HOST);
  15322. auto t = thread([&] { svr.listen_after_bind(); });
  15323. auto se = detail::scope_exit([&] {
  15324. svr.stop();
  15325. t.join();
  15326. ASSERT_FALSE(svr.is_running());
  15327. ASSERT_TRUE(handled);
  15328. std::remove(tmp_path.c_str());
  15329. });
  15330. svr.wait_until_ready();
  15331. auto fb = make_file_body(tmp_path);
  15332. ASSERT_GT(fb.first, 0u);
  15333. Client cli(HOST, port);
  15334. auto res =
  15335. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  15336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15337. EXPECT_EQ(StatusCode::OK_200, res->status);
  15338. }
  15339. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  15340. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  15341. {
  15342. std::ofstream ofs(path, std::ios::binary);
  15343. const std::string content(100, 'A');
  15344. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15345. }
  15346. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15347. auto body = make_file_body(path);
  15348. ASSERT_EQ(100u, body.first);
  15349. ASSERT_TRUE(static_cast<bool>(body.second));
  15350. // Rewritten shorter after its length was measured - and, on a server, after
  15351. // that length has already gone out as Content-Length.
  15352. {
  15353. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  15354. const std::string content(10, 'A');
  15355. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15356. }
  15357. std::string written;
  15358. DataSink sink;
  15359. sink.write = [&](const char *d, size_t l) {
  15360. written.append(d, l);
  15361. return true;
  15362. };
  15363. // The provider has to report failure. write_content_with_progress() advances
  15364. // its offset only by what was written, so a provider that returns true
  15365. // without completing the length it promised is called again straight away,
  15366. // and again.
  15367. EXPECT_FALSE(body.second(0, body.first, sink));
  15368. EXPECT_EQ(std::string(10, 'A'), written);
  15369. }
  15370. TEST(MakeFileBodyTest, WholeFileIsSent) {
  15371. const std::string path = "./httplib_test_make_file_body_whole.bin";
  15372. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  15373. {
  15374. std::ofstream ofs(path, std::ios::binary);
  15375. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15376. }
  15377. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15378. auto body = make_file_body(path);
  15379. ASSERT_EQ(content.size(), body.first);
  15380. ASSERT_TRUE(static_cast<bool>(body.second));
  15381. std::string written;
  15382. DataSink sink;
  15383. sink.write = [&](const char *d, size_t l) {
  15384. written.append(d, l);
  15385. return true;
  15386. };
  15387. EXPECT_TRUE(body.second(0, body.first, sink));
  15388. EXPECT_EQ(content, written);
  15389. }
  15390. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  15391. static constexpr unsigned int number_of_tasks{1000000};
  15392. std::atomic_uint count{0};
  15393. std::unique_ptr<TaskQueue> task_queue{
  15394. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  15395. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15396. auto queued = task_queue->enqueue(
  15397. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  15398. EXPECT_TRUE(queued);
  15399. }
  15400. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15401. task_queue->shutdown();
  15402. #else
  15403. EXPECT_NO_THROW(task_queue->shutdown());
  15404. #endif
  15405. EXPECT_EQ(number_of_tasks, count.load());
  15406. }
  15407. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  15408. static constexpr unsigned int number_of_tasks{1000000};
  15409. static constexpr unsigned int qlimit{2};
  15410. unsigned int queued_count{0};
  15411. std::atomic_uint count{0};
  15412. std::unique_ptr<TaskQueue> task_queue{
  15413. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  15414. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15415. if (task_queue->enqueue(
  15416. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  15417. queued_count++;
  15418. }
  15419. }
  15420. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15421. task_queue->shutdown();
  15422. #else
  15423. EXPECT_NO_THROW(task_queue->shutdown());
  15424. #endif
  15425. EXPECT_EQ(queued_count, count.load());
  15426. EXPECT_TRUE(queued_count <= number_of_tasks);
  15427. EXPECT_TRUE(queued_count >= qlimit);
  15428. }
  15429. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  15430. // Use a short idle timeout so a dynamic thread spawns, times out and
  15431. // exits during the test, and the pool keeps working afterwards.
  15432. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  15433. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  15434. /*idle_timeout_sec=*/1}};
  15435. std::atomic_uint count{0};
  15436. std::condition_variable cv;
  15437. std::mutex mtx;
  15438. bool release = false;
  15439. // Block the base thread so the second task spawns a dynamic thread.
  15440. EXPECT_TRUE(task_queue->enqueue([&] {
  15441. std::unique_lock<std::mutex> lock(mtx);
  15442. while (!release) {
  15443. cv.wait(lock);
  15444. }
  15445. count++;
  15446. }));
  15447. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15448. // Let the dynamic thread finish its task and exceed the idle timeout.
  15449. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  15450. {
  15451. std::unique_lock<std::mutex> lock(mtx);
  15452. release = true;
  15453. }
  15454. cv.notify_all();
  15455. // The pool must still accept and run tasks after the dynamic thread exited.
  15456. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15457. task_queue->shutdown();
  15458. EXPECT_EQ(3u, count.load());
  15459. }
  15460. TEST(TaskQueueTest, MaxQueuedRequests) {
  15461. static constexpr unsigned int qlimit{3};
  15462. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  15463. std::condition_variable sem_cv;
  15464. std::mutex sem_mtx;
  15465. int credits = 0;
  15466. bool queued;
  15467. /* Fill up the queue with tasks that will block until we give them credits to
  15468. * complete. */
  15469. for (unsigned int n = 0; n <= qlimit;) {
  15470. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  15471. std::unique_lock<std::mutex> lock(sem_mtx);
  15472. while (credits <= 0) {
  15473. sem_cv.wait(lock);
  15474. }
  15475. /* Consume the credit and signal the test code if they are all gone. */
  15476. if (--credits == 0) { sem_cv.notify_one(); }
  15477. });
  15478. if (n < qlimit) {
  15479. /* The first qlimit enqueues must succeed. */
  15480. EXPECT_TRUE(queued);
  15481. } else {
  15482. /* The last one will succeed only when the worker thread
  15483. * starts and dequeues the first blocking task. Although
  15484. * not necessary for the correctness of this test, we sleep for
  15485. * a short while to avoid busy waiting. */
  15486. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15487. }
  15488. if (queued) { n++; }
  15489. }
  15490. /* Further enqueues must fail since the queue is full. */
  15491. for (auto i = 0; i < 4; i++) {
  15492. queued = task_queue->enqueue([] {});
  15493. EXPECT_FALSE(queued);
  15494. }
  15495. /* Give the credits to allow the previous tasks to complete. */
  15496. {
  15497. std::unique_lock<std::mutex> lock(sem_mtx);
  15498. credits += qlimit + 1;
  15499. }
  15500. sem_cv.notify_all();
  15501. /* Wait for all the credits to be consumed. */
  15502. {
  15503. std::unique_lock<std::mutex> lock(sem_mtx);
  15504. while (credits > 0) {
  15505. sem_cv.wait(lock);
  15506. }
  15507. }
  15508. /* Check that we are able again to enqueue at least qlimit tasks. */
  15509. for (unsigned int i = 0; i < qlimit; i++) {
  15510. queued = task_queue->enqueue([] {});
  15511. EXPECT_TRUE(queued);
  15512. }
  15513. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15514. task_queue->shutdown();
  15515. #else
  15516. EXPECT_NO_THROW(task_queue->shutdown());
  15517. #endif
  15518. }
  15519. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  15520. Server svr;
  15521. std::string method;
  15522. std::string body;
  15523. auto has_content_length = false;
  15524. auto has_transfer_encoding = false;
  15525. std::atomic<int> bad_requests{0};
  15526. // Leftover body bytes get parsed as a malformed request and answered with
  15527. // 400
  15528. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  15529. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  15530. });
  15531. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  15532. res.set_redirect("/down", StatusCode::SeeOther_303);
  15533. });
  15534. svr.Get("/down", [&](const Request &req, Response &res) {
  15535. method = req.method;
  15536. body = req.body;
  15537. has_content_length = req.has_header("Content-Length");
  15538. has_transfer_encoding = req.has_header("Transfer-Encoding");
  15539. res.set_content("ok", "text/plain");
  15540. });
  15541. auto port = svr.bind_to_any_port(HOST);
  15542. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15543. auto se = detail::scope_exit([&] {
  15544. svr.stop();
  15545. thread.join();
  15546. ASSERT_FALSE(svr.is_running());
  15547. });
  15548. svr.wait_until_ready();
  15549. const std::string payload = "SECRET-BODY";
  15550. auto check = [&](Client &cli, const Result &res) {
  15551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15552. EXPECT_EQ(StatusCode::OK_200, res->status);
  15553. EXPECT_EQ("ok", res->body);
  15554. EXPECT_EQ("GET", method);
  15555. EXPECT_TRUE(body.empty());
  15556. EXPECT_FALSE(has_content_length);
  15557. EXPECT_FALSE(has_transfer_encoding);
  15558. // Nothing of the original body may be left on the connection
  15559. auto res2 = cli.Get("/down");
  15560. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  15561. EXPECT_EQ(StatusCode::OK_200, res2->status);
  15562. EXPECT_EQ("ok", res2->body);
  15563. EXPECT_EQ(0, bad_requests);
  15564. };
  15565. // With content length
  15566. {
  15567. Client cli(HOST, port);
  15568. cli.set_keep_alive(true);
  15569. cli.set_follow_location(true);
  15570. auto res = cli.Post(
  15571. "/up", payload.size(),
  15572. [&](size_t offset, size_t length, DataSink &sink) {
  15573. return sink.write(payload.data() + offset, length);
  15574. },
  15575. "text/plain");
  15576. check(cli, res);
  15577. }
  15578. // Without content length (chunked)
  15579. {
  15580. Client cli(HOST, port);
  15581. cli.set_keep_alive(true);
  15582. cli.set_follow_location(true);
  15583. auto res = cli.Post(
  15584. "/up",
  15585. [&](size_t /*offset*/, DataSink &sink) {
  15586. sink.write(payload.data(), payload.size());
  15587. sink.done();
  15588. return true;
  15589. },
  15590. "text/plain");
  15591. check(cli, res);
  15592. }
  15593. }
  15594. TEST(RedirectTest, LocationPathIsNotDecoded) {
  15595. Server svr;
  15596. std::string target;
  15597. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  15598. // Echo the still-encoded name back in the Location
  15599. const std::string prefix = "/start/";
  15600. res.status = StatusCode::Found_302;
  15601. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  15602. });
  15603. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  15604. target = req.target;
  15605. res.set_content("ok", "text/plain");
  15606. });
  15607. auto port = svr.bind_to_any_port(HOST);
  15608. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15609. auto se = detail::scope_exit([&] {
  15610. svr.stop();
  15611. thread.join();
  15612. ASSERT_FALSE(svr.is_running());
  15613. });
  15614. svr.wait_until_ready();
  15615. // Decoding the Location path would turn the first four into a path
  15616. // separator, a query delimiter, a fragment delimiter and a different
  15617. // percent-encoded octet. The rest must keep reaching the server as they are.
  15618. const std::vector<std::string> names = {
  15619. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  15620. };
  15621. for (auto path_encode : {true, false}) {
  15622. Client cli(HOST, port);
  15623. cli.set_follow_location(true);
  15624. cli.set_path_encode(path_encode);
  15625. for (const auto &name : names) {
  15626. target.clear();
  15627. auto res = cli.Get("/start/" + name);
  15628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15629. EXPECT_EQ(StatusCode::OK_200, res->status);
  15630. EXPECT_EQ("/dest/" + name, target);
  15631. }
  15632. }
  15633. }
  15634. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  15635. Server svr;
  15636. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15637. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  15638. });
  15639. svr.Get("/hello", [](const Request &req, Response &res) {
  15640. res.set_content(req.get_param_value("key"), "text/plain");
  15641. });
  15642. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15643. auto se = detail::scope_exit([&] {
  15644. svr.stop();
  15645. thread.join();
  15646. ASSERT_FALSE(svr.is_running());
  15647. });
  15648. svr.wait_until_ready();
  15649. {
  15650. Client cli(HOST, PORT);
  15651. cli.set_follow_location(true);
  15652. auto res = cli.Get("/");
  15653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15654. EXPECT_EQ(StatusCode::OK_200, res->status);
  15655. EXPECT_EQ("val&key2=val2", res->body);
  15656. }
  15657. }
  15658. #endif
  15659. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  15660. Server svr;
  15661. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15662. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  15663. });
  15664. svr.Get("/hello", [](const Request &req, Response &res) {
  15665. res.set_content(req.get_param_value("key"), "text/plain");
  15666. });
  15667. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15668. auto se = detail::scope_exit([&] {
  15669. svr.stop();
  15670. thread.join();
  15671. ASSERT_FALSE(svr.is_running());
  15672. });
  15673. svr.wait_until_ready();
  15674. {
  15675. Client cli(HOST, PORT);
  15676. cli.set_follow_location(true);
  15677. auto res = cli.Get("/");
  15678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15679. EXPECT_EQ(StatusCode::OK_200, res->status);
  15680. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  15681. }
  15682. }
  15683. TEST(RedirectTest, RedirectWithPlusInPath) {
  15684. Server svr;
  15685. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15686. res.set_redirect("/a+b");
  15687. });
  15688. // Route pattern uses regex; escape + as \\+
  15689. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  15690. res.set_content(req.path, "text/plain");
  15691. });
  15692. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15693. auto se = detail::scope_exit([&] {
  15694. svr.stop();
  15695. thread.join();
  15696. ASSERT_FALSE(svr.is_running());
  15697. });
  15698. svr.wait_until_ready();
  15699. {
  15700. Client cli(HOST, PORT);
  15701. cli.set_follow_location(true);
  15702. auto res = cli.Get("/");
  15703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15704. EXPECT_EQ(StatusCode::OK_200, res->status);
  15705. EXPECT_EQ("/a+b", res->body);
  15706. }
  15707. }
  15708. TEST(RedirectTest, ResolveRelativeLocation) {
  15709. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  15710. const std::vector<std::pair<std::string, std::string>> cases = {
  15711. {"g", "/b/c/g"},
  15712. {"./g", "/b/c/g"},
  15713. {"g/", "/b/c/g/"},
  15714. {"?y", "/b/c/d;p?y"},
  15715. {"g?y", "/b/c/g?y"},
  15716. {"#s", "/b/c/d;p?q#s"},
  15717. {"g#s", "/b/c/g#s"},
  15718. {"g?y#s", "/b/c/g?y#s"},
  15719. {";x", "/b/c/;x"},
  15720. {"g;x", "/b/c/g;x"},
  15721. {".", "/b/c/"},
  15722. {"./", "/b/c/"},
  15723. {"..", "/b/"},
  15724. {"../", "/b/"},
  15725. {"../g", "/b/g"},
  15726. {"../..", "/"},
  15727. {"../../", "/"},
  15728. {"../../g", "/g"},
  15729. {"../../../g", "/g"},
  15730. {"g.", "/b/c/g."},
  15731. {".g", "/b/c/.g"},
  15732. {"g..", "/b/c/g.."},
  15733. {"..g", "/b/c/..g"},
  15734. {"./../g", "/b/g"},
  15735. {"./g/.", "/b/c/g/"},
  15736. {"g/./h", "/b/c/g/h"},
  15737. {"g/../h", "/b/c/h"},
  15738. {"g;x=1/./y", "/b/c/g;x=1/y"},
  15739. {"g;x=1/../y", "/b/c/y"},
  15740. {"g?y/./x", "/b/c/g?y/./x"},
  15741. {"g#s/../x", "/b/c/g#s/../x"},
  15742. // Not relative-path references, so left for parse_url.
  15743. {"/g", "/g"},
  15744. {"//g", "//g"},
  15745. {"http://g/x", "http://g/x"},
  15746. {"g:h", "g:h"},
  15747. };
  15748. for (const auto &c : cases) {
  15749. EXPECT_EQ(c.second,
  15750. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  15751. << c.first;
  15752. }
  15753. }
  15754. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  15755. Server svr;
  15756. svr.Get("/dir/page", [](const Request &req, Response &res) {
  15757. res.set_redirect(req.get_param_value("to"));
  15758. });
  15759. svr.Get("/dir/next", [](const Request &req, Response &res) {
  15760. res.set_content(req.target, "text/plain");
  15761. });
  15762. svr.Get("/other", [](const Request &req, Response &res) {
  15763. res.set_content(req.target, "text/plain");
  15764. });
  15765. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15766. auto se = detail::scope_exit([&] {
  15767. svr.stop();
  15768. thread.join();
  15769. ASSERT_FALSE(svr.is_running());
  15770. });
  15771. svr.wait_until_ready();
  15772. const std::vector<std::pair<std::string, std::string>> cases = {
  15773. {"next", "/dir/next"},
  15774. {"./next?x=1", "/dir/next?x=1"},
  15775. {"../other", "/other"},
  15776. };
  15777. for (const auto &c : cases) {
  15778. Client cli(HOST, PORT);
  15779. cli.set_follow_location(true);
  15780. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  15781. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  15782. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  15783. EXPECT_EQ(c.second, res->body) << c.first;
  15784. }
  15785. }
  15786. #ifdef CPPHTTPLIB_SSL_ENABLED
  15787. TEST(RedirectTest, Issue2185_Online) {
  15788. SSLClient client("github.com");
  15789. client.set_follow_location(true);
  15790. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  15791. "Coollab-Windows.zip");
  15792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15793. EXPECT_EQ(StatusCode::OK_200, res->status);
  15794. EXPECT_EQ(9920427U, res->body.size());
  15795. }
  15796. #endif
  15797. TEST(VulnerabilityTest, CRLFInjection) {
  15798. Server svr;
  15799. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  15800. res.set_content("Hello 1", "text/plain");
  15801. });
  15802. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  15803. res.set_content("Hello 2", "text/plain");
  15804. });
  15805. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  15806. res.set_content("Hello 3", "text/plain");
  15807. });
  15808. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  15809. res.set_content("Hello 4", "text/plain");
  15810. });
  15811. svr.set_logger([](const Request &req, const Response & /*res*/) {
  15812. for (const auto &x : req.headers) {
  15813. auto key = x.first;
  15814. EXPECT_STRNE("evil", key.c_str());
  15815. }
  15816. });
  15817. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15818. auto se = detail::scope_exit([&] {
  15819. svr.stop();
  15820. thread.join();
  15821. ASSERT_FALSE(svr.is_running());
  15822. });
  15823. svr.wait_until_ready();
  15824. {
  15825. Client cli(HOST, PORT);
  15826. cli.Post("/test1", "A=B",
  15827. "application/x-www-form-urlencoded\r\nevil: hello1");
  15828. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  15829. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  15830. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  15831. }
  15832. }
  15833. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  15834. auto server_thread = std::thread([] {
  15835. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15836. default_socket_options(srv);
  15837. sockaddr_in addr{};
  15838. addr.sin_family = AF_INET;
  15839. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15840. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15841. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  15842. ::listen(srv, 1);
  15843. sockaddr_in cli_addr{};
  15844. socklen_t cli_len = sizeof(cli_addr);
  15845. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15846. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  15847. std::string buf_all;
  15848. char buf[2048];
  15849. ssize_t n;
  15850. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  15851. buf_all.append(buf, static_cast<size_t>(n));
  15852. size_t pos;
  15853. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  15854. auto request_block = buf_all.substr(0, pos + 4); // include separator
  15855. auto e = request_block.find("\r\n");
  15856. if (e != std::string::npos) {
  15857. auto request_line = request_block.substr(0, e);
  15858. std::string msg =
  15859. "CRLF injection detected in request line: '" + request_line + "'";
  15860. EXPECT_FALSE(true) << msg;
  15861. }
  15862. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  15863. ::send(cli,
  15864. #ifdef _WIN32
  15865. static_cast<const char *>(resp.c_str()),
  15866. static_cast<int>(resp.size()),
  15867. #else
  15868. resp.c_str(), resp.size(),
  15869. #endif
  15870. 0);
  15871. buf_all.erase(0, pos + 4);
  15872. }
  15873. }
  15874. detail::close_socket(cli);
  15875. detail::close_socket(srv);
  15876. });
  15877. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15878. auto cli = Client("127.0.0.1", PORT + 1);
  15879. auto headers = Headers{
  15880. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  15881. {"Connection", "keep-alive"}};
  15882. auto res = cli.Get("/hi", headers);
  15883. EXPECT_FALSE(res);
  15884. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15885. server_thread.join();
  15886. }
  15887. // A request rejected before any byte reaches the socket must fail right away
  15888. // instead of waiting for a response the server will never send.
  15889. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  15890. // The kernel completes the TCP handshake from the listen backlog, so the
  15891. // client connects, but nothing ever reads, responds or closes.
  15892. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15893. default_socket_options(srv);
  15894. sockaddr_in addr{};
  15895. addr.sin_family = AF_INET;
  15896. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15897. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15898. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15899. ASSERT_EQ(0, ::listen(srv, 8));
  15900. auto cli = Client("127.0.0.1", PORT + 1);
  15901. cli.set_read_timeout(10, 0);
  15902. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  15903. return std::chrono::duration_cast<std::chrono::milliseconds>(
  15904. std::chrono::steady_clock::now() - start)
  15905. .count();
  15906. };
  15907. {
  15908. Request req;
  15909. req.method = "GE T";
  15910. req.path = "/";
  15911. auto start = std::chrono::steady_clock::now();
  15912. auto res = cli.send(req);
  15913. EXPECT_FALSE(res);
  15914. EXPECT_EQ(Error::Write, res.error());
  15915. EXPECT_LT(elapsed_ms(start), 1000);
  15916. }
  15917. {
  15918. auto start = std::chrono::steady_clock::now();
  15919. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  15920. EXPECT_FALSE(res);
  15921. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15922. EXPECT_LT(elapsed_ms(start), 1000);
  15923. }
  15924. EXPECT_FALSE(cli.is_socket_open());
  15925. detail::close_socket(srv);
  15926. }
  15927. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  15928. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15929. default_socket_options(srv);
  15930. sockaddr_in addr{};
  15931. addr.sin_family = AF_INET;
  15932. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15933. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15934. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15935. ASSERT_EQ(0, ::listen(srv, 1));
  15936. std::string received;
  15937. auto server_thread = std::thread([&] {
  15938. auto sock = ::accept(srv, nullptr, nullptr);
  15939. if (sock == INVALID_SOCKET) { return; }
  15940. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  15941. char buf[2048];
  15942. ssize_t n;
  15943. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  15944. received.append(buf, static_cast<size_t>(n));
  15945. }
  15946. detail::close_socket(sock);
  15947. });
  15948. {
  15949. auto cli = Client("127.0.0.1", PORT + 1);
  15950. // "Z" sorts after the default headers, so writing straight to the socket
  15951. // would have sent the request line and those headers before the rejection.
  15952. auto handle =
  15953. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  15954. EXPECT_FALSE(handle.is_valid());
  15955. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  15956. }
  15957. server_thread.join();
  15958. detail::close_socket(srv);
  15959. EXPECT_TRUE(received.empty()) << received;
  15960. }
  15961. TEST(PathParamsTest, StaticMatch) {
  15962. const auto pattern = "/users/all";
  15963. detail::PathParamsMatcher matcher(pattern);
  15964. Request request;
  15965. request.path = "/users/all";
  15966. ASSERT_TRUE(matcher.match(request));
  15967. std::unordered_map<std::string, std::string> expected_params = {};
  15968. EXPECT_EQ(request.path_params, expected_params);
  15969. }
  15970. TEST(PathParamsTest, StaticMismatch) {
  15971. const auto pattern = "/users/all";
  15972. detail::PathParamsMatcher matcher(pattern);
  15973. Request request;
  15974. request.path = "/users/1";
  15975. ASSERT_FALSE(matcher.match(request));
  15976. }
  15977. TEST(PathParamsTest, SingleParamInTheMiddle) {
  15978. const auto pattern = "/users/:id/subscriptions";
  15979. detail::PathParamsMatcher matcher(pattern);
  15980. Request request;
  15981. request.path = "/users/42/subscriptions";
  15982. ASSERT_TRUE(matcher.match(request));
  15983. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15984. EXPECT_EQ(request.path_params, expected_params);
  15985. }
  15986. TEST(PathParamsTest, SingleParamInTheEnd) {
  15987. const auto pattern = "/users/:id";
  15988. detail::PathParamsMatcher matcher(pattern);
  15989. Request request;
  15990. request.path = "/users/24";
  15991. ASSERT_TRUE(matcher.match(request));
  15992. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  15993. EXPECT_EQ(request.path_params, expected_params);
  15994. }
  15995. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  15996. const auto pattern = "/users/:id/";
  15997. detail::PathParamsMatcher matcher(pattern);
  15998. Request request;
  15999. request.path = "/users/42/";
  16000. ASSERT_TRUE(matcher.match(request));
  16001. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16002. EXPECT_EQ(request.path_params, expected_params);
  16003. }
  16004. TEST(PathParamsTest, EmptyParam) {
  16005. const auto pattern = "/users/:id/";
  16006. detail::PathParamsMatcher matcher(pattern);
  16007. Request request;
  16008. request.path = "/users//";
  16009. ASSERT_TRUE(matcher.match(request));
  16010. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  16011. EXPECT_EQ(request.path_params, expected_params);
  16012. }
  16013. TEST(PathParamsTest, FragmentMismatch) {
  16014. const auto pattern = "/users/:id/";
  16015. detail::PathParamsMatcher matcher(pattern);
  16016. Request request;
  16017. request.path = "/admins/24/";
  16018. ASSERT_FALSE(matcher.match(request));
  16019. }
  16020. TEST(PathParamsTest, ExtraFragments) {
  16021. const auto pattern = "/users/:id";
  16022. detail::PathParamsMatcher matcher(pattern);
  16023. Request request;
  16024. request.path = "/users/42/subscriptions";
  16025. ASSERT_FALSE(matcher.match(request));
  16026. }
  16027. TEST(PathParamsTest, MissingTrailingParam) {
  16028. const auto pattern = "/users/:id";
  16029. detail::PathParamsMatcher matcher(pattern);
  16030. Request request;
  16031. request.path = "/users";
  16032. ASSERT_FALSE(matcher.match(request));
  16033. }
  16034. TEST(PathParamsTest, MissingParamInTheMiddle) {
  16035. const auto pattern = "/users/:id/subscriptions";
  16036. detail::PathParamsMatcher matcher(pattern);
  16037. Request request;
  16038. request.path = "/users/subscriptions";
  16039. ASSERT_FALSE(matcher.match(request));
  16040. }
  16041. TEST(PathParamsTest, MultipleParams) {
  16042. const auto pattern = "/users/:userid/subscriptions/:subid";
  16043. detail::PathParamsMatcher matcher(pattern);
  16044. Request request;
  16045. request.path = "/users/42/subscriptions/2";
  16046. ASSERT_TRUE(matcher.match(request));
  16047. std::unordered_map<std::string, std::string> expected_params = {
  16048. {"userid", "42"}, {"subid", "2"}};
  16049. EXPECT_EQ(request.path_params, expected_params);
  16050. }
  16051. TEST(PathParamsTest, SequenceOfParams) {
  16052. const auto pattern = "/values/:x/:y/:z";
  16053. detail::PathParamsMatcher matcher(pattern);
  16054. Request request;
  16055. request.path = "/values/1/2/3";
  16056. ASSERT_TRUE(matcher.match(request));
  16057. std::unordered_map<std::string, std::string> expected_params = {
  16058. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  16059. EXPECT_EQ(request.path_params, expected_params);
  16060. }
  16061. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  16062. const auto pattern = "/prefix:suffix";
  16063. detail::PathParamsMatcher matcher(pattern);
  16064. Request request;
  16065. request.path = "/prefix:suffix";
  16066. ASSERT_TRUE(matcher.match(request));
  16067. const std::unordered_map<std::string, std::string> expected_params = {};
  16068. EXPECT_EQ(request.path_params, expected_params);
  16069. }
  16070. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  16071. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  16072. // calling thread's stack on a long enough path for a quantified pattern;
  16073. // RegexMatcher must refuse to run regex matching on paths beyond
  16074. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  16075. detail::RegexMatcher matcher("/files/(.*)");
  16076. Request within_limit;
  16077. within_limit.path = "/files/" + std::string(10, 'A');
  16078. EXPECT_TRUE(matcher.match(within_limit));
  16079. Request over_limit;
  16080. over_limit.path =
  16081. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  16082. EXPECT_FALSE(matcher.match(over_limit));
  16083. }
  16084. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  16085. Server svr;
  16086. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  16087. res.set_content("ok", "text/plain");
  16088. });
  16089. auto port = svr.bind_to_any_port(HOST);
  16090. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16091. auto se = detail::scope_exit([&] {
  16092. svr.stop();
  16093. thread.join();
  16094. ASSERT_FALSE(svr.is_running());
  16095. });
  16096. svr.wait_until_ready();
  16097. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  16098. // request URI limit; this used to be able to crash the process.
  16099. std::string path =
  16100. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  16101. std::string req = "GET " + path +
  16102. " HTTP/1.1\r\n"
  16103. "Host: " +
  16104. std::string(HOST) + ":" + std::to_string(port) +
  16105. "\r\n"
  16106. "Connection: close\r\n"
  16107. "\r\n";
  16108. std::string response;
  16109. ASSERT_TRUE(send_request(5, req, &response, port));
  16110. EXPECT_NE(std::string::npos, response.find("404"));
  16111. }
  16112. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  16113. Server svr;
  16114. auto handler = [](const Request & /*req*/, Response &res) {
  16115. res.set_content("hit", "text/plain");
  16116. };
  16117. // No regex metacharacter, so this one is compared literally
  16118. svr.Get("/literal/route", handler);
  16119. // '.' is a regex metacharacter, so this one must keep regex semantics
  16120. svr.Get("/a.c", handler);
  16121. auto port = svr.bind_to_any_port(HOST);
  16122. std::thread t([&]() { svr.listen_after_bind(); });
  16123. auto se = detail::scope_exit([&] {
  16124. svr.stop();
  16125. t.join();
  16126. ASSERT_FALSE(svr.is_running());
  16127. });
  16128. svr.wait_until_ready();
  16129. Client cli(HOST, port);
  16130. struct {
  16131. const char *path;
  16132. int status;
  16133. } cases[] = {
  16134. {"/literal/route", StatusCode::OK_200},
  16135. {"/literal/routes", StatusCode::NotFound_404},
  16136. {"/literal/rout", StatusCode::NotFound_404},
  16137. {"/abc", StatusCode::OK_200},
  16138. {"/a.c", StatusCode::OK_200},
  16139. };
  16140. for (const auto &x : cases) {
  16141. auto res = cli.Get(x.path);
  16142. ASSERT_TRUE(res) << x.path;
  16143. EXPECT_EQ(x.status, res->status) << x.path;
  16144. }
  16145. }
  16146. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  16147. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  16148. // from exhausting the stack, so it must only constrain routes that actually
  16149. // run a regular expression. A literal route is matched by comparison and
  16150. // stays usable at any length.
  16151. Server svr;
  16152. const std::string pattern =
  16153. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  16154. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  16155. res.set_content("hit", "text/plain");
  16156. });
  16157. auto port = svr.bind_to_any_port(HOST);
  16158. std::thread t([&]() { svr.listen_after_bind(); });
  16159. auto se = detail::scope_exit([&] {
  16160. svr.stop();
  16161. t.join();
  16162. ASSERT_FALSE(svr.is_running());
  16163. });
  16164. svr.wait_until_ready();
  16165. Client cli(HOST, port);
  16166. auto res = cli.Get(pattern);
  16167. ASSERT_TRUE(res);
  16168. EXPECT_EQ(StatusCode::OK_200, res->status);
  16169. }
  16170. TEST(ParseUrlTest, VariousPatterns) {
  16171. {
  16172. detail::UrlComponents uc;
  16173. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  16174. EXPECT_EQ("http", uc.scheme);
  16175. EXPECT_EQ("example.com", uc.host);
  16176. EXPECT_EQ("8080", uc.port);
  16177. EXPECT_EQ("/path", uc.path);
  16178. EXPECT_EQ("?q=1", uc.query);
  16179. }
  16180. {
  16181. detail::UrlComponents uc;
  16182. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  16183. EXPECT_EQ("https", uc.scheme);
  16184. EXPECT_EQ("example.com", uc.host);
  16185. EXPECT_TRUE(uc.port.empty());
  16186. EXPECT_EQ("/path", uc.path);
  16187. }
  16188. {
  16189. detail::UrlComponents uc;
  16190. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  16191. EXPECT_EQ("::1", uc.host);
  16192. EXPECT_EQ("8080", uc.port);
  16193. EXPECT_EQ("/path", uc.path);
  16194. }
  16195. {
  16196. detail::UrlComponents uc;
  16197. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  16198. }
  16199. {
  16200. // Bytes after the IPv6 literal must be a delimiter, not folded into
  16201. // the path while the connection still targets the bracketed host.
  16202. detail::UrlComponents uc;
  16203. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  16204. }
  16205. {
  16206. detail::UrlComponents uc;
  16207. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  16208. }
  16209. {
  16210. detail::UrlComponents uc;
  16211. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  16212. EXPECT_EQ("::1", uc.host);
  16213. EXPECT_TRUE(uc.port.empty());
  16214. EXPECT_EQ("/path", uc.path);
  16215. }
  16216. {
  16217. detail::UrlComponents uc;
  16218. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  16219. EXPECT_TRUE(uc.scheme.empty());
  16220. EXPECT_EQ("example.com", uc.host);
  16221. EXPECT_EQ("/path", uc.path);
  16222. EXPECT_EQ("?q=1", uc.query);
  16223. }
  16224. {
  16225. detail::UrlComponents uc;
  16226. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  16227. EXPECT_TRUE(uc.host.empty());
  16228. EXPECT_EQ("/path", uc.path);
  16229. EXPECT_EQ("?q=1", uc.query);
  16230. }
  16231. {
  16232. detail::UrlComponents uc;
  16233. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  16234. EXPECT_EQ("example.com", uc.host);
  16235. EXPECT_EQ("8080", uc.port);
  16236. }
  16237. {
  16238. // Unix socket path — must not be parsed as host
  16239. detail::UrlComponents uc;
  16240. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  16241. EXPECT_TRUE(uc.host.empty());
  16242. }
  16243. {
  16244. detail::UrlComponents uc;
  16245. ASSERT_TRUE(detail::parse_url("", uc));
  16246. EXPECT_TRUE(uc.host.empty());
  16247. EXPECT_TRUE(uc.path.empty());
  16248. }
  16249. {
  16250. detail::UrlComponents uc;
  16251. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  16252. }
  16253. {
  16254. detail::UrlComponents uc;
  16255. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  16256. }
  16257. {
  16258. // Accepted by parse_url; callers restrict to http/https
  16259. detail::UrlComponents uc;
  16260. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  16261. EXPECT_EQ("ftp", uc.scheme);
  16262. }
  16263. {
  16264. detail::UrlComponents uc;
  16265. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  16266. }
  16267. {
  16268. detail::UrlComponents uc;
  16269. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  16270. }
  16271. }
  16272. TEST(ParseUrlTest, FragmentHandling) {
  16273. {
  16274. detail::UrlComponents uc;
  16275. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  16276. EXPECT_EQ("/path", uc.path);
  16277. EXPECT_TRUE(uc.query.empty());
  16278. }
  16279. {
  16280. detail::UrlComponents uc;
  16281. ASSERT_TRUE(detail::parse_url("#frag", uc));
  16282. EXPECT_TRUE(uc.path.empty());
  16283. EXPECT_TRUE(uc.query.empty());
  16284. }
  16285. }
  16286. TEST(ParseUrlTest, UserinfoHandling) {
  16287. // Userinfo with @ but no colon — host includes @
  16288. detail::UrlComponents uc;
  16289. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  16290. EXPECT_EQ("user@host.com", uc.host);
  16291. EXPECT_EQ("/path", uc.path);
  16292. }
  16293. TEST(ParseUrlTest, IPv6EdgeCases) {
  16294. {
  16295. detail::UrlComponents uc;
  16296. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  16297. EXPECT_TRUE(uc.scheme.empty());
  16298. EXPECT_EQ("::1", uc.host);
  16299. EXPECT_EQ("8080", uc.port);
  16300. }
  16301. {
  16302. // Zone ID '%25' is not in [a-fA-F0-9:]
  16303. detail::UrlComponents uc;
  16304. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  16305. }
  16306. }
  16307. TEST(ParseUrlTest, SchemeEdgeCases) {
  16308. {
  16309. detail::UrlComponents uc;
  16310. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  16311. }
  16312. {
  16313. detail::UrlComponents uc;
  16314. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  16315. }
  16316. {
  16317. detail::UrlComponents uc;
  16318. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  16319. }
  16320. }
  16321. TEST(ParseUrlTest, PortEdgeCases) {
  16322. {
  16323. detail::UrlComponents uc;
  16324. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  16325. EXPECT_TRUE(uc.port.empty());
  16326. EXPECT_EQ("/path", uc.path);
  16327. }
  16328. {
  16329. // parse_url accepts any port string; validation is done by parse_port
  16330. detail::UrlComponents uc;
  16331. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  16332. EXPECT_EQ("abc", uc.port);
  16333. }
  16334. }
  16335. TEST(ParseUrlTest, WebSocketPatterns) {
  16336. {
  16337. detail::UrlComponents uc;
  16338. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  16339. EXPECT_EQ("ws", uc.scheme);
  16340. EXPECT_EQ("echo.example.com", uc.host);
  16341. EXPECT_EQ("8080", uc.port);
  16342. EXPECT_EQ("/ws", uc.path);
  16343. }
  16344. {
  16345. detail::UrlComponents uc;
  16346. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  16347. EXPECT_EQ("wss", uc.scheme);
  16348. EXPECT_EQ("echo.example.com", uc.host);
  16349. EXPECT_TRUE(uc.port.empty());
  16350. EXPECT_EQ("/ws", uc.path);
  16351. }
  16352. }
  16353. TEST(ParseUrlTest, QueryOnly) {
  16354. detail::UrlComponents uc;
  16355. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  16356. EXPECT_TRUE(uc.host.empty());
  16357. EXPECT_TRUE(uc.path.empty());
  16358. EXPECT_EQ("?q=1&r=2", uc.query);
  16359. }
  16360. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  16361. detail::UrlComponents uc;
  16362. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  16363. EXPECT_TRUE(uc.scheme.empty());
  16364. EXPECT_EQ("example.com", uc.host);
  16365. EXPECT_EQ("443", uc.port);
  16366. EXPECT_EQ("/path", uc.path);
  16367. }
  16368. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  16369. // If ipv6 regex working, regex match codepath is taken.
  16370. // else port will default to 80 in Client impl
  16371. int clientImplMagicPort = 80;
  16372. int port = 4321;
  16373. // above ports must be different to avoid false negative
  16374. EXPECT_NE(clientImplMagicPort, port);
  16375. std::string ipV6TestURL = "http://[ff06::c3]";
  16376. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  16377. CLIENT_PRIVATE_KEY_FILE);
  16378. EXPECT_EQ(cli.port(), port);
  16379. }
  16380. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  16381. auto file_path = "./www/dir/index.html";
  16382. auto dir_path = "./www/dir";
  16383. detail::FileStat stat_file(file_path);
  16384. EXPECT_TRUE(stat_file.is_file());
  16385. EXPECT_FALSE(stat_file.is_dir());
  16386. detail::FileStat stat_dir(dir_path);
  16387. EXPECT_FALSE(stat_dir.is_file());
  16388. EXPECT_TRUE(stat_dir.is_dir());
  16389. }
  16390. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  16391. // IPv4 with default HTTP port (80)
  16392. EXPECT_EQ("example.com",
  16393. detail::make_host_and_port_string("example.com", 80, false));
  16394. // IPv4 with default HTTPS port (443)
  16395. EXPECT_EQ("example.com",
  16396. detail::make_host_and_port_string("example.com", 443, true));
  16397. // IPv4 with non-default HTTP port
  16398. EXPECT_EQ("example.com:8080",
  16399. detail::make_host_and_port_string("example.com", 8080, false));
  16400. // IPv4 with non-default HTTPS port
  16401. EXPECT_EQ("example.com:8443",
  16402. detail::make_host_and_port_string("example.com", 8443, true));
  16403. // IPv6 with default HTTP port (80)
  16404. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  16405. // IPv6 with default HTTPS port (443)
  16406. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  16407. // IPv6 with non-default HTTP port
  16408. EXPECT_EQ("[::1]:8080",
  16409. detail::make_host_and_port_string("::1", 8080, false));
  16410. // IPv6 with non-default HTTPS port
  16411. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  16412. // IPv6 full address with default port
  16413. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  16414. detail::make_host_and_port_string(
  16415. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  16416. // IPv6 full address with non-default port
  16417. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  16418. detail::make_host_and_port_string(
  16419. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  16420. // IPv6 localhost with non-default port
  16421. EXPECT_EQ("[::1]:3000",
  16422. detail::make_host_and_port_string("::1", 3000, false));
  16423. // IPv6 with zone ID (link-local address) with default port
  16424. EXPECT_EQ("[fe80::1%eth0]",
  16425. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  16426. // IPv6 with zone ID (link-local address) with non-default port
  16427. EXPECT_EQ("[fe80::1%eth0]:8080",
  16428. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  16429. // Edge case: Port 443 with is_ssl=false (should add port)
  16430. EXPECT_EQ("example.com:443",
  16431. detail::make_host_and_port_string("example.com", 443, false));
  16432. // Edge case: Port 80 with is_ssl=true (should add port)
  16433. EXPECT_EQ("example.com:80",
  16434. detail::make_host_and_port_string("example.com", 80, true));
  16435. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  16436. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  16437. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  16438. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  16439. // Security fix: Already bracketed IPv6 should not get double brackets
  16440. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  16441. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  16442. EXPECT_EQ("[::1]:8080",
  16443. detail::make_host_and_port_string("[::1]", 8080, false));
  16444. EXPECT_EQ("[2001:db8::1]:8080",
  16445. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  16446. EXPECT_EQ("[fe80::1%eth0]",
  16447. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  16448. EXPECT_EQ("[fe80::1%eth0]:8080",
  16449. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  16450. // Edge case: Empty host (should return as-is)
  16451. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  16452. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  16453. // This is a known limitation but shouldn't crash
  16454. EXPECT_EQ("[host:name]",
  16455. detail::make_host_and_port_string("host:name", 80, false));
  16456. // Port number edge cases (no validation, but should not crash)
  16457. EXPECT_EQ("example.com:0",
  16458. detail::make_host_and_port_string("example.com", 0, false));
  16459. EXPECT_EQ("example.com:-1",
  16460. detail::make_host_and_port_string("example.com", -1, false));
  16461. EXPECT_EQ("example.com:65535",
  16462. detail::make_host_and_port_string("example.com", 65535, false));
  16463. EXPECT_EQ("example.com:65536",
  16464. detail::make_host_and_port_string("example.com", 65536, false));
  16465. }
  16466. #ifdef CPPHTTPLIB_SSL_ENABLED
  16467. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  16468. httplib::SSLClient cli("roblox.com", 443);
  16469. cli.set_follow_location(true);
  16470. auto res = cli.Get("/");
  16471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16472. EXPECT_EQ(StatusCode::OK_200, res->status);
  16473. }
  16474. #endif
  16475. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  16476. Server svr;
  16477. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16478. EXPECT_EQ(res.status, 400);
  16479. });
  16480. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16481. auto se = detail::scope_exit([&] {
  16482. svr.stop();
  16483. thread.join();
  16484. ASSERT_FALSE(svr.is_running());
  16485. });
  16486. svr.wait_until_ready();
  16487. Client cli(HOST, PORT);
  16488. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  16489. }
  16490. TEST(InvalidHeaderCharsTest, is_field_name) {
  16491. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  16492. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  16493. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  16494. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  16495. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  16496. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  16497. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  16498. EXPECT_FALSE(detail::fields::is_field_name(""));
  16499. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  16500. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  16501. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  16502. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  16503. }
  16504. TEST(InvalidHeaderCharsTest, is_field_value) {
  16505. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  16506. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  16507. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  16508. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  16509. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  16510. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  16511. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  16512. EXPECT_TRUE(detail::fields::is_field_value(""));
  16513. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  16514. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  16515. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  16516. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  16517. EXPECT_TRUE(detail::fields::is_field_value("0"));
  16518. }
  16519. TEST(InvalidHeaderCharsTest, OnServer) {
  16520. Server svr;
  16521. svr.Get("/test_name", [&](const Request &req, Response &res) {
  16522. std::string header = "Not Set";
  16523. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16524. res.set_header(header, "value");
  16525. res.set_content("Page Content Page Content", "text/plain");
  16526. });
  16527. svr.Get("/test_value", [&](const Request &req, Response &res) {
  16528. std::string header = "Not Set";
  16529. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16530. res.set_header("X-Test", header);
  16531. res.set_content("Page Content Page Content", "text/plain");
  16532. });
  16533. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16534. auto se = detail::scope_exit([&] {
  16535. svr.stop();
  16536. thread.join();
  16537. ASSERT_FALSE(svr.is_running());
  16538. });
  16539. svr.wait_until_ready();
  16540. Client cli(HOST, PORT);
  16541. {
  16542. auto res = cli.Get(
  16543. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16545. EXPECT_EQ("Page Content Page Content", res->body);
  16546. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16547. }
  16548. {
  16549. auto res = cli.Get(
  16550. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16552. EXPECT_EQ("Page Content Page Content", res->body);
  16553. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16554. }
  16555. }
  16556. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  16557. auto handled = false;
  16558. Server svr;
  16559. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16560. thread t = thread([&] { svr.listen(HOST, PORT); });
  16561. auto se = detail::scope_exit([&] {
  16562. svr.stop();
  16563. t.join();
  16564. ASSERT_FALSE(svr.is_running());
  16565. ASSERT_FALSE(handled);
  16566. });
  16567. svr.wait_until_ready();
  16568. auto req = "POST /test HTTP/1.1\r\n"
  16569. "Content-Length: x\r\n"
  16570. "\r\n";
  16571. std::string response;
  16572. ASSERT_TRUE(send_request(1, req, &response));
  16573. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16574. response.substr(0, response.find("\r\n")));
  16575. }
  16576. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  16577. // case-insensitive, and a server that receives a 100-continue expectation in
  16578. // an HTTP/1.0 request MUST ignore it.
  16579. static void probe_expect(int port, const std::string &req, bool *got_100) {
  16580. std::string response;
  16581. ASSERT_TRUE(send_request(1, req, &response, port));
  16582. *got_100 = response.find("100 Continue") != std::string::npos;
  16583. }
  16584. class ExpectTokenTest : public ::testing::Test {
  16585. protected:
  16586. void SetUp() override {
  16587. svr_.Post("/p", [](const Request &, Response &res) {
  16588. res.set_content("ok", "text/plain");
  16589. });
  16590. port_ = svr_.bind_to_any_port(HOST);
  16591. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16592. svr_.wait_until_ready();
  16593. }
  16594. void TearDown() override {
  16595. svr_.stop();
  16596. if (thread_.joinable()) { thread_.join(); }
  16597. }
  16598. std::string request(const char *version, const char *expect_value) const {
  16599. return std::string("POST /p ") + version +
  16600. "\r\n"
  16601. "Host: localhost\r\n"
  16602. "Content-Length: 2\r\n"
  16603. "Connection: close\r\n"
  16604. "Expect: " +
  16605. expect_value +
  16606. "\r\n"
  16607. "\r\n"
  16608. "hi";
  16609. }
  16610. Server svr_;
  16611. int port_ = 0;
  16612. thread thread_;
  16613. };
  16614. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  16615. bool got_100 = false;
  16616. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  16617. EXPECT_TRUE(got_100);
  16618. }
  16619. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  16620. bool got_100 = true;
  16621. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  16622. EXPECT_FALSE(got_100);
  16623. }
  16624. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  16625. bool got_100 = false;
  16626. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  16627. EXPECT_TRUE(got_100);
  16628. }
  16629. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  16630. bool got_100 = false;
  16631. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  16632. EXPECT_TRUE(got_100);
  16633. }
  16634. // `100 Continue` is sent only when the server starts reading the body, so a
  16635. // request rejected before that never invites the client to send it. The
  16636. // requests below carry the expectation but withhold the body, as a client
  16637. // waiting for `100 Continue` would.
  16638. // A POST that expects `100 Continue` and withholds its two-byte body.
  16639. static std::string expect_headers_only(const std::string &path) {
  16640. return "POST " + path +
  16641. " HTTP/1.1\r\n"
  16642. "Host: localhost\r\n"
  16643. "Content-Length: 2\r\n"
  16644. "Expect: 100-continue\r\n"
  16645. "\r\n";
  16646. }
  16647. class ExpectLazyContinueTest : public ::testing::Test {
  16648. protected:
  16649. void SetUp() override {
  16650. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  16651. if (req.path == "/pre-routing") {
  16652. res.status = StatusCode::Unauthorized_401;
  16653. return Server::HandlerResponse::Handled;
  16654. }
  16655. return Server::HandlerResponse::Unhandled;
  16656. });
  16657. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  16658. if (req.matched_route == "/pre-request") {
  16659. res.status = StatusCode::Forbidden_403;
  16660. return Server::HandlerResponse::Handled;
  16661. }
  16662. return Server::HandlerResponse::Unhandled;
  16663. });
  16664. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  16665. res.set_content("ok", "text/plain");
  16666. });
  16667. svr_.Post("/pre-request", [](const Request &, Response &res) {
  16668. res.set_content("ok", "text/plain");
  16669. });
  16670. svr_.Post("/reader-used", [](const Request &, Response &res,
  16671. const ContentReader &content_reader) {
  16672. std::string body;
  16673. content_reader([&](const char *data, size_t len) {
  16674. body.append(data, len);
  16675. return true;
  16676. });
  16677. res.set_content(body, "text/plain");
  16678. });
  16679. svr_.Post("/reader-unused",
  16680. [](const Request &, Response &res, const ContentReader &) {
  16681. res.set_content("ignored", "text/plain");
  16682. });
  16683. port_ = svr_.bind_to_any_port(HOST);
  16684. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16685. svr_.wait_until_ready();
  16686. }
  16687. void TearDown() override {
  16688. svr_.stop();
  16689. if (thread_.joinable()) { thread_.join(); }
  16690. }
  16691. // Sends `req` and reads until the server closes the connection. Returns
  16692. // false if the read had to wait for the client-side timeout instead.
  16693. bool send_until_closed(const std::string &req, std::string *resp) const {
  16694. auto start = std::chrono::steady_clock::now();
  16695. if (!send_request(3, req, resp, port_)) { return false; }
  16696. auto elapsed = std::chrono::steady_clock::now() - start;
  16697. return elapsed < std::chrono::seconds(2);
  16698. }
  16699. // The final response comes without `100 Continue`, and the server closes
  16700. // the connection since the body may or may not follow.
  16701. void expect_final_without_interim(const std::string &path,
  16702. const char *status_line) const {
  16703. std::string resp;
  16704. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  16705. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  16706. EXPECT_EQ(0u, resp.find(status_line));
  16707. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16708. }
  16709. Server svr_;
  16710. int port_ = 0;
  16711. thread thread_;
  16712. };
  16713. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  16714. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  16715. }
  16716. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  16717. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  16718. }
  16719. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  16720. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  16721. }
  16722. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  16723. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  16724. }
  16725. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  16726. // The body follows once `100 Continue` has had time to arrive.
  16727. auto req = expect_headers_only("/reader-used");
  16728. req.insert(req.size() - 2, "Connection: close\r\n");
  16729. std::string resp;
  16730. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  16731. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  16732. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  16733. EXPECT_NE(std::string::npos, resp.find("hi"));
  16734. }
  16735. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  16736. // Large enough for the client to add `Expect: 100-continue` itself.
  16737. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  16738. std::atomic<bool> body_sent{false};
  16739. Client cli(HOST, port_);
  16740. auto res = cli.Post(
  16741. "/pre-request", length,
  16742. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  16743. body_sent = true;
  16744. std::string chunk(len, 'x');
  16745. sink.write(chunk.data(), chunk.size());
  16746. return true;
  16747. },
  16748. "application/octet-stream");
  16749. ASSERT_TRUE(res);
  16750. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16751. EXPECT_FALSE(body_sent);
  16752. }
  16753. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  16754. Server svr;
  16755. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  16756. return StatusCode::ExpectationFailed_417;
  16757. });
  16758. svr.Post("/p", [](const Request &, Response &res) {
  16759. res.set_content("ok", "text/plain");
  16760. });
  16761. auto port = svr.bind_to_any_port(HOST);
  16762. thread t = thread([&] { svr.listen_after_bind(); });
  16763. auto se = detail::scope_exit([&] {
  16764. svr.stop();
  16765. t.join();
  16766. });
  16767. svr.wait_until_ready();
  16768. std::string resp;
  16769. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  16770. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  16771. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16772. // Exactly one response: the route handler must not run after the 417.
  16773. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  16774. }
  16775. #ifndef _WIN32
  16776. TEST(Expect100ContinueTest, ServerClosesConnection) {
  16777. static constexpr char reject[] = "Unauthorized";
  16778. static constexpr char accept[] = "Upload accepted";
  16779. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  16780. Server svr;
  16781. svr.set_expect_100_continue_handler(
  16782. [](const Request & /*req*/, Response &res) {
  16783. res.status = StatusCode::Unauthorized_401;
  16784. res.set_content(reject, "text/plain");
  16785. return res.status;
  16786. });
  16787. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  16788. res.set_content(accept, "text/plain");
  16789. });
  16790. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16791. auto se = detail::scope_exit([&] {
  16792. svr.stop();
  16793. thread.join();
  16794. ASSERT_FALSE(svr.is_running());
  16795. });
  16796. svr.wait_until_ready();
  16797. {
  16798. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  16799. curl_easy_init(), &curl_easy_cleanup};
  16800. ASSERT_NE(curl, nullptr);
  16801. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  16802. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  16803. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  16804. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  16805. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  16806. &curl_slist_free_all};
  16807. ASSERT_NE(list, nullptr);
  16808. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  16809. struct read_data {
  16810. size_t read_size;
  16811. size_t total_size;
  16812. } data = {0, total_size};
  16813. using read_callback_t =
  16814. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16815. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  16816. void *userdata) -> size_t {
  16817. read_data *d = (read_data *)userdata;
  16818. if (!userdata || d->read_size >= d->total_size) { return 0; }
  16819. std::fill_n(ptr, size * nmemb, 'A');
  16820. d->read_size += size * nmemb;
  16821. return size * nmemb;
  16822. };
  16823. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  16824. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  16825. std::vector<char> buffer;
  16826. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  16827. using write_callback_t =
  16828. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16829. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  16830. void *userdata) -> size_t {
  16831. std::vector<char> *buf = (std::vector<char> *)userdata;
  16832. buf->reserve(buf->size() + size * nmemb + 1);
  16833. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  16834. return size * nmemb;
  16835. };
  16836. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  16837. {
  16838. const auto res = curl_easy_perform(curl.get());
  16839. ASSERT_EQ(res, CURLE_OK);
  16840. }
  16841. {
  16842. auto response_code = long{};
  16843. const auto res =
  16844. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  16845. ASSERT_EQ(res, CURLE_OK);
  16846. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  16847. }
  16848. {
  16849. auto dl = curl_off_t{};
  16850. const auto res =
  16851. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  16852. ASSERT_EQ(res, CURLE_OK);
  16853. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  16854. }
  16855. {
  16856. buffer.push_back('\0');
  16857. ASSERT_STRCASEEQ(buffer.data(), reject);
  16858. }
  16859. }
  16860. }
  16861. #endif
  16862. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  16863. // Regression test for #2458.
  16864. //
  16865. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  16866. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  16867. // ticket can make the client socket spuriously readable during the
  16868. // 100-continue wait. If the readiness is mistaken for an incoming response,
  16869. // the client withholds the body and then blocks reading a response that never
  16870. // comes, failing with `Failed to read connection`.
  16871. //
  16872. // A correct client (like curl) sends the body once no `100 Continue` arrives
  16873. // within the timeout. This raw OpenSSL server deliberately never sends
  16874. // `100 Continue`; the client must still deliver the body and receive 200.
  16875. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  16876. signal(SIGPIPE, SIG_IGN);
  16877. const auto port = PORT + 4;
  16878. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16879. ASSERT_NE(srv, INVALID_SOCKET);
  16880. int opt = 1;
  16881. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  16882. sockaddr_in addr{};
  16883. addr.sin_family = AF_INET;
  16884. addr.sin_port = htons(static_cast<uint16_t>(port));
  16885. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16886. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16887. ASSERT_EQ(0, ::listen(srv, 1));
  16888. std::atomic<size_t> server_body_bytes{0};
  16889. auto server_thread = std::thread([&] {
  16890. sockaddr_in cli_addr{};
  16891. socklen_t cli_len = sizeof(cli_addr);
  16892. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16893. if (cli == INVALID_SOCKET) { return; }
  16894. // Bound the lifetime of the server side so a buggy client (which never
  16895. // sends the body) cannot make this thread block forever on join.
  16896. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  16897. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  16898. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  16899. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  16900. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  16901. SSL *ssl = SSL_new(ctx);
  16902. SSL_set_fd(ssl, static_cast<int>(cli));
  16903. if (SSL_accept(ssl) > 0) {
  16904. // Read the request headers. Reading here also flushes the TLS 1.3
  16905. // session tickets to the client. Deliberately do NOT send
  16906. // `100 Continue`.
  16907. std::string buf;
  16908. char tmp[1024];
  16909. while (buf.find("\r\n\r\n") == std::string::npos) {
  16910. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16911. if (n <= 0) { break; }
  16912. buf.append(tmp, static_cast<size_t>(n));
  16913. }
  16914. // A correct client sends the body now; count what arrives.
  16915. auto pos = buf.find("\r\n\r\n");
  16916. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  16917. while (body < 4096) {
  16918. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16919. if (n <= 0) { break; }
  16920. body += static_cast<size_t>(n);
  16921. }
  16922. server_body_bytes = body;
  16923. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  16924. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  16925. SSL_shutdown(ssl);
  16926. }
  16927. SSL_free(ssl);
  16928. detail::close_socket(cli);
  16929. SSL_CTX_free(ctx);
  16930. });
  16931. auto se = detail::scope_exit([&] {
  16932. server_thread.join();
  16933. detail::close_socket(srv);
  16934. });
  16935. SSLClient cli("127.0.0.1", port);
  16936. cli.enable_server_certificate_verification(false);
  16937. cli.set_connection_timeout(5, 0);
  16938. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  16939. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  16940. std::string body(4096, 'A');
  16941. auto res = cli.Put("/api/test", body, "application/json");
  16942. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  16943. EXPECT_EQ(StatusCode::OK_200, res->status);
  16944. EXPECT_EQ(body.size(), server_body_bytes.load());
  16945. }
  16946. #endif
  16947. template <typename S, typename C>
  16948. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  16949. svr.Get("/stream", [&](const Request &, Response &res) {
  16950. auto data = new std::string("01234567890123456789");
  16951. res.set_content_provider(
  16952. data->size(), "text/plain",
  16953. [&, data](size_t offset, size_t length, DataSink &sink) {
  16954. const size_t DATA_CHUNK_SIZE = 4;
  16955. const auto &d = *data;
  16956. std::this_thread::sleep_for(std::chrono::seconds(1));
  16957. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  16958. return true;
  16959. },
  16960. [data](bool success) {
  16961. EXPECT_FALSE(success);
  16962. delete data;
  16963. });
  16964. });
  16965. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  16966. auto i = new size_t(0);
  16967. res.set_content_provider(
  16968. "text/plain",
  16969. [i](size_t, DataSink &sink) {
  16970. if (*i < 5) {
  16971. std::this_thread::sleep_for(std::chrono::seconds(1));
  16972. sink.write("abcd", 4);
  16973. (*i)++;
  16974. } else {
  16975. sink.done();
  16976. }
  16977. return true;
  16978. },
  16979. [i](bool success) {
  16980. EXPECT_FALSE(success);
  16981. delete i;
  16982. });
  16983. });
  16984. svr.Get("/chunked", [&](const Request &, Response &res) {
  16985. auto i = new size_t(0);
  16986. res.set_chunked_content_provider(
  16987. "text/plain",
  16988. [i](size_t, DataSink &sink) {
  16989. if (*i < 5) {
  16990. std::this_thread::sleep_for(std::chrono::seconds(1));
  16991. sink.os << "abcd";
  16992. (*i)++;
  16993. } else {
  16994. sink.done();
  16995. }
  16996. return true;
  16997. },
  16998. [i](bool success) {
  16999. EXPECT_FALSE(success);
  17000. delete i;
  17001. });
  17002. });
  17003. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  17004. auto se = detail::scope_exit([&] {
  17005. svr.stop();
  17006. listen_thread.join();
  17007. ASSERT_FALSE(svr.is_running());
  17008. });
  17009. svr.wait_until_ready();
  17010. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  17011. {
  17012. auto start = std::chrono::steady_clock::now();
  17013. auto res = cli.Get("/stream");
  17014. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17015. std::chrono::steady_clock::now() - start)
  17016. .count();
  17017. ASSERT_FALSE(res);
  17018. EXPECT_EQ(Error::Read, res.error());
  17019. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17020. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17021. }
  17022. {
  17023. auto start = std::chrono::steady_clock::now();
  17024. auto res = cli.Get("/stream_without_length");
  17025. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17026. std::chrono::steady_clock::now() - start)
  17027. .count();
  17028. ASSERT_FALSE(res);
  17029. EXPECT_EQ(Error::Read, res.error());
  17030. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17031. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17032. }
  17033. {
  17034. auto start = std::chrono::steady_clock::now();
  17035. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  17036. EXPECT_EQ("abcd", string(data, data_length));
  17037. return true;
  17038. });
  17039. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17040. std::chrono::steady_clock::now() - start)
  17041. .count();
  17042. ASSERT_FALSE(res);
  17043. EXPECT_EQ(Error::Read, res.error());
  17044. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17045. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17046. }
  17047. }
  17048. TEST(MaxTimeoutTest, ContentStream) {
  17049. time_t timeout = 2000;
  17050. time_t threshold = 200;
  17051. Server svr;
  17052. Client cli("localhost", PORT);
  17053. max_timeout_test(svr, cli, timeout, threshold);
  17054. }
  17055. #ifdef CPPHTTPLIB_SSL_ENABLED
  17056. TEST(MaxTimeoutTest, ContentStreamSSL) {
  17057. time_t timeout = 2000;
  17058. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  17059. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17060. SSLClient cli("localhost", PORT);
  17061. cli.enable_server_certificate_verification(false);
  17062. max_timeout_test(svr, cli, timeout, threshold);
  17063. }
  17064. #endif
  17065. class EventDispatcher {
  17066. public:
  17067. EventDispatcher() {}
  17068. bool wait_event(DataSink *sink) {
  17069. unique_lock<mutex> lk(m_);
  17070. int id = id_;
  17071. // Wait with timeout to prevent hanging if client disconnects
  17072. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  17073. [&] { return cid_ == id; })) {
  17074. return false; // Timeout occurred
  17075. }
  17076. sink->write(message_.data(), message_.size());
  17077. return true;
  17078. }
  17079. void send_event(const string &message) {
  17080. lock_guard<mutex> lk(m_);
  17081. cid_ = id_++;
  17082. message_ = message;
  17083. cv_.notify_all();
  17084. }
  17085. private:
  17086. mutex m_;
  17087. condition_variable cv_;
  17088. atomic_int id_{0};
  17089. atomic_int cid_{-1};
  17090. string message_;
  17091. };
  17092. TEST(ClientInThreadTest, Issue2068) {
  17093. EventDispatcher ed;
  17094. Server svr;
  17095. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  17096. res.set_chunked_content_provider("text/event-stream",
  17097. [&](size_t /*offset*/, DataSink &sink) {
  17098. return ed.wait_event(&sink);
  17099. });
  17100. });
  17101. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  17102. svr.wait_until_ready();
  17103. thread event_thread([&] {
  17104. int id = 0;
  17105. while (svr.is_running()) {
  17106. this_thread::sleep_for(chrono::milliseconds(500));
  17107. std::stringstream ss;
  17108. ss << "data: " << id << "\n\n";
  17109. ed.send_event(ss.str());
  17110. id++;
  17111. }
  17112. });
  17113. auto se = detail::scope_exit([&] {
  17114. svr.stop();
  17115. listen_thread.join();
  17116. event_thread.join();
  17117. ASSERT_FALSE(svr.is_running());
  17118. });
  17119. {
  17120. auto client = detail::make_unique<Client>(HOST, PORT);
  17121. client->set_read_timeout(std::chrono::minutes(10));
  17122. std::atomic<bool> stop{false};
  17123. std::thread t([&] {
  17124. client->Get("/event1",
  17125. [&](const char *, size_t) -> bool { return !stop; });
  17126. });
  17127. std::this_thread::sleep_for(std::chrono::seconds(2));
  17128. stop = true;
  17129. client->stop();
  17130. t.join();
  17131. // Reset client after thread has finished
  17132. client.reset();
  17133. }
  17134. }
  17135. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  17136. auto handled = false;
  17137. Server svr;
  17138. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17139. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17140. auto se = detail::scope_exit([&] {
  17141. svr.stop();
  17142. t.join();
  17143. ASSERT_FALSE(svr.is_running());
  17144. ASSERT_FALSE(handled);
  17145. });
  17146. svr.wait_until_ready();
  17147. // Two Content-Length headers with different values — must be rejected
  17148. auto req = "POST /test HTTP/1.1\r\n"
  17149. "Content-Length: 5\r\n"
  17150. "Content-Length: 10\r\n"
  17151. "\r\n"
  17152. "hello";
  17153. std::string response;
  17154. ASSERT_TRUE(send_request(1, req, &response));
  17155. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17156. response.substr(0, response.find("\r\n")));
  17157. }
  17158. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  17159. auto handled = false;
  17160. Server svr;
  17161. svr.Post("/test", [&](const Request &, Response &res) {
  17162. handled = true;
  17163. res.set_content("ok", "text/plain");
  17164. });
  17165. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17166. auto se = detail::scope_exit([&] {
  17167. svr.stop();
  17168. t.join();
  17169. ASSERT_FALSE(svr.is_running());
  17170. ASSERT_TRUE(handled);
  17171. });
  17172. svr.wait_until_ready();
  17173. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  17174. auto req = "POST /test HTTP/1.1\r\n"
  17175. "Content-Length: 5\r\n"
  17176. "Content-Length: 5\r\n"
  17177. "\r\n"
  17178. "hello";
  17179. std::string response;
  17180. ASSERT_TRUE(send_request(1, req, &response));
  17181. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  17182. }
  17183. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  17184. Server svr;
  17185. svr.Get("/test", [](const Request &, Response &res) {
  17186. res.set_content("ok", "text/plain");
  17187. });
  17188. auto port = svr.bind_to_any_port(HOST);
  17189. thread t = thread([&] { svr.listen_after_bind(); });
  17190. auto se = detail::scope_exit([&] {
  17191. svr.stop();
  17192. t.join();
  17193. ASSERT_FALSE(svr.is_running());
  17194. });
  17195. svr.wait_until_ready();
  17196. auto status_line = [&](const std::string &host_lines) {
  17197. std::string res;
  17198. send_request(
  17199. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  17200. &res, port);
  17201. return res.substr(0, res.find("\r\n"));
  17202. };
  17203. const char *accepted[] = {
  17204. "Host: localhost\r\n",
  17205. "Host: a.example:8080\r\n",
  17206. "Host: my_service\r\n",
  17207. "Host: [::1]:8080\r\n",
  17208. "Host: [fe80::1%25eth0]\r\n",
  17209. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  17210. };
  17211. for (auto host_lines : accepted) {
  17212. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  17213. }
  17214. const char *rejected[] = {
  17215. "Host: a.example\r\nHost: b.example\r\n",
  17216. "Host: a.example\r\nHost: a.example\r\n",
  17217. "Host: a@b.example\r\n",
  17218. "Host: a.example/b\r\n",
  17219. "Host: a.example\\b\r\n",
  17220. "Host: a.example?b\r\n",
  17221. "Host: a.example#b\r\n",
  17222. "Host: a.example b.example\r\n",
  17223. };
  17224. for (auto host_lines : rejected) {
  17225. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  17226. << host_lines;
  17227. }
  17228. }
  17229. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  17230. Server svr;
  17231. svr.Get("/", [](const Request &req, Response &res) {
  17232. EXPECT_EQ(2U, req.trailers.size());
  17233. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  17234. // Denied
  17235. EXPECT_FALSE(req.has_trailer("Content-Length"));
  17236. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  17237. // Accepted
  17238. EXPECT_TRUE(req.has_trailer("X-Hello"));
  17239. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  17240. EXPECT_TRUE(req.has_trailer("X-World"));
  17241. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  17242. res.set_content("ok", "text/plain");
  17243. });
  17244. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17245. auto se = detail::scope_exit([&] {
  17246. svr.stop();
  17247. t.join();
  17248. ASSERT_FALSE(svr.is_running());
  17249. });
  17250. svr.wait_until_ready();
  17251. const std::string req = "GET / HTTP/1.1\r\n"
  17252. "Transfer-Encoding: chunked\r\n"
  17253. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  17254. "\r\n"
  17255. "0\r\n"
  17256. "Content-Length: 10\r\n"
  17257. "Host: internal.local\r\n"
  17258. "Content-Type: malicious/content\r\n"
  17259. "Cookie: any\r\n"
  17260. "Set-Cookie: any\r\n"
  17261. "X-Forwarded-For: attacker.com\r\n"
  17262. "X-Real-Ip: 1.1.1.1\r\n"
  17263. "X-Hello: hello\r\n"
  17264. "X-World: world\r\n"
  17265. "\r\n";
  17266. std::string res;
  17267. ASSERT_TRUE(send_request(1, req, &res));
  17268. }
  17269. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  17270. // several field lines, and the combined value is what has to be parsed. A
  17271. // Trailer field split across lines therefore declares every name it lists;
  17272. // reading only the first line silently drops the trailers the later lines
  17273. // declare. The prohibited-trailer filter still applies to every line.
  17274. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  17275. Server svr;
  17276. size_t observed_trailer_count = 0;
  17277. std::string observed_hello;
  17278. std::string observed_world;
  17279. bool observed_content_length = true;
  17280. svr.Get("/", [&](const Request &req, Response &res) {
  17281. observed_trailer_count = req.trailers.size();
  17282. observed_hello = req.get_trailer_value("X-Hello");
  17283. observed_world = req.get_trailer_value("X-World");
  17284. observed_content_length = req.has_trailer("Content-Length");
  17285. res.set_content("ok", "text/plain");
  17286. });
  17287. auto port = svr.bind_to_any_port(HOST);
  17288. thread t = thread([&]() { svr.listen_after_bind(); });
  17289. auto se = detail::scope_exit([&] {
  17290. svr.stop();
  17291. t.join();
  17292. ASSERT_FALSE(svr.is_running());
  17293. });
  17294. svr.wait_until_ready();
  17295. const std::string req = "GET / HTTP/1.1\r\n"
  17296. "Transfer-Encoding: chunked\r\n"
  17297. "Trailer: X-Hello\r\n"
  17298. "Trailer: X-World, Content-Length\r\n"
  17299. "\r\n"
  17300. "0\r\n"
  17301. "X-Hello: hello\r\n"
  17302. "X-World: world\r\n"
  17303. "Content-Length: 10\r\n"
  17304. "\r\n";
  17305. std::string res;
  17306. ASSERT_TRUE(send_request(1, req, &res, port));
  17307. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  17308. // Accepted: both field lines contribute to the declared set
  17309. EXPECT_EQ(2U, observed_trailer_count);
  17310. EXPECT_EQ(observed_hello, "hello");
  17311. EXPECT_EQ(observed_world, "world");
  17312. // Denied: a prohibited name stays prohibited on a later field line
  17313. EXPECT_FALSE(observed_content_length);
  17314. }
  17315. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  17316. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  17317. // unbounded run of fields that are never declared, because the counter would
  17318. // only advance for declared fields.
  17319. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  17320. Server svr;
  17321. bool handler_called = false;
  17322. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  17323. handler_called = true;
  17324. res.set_content("ok", "text/plain");
  17325. });
  17326. auto port = svr.bind_to_any_port(HOST);
  17327. thread t = thread([&]() { svr.listen_after_bind(); });
  17328. auto se = detail::scope_exit([&] {
  17329. svr.stop();
  17330. t.join();
  17331. ASSERT_FALSE(svr.is_running());
  17332. });
  17333. svr.wait_until_ready();
  17334. // Declare nothing, then send far more undeclared trailer fields than the
  17335. // header-count limit. Parsing must stop and reject the request rather than
  17336. // read every line.
  17337. std::string req = "GET / HTTP/1.1\r\n"
  17338. "Transfer-Encoding: chunked\r\n"
  17339. "\r\n"
  17340. "0\r\n";
  17341. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  17342. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  17343. }
  17344. req += "\r\n";
  17345. std::string res;
  17346. ASSERT_TRUE(send_request(1, req, &res, port));
  17347. // The request is rejected before the handler runs.
  17348. EXPECT_FALSE(handler_called);
  17349. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  17350. }
  17351. // The set of declared trailer names is capped so a peer cannot grow it without
  17352. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  17353. // declared past the cap is not honored, even if the field is actually sent.
  17354. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  17355. Server svr;
  17356. // One name inside the cap and one past it, so the test tracks the cap rather
  17357. // than a fixed count.
  17358. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  17359. const std::string within_cap_name = "X-T-0";
  17360. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  17361. bool observed_within_cap = false;
  17362. bool observed_past_cap = false;
  17363. svr.Get("/", [&](const Request &req, Response &res) {
  17364. observed_within_cap = req.has_trailer(within_cap_name);
  17365. observed_past_cap = req.has_trailer(past_cap_name);
  17366. res.set_content("ok", "text/plain");
  17367. });
  17368. auto port = svr.bind_to_any_port(HOST);
  17369. thread t = thread([&]() { svr.listen_after_bind(); });
  17370. auto se = detail::scope_exit([&] {
  17371. svr.stop();
  17372. t.join();
  17373. ASSERT_FALSE(svr.is_running());
  17374. });
  17375. svr.wait_until_ready();
  17376. // Declare more trailer names than the cap in a single Trailer field, then
  17377. // actually send the first (within the cap) and the last (past it).
  17378. std::string trailer_decl = "Trailer: ";
  17379. for (int i = 0; i < declared_count; i++) {
  17380. if (i != 0) { trailer_decl += ", "; }
  17381. trailer_decl += "X-T-" + std::to_string(i);
  17382. }
  17383. trailer_decl += "\r\n";
  17384. const std::string req = "GET / HTTP/1.1\r\n"
  17385. "Transfer-Encoding: chunked\r\n" +
  17386. trailer_decl +
  17387. "\r\n"
  17388. "0\r\n" +
  17389. within_cap_name + ": a\r\n" + past_cap_name +
  17390. ": b\r\n"
  17391. "\r\n";
  17392. std::string res;
  17393. ASSERT_TRUE(send_request(1, req, &res, port));
  17394. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  17395. // A name within the cap is honored; one declared past the cap is dropped.
  17396. EXPECT_TRUE(observed_within_cap);
  17397. EXPECT_FALSE(observed_past_cap);
  17398. }
  17399. // A direct client that is not listed in trusted_proxies must not be able to
  17400. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  17401. // the peer address on the actual TCP connection determines whether the
  17402. // header is honored.
  17403. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  17404. Server svr;
  17405. // Deliberately does NOT include the loopback address the test client
  17406. // actually connects from, so the direct connection is not a trusted proxy.
  17407. svr.set_trusted_proxies({"203.0.113.66"});
  17408. std::string observed_remote_addr;
  17409. svr.Get("/ip", [&](const Request &req, Response &res) {
  17410. observed_remote_addr = req.remote_addr;
  17411. res.set_content("ok", "text/plain");
  17412. });
  17413. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17414. auto se = detail::scope_exit([&] {
  17415. svr.stop();
  17416. t.join();
  17417. ASSERT_FALSE(svr.is_running());
  17418. });
  17419. svr.wait_until_ready();
  17420. Client cli(HOST, PORT);
  17421. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  17422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17423. EXPECT_EQ(StatusCode::OK_200, res->status);
  17424. // The connecting peer is not a trusted proxy, so the spoofed header must be
  17425. // ignored entirely and the real connection-level address retained.
  17426. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17427. observed_remote_addr == "127.0.0.1");
  17428. }
  17429. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  17430. Server svr;
  17431. std::string observed_remote_addr;
  17432. std::string observed_xff;
  17433. svr.Get("/ip", [&](const Request &req, Response &res) {
  17434. observed_remote_addr = req.remote_addr;
  17435. observed_xff = req.get_header_value("X-Forwarded-For");
  17436. res.set_content("ok", "text/plain");
  17437. });
  17438. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17439. auto se = detail::scope_exit([&] {
  17440. svr.stop();
  17441. t.join();
  17442. ASSERT_FALSE(svr.is_running());
  17443. });
  17444. svr.wait_until_ready();
  17445. Client cli(HOST, PORT);
  17446. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  17447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17448. EXPECT_EQ(StatusCode::OK_200, res->status);
  17449. EXPECT_EQ(observed_xff, "203.0.113.66");
  17450. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17451. observed_remote_addr == "127.0.0.1");
  17452. }
  17453. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  17454. Server svr;
  17455. svr.set_trusted_proxies({"203.0.113.66"});
  17456. std::string observed_remote_addr;
  17457. std::string observed_xff;
  17458. svr.Get("/ip", [&](const Request &req, Response &res) {
  17459. observed_remote_addr = req.remote_addr;
  17460. observed_xff = req.get_header_value("X-Forwarded-For");
  17461. res.set_content("ok", "text/plain");
  17462. });
  17463. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17464. auto se = detail::scope_exit([&] {
  17465. svr.stop();
  17466. t.join();
  17467. ASSERT_FALSE(svr.is_running());
  17468. });
  17469. svr.wait_until_ready();
  17470. Client cli(HOST, PORT);
  17471. auto res = cli.Get("/ip");
  17472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17473. EXPECT_EQ(StatusCode::OK_200, res->status);
  17474. EXPECT_EQ(observed_xff, "");
  17475. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17476. observed_remote_addr == "127.0.0.1");
  17477. }
  17478. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  17479. Server svr;
  17480. // Include the loopback address the test client actually connects from, so
  17481. // the direct connection itself is recognized as the trusted proxy hop.
  17482. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  17483. std::string observed_remote_addr;
  17484. std::string observed_xff;
  17485. svr.Get("/ip", [&](const Request &req, Response &res) {
  17486. observed_remote_addr = req.remote_addr;
  17487. observed_xff = req.get_header_value("X-Forwarded-For");
  17488. res.set_content("ok", "text/plain");
  17489. });
  17490. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17491. auto se = detail::scope_exit([&] {
  17492. svr.stop();
  17493. t.join();
  17494. ASSERT_FALSE(svr.is_running());
  17495. });
  17496. svr.wait_until_ready();
  17497. Client cli(HOST, PORT);
  17498. auto res = cli.Get(
  17499. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  17500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17501. EXPECT_EQ(StatusCode::OK_200, res->status);
  17502. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  17503. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17504. }
  17505. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  17506. Server svr;
  17507. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  17508. std::string observed_remote_addr;
  17509. std::string observed_xff;
  17510. svr.Get("/ip", [&](const Request &req, Response &res) {
  17511. observed_remote_addr = req.remote_addr;
  17512. observed_xff = req.get_header_value("X-Forwarded-For");
  17513. res.set_content("ok", "text/plain");
  17514. });
  17515. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17516. auto se = detail::scope_exit([&] {
  17517. svr.stop();
  17518. t.join();
  17519. ASSERT_FALSE(svr.is_running());
  17520. });
  17521. svr.wait_until_ready();
  17522. Client cli(HOST, PORT);
  17523. auto res = cli.Get(
  17524. "/ip",
  17525. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17527. EXPECT_EQ(StatusCode::OK_200, res->status);
  17528. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17529. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17530. }
  17531. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  17532. Server svr;
  17533. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17534. std::string observed_remote_addr;
  17535. std::string observed_xff;
  17536. svr.Get("/ip", [&](const Request &req, Response &res) {
  17537. observed_remote_addr = req.remote_addr;
  17538. observed_xff = req.get_header_value("X-Forwarded-For");
  17539. res.set_content("ok", "text/plain");
  17540. });
  17541. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17542. auto se = detail::scope_exit([&] {
  17543. svr.stop();
  17544. t.join();
  17545. ASSERT_FALSE(svr.is_running());
  17546. });
  17547. svr.wait_until_ready();
  17548. Client cli(HOST, PORT);
  17549. auto res = cli.Get(
  17550. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  17551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17552. EXPECT_EQ(StatusCode::OK_200, res->status);
  17553. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  17554. // by the closest hop) is used. The leftmost entry is fully client-controlled
  17555. // and must not be selected.
  17556. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  17557. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  17558. }
  17559. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  17560. Server svr;
  17561. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  17562. std::string observed_remote_addr;
  17563. svr.Get("/ip", [&](const Request &req, Response &res) {
  17564. observed_remote_addr = req.remote_addr;
  17565. res.set_content("ok", "text/plain");
  17566. });
  17567. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17568. auto se = detail::scope_exit([&] {
  17569. svr.stop();
  17570. t.join();
  17571. ASSERT_FALSE(svr.is_running());
  17572. });
  17573. svr.wait_until_ready();
  17574. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  17575. // a forged address and the trusted proxy's own address; the forged value must
  17576. // not win over the address the trusted proxy actually recorded.
  17577. Client cli(HOST, PORT);
  17578. auto res = cli.Get(
  17579. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  17580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17581. EXPECT_EQ(StatusCode::OK_200, res->status);
  17582. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  17583. }
  17584. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  17585. Server svr;
  17586. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17587. std::string observed_remote_addr;
  17588. std::string observed_xff;
  17589. svr.Get("/ip", [&](const Request &req, Response &res) {
  17590. observed_remote_addr = req.remote_addr;
  17591. observed_xff = req.get_header_value("X-Forwarded-For");
  17592. res.set_content("ok", "text/plain");
  17593. });
  17594. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17595. auto se = detail::scope_exit([&] {
  17596. svr.stop();
  17597. t.join();
  17598. ASSERT_FALSE(svr.is_running());
  17599. });
  17600. svr.wait_until_ready();
  17601. Client cli(HOST, PORT);
  17602. auto res = cli.Get(
  17603. "/ip",
  17604. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17606. EXPECT_EQ(StatusCode::OK_200, res->status);
  17607. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17608. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17609. }
  17610. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  17611. Server svr;
  17612. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17613. std::string observed_remote_addr;
  17614. std::string observed_xff;
  17615. svr.Get("/ip", [&](const Request &req, Response &res) {
  17616. observed_remote_addr = req.remote_addr;
  17617. observed_xff = req.get_header_value("X-Forwarded-For");
  17618. res.set_content("ok", "text/plain");
  17619. });
  17620. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17621. auto se = detail::scope_exit([&] {
  17622. svr.stop();
  17623. t.join();
  17624. ASSERT_FALSE(svr.is_running());
  17625. });
  17626. svr.wait_until_ready();
  17627. std::string raw_req =
  17628. "GET /ip HTTP/1.1\r\n"
  17629. "Host: localhost\r\n"
  17630. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  17631. "Connection: close\r\n"
  17632. "\r\n";
  17633. std::string out;
  17634. ASSERT_TRUE(send_request(5, raw_req, &out));
  17635. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17636. // Header parser trims surrounding whitespace of the header value
  17637. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  17638. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17639. }
  17640. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  17641. // one comma-joined value, in the order received. Proxies such as HAProxy append
  17642. // their own X-Forwarded-For as a separate field line rather than extending the
  17643. // one the client sent, so every occurrence has to be taken into account.
  17644. // Reading only the first one hands back the address the client chose.
  17645. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  17646. Server svr;
  17647. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17648. std::string observed_remote_addr;
  17649. size_t observed_xff_count = 0;
  17650. svr.Get("/ip", [&](const Request &req, Response &res) {
  17651. observed_remote_addr = req.remote_addr;
  17652. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  17653. res.set_content("ok", "text/plain");
  17654. });
  17655. auto port = svr.bind_to_any_port(HOST);
  17656. thread t = thread([&]() { svr.listen_after_bind(); });
  17657. auto se = detail::scope_exit([&] {
  17658. svr.stop();
  17659. t.join();
  17660. ASSERT_FALSE(svr.is_running());
  17661. });
  17662. svr.wait_until_ready();
  17663. // The client supplies the first field line; the trusted proxy appends the
  17664. // address it observed as a second one.
  17665. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  17666. "Host: localhost\r\n"
  17667. "X-Forwarded-For: 1.2.3.4\r\n"
  17668. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  17669. "Connection: close\r\n"
  17670. "\r\n";
  17671. std::string out;
  17672. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17673. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17674. EXPECT_EQ(observed_xff_count, 2U);
  17675. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17676. // The same chain spread over one field line per hop derives the same client
  17677. // address, i.e. the split and the comma-joined representations agree.
  17678. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  17679. "Host: localhost\r\n"
  17680. "X-Forwarded-For: 1.2.3.4\r\n"
  17681. "X-Forwarded-For: 198.51.100.23\r\n"
  17682. "X-Forwarded-For: 192.0.2.45\r\n"
  17683. "Connection: close\r\n"
  17684. "\r\n";
  17685. out.clear();
  17686. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  17687. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17688. EXPECT_EQ(observed_xff_count, 3U);
  17689. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17690. }
  17691. // An X-Forwarded-For header whose value parses to zero IP segments must not
  17692. // crash the server (it used to call front() on an empty vector inside
  17693. // get_client_ip). The connection-level remote address must be retained instead.
  17694. static void run_malformed_xff_test(const std::string &xff_value) {
  17695. Server svr;
  17696. svr.set_trusted_proxies({"192.0.2.45"});
  17697. std::string observed_remote_addr;
  17698. svr.Get("/ip", [&](const Request &req, Response &res) {
  17699. observed_remote_addr = req.remote_addr;
  17700. res.set_content("ok", "text/plain");
  17701. });
  17702. int port = 0;
  17703. thread t = thread([&]() {
  17704. port = svr.bind_to_any_port(HOST);
  17705. svr.listen_after_bind();
  17706. });
  17707. auto se = detail::scope_exit([&] {
  17708. svr.stop();
  17709. t.join();
  17710. ASSERT_FALSE(svr.is_running());
  17711. });
  17712. svr.wait_until_ready();
  17713. Client cli(HOST, port);
  17714. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  17715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17716. EXPECT_EQ(StatusCode::OK_200, res->status);
  17717. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17718. observed_remote_addr == "127.0.0.1");
  17719. }
  17720. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  17721. run_malformed_xff_test("");
  17722. }
  17723. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  17724. run_malformed_xff_test(",");
  17725. }
  17726. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  17727. run_malformed_xff_test(", , ,");
  17728. }
  17729. // The same rule applies to Accept: a request whose acceptable types are spread
  17730. // over several field lines must be negotiated against all of them.
  17731. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  17732. // case-insensitive connection options. Comparing the whole field value against
  17733. // one option misses a client that sends several of them, and misses every
  17734. // casing but the one written in the comparison.
  17735. //
  17736. // Sends req, reads the response, then reuses the same socket for a second
  17737. // request to find out whether the server kept the connection.
  17738. static void probe_connection_reuse(int port, const std::string &req,
  17739. bool *announced_close, bool *reusable) {
  17740. auto error = Error::Success;
  17741. auto sock = detail::create_client_socket(
  17742. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17743. /*connection_timeout_sec=*/5, 0,
  17744. /*read_timeout_sec=*/1, 0,
  17745. /*write_timeout_sec=*/5, 0, std::string(), error);
  17746. ASSERT_NE(sock, INVALID_SOCKET);
  17747. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  17748. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  17749. "Host: localhost\r\n"
  17750. "Connection: close\r\n"
  17751. "\r\n";
  17752. std::string first_response;
  17753. std::string second_response;
  17754. detail::process_client_socket(
  17755. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  17756. [&](Stream &strm) {
  17757. if (strm.write(req.data(), req.size()) !=
  17758. static_cast<ssize_t>(req.size())) {
  17759. return false;
  17760. }
  17761. char buf[512];
  17762. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  17763. // Headers plus the two-byte body of the handler below
  17764. while (reader.getline()) {
  17765. first_response += reader.ptr();
  17766. if (first_response.find("ok") != std::string::npos) { break; }
  17767. }
  17768. if (strm.write(second.data(), second.size()) !=
  17769. static_cast<ssize_t>(second.size())) {
  17770. return true;
  17771. }
  17772. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  17773. while (reader2.getline()) {
  17774. second_response += reader2.ptr();
  17775. if (second_response.find("ok") != std::string::npos) { break; }
  17776. }
  17777. return true;
  17778. });
  17779. *announced_close =
  17780. first_response.find("Connection: close") != std::string::npos;
  17781. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  17782. }
  17783. class ConnectionTokenTest : public ::testing::Test {
  17784. protected:
  17785. void SetUp() override {
  17786. svr_.Get("/keepalive", [](const Request &, Response &res) {
  17787. res.set_content("ok", "text/plain");
  17788. });
  17789. port_ = svr_.bind_to_any_port(HOST);
  17790. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17791. svr_.wait_until_ready();
  17792. }
  17793. void TearDown() override {
  17794. svr_.stop();
  17795. if (thread_.joinable()) { thread_.join(); }
  17796. }
  17797. Server svr_;
  17798. int port_ = 0;
  17799. thread thread_;
  17800. };
  17801. // "close" alongside another option still closes the connection, and the
  17802. // response says so rather than leaving the peer to discover it.
  17803. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  17804. bool announced_close = false;
  17805. bool reusable = true;
  17806. probe_connection_reuse(port_,
  17807. "GET /keepalive HTTP/1.1\r\n"
  17808. "Host: localhost\r\n"
  17809. "Connection: keep-alive, close\r\n"
  17810. "\r\n",
  17811. &announced_close, &reusable);
  17812. EXPECT_TRUE(announced_close);
  17813. EXPECT_FALSE(reusable);
  17814. }
  17815. // "close" split over two field lines is the same list, so it is honored too.
  17816. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  17817. bool announced_close = false;
  17818. bool reusable = true;
  17819. probe_connection_reuse(port_,
  17820. "GET /keepalive HTTP/1.1\r\n"
  17821. "Host: localhost\r\n"
  17822. "Connection: keep-alive\r\n"
  17823. "Connection: close\r\n"
  17824. "\r\n",
  17825. &announced_close, &reusable);
  17826. EXPECT_TRUE(announced_close);
  17827. EXPECT_FALSE(reusable);
  17828. }
  17829. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  17830. // keep-alive in the spelling everyone actually sends keeps its connection.
  17831. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  17832. bool announced_close = false;
  17833. bool reusable = false;
  17834. probe_connection_reuse(port_,
  17835. "GET /keepalive HTTP/1.0\r\n"
  17836. "Host: localhost\r\n"
  17837. "Connection: keep-alive\r\n"
  17838. "\r\n",
  17839. &announced_close, &reusable);
  17840. EXPECT_FALSE(announced_close);
  17841. EXPECT_TRUE(reusable);
  17842. }
  17843. // A token the value merely contains is not the token itself.
  17844. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  17845. bool announced_close = false;
  17846. bool reusable = false;
  17847. probe_connection_reuse(port_,
  17848. "GET /keepalive HTTP/1.1\r\n"
  17849. "Host: localhost\r\n"
  17850. "Connection: notclose\r\n"
  17851. "\r\n",
  17852. &announced_close, &reusable);
  17853. EXPECT_FALSE(announced_close);
  17854. EXPECT_TRUE(reusable);
  17855. }
  17856. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  17857. Server svr;
  17858. std::vector<std::string> observed_types;
  17859. svr.Get("/", [&](const Request &req, Response &res) {
  17860. observed_types = req.accept_content_types;
  17861. res.set_content("ok", "text/plain");
  17862. });
  17863. auto port = svr.bind_to_any_port(HOST);
  17864. thread t = thread([&]() { svr.listen_after_bind(); });
  17865. auto se = detail::scope_exit([&] {
  17866. svr.stop();
  17867. t.join();
  17868. ASSERT_FALSE(svr.is_running());
  17869. });
  17870. svr.wait_until_ready();
  17871. Client cli(HOST, port);
  17872. Headers headers;
  17873. headers.emplace("Accept", "text/plain;q=0.5");
  17874. headers.emplace("Accept", "application/json");
  17875. auto res = cli.Get("/", headers);
  17876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17877. EXPECT_EQ(StatusCode::OK_200, res->status);
  17878. // Sorted by q-value, so the second field line's type comes first
  17879. ASSERT_EQ(2U, observed_types.size());
  17880. EXPECT_EQ("application/json", observed_types[0]);
  17881. EXPECT_EQ("text/plain", observed_types[1]);
  17882. }
  17883. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  17884. // empty field line must not contribute a bare comma to the combined value.
  17885. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  17886. Server svr;
  17887. std::vector<std::string> observed_types;
  17888. svr.Get("/", [&](const Request &req, Response &res) {
  17889. observed_types = req.accept_content_types;
  17890. res.set_content("ok", "text/plain");
  17891. });
  17892. auto port = svr.bind_to_any_port(HOST);
  17893. thread t = thread([&]() { svr.listen_after_bind(); });
  17894. auto se = detail::scope_exit([&] {
  17895. svr.stop();
  17896. t.join();
  17897. ASSERT_FALSE(svr.is_running());
  17898. });
  17899. svr.wait_until_ready();
  17900. // Empty first field line, then a real one
  17901. std::string raw_req = "GET / HTTP/1.1\r\n"
  17902. "Host: localhost\r\n"
  17903. "Accept:\r\n"
  17904. "Accept: application/json\r\n"
  17905. "Connection: close\r\n"
  17906. "\r\n";
  17907. std::string out;
  17908. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17909. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17910. ASSERT_EQ(1U, observed_types.size());
  17911. EXPECT_EQ("application/json", observed_types[0]);
  17912. }
  17913. // The skip in get_combined_header_value() is what keeps an empty field line
  17914. // from contributing a bare comma. Only a trailing empty field line exercises
  17915. // it: a leading one is already covered by the "combined is still empty" check,
  17916. // and parse_accept_header() now ignores the empty element either way, so the
  17917. // request-level test above can no longer tell the two apart.
  17918. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  17919. Headers headers;
  17920. headers.emplace("Accept", "text/html");
  17921. headers.emplace("Accept", "");
  17922. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  17923. headers.clear();
  17924. headers.emplace("Accept", "");
  17925. headers.emplace("Accept", "application/json");
  17926. EXPECT_EQ("application/json",
  17927. detail::get_combined_header_value(headers, "Accept"));
  17928. }
  17929. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17930. // An encoding offered on a later Accept-Encoding field line is still offered.
  17931. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  17932. Server svr;
  17933. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17934. res.set_content(std::string(1024, 'x'), "text/plain");
  17935. });
  17936. auto port = svr.bind_to_any_port(HOST);
  17937. thread t = thread([&]() { svr.listen_after_bind(); });
  17938. auto se = detail::scope_exit([&] {
  17939. svr.stop();
  17940. t.join();
  17941. ASSERT_FALSE(svr.is_running());
  17942. });
  17943. svr.wait_until_ready();
  17944. Client cli(HOST, port);
  17945. cli.set_decompress(false);
  17946. Headers headers;
  17947. headers.emplace("Accept-Encoding", "identity");
  17948. headers.emplace("Accept-Encoding", "gzip");
  17949. auto res = cli.Get("/", headers);
  17950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17951. EXPECT_EQ(StatusCode::OK_200, res->status);
  17952. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  17953. }
  17954. #endif
  17955. #ifndef _WIN32
  17956. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  17957. Server svr;
  17958. svr.Post("/post", [&](const Request &req, Response &res) {
  17959. res.set_content(req.body, "text/plain");
  17960. });
  17961. svr.Put("/put", [&](const Request &req, Response &res) {
  17962. res.set_content(req.body, "text/plain");
  17963. });
  17964. svr.Patch("/patch", [&](const Request &req, Response &res) {
  17965. res.set_content(req.body, "text/plain");
  17966. });
  17967. svr.Delete("/delete", [&](const Request &req, Response &res) {
  17968. res.set_content(req.body, "text/plain");
  17969. });
  17970. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17971. auto se = detail::scope_exit([&] {
  17972. svr.stop();
  17973. t.join();
  17974. ASSERT_FALSE(svr.is_running());
  17975. });
  17976. svr.wait_until_ready();
  17977. std::string resp;
  17978. // POST without Content-Length
  17979. ASSERT_TRUE(send_request(5,
  17980. "POST /post HTTP/1.1\r\n"
  17981. "Host: localhost\r\n"
  17982. "Connection: close\r\n"
  17983. "\r\n",
  17984. &resp));
  17985. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17986. // PUT without Content-Length
  17987. resp.clear();
  17988. ASSERT_TRUE(send_request(5,
  17989. "PUT /put HTTP/1.1\r\n"
  17990. "Host: localhost\r\n"
  17991. "Connection: close\r\n"
  17992. "\r\n",
  17993. &resp));
  17994. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17995. // PATCH without Content-Length
  17996. resp.clear();
  17997. ASSERT_TRUE(send_request(5,
  17998. "PATCH /patch HTTP/1.1\r\n"
  17999. "Host: localhost\r\n"
  18000. "Connection: close\r\n"
  18001. "\r\n",
  18002. &resp));
  18003. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18004. // DELETE without Content-Length
  18005. resp.clear();
  18006. ASSERT_TRUE(send_request(5,
  18007. "DELETE /delete HTTP/1.1\r\n"
  18008. "Host: localhost\r\n"
  18009. "Connection: close\r\n"
  18010. "\r\n",
  18011. &resp));
  18012. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18013. }
  18014. #endif
  18015. //==============================================================================
  18016. // open_stream() Tests
  18017. //==============================================================================
  18018. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  18019. std::string result;
  18020. char buf[8192];
  18021. ssize_t n;
  18022. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18023. result.append(buf, static_cast<size_t>(n));
  18024. }
  18025. return result;
  18026. }
  18027. // Mock stream for unit tests
  18028. class MockStream : public Stream {
  18029. public:
  18030. std::string data;
  18031. size_t pos = 0;
  18032. ssize_t error_after = -1; // -1 = no error
  18033. explicit MockStream(const std::string &d, ssize_t err = -1)
  18034. : data(d), error_after(err) {}
  18035. bool is_readable() const override { return true; }
  18036. bool wait_readable() const override { return true; }
  18037. bool wait_writable() const override { return true; }
  18038. ssize_t read(char *ptr, size_t size) override {
  18039. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  18040. if (pos >= data.size()) return 0;
  18041. size_t limit =
  18042. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  18043. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  18044. std::memcpy(ptr, data.data() + pos, to_read);
  18045. pos += to_read;
  18046. return static_cast<ssize_t>(to_read);
  18047. }
  18048. ssize_t write(const char *, size_t) override { return -1; }
  18049. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  18050. ip = "127.0.0.1";
  18051. port = 0;
  18052. }
  18053. void get_local_ip_and_port(std::string &ip, int &port) const override {
  18054. ip = "127.0.0.1";
  18055. port = 0;
  18056. }
  18057. socket_t socket() const override { return INVALID_SOCKET; }
  18058. time_t duration() const override { return 0; }
  18059. };
  18060. TEST(StreamHandleTest, Basic) {
  18061. ClientImpl::StreamHandle handle;
  18062. EXPECT_FALSE(handle.is_valid());
  18063. handle.response = detail::make_unique<Response>();
  18064. handle.error = Error::Connection;
  18065. EXPECT_FALSE(handle.is_valid());
  18066. handle.error = Error::Success;
  18067. EXPECT_TRUE(handle.is_valid());
  18068. }
  18069. TEST(BodyReaderTest, Basic) {
  18070. MockStream stream("Hello, World!");
  18071. detail::BodyReader reader;
  18072. reader.stream = &stream;
  18073. reader.content_length = 13;
  18074. char buf[32];
  18075. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  18076. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  18077. EXPECT_TRUE(reader.eof);
  18078. }
  18079. TEST(BodyReaderTest, NoStream) {
  18080. detail::BodyReader reader;
  18081. char buf[32];
  18082. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18083. EXPECT_EQ(Error::Connection, reader.last_error);
  18084. }
  18085. TEST(BodyReaderTest, Error) {
  18086. MockStream stream("Hello, World!", 5);
  18087. detail::BodyReader reader;
  18088. reader.stream = &stream;
  18089. reader.content_length = 13;
  18090. char buf[32];
  18091. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  18092. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18093. EXPECT_EQ(Error::Read, reader.last_error);
  18094. }
  18095. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  18096. // Mock-based StreamHandle tests relying on private internals are removed.
  18097. class OpenStreamTest : public ::testing::Test {
  18098. protected:
  18099. void SetUp() override {
  18100. svr_.Get("/hello", [](const Request &, Response &res) {
  18101. res.set_content("Hello World!", "text/plain");
  18102. });
  18103. svr_.Get("/large", [](const Request &, Response &res) {
  18104. res.set_content(std::string(10000, 'X'), "text/plain");
  18105. });
  18106. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  18107. res.set_content("Hello World!", "image/jpeg");
  18108. res.set_header("Content-Encoding", "UTF-8");
  18109. });
  18110. svr_.Get("/chunked", [](const Request &, Response &res) {
  18111. res.set_chunked_content_provider("text/plain",
  18112. [](size_t offset, DataSink &sink) {
  18113. if (offset < 15) {
  18114. sink.write("chunk", 5);
  18115. return true;
  18116. }
  18117. sink.done();
  18118. return true;
  18119. });
  18120. });
  18121. svr_.Get("/compressible", [](const Request &, Response &res) {
  18122. res.set_chunked_content_provider("text/plain", [](size_t offset,
  18123. DataSink &sink) {
  18124. if (offset < 100 * 1024) {
  18125. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  18126. sink.write(chunk.data(), chunk.size());
  18127. return true;
  18128. }
  18129. sink.done();
  18130. return true;
  18131. });
  18132. });
  18133. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  18134. [](const Request & /*req*/, Response &res) {
  18135. auto i = new int(0);
  18136. res.set_header("Trailer", "Content-Length, X-Allowed");
  18137. res.set_chunked_content_provider(
  18138. "text/plain",
  18139. [i](size_t /*offset*/, DataSink &sink) {
  18140. switch (*i) {
  18141. case 0: sink.os << "123"; break;
  18142. case 1: sink.os << "456"; break;
  18143. case 2: sink.os << "789"; break;
  18144. case 3: {
  18145. sink.done_with_trailer(
  18146. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  18147. } break;
  18148. }
  18149. (*i)++;
  18150. return true;
  18151. },
  18152. [i](bool success) {
  18153. EXPECT_TRUE(success);
  18154. delete i;
  18155. });
  18156. });
  18157. // Echo headers endpoint for header-related tests
  18158. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  18159. std::string body;
  18160. for (const auto &h : req.headers) {
  18161. body.append(h.first);
  18162. body.push_back(':');
  18163. body.append(h.second);
  18164. body.push_back('\n');
  18165. }
  18166. res.set_content(body, "text/plain");
  18167. });
  18168. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  18169. std::string body;
  18170. for (const auto &h : req.headers) {
  18171. body.append(h.first);
  18172. body.push_back(':');
  18173. body.append(h.second);
  18174. body.push_back('\n');
  18175. }
  18176. res.set_content(body, "text/plain");
  18177. });
  18178. port_ = svr_.bind_to_any_port("127.0.0.1");
  18179. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18180. svr_.wait_until_ready();
  18181. }
  18182. void TearDown() override {
  18183. svr_.stop();
  18184. if (thread_.joinable()) thread_.join();
  18185. }
  18186. Server svr_;
  18187. std::thread thread_;
  18188. int port_ = 0;
  18189. };
  18190. TEST_F(OpenStreamTest, Basic) {
  18191. Client cli("127.0.0.1", port_);
  18192. auto handle = cli.open_stream("GET", "/hello");
  18193. EXPECT_TRUE(handle.is_valid());
  18194. EXPECT_EQ("Hello World!", read_all(handle));
  18195. }
  18196. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  18197. Client cli("127.0.0.1", port_);
  18198. auto handle = cli.open_stream("GET", "/unknown-encoding");
  18199. ASSERT_TRUE(handle.is_valid());
  18200. EXPECT_EQ("Hello World!", read_all(handle));
  18201. }
  18202. TEST_F(OpenStreamTest, SmallBuffer) {
  18203. Client cli("127.0.0.1", port_);
  18204. auto handle = cli.open_stream("GET", "/hello");
  18205. std::string result;
  18206. char buf[4];
  18207. ssize_t n;
  18208. while ((n = handle.read(buf, sizeof(buf))) > 0)
  18209. result.append(buf, static_cast<size_t>(n));
  18210. EXPECT_EQ("Hello World!", result);
  18211. }
  18212. TEST_F(OpenStreamTest, DefaultHeaders) {
  18213. Client cli("127.0.0.1", port_);
  18214. // open_stream GET should include Host, User-Agent and Accept-Encoding
  18215. {
  18216. auto handle = cli.open_stream("GET", "/echo-headers");
  18217. ASSERT_TRUE(handle.is_valid());
  18218. auto body = read_all(handle);
  18219. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  18220. std::string::npos);
  18221. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  18222. std::string::npos);
  18223. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  18224. }
  18225. // open_stream POST with body and no explicit content_type should NOT add
  18226. // text/plain Content-Type (behavior differs from non-streaming path), but
  18227. // should include Content-Length
  18228. {
  18229. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  18230. ASSERT_TRUE(handle.is_valid());
  18231. auto body = read_all(handle);
  18232. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  18233. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  18234. }
  18235. // open_stream POST with explicit Content-Type should preserve it
  18236. {
  18237. auto handle = cli.open_stream("POST", "/echo-headers", {},
  18238. {{"Content-Type", "application/custom"}},
  18239. "{}", "application/custom");
  18240. ASSERT_TRUE(handle.is_valid());
  18241. auto body = read_all(handle);
  18242. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  18243. }
  18244. // User-specified User-Agent must not be overwritten for stream API
  18245. {
  18246. auto handle = cli.open_stream("GET", "/echo-headers", {},
  18247. {{"User-Agent", "MyAgent/1.2"}});
  18248. ASSERT_TRUE(handle.is_valid());
  18249. auto body = read_all(handle);
  18250. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  18251. }
  18252. }
  18253. TEST_F(OpenStreamTest, Large) {
  18254. Client cli("127.0.0.1", port_);
  18255. auto handle = cli.open_stream("GET", "/large");
  18256. EXPECT_EQ(10000u, read_all(handle).size());
  18257. }
  18258. TEST_F(OpenStreamTest, ConnectionError) {
  18259. Client cli("127.0.0.1", 9999);
  18260. auto handle = cli.open_stream("GET", "/hello");
  18261. EXPECT_FALSE(handle.is_valid());
  18262. }
  18263. TEST_F(OpenStreamTest, Chunked) {
  18264. Client cli("127.0.0.1", port_);
  18265. auto handle = cli.open_stream("GET", "/chunked");
  18266. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18267. "Transfer-Encoding") == "chunked");
  18268. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  18269. }
  18270. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  18271. Client cli("127.0.0.1", port_);
  18272. auto handle =
  18273. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  18274. ASSERT_TRUE(handle.is_valid());
  18275. // Consume body to allow trailers to be received/parsed
  18276. auto body = read_all(handle);
  18277. // Explicitly parse trailers (ensure trailers are available for assertion)
  18278. handle.parse_trailers_if_needed();
  18279. EXPECT_EQ(std::string("123456789"), body);
  18280. // The response should include a Trailer header declaring both names
  18281. ASSERT_TRUE(handle.response);
  18282. EXPECT_TRUE(handle.response->has_header("Trailer"));
  18283. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  18284. handle.response->get_header_value("Trailer"));
  18285. // Prohibited trailer must not be present
  18286. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  18287. // Allowed trailer should be present
  18288. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  18289. EXPECT_EQ(std::string("yes"),
  18290. handle.response->get_trailer_value("X-Allowed"));
  18291. // Verify trailers are NOT present as regular headers
  18292. EXPECT_EQ(std::string(""),
  18293. handle.response->get_header_value("Content-Length"));
  18294. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  18295. }
  18296. static std::thread serve_single_response(std::promise<int> &port_promise,
  18297. const std::string &response) {
  18298. return std::thread([&port_promise, response] {
  18299. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18300. default_socket_options(srv);
  18301. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18302. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  18303. sockaddr_in addr{};
  18304. addr.sin_family = AF_INET;
  18305. addr.sin_port = htons(0); // Let OS assign a free port
  18306. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18307. int opt = 1;
  18308. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  18309. #ifdef _WIN32
  18310. reinterpret_cast<const char *>(&opt),
  18311. #else
  18312. &opt,
  18313. #endif
  18314. sizeof(opt));
  18315. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  18316. ::listen(srv, 1) != 0) {
  18317. port_promise.set_value(-1);
  18318. detail::close_socket(srv);
  18319. return;
  18320. }
  18321. socklen_t addr_len = sizeof(addr);
  18322. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  18323. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  18324. sockaddr_in cli_addr{};
  18325. socklen_t cli_len = sizeof(cli_addr);
  18326. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18327. if (cli != INVALID_SOCKET) {
  18328. // Read the complete HTTP request (until the blank line that terminates
  18329. // headers) before sending the response. If the server closes the socket
  18330. // while the client's request data is still unread in the kernel receive
  18331. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  18332. // connection on both sides: it discards the client's receive buffer
  18333. // (which already holds our response) and causes any in-progress write on
  18334. // the client to fail with ECONNRESET. Reading all request data first
  18335. // ensures close() emits a graceful FIN.
  18336. {
  18337. char rbuf[256];
  18338. std::string req;
  18339. while (req.find("\r\n\r\n") == std::string::npos) {
  18340. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  18341. if (n <= 0) { break; }
  18342. req.append(rbuf, static_cast<size_t>(n));
  18343. }
  18344. }
  18345. ::send(cli,
  18346. #ifdef _WIN32
  18347. static_cast<const char *>(response.c_str()),
  18348. static_cast<int>(response.size()),
  18349. #else
  18350. response.c_str(), response.size(),
  18351. #endif
  18352. 0);
  18353. detail::close_socket(cli);
  18354. }
  18355. detail::close_socket(srv);
  18356. });
  18357. }
  18358. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  18359. #ifndef _WIN32
  18360. signal(SIGPIPE, SIG_IGN);
  18361. #endif
  18362. std::promise<int> port_promise;
  18363. auto port_future = port_promise.get_future();
  18364. auto server_thread =
  18365. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  18366. "Content-Type: text/plain\r\n"
  18367. "Content-Length: not-a-number\r\n"
  18368. "Connection: close\r\n"
  18369. "\r\n"
  18370. "hello");
  18371. auto port = port_future.get();
  18372. ASSERT_GT(port, 0);
  18373. Client cli("127.0.0.1", port);
  18374. auto handle = cli.open_stream("GET", "/");
  18375. EXPECT_FALSE(handle.is_valid());
  18376. server_thread.join();
  18377. }
  18378. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  18379. #ifndef _WIN32
  18380. signal(SIGPIPE, SIG_IGN);
  18381. #endif
  18382. std::promise<int> port_promise;
  18383. auto port_future = port_promise.get_future();
  18384. auto server_thread = serve_single_response(
  18385. port_promise, "HTTP/1.1 200 OK\r\n"
  18386. "Content-Type: text/plain\r\n"
  18387. "Content-Length: 99999999999999999999999999\r\n"
  18388. "Connection: close\r\n"
  18389. "\r\n"
  18390. "hello");
  18391. auto port = port_future.get();
  18392. ASSERT_GT(port, 0);
  18393. // Historically std::stoull would throw std::out_of_range here and crash
  18394. // the process, then parsing silently clamped to a bogus framing length and
  18395. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  18396. // so the stream fails to open, matching the not-a-number case above. The
  18397. // process still must NOT terminate.
  18398. Client cli("127.0.0.1", port);
  18399. auto handle = cli.open_stream("GET", "/");
  18400. EXPECT_FALSE(handle.is_valid());
  18401. server_thread.join();
  18402. }
  18403. // Serves `response` to the single request `fn` makes with a fresh client.
  18404. template <typename Fn>
  18405. static void with_single_response(const std::string &response, Fn fn) {
  18406. #ifndef _WIN32
  18407. signal(SIGPIPE, SIG_IGN);
  18408. #endif
  18409. std::promise<int> port_promise;
  18410. auto port_future = port_promise.get_future();
  18411. auto server_thread = serve_single_response(port_promise, response);
  18412. auto se = detail::scope_exit([&] { server_thread.join(); });
  18413. auto port = port_future.get();
  18414. ASSERT_GT(port, 0);
  18415. Client cli("127.0.0.1", port);
  18416. fn(cli);
  18417. }
  18418. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  18419. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  18420. // the chunked coding and drop Content-Length, so a front-end that trusts
  18421. // Content-Length would disagree about where the body ends (response
  18422. // smuggling). The client must reject such a response.
  18423. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  18424. for (const char *te : {"chunked", "gzip, chunked"}) {
  18425. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  18426. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  18427. "\r\n" + "Connection: close\r\n" + "\r\n" +
  18428. "5\r\nhello\r\n0\r\n\r\n";
  18429. with_single_response(response, [&](Client &cli) {
  18430. auto res = cli.Get("/");
  18431. EXPECT_FALSE(static_cast<bool>(res)) << te;
  18432. EXPECT_EQ(Error::Read, res.error()) << te;
  18433. });
  18434. with_single_response(response, [&](Client &cli) {
  18435. auto handle = cli.open_stream("GET", "/");
  18436. EXPECT_FALSE(handle.is_valid()) << te;
  18437. EXPECT_EQ(Error::Read, handle.error) << te;
  18438. });
  18439. }
  18440. }
  18441. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  18442. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  18443. // closing the connection (unlike a request, which must be rejected).
  18444. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  18445. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18446. "Transfer-Encoding: chunked\r\n"
  18447. "Connection: close\r\n"
  18448. "\r\n"
  18449. "5\r\nhello\r\n0\r\n\r\n",
  18450. "HTTP/1.1 200 OK\r\n"
  18451. "Transfer-Encoding: gzip\r\n"
  18452. "Connection: close\r\n"
  18453. "\r\n"
  18454. "hello"}) {
  18455. with_single_response(response, [&](Client &cli) {
  18456. auto res = cli.Get("/");
  18457. ASSERT_TRUE(static_cast<bool>(res)) << response;
  18458. EXPECT_EQ("hello", res->body);
  18459. });
  18460. with_single_response(response, [&](Client &cli) {
  18461. auto handle = cli.open_stream("GET", "/");
  18462. ASSERT_TRUE(handle.is_valid()) << response;
  18463. EXPECT_EQ("hello", read_all(handle));
  18464. });
  18465. }
  18466. }
  18467. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  18468. // framing headers describe nothing to read and must not be rejected.
  18469. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  18470. const std::string framing = "Content-Length: 5\r\n"
  18471. "Transfer-Encoding: chunked\r\n"
  18472. "Connection: close\r\n"
  18473. "\r\n";
  18474. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18475. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  18476. });
  18477. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18478. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  18479. });
  18480. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  18481. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  18482. with_single_response(response, [&](Client &cli) {
  18483. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  18484. });
  18485. with_single_response(response, [&](Client &cli) {
  18486. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  18487. });
  18488. }
  18489. }
  18490. // A payload max length of 0 means no limit, however the body is framed.
  18491. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  18492. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18493. "Transfer-Encoding: chunked\r\n"
  18494. "\r\n"
  18495. "5\r\nhello\r\n0\r\n\r\n",
  18496. "HTTP/1.1 200 OK\r\n"
  18497. "Connection: close\r\n"
  18498. "\r\n"
  18499. "hello"}) {
  18500. with_single_response(response, [&](Client &cli) {
  18501. cli.set_payload_max_length(0);
  18502. auto res = cli.Get("/");
  18503. ASSERT_TRUE(res) << response;
  18504. EXPECT_EQ("hello", res->body) << response;
  18505. });
  18506. }
  18507. }
  18508. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  18509. Server svr;
  18510. svr.set_payload_max_length(0);
  18511. svr.Post("/echo", [](const Request &req, Response &res) {
  18512. res.set_content(req.body, "text/plain");
  18513. });
  18514. auto port = svr.bind_to_any_port(HOST);
  18515. thread t = thread([&] { svr.listen_after_bind(); });
  18516. auto se = detail::scope_exit([&] {
  18517. svr.stop();
  18518. t.join();
  18519. ASSERT_FALSE(svr.is_running());
  18520. });
  18521. svr.wait_until_ready();
  18522. Client cli(HOST, port);
  18523. auto res = cli.Post(
  18524. "/echo",
  18525. [](size_t /*offset*/, DataSink &sink) {
  18526. sink.write("hello", 5);
  18527. sink.done();
  18528. return true;
  18529. },
  18530. "text/plain");
  18531. ASSERT_TRUE(res);
  18532. EXPECT_EQ(StatusCode::OK_200, res->status);
  18533. EXPECT_EQ("hello", res->body);
  18534. }
  18535. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18536. TEST_F(OpenStreamTest, Gzip) {
  18537. Client cli("127.0.0.1", port_);
  18538. auto handle = cli.open_stream("GET", "/compressible", {},
  18539. {{"Accept-Encoding", "gzip"}});
  18540. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  18541. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18542. }
  18543. #endif
  18544. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18545. TEST_F(OpenStreamTest, Brotli) {
  18546. Client cli("127.0.0.1", port_);
  18547. auto handle =
  18548. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  18549. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  18550. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18551. }
  18552. #endif
  18553. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18554. TEST_F(OpenStreamTest, Zstd) {
  18555. Client cli("127.0.0.1", port_);
  18556. auto handle = cli.open_stream("GET", "/compressible", {},
  18557. {{"Accept-Encoding", "zstd"}});
  18558. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  18559. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18560. }
  18561. #endif
  18562. #ifdef CPPHTTPLIB_SSL_ENABLED
  18563. class SSLOpenStreamTest : public ::testing::Test {
  18564. protected:
  18565. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  18566. void SetUp() override {
  18567. svr_.Get("/hello", [](const Request &, Response &res) {
  18568. res.set_content("Hello SSL World!", "text/plain");
  18569. });
  18570. svr_.Get("/chunked", [](const Request &, Response &res) {
  18571. res.set_chunked_content_provider("text/plain",
  18572. [](size_t offset, DataSink &sink) {
  18573. if (offset < 15) {
  18574. sink.write("chunk", 5);
  18575. return true;
  18576. }
  18577. sink.done();
  18578. return true;
  18579. });
  18580. });
  18581. svr_.Post("/echo", [](const Request &req, Response &res) {
  18582. res.set_content(req.body, req.get_header_value("Content-Type"));
  18583. });
  18584. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  18585. std::string body = req.body;
  18586. res.set_chunked_content_provider(
  18587. "text/plain", [body](size_t offset, DataSink &sink) {
  18588. if (offset < body.size()) {
  18589. sink.write(body.data() + offset, body.size() - offset);
  18590. }
  18591. sink.done();
  18592. return true;
  18593. });
  18594. });
  18595. port_ = svr_.bind_to_any_port("127.0.0.1");
  18596. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18597. svr_.wait_until_ready();
  18598. }
  18599. void TearDown() override {
  18600. svr_.stop();
  18601. if (thread_.joinable()) thread_.join();
  18602. }
  18603. SSLServer svr_;
  18604. std::thread thread_;
  18605. int port_ = 0;
  18606. };
  18607. TEST_F(SSLOpenStreamTest, Basic) {
  18608. SSLClient cli("127.0.0.1", port_);
  18609. cli.enable_server_certificate_verification(false);
  18610. auto handle = cli.open_stream("GET", "/hello");
  18611. ASSERT_TRUE(handle.is_valid());
  18612. EXPECT_EQ("Hello SSL World!", read_all(handle));
  18613. }
  18614. TEST_F(SSLOpenStreamTest, Chunked) {
  18615. SSLClient cli("127.0.0.1", port_);
  18616. cli.enable_server_certificate_verification(false);
  18617. auto handle = cli.open_stream("GET", "/chunked");
  18618. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18619. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18620. "Transfer-Encoding") == "chunked");
  18621. auto body = read_all(handle);
  18622. EXPECT_EQ("chunkchunkchunk", body);
  18623. }
  18624. TEST_F(SSLOpenStreamTest, Post) {
  18625. SSLClient cli("127.0.0.1", port_);
  18626. cli.enable_server_certificate_verification(false);
  18627. auto handle =
  18628. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  18629. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18630. EXPECT_EQ(200, handle.response->status);
  18631. auto body = read_all(handle);
  18632. EXPECT_EQ("Hello SSL POST", body);
  18633. }
  18634. TEST_F(SSLOpenStreamTest, PostChunked) {
  18635. SSLClient cli("127.0.0.1", port_);
  18636. cli.enable_server_certificate_verification(false);
  18637. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  18638. "Chunked SSL Data", "text/plain");
  18639. ASSERT_TRUE(handle.is_valid());
  18640. EXPECT_EQ(200, handle.response->status);
  18641. auto body = read_all(handle);
  18642. EXPECT_EQ("Chunked SSL Data", body);
  18643. }
  18644. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  18645. // Content-Length is terminated by the server closing the connection. When the
  18646. // SSL peer sends a close_notify after the body, the client must treat it as a
  18647. // clean EOF and return a successful response rather than an error.
  18648. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  18649. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18650. ASSERT_TRUE(svr.is_valid());
  18651. svr.set_keep_alive_max_count(1);
  18652. const std::string expected_body = "Hello from connection-close response!";
  18653. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  18654. res.set_content_provider("text/plain",
  18655. [&](size_t offset, DataSink &sink) -> bool {
  18656. if (offset < expected_body.size()) {
  18657. sink.write(expected_body.data() + offset,
  18658. expected_body.size() - offset);
  18659. }
  18660. sink.done();
  18661. return true;
  18662. });
  18663. });
  18664. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  18665. auto se = detail::scope_exit([&] {
  18666. svr.stop();
  18667. listen_thread.join();
  18668. ASSERT_FALSE(svr.is_running());
  18669. });
  18670. svr.wait_until_ready();
  18671. SSLClient cli(HOST, PORT);
  18672. cli.enable_server_certificate_verification(false);
  18673. auto res = cli.Get("/no-content-length");
  18674. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  18675. EXPECT_EQ(StatusCode::OK_200, res->status);
  18676. EXPECT_EQ(expected_body, res->body);
  18677. }
  18678. #endif // CPPHTTPLIB_SSL_ENABLED
  18679. //==============================================================================
  18680. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  18681. // results for various scenarios.
  18682. //==============================================================================
  18683. TEST(ParityTest, GetVsOpenStream) {
  18684. Server svr;
  18685. const std::string path = "/parity";
  18686. const std::string content = "Parity test content: hello world";
  18687. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18688. res.set_content(content, "text/plain");
  18689. });
  18690. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18691. auto se = detail::scope_exit([&] {
  18692. svr.stop();
  18693. t.join();
  18694. ASSERT_FALSE(svr.is_running());
  18695. });
  18696. svr.wait_until_ready();
  18697. Client cli(HOST, PORT);
  18698. // Non-stream path
  18699. auto r1 = cli.Get(path);
  18700. ASSERT_TRUE(r1);
  18701. EXPECT_EQ(StatusCode::OK_200, r1->status);
  18702. // Stream path
  18703. auto h = cli.open_stream("GET", path);
  18704. ASSERT_TRUE(h.is_valid());
  18705. EXPECT_EQ(r1->body, read_all(h));
  18706. }
  18707. // Helper to compress data with provided compressor type T
  18708. template <typename Compressor>
  18709. static std::string compress_payload_for_parity(const std::string &in) {
  18710. std::string out;
  18711. Compressor compressor;
  18712. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  18713. [&](const char *data, size_t n) {
  18714. out.append(data, n);
  18715. return true;
  18716. });
  18717. EXPECT_TRUE(ok);
  18718. return out;
  18719. }
  18720. // Helper function for compression parity tests
  18721. template <typename Compressor>
  18722. static void test_compression_parity(const std::string &original,
  18723. const std::string &path,
  18724. const std::string &encoding) {
  18725. const std::string compressed =
  18726. compress_payload_for_parity<Compressor>(original);
  18727. Server svr;
  18728. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18729. res.set_content(compressed, "application/octet-stream");
  18730. res.set_header("Content-Encoding", encoding);
  18731. });
  18732. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  18733. auto se = detail::scope_exit([&] {
  18734. svr.stop();
  18735. t.join();
  18736. ASSERT_FALSE(svr.is_running());
  18737. });
  18738. svr.wait_until_ready();
  18739. Client cli(HOST, PORT);
  18740. // Non-streaming
  18741. {
  18742. auto res = cli.Get(path);
  18743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18744. EXPECT_EQ(StatusCode::OK_200, res->status);
  18745. EXPECT_EQ(original, res->body);
  18746. }
  18747. // Streaming
  18748. {
  18749. auto h = cli.open_stream("GET", path);
  18750. ASSERT_TRUE(h.is_valid());
  18751. EXPECT_EQ(original, read_all(h));
  18752. }
  18753. }
  18754. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18755. TEST(ParityTest, Gzip) {
  18756. test_compression_parity<detail::gzip_compressor>(
  18757. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  18758. }
  18759. #endif
  18760. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18761. TEST(ParityTest, Brotli) {
  18762. test_compression_parity<detail::brotli_compressor>(
  18763. "Hello, brotli parity test payload", "/parity-br", "br");
  18764. }
  18765. #endif
  18766. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18767. TEST(ParityTest, Zstd) {
  18768. test_compression_parity<detail::zstd_compressor>(
  18769. "Zstandard parity test payload", "/parity-zstd", "zstd");
  18770. }
  18771. #endif
  18772. //==============================================================================
  18773. // New Stream API Tests
  18774. //==============================================================================
  18775. inline std::string read_body(httplib::stream::Result &result) {
  18776. std::string body;
  18777. while (result.next()) {
  18778. body.append(result.data(), result.size());
  18779. }
  18780. return body;
  18781. }
  18782. TEST(ClientConnectionTest, Basic) {
  18783. httplib::ClientConnection conn;
  18784. EXPECT_FALSE(conn.is_open());
  18785. conn.sock = 1;
  18786. EXPECT_TRUE(conn.is_open());
  18787. httplib::ClientConnection conn2(std::move(conn));
  18788. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  18789. conn2.sock = INVALID_SOCKET;
  18790. }
  18791. // Unified test server for all stream::* tests
  18792. class StreamApiTest : public ::testing::Test {
  18793. protected:
  18794. void SetUp() override {
  18795. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18796. res.set_content("Hello World!", "text/plain");
  18797. });
  18798. svr_.Get("/echo-params",
  18799. [](const httplib::Request &req, httplib::Response &res) {
  18800. std::string r;
  18801. for (const auto &p : req.params) {
  18802. if (!r.empty()) r += "&";
  18803. r += p.first + "=" + p.second;
  18804. }
  18805. res.set_content(r, "text/plain");
  18806. });
  18807. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18808. res.set_content(req.body, req.get_header_value("Content-Type"));
  18809. });
  18810. svr_.Post("/echo-headers",
  18811. [](const httplib::Request &req, httplib::Response &res) {
  18812. std::string r;
  18813. for (const auto &h : req.headers)
  18814. r += h.first + ": " + h.second + "\n";
  18815. res.set_content(r, "text/plain");
  18816. });
  18817. svr_.Post("/echo-params",
  18818. [](const httplib::Request &req, httplib::Response &res) {
  18819. std::string r = "params:";
  18820. for (const auto &p : req.params)
  18821. r += p.first + "=" + p.second + ";";
  18822. res.set_content(r + " body:" + req.body, "text/plain");
  18823. });
  18824. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  18825. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  18826. });
  18827. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18828. res.set_content("PUT:" + req.body, "text/plain");
  18829. });
  18830. svr_.Patch("/echo",
  18831. [](const httplib::Request &req, httplib::Response &res) {
  18832. res.set_content("PATCH:" + req.body, "text/plain");
  18833. });
  18834. svr_.Delete(
  18835. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  18836. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  18837. "text/plain");
  18838. });
  18839. svr_.Get("/head-test",
  18840. [](const httplib::Request &, httplib::Response &res) {
  18841. res.set_content("body for HEAD", "text/plain");
  18842. });
  18843. svr_.Options("/options",
  18844. [](const httplib::Request &, httplib::Response &res) {
  18845. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  18846. });
  18847. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  18848. svr_.wait_until_ready();
  18849. }
  18850. void TearDown() override {
  18851. svr_.stop();
  18852. if (thread_.joinable()) thread_.join();
  18853. }
  18854. httplib::Server svr_;
  18855. std::thread thread_;
  18856. };
  18857. // stream::Get tests
  18858. TEST_F(StreamApiTest, GetBasic) {
  18859. httplib::Client cli(HOST, PORT);
  18860. auto result = httplib::stream::Get(cli, "/hello");
  18861. ASSERT_TRUE(result.is_valid());
  18862. EXPECT_EQ(200, result.status());
  18863. EXPECT_EQ("Hello World!", read_body(result));
  18864. }
  18865. TEST_F(StreamApiTest, GetWithParams) {
  18866. httplib::Client cli(HOST, PORT);
  18867. httplib::Params params{{"foo", "bar"}};
  18868. auto result = httplib::stream::Get(cli, "/echo-params", params);
  18869. ASSERT_TRUE(result.is_valid());
  18870. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  18871. }
  18872. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18873. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  18874. httplib::Client cli(HOST, PORT);
  18875. cli.set_payload_max_length(0);
  18876. auto result = httplib::stream::Get(cli, "/hello");
  18877. ASSERT_TRUE(result.is_valid());
  18878. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  18879. EXPECT_EQ("Hello World!", read_body(result));
  18880. }
  18881. #endif
  18882. TEST_F(StreamApiTest, GetConnectionError) {
  18883. httplib::Client cli(HOST, 9999);
  18884. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  18885. }
  18886. TEST_F(StreamApiTest, Get404) {
  18887. httplib::Client cli(HOST, PORT);
  18888. auto result = httplib::stream::Get(cli, "/nonexistent");
  18889. EXPECT_TRUE(result.is_valid());
  18890. EXPECT_EQ(404, result.status());
  18891. }
  18892. // stream::Post tests
  18893. TEST_F(StreamApiTest, PostBasic) {
  18894. httplib::Client cli(HOST, PORT);
  18895. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  18896. "application/json");
  18897. ASSERT_TRUE(result.is_valid());
  18898. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  18899. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  18900. }
  18901. TEST_F(StreamApiTest, PostWithHeaders) {
  18902. httplib::Client cli(HOST, PORT);
  18903. httplib::Headers headers{{"X-Custom", "value"}};
  18904. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  18905. "text/plain");
  18906. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  18907. }
  18908. TEST_F(StreamApiTest, PostWithParams) {
  18909. httplib::Client cli(HOST, PORT);
  18910. httplib::Params params{{"k", "v"}};
  18911. auto result =
  18912. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  18913. auto body = read_body(result);
  18914. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  18915. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  18916. }
  18917. TEST_F(StreamApiTest, PostLarge) {
  18918. httplib::Client cli(HOST, PORT);
  18919. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  18920. size_t total = 0;
  18921. while (result.next()) {
  18922. total += result.size();
  18923. }
  18924. EXPECT_EQ(100u * 1024u, total);
  18925. }
  18926. // stream::Put/Patch tests
  18927. TEST_F(StreamApiTest, PutAndPatch) {
  18928. httplib::Client cli(HOST, PORT);
  18929. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  18930. EXPECT_EQ("PUT:test", read_body(put));
  18931. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  18932. EXPECT_EQ("PATCH:test", read_body(patch));
  18933. }
  18934. // stream::Delete tests
  18935. TEST_F(StreamApiTest, Delete) {
  18936. httplib::Client cli(HOST, PORT);
  18937. auto del1 = httplib::stream::Delete(cli, "/resource");
  18938. EXPECT_EQ("Deleted", read_body(del1));
  18939. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  18940. EXPECT_EQ("Deleted:data", read_body(del2));
  18941. }
  18942. // stream::Head/Options tests
  18943. TEST_F(StreamApiTest, HeadAndOptions) {
  18944. httplib::Client cli(HOST, PORT);
  18945. auto head = httplib::stream::Head(cli, "/head-test");
  18946. EXPECT_TRUE(head.is_valid());
  18947. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  18948. auto opts = httplib::stream::Options(cli, "/options");
  18949. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  18950. }
  18951. // SSL stream::* tests
  18952. #ifdef CPPHTTPLIB_SSL_ENABLED
  18953. class SSLStreamApiTest : public ::testing::Test {
  18954. protected:
  18955. void SetUp() override {
  18956. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18957. res.set_content("Hello SSL!", "text/plain");
  18958. });
  18959. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18960. res.set_content(req.body, "text/plain");
  18961. });
  18962. port_ = svr_.bind_to_any_port("127.0.0.1");
  18963. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18964. svr_.wait_until_ready();
  18965. }
  18966. void TearDown() override {
  18967. svr_.stop();
  18968. if (thread_.joinable()) thread_.join();
  18969. }
  18970. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  18971. std::thread thread_;
  18972. int port_ = 0;
  18973. };
  18974. TEST_F(SSLStreamApiTest, GetAndPost) {
  18975. httplib::SSLClient cli("127.0.0.1", port_);
  18976. cli.enable_server_certificate_verification(false);
  18977. auto get = httplib::stream::Get(cli, "/hello");
  18978. EXPECT_EQ("Hello SSL!", read_body(get));
  18979. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  18980. EXPECT_EQ("test", read_body(post));
  18981. }
  18982. #endif
  18983. // Tests for Error::Timeout and Error::ConnectionClosed error types
  18984. // These errors are set in SocketStream/SSLSocketStream and propagated through
  18985. // BodyReader
  18986. TEST(ErrorHandlingTest, StreamReadTimeout) {
  18987. // Test that read timeout during streaming is detected
  18988. // Use a large content-length response where server delays mid-stream
  18989. Server svr;
  18990. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18991. // Send a large response with delay in the middle
  18992. res.set_content_provider(
  18993. 1000, // content_length
  18994. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  18995. if (offset < 100) {
  18996. // Send first 100 bytes immediately
  18997. std::string data(100, 'A');
  18998. sink.write(data.c_str(), data.size());
  18999. return true;
  19000. }
  19001. // Then delay longer than client timeout
  19002. std::this_thread::sleep_for(std::chrono::seconds(3));
  19003. std::string data(900, 'B');
  19004. sink.write(data.c_str(), data.size());
  19005. return true;
  19006. });
  19007. });
  19008. auto port = 8091;
  19009. std::thread t([&]() { svr.listen("localhost", port); });
  19010. svr.wait_until_ready();
  19011. Client cli("localhost", port);
  19012. cli.set_read_timeout(1, 0); // 1 second timeout
  19013. auto handle = cli.open_stream("GET", "/slow-stream");
  19014. ASSERT_TRUE(handle.is_valid());
  19015. char buf[256];
  19016. ssize_t total = 0;
  19017. ssize_t n;
  19018. bool got_error = false;
  19019. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19020. total += n;
  19021. }
  19022. if (n < 0) {
  19023. got_error = true;
  19024. // Should be timeout or read error
  19025. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19026. handle.get_read_error() == Error::Read)
  19027. << "Actual error: " << to_string(handle.get_read_error());
  19028. }
  19029. // Either we got an error, or we got less data than expected
  19030. EXPECT_TRUE(got_error || total < 1000)
  19031. << "Expected timeout but got all " << total << " bytes";
  19032. svr.stop();
  19033. t.join();
  19034. }
  19035. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  19036. // Test connection closed detection via BodyReader
  19037. Server svr;
  19038. std::atomic<bool> close_now{false};
  19039. svr.Get("/will-close", [&](const Request &, Response &res) {
  19040. res.set_content_provider(
  19041. 10000, // Large content_length that we won't fully send
  19042. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19043. if (offset < 100) {
  19044. std::string data(100, 'X');
  19045. sink.write(data.c_str(), data.size());
  19046. return true;
  19047. }
  19048. // Wait for signal then abort
  19049. while (!close_now) {
  19050. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19051. }
  19052. return false; // Abort - server will close connection
  19053. });
  19054. });
  19055. auto port = 8092;
  19056. std::thread t([&]() { svr.listen("localhost", port); });
  19057. svr.wait_until_ready();
  19058. Client cli("localhost", port);
  19059. auto handle = cli.open_stream("GET", "/will-close");
  19060. ASSERT_TRUE(handle.is_valid());
  19061. char buf[256];
  19062. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19063. EXPECT_GT(n, 0) << "First read should succeed";
  19064. // Signal server to close
  19065. close_now = true;
  19066. // Keep reading until error or EOF
  19067. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19068. // Keep reading
  19069. }
  19070. // Should get an error since content_length wasn't satisfied
  19071. if (n < 0) {
  19072. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19073. handle.get_read_error() == Error::Read)
  19074. << "Actual error: " << to_string(handle.get_read_error());
  19075. }
  19076. svr.stop();
  19077. t.join();
  19078. }
  19079. #ifdef CPPHTTPLIB_SSL_ENABLED
  19080. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  19081. // Test that read timeout during SSL streaming is detected
  19082. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19083. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19084. res.set_content_provider(
  19085. 1000, "text/plain",
  19086. [](size_t offset, size_t /*length*/, DataSink &sink) {
  19087. if (offset < 100) {
  19088. std::string data(100, 'A');
  19089. sink.write(data.c_str(), data.size());
  19090. return true;
  19091. }
  19092. std::this_thread::sleep_for(std::chrono::seconds(3));
  19093. std::string data(900, 'B');
  19094. sink.write(data.c_str(), data.size());
  19095. return true;
  19096. });
  19097. });
  19098. auto port = 8093;
  19099. std::thread t([&]() { svr.listen("localhost", port); });
  19100. svr.wait_until_ready();
  19101. SSLClient cli("localhost", port);
  19102. cli.enable_server_certificate_verification(false);
  19103. cli.set_read_timeout(1, 0); // 1 second timeout
  19104. auto handle = cli.open_stream("GET", "/slow-stream");
  19105. ASSERT_TRUE(handle.is_valid());
  19106. char buf[256];
  19107. ssize_t total = 0;
  19108. ssize_t n;
  19109. bool got_error = false;
  19110. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19111. total += n;
  19112. }
  19113. if (n < 0) {
  19114. got_error = true;
  19115. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19116. handle.get_read_error() == Error::Read)
  19117. << "Actual error: " << to_string(handle.get_read_error());
  19118. }
  19119. EXPECT_TRUE(got_error || total < 1000)
  19120. << "Expected timeout but got all " << total << " bytes";
  19121. svr.stop();
  19122. t.join();
  19123. }
  19124. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  19125. // Test SSL connection closed detection
  19126. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19127. std::atomic<bool> close_now{false};
  19128. svr.Get("/will-close", [&](const Request &, Response &res) {
  19129. res.set_content_provider(
  19130. 10000, "text/plain",
  19131. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19132. if (offset < 100) {
  19133. std::string data(100, 'X');
  19134. sink.write(data.c_str(), data.size());
  19135. return true;
  19136. }
  19137. while (!close_now) {
  19138. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19139. }
  19140. return false;
  19141. });
  19142. });
  19143. auto port = 8094;
  19144. std::thread t([&]() { svr.listen("localhost", port); });
  19145. svr.wait_until_ready();
  19146. SSLClient cli("localhost", port);
  19147. cli.enable_server_certificate_verification(false);
  19148. auto handle = cli.open_stream("GET", "/will-close");
  19149. ASSERT_TRUE(handle.is_valid());
  19150. char buf[256];
  19151. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19152. EXPECT_GT(n, 0);
  19153. // Signal server to close
  19154. close_now = true;
  19155. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19156. // Keep reading
  19157. }
  19158. if (n < 0) {
  19159. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19160. handle.get_read_error() == Error::Read)
  19161. << "Actual error: " << to_string(handle.get_read_error());
  19162. }
  19163. svr.stop();
  19164. t.join();
  19165. }
  19166. #endif
  19167. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  19168. using namespace httplib;
  19169. // Create a test file
  19170. const char *fname = "etag_testfile.txt";
  19171. const char *content = "etag-content";
  19172. {
  19173. std::ofstream ofs(fname);
  19174. ofs << content;
  19175. ASSERT_TRUE(ofs.good());
  19176. }
  19177. Server svr;
  19178. svr.set_mount_point("/static", ".");
  19179. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19180. svr.wait_until_ready();
  19181. Client cli(HOST, PORT);
  19182. // First request: should get 200 with ETag header
  19183. auto res1 = cli.Get("/static/etag_testfile.txt");
  19184. ASSERT_TRUE(res1);
  19185. ASSERT_EQ(200, res1->status);
  19186. ASSERT_TRUE(res1->has_header("ETag"));
  19187. std::string etag = res1->get_header_value("ETag");
  19188. EXPECT_FALSE(etag.empty());
  19189. // Verify ETag format: W/"hex-hex"
  19190. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  19191. EXPECT_EQ('W', etag[0]);
  19192. EXPECT_EQ('/', etag[1]);
  19193. EXPECT_EQ('"', etag[2]);
  19194. EXPECT_EQ('"', etag.back());
  19195. // Exact match: expect 304 Not Modified
  19196. Headers h2 = {{"If-None-Match", etag}};
  19197. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  19198. ASSERT_TRUE(res2);
  19199. EXPECT_EQ(304, res2->status);
  19200. // Wildcard match: expect 304 Not Modified
  19201. Headers h3 = {{"If-None-Match", "*"}};
  19202. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  19203. ASSERT_TRUE(res3);
  19204. EXPECT_EQ(304, res3->status);
  19205. // Non-matching ETag: expect 200
  19206. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  19207. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  19208. ASSERT_TRUE(res4);
  19209. EXPECT_EQ(200, res4->status);
  19210. // Multiple ETags with one matching: expect 304
  19211. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  19212. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  19213. ASSERT_TRUE(res5);
  19214. EXPECT_EQ(304, res5->status);
  19215. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  19216. // that equivalent to the single comma-separated list above, so the match on
  19217. // the second line must still be found.
  19218. Headers h6;
  19219. h6.emplace("If-None-Match", "W/\"other\"");
  19220. h6.emplace("If-None-Match", etag);
  19221. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  19222. ASSERT_TRUE(res6);
  19223. EXPECT_EQ(304, res6->status);
  19224. svr.stop();
  19225. t.join();
  19226. std::remove(fname);
  19227. }
  19228. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  19229. using namespace httplib;
  19230. Server svr;
  19231. svr.set_mount_point("/static", ".");
  19232. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19233. svr.wait_until_ready();
  19234. Client cli(HOST, PORT);
  19235. // Send If-None-Match: * to a non-existent file
  19236. Headers h = {{"If-None-Match", "*"}};
  19237. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  19238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19239. EXPECT_EQ(404, res->status);
  19240. svr.stop();
  19241. t.join();
  19242. }
  19243. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  19244. using namespace httplib;
  19245. // Create a test file
  19246. const char *fname = "etag_boundary_testfile.txt";
  19247. const char *content = "boundary-test";
  19248. {
  19249. std::ofstream ofs(fname);
  19250. ofs << content;
  19251. ASSERT_TRUE(ofs.good());
  19252. }
  19253. Server svr;
  19254. svr.set_mount_point("/static", ".");
  19255. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19256. svr.wait_until_ready();
  19257. Client cli(HOST, PORT);
  19258. // Get the actual ETag
  19259. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  19260. ASSERT_TRUE(res1);
  19261. ASSERT_EQ(200, res1->status);
  19262. ASSERT_TRUE(res1->has_header("ETag"));
  19263. std::string etag = res1->get_header_value("ETag");
  19264. // Test 1: Very long ETag value (longer than actual ETag)
  19265. // Should NOT match and return 200 (not trigger out-of-bounds read)
  19266. Headers h1 = {{"If-None-Match", "W/"
  19267. "\"very-long-etag-value-that-is-much-longer-"
  19268. "than-the-actual-etag-value\""}};
  19269. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  19270. ASSERT_TRUE(res2);
  19271. EXPECT_EQ(200, res2->status); // Should not match
  19272. // Test 2: Long string followed by wildcard
  19273. // Should match on "*" and return 304 (without out-of-bounds read on the long
  19274. // string)
  19275. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  19276. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  19277. ASSERT_TRUE(res3);
  19278. EXPECT_EQ(304, res3->status); // Should match on "*"
  19279. // Test 3: Wildcard followed by long string
  19280. // Should match on "*" immediately and return 304
  19281. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  19282. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  19283. ASSERT_TRUE(res4);
  19284. EXPECT_EQ(304, res4->status); // Should match on "*"
  19285. // Test 4: Multiple long non-matching values
  19286. // Should NOT match and return 200 (test that all comparisons are safe)
  19287. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  19288. "W/\"second-long-non-matching-value\", "
  19289. "W/\"third-long-non-matching-value\""}};
  19290. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  19291. ASSERT_TRUE(res5);
  19292. EXPECT_EQ(200, res5->status); // Should not match
  19293. // Test 5: Single character that is not "*" (edge case)
  19294. Headers h5 = {{"If-None-Match", "X"}};
  19295. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  19296. ASSERT_TRUE(res6);
  19297. EXPECT_EQ(200, res6->status); // Should not match
  19298. svr.stop();
  19299. t.join();
  19300. std::remove(fname);
  19301. }
  19302. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  19303. using namespace httplib;
  19304. // Create a test file
  19305. const char *fname = "ims_testfile.txt";
  19306. const char *content = "if-modified-since-test";
  19307. {
  19308. std::ofstream ofs(fname);
  19309. ofs << content;
  19310. ASSERT_TRUE(ofs.good());
  19311. }
  19312. Server svr;
  19313. svr.set_mount_point("/static", ".");
  19314. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19315. svr.wait_until_ready();
  19316. Client cli(HOST, PORT);
  19317. // First request: should get 200 with Last-Modified header
  19318. auto res1 = cli.Get("/static/ims_testfile.txt");
  19319. ASSERT_TRUE(res1);
  19320. ASSERT_EQ(200, res1->status);
  19321. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19322. std::string last_modified = res1->get_header_value("Last-Modified");
  19323. EXPECT_FALSE(last_modified.empty());
  19324. // If-Modified-Since with same time: expect 304
  19325. Headers h2 = {{"If-Modified-Since", last_modified}};
  19326. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  19327. ASSERT_TRUE(res2);
  19328. EXPECT_EQ(304, res2->status);
  19329. // If-Modified-Since with future time: expect 304
  19330. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19331. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  19332. ASSERT_TRUE(res3);
  19333. EXPECT_EQ(304, res3->status);
  19334. // If-Modified-Since with past time: expect 200
  19335. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19336. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  19337. ASSERT_TRUE(res4);
  19338. EXPECT_EQ(200, res4->status);
  19339. // If-None-Match takes precedence over If-Modified-Since
  19340. // (send matching ETag with old If-Modified-Since -> should still be 304)
  19341. ASSERT_TRUE(res1->has_header("ETag"));
  19342. std::string etag = res1->get_header_value("ETag");
  19343. Headers h5 = {{"If-None-Match", etag},
  19344. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19345. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  19346. ASSERT_TRUE(res5);
  19347. EXPECT_EQ(304, res5->status);
  19348. svr.stop();
  19349. t.join();
  19350. std::remove(fname);
  19351. }
  19352. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  19353. using namespace httplib;
  19354. Server svr;
  19355. // Endpoint that returns compressible content
  19356. svr.Get("/compressible", [](const Request &, Response &res) {
  19357. // Return a large enough body to trigger compression
  19358. std::string body(1000, 'a');
  19359. res.set_content(body, "text/plain");
  19360. });
  19361. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19362. svr.wait_until_ready();
  19363. Client cli(HOST, PORT);
  19364. // Request with gzip support: should get Vary header when compressed
  19365. cli.set_compress(true);
  19366. auto res1 = cli.Get("/compressible");
  19367. ASSERT_TRUE(res1);
  19368. EXPECT_EQ(200, res1->status);
  19369. // If Content-Encoding is set, Vary should also be set
  19370. if (res1->has_header("Content-Encoding")) {
  19371. EXPECT_TRUE(res1->has_header("Vary"));
  19372. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  19373. }
  19374. // Request without Accept-Encoding header: should not have compression
  19375. Headers h_no_compress;
  19376. auto res2 = cli.Get("/compressible", h_no_compress);
  19377. ASSERT_TRUE(res2);
  19378. EXPECT_EQ(200, res2->status);
  19379. // Verify Vary header is present when compression is applied
  19380. // (the exact behavior depends on server configuration)
  19381. svr.stop();
  19382. t.join();
  19383. }
  19384. TEST(ETagTest, IfRangeWithETag) {
  19385. using namespace httplib;
  19386. // Create a test file with known content
  19387. const char *fname = "if_range_testfile.txt";
  19388. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  19389. {
  19390. std::ofstream ofs(fname);
  19391. ofs << content;
  19392. ASSERT_TRUE(ofs.good());
  19393. }
  19394. Server svr;
  19395. svr.set_mount_point("/static", ".");
  19396. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19397. svr.wait_until_ready();
  19398. Client cli(HOST, PORT);
  19399. // First request: get ETag
  19400. auto res1 = cli.Get("/static/if_range_testfile.txt");
  19401. ASSERT_TRUE(res1);
  19402. ASSERT_EQ(200, res1->status);
  19403. ASSERT_TRUE(res1->has_header("ETag"));
  19404. std::string etag = res1->get_header_value("ETag");
  19405. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  19406. // Since our server generates weak ETags (W/"..."), If-Range with our
  19407. // ETag should NOT result in partial content - it should return full content.
  19408. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  19409. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  19410. ASSERT_TRUE(res2);
  19411. // Weak ETag in If-Range -> full content (200), not partial (206)
  19412. EXPECT_EQ(200, res2->status);
  19413. EXPECT_EQ(content, res2->body);
  19414. EXPECT_FALSE(res2->has_header("Content-Range"));
  19415. // Range request with non-matching If-Range (ETag): should get 200 (full
  19416. // content)
  19417. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  19418. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  19419. ASSERT_TRUE(res3);
  19420. EXPECT_EQ(200, res3->status);
  19421. EXPECT_EQ(content, res3->body);
  19422. EXPECT_FALSE(res3->has_header("Content-Range"));
  19423. // Range request with strong ETag (hypothetical - our server doesn't generate
  19424. // strong ETags, but if client sends a strong ETag that doesn't match, it
  19425. // should return full content)
  19426. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  19427. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  19428. ASSERT_TRUE(res4);
  19429. EXPECT_EQ(200, res4->status);
  19430. EXPECT_EQ(content, res4->body);
  19431. EXPECT_FALSE(res4->has_header("Content-Range"));
  19432. svr.stop();
  19433. t.join();
  19434. std::remove(fname);
  19435. }
  19436. TEST(ETagTest, IfRangeWithDate) {
  19437. using namespace httplib;
  19438. // Create a test file
  19439. const char *fname = "if_range_date_testfile.txt";
  19440. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  19441. {
  19442. std::ofstream ofs(fname);
  19443. ofs << content;
  19444. ASSERT_TRUE(ofs.good());
  19445. }
  19446. Server svr;
  19447. svr.set_mount_point("/static", ".");
  19448. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19449. svr.wait_until_ready();
  19450. Client cli(HOST, PORT);
  19451. // First request: get Last-Modified
  19452. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  19453. ASSERT_TRUE(res1);
  19454. ASSERT_EQ(200, res1->status);
  19455. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19456. std::string last_modified = res1->get_header_value("Last-Modified");
  19457. // Range request with matching If-Range (date): should get 206
  19458. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  19459. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  19460. ASSERT_TRUE(res2);
  19461. EXPECT_EQ(206, res2->status);
  19462. EXPECT_EQ("FGHIJ", res2->body);
  19463. // Range request with old If-Range date: should get 200 (full content)
  19464. Headers h3 = {{"Range", "bytes=5-9"},
  19465. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19466. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  19467. ASSERT_TRUE(res3);
  19468. EXPECT_EQ(200, res3->status);
  19469. EXPECT_EQ(content, res3->body);
  19470. // Range request with future If-Range date: should get 206
  19471. Headers h4 = {{"Range", "bytes=0-4"},
  19472. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19473. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  19474. ASSERT_TRUE(res4);
  19475. EXPECT_EQ(206, res4->status);
  19476. EXPECT_EQ("ABCDE", res4->body);
  19477. svr.stop();
  19478. t.join();
  19479. std::remove(fname);
  19480. }
  19481. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  19482. using namespace httplib;
  19483. const char *fname = "etag_malformed.txt";
  19484. const char *content = "malformed-etag";
  19485. {
  19486. std::ofstream ofs(fname);
  19487. ofs << content;
  19488. ASSERT_TRUE(ofs.good());
  19489. }
  19490. Server svr;
  19491. svr.set_mount_point("/static", ".");
  19492. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19493. svr.wait_until_ready();
  19494. Client cli(HOST, PORT);
  19495. // baseline: should get 200 and an ETag
  19496. auto res1 = cli.Get("/static/etag_malformed.txt");
  19497. ASSERT_TRUE(res1);
  19498. ASSERT_EQ(200, res1->status);
  19499. ASSERT_TRUE(res1->has_header("ETag"));
  19500. // Malformed ETag value (missing quotes) should be treated as non-matching
  19501. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  19502. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  19503. ASSERT_TRUE(res_bad);
  19504. EXPECT_EQ(200, res_bad->status);
  19505. // Whitespace-only header value should be considered invalid / non-matching
  19506. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  19507. "Host: localhost\r\n"
  19508. "If-None-Match: \r\n"
  19509. "Connection: close\r\n"
  19510. "\r\n";
  19511. std::string out;
  19512. ASSERT_TRUE(send_request(5, raw_req, &out));
  19513. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19514. svr.stop();
  19515. t.join();
  19516. std::remove(fname);
  19517. }
  19518. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  19519. using namespace httplib;
  19520. const char *fname = "ims_invalid_format.txt";
  19521. const char *content = "ims-bad-format";
  19522. {
  19523. std::ofstream ofs(fname);
  19524. ofs << content;
  19525. ASSERT_TRUE(ofs.good());
  19526. }
  19527. Server svr;
  19528. svr.set_mount_point("/static", ".");
  19529. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19530. svr.wait_until_ready();
  19531. Client cli(HOST, PORT);
  19532. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  19533. ASSERT_TRUE(res1);
  19534. ASSERT_EQ(200, res1->status);
  19535. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19536. // If-Modified-Since with invalid format should not result in 304
  19537. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  19538. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  19539. ASSERT_TRUE(res_bad);
  19540. EXPECT_EQ(200, res_bad->status);
  19541. // If-Range with invalid date format should be treated as mismatch -> full
  19542. // content (200)
  19543. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  19544. {"If-Range", "invalid-date"}};
  19545. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  19546. ASSERT_TRUE(res_ifrange);
  19547. EXPECT_EQ(200, res_ifrange->status);
  19548. svr.stop();
  19549. t.join();
  19550. std::remove(fname);
  19551. }
  19552. TEST(ETagTest, IfRangeWithMalformedETag) {
  19553. using namespace httplib;
  19554. const char *fname = "ifrange_malformed.txt";
  19555. const std::string content = "0123456789";
  19556. {
  19557. std::ofstream ofs(fname);
  19558. ofs << content;
  19559. ASSERT_TRUE(ofs.good());
  19560. }
  19561. Server svr;
  19562. svr.set_mount_point("/static", ".");
  19563. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19564. svr.wait_until_ready();
  19565. Client cli(HOST, PORT);
  19566. // First request: get ETag
  19567. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  19568. ASSERT_TRUE(res1);
  19569. ASSERT_EQ(200, res1->status);
  19570. ASSERT_TRUE(res1->has_header("ETag"));
  19571. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  19572. // full content (200)
  19573. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  19574. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  19575. ASSERT_TRUE(res2);
  19576. EXPECT_EQ(200, res2->status);
  19577. EXPECT_EQ(content, res2->body);
  19578. svr.stop();
  19579. t.join();
  19580. std::remove(fname);
  19581. }
  19582. TEST(ETagTest, ExtremeLargeDateValues) {
  19583. using namespace httplib;
  19584. const char *fname = "ims_extreme_date.txt";
  19585. const char *content = "ims-extreme-date";
  19586. {
  19587. std::ofstream ofs(fname);
  19588. ofs << content;
  19589. ASSERT_TRUE(ofs.good());
  19590. }
  19591. Server svr;
  19592. svr.set_mount_point("/static", ".");
  19593. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19594. svr.wait_until_ready();
  19595. Client cli(HOST, PORT);
  19596. auto res1 = cli.Get(std::string("/static/") + fname);
  19597. ASSERT_TRUE(res1);
  19598. ASSERT_EQ(200, res1->status);
  19599. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19600. // Extremely large year that may overflow date parsing routines.
  19601. Headers h_large_date = {
  19602. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19603. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  19604. ASSERT_TRUE(res_bad);
  19605. // Expect server to treat this as invalid/mismatch and return full content
  19606. EXPECT_EQ(200, res_bad->status);
  19607. // If-Range with extremely large date should be treated as mismatch -> full
  19608. // content (200)
  19609. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  19610. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19611. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  19612. ASSERT_TRUE(res_ifrange);
  19613. EXPECT_EQ(200, res_ifrange->status);
  19614. svr.stop();
  19615. t.join();
  19616. std::remove(fname);
  19617. }
  19618. TEST(ETagTest, NegativeFileModificationTime) {
  19619. using namespace httplib;
  19620. const char *fname = "ims_negative_mtime.txt";
  19621. const std::string content = "negative-mtime";
  19622. {
  19623. std::ofstream ofs(fname);
  19624. ofs << content;
  19625. ASSERT_TRUE(ofs.good());
  19626. }
  19627. // Try to set file mtime to a negative value. This may fail on some
  19628. // platforms/filesystems; if it fails, the test will still verify server
  19629. // behaves safely by performing a regular conditional request.
  19630. #if defined(__APPLE__) || defined(__linux__)
  19631. bool set_negative = false;
  19632. do {
  19633. struct timeval times[2];
  19634. // access time: now
  19635. times[0].tv_sec = time(nullptr);
  19636. times[0].tv_usec = 0;
  19637. // modification time: negative (e.g., -1)
  19638. times[1].tv_sec = -1;
  19639. times[1].tv_usec = 0;
  19640. if (utimes(fname, times) == 0) { set_negative = true; }
  19641. } while (0);
  19642. #else
  19643. bool set_negative = false;
  19644. #endif
  19645. Server svr;
  19646. svr.set_mount_point("/static", ".");
  19647. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19648. svr.wait_until_ready();
  19649. Client cli(HOST, PORT);
  19650. auto res1 = cli.Get(std::string("/static/") + fname);
  19651. ASSERT_TRUE(res1);
  19652. ASSERT_EQ(200, res1->status);
  19653. bool has_last_modified = res1->has_header("Last-Modified");
  19654. std::string last_modified;
  19655. if (has_last_modified) {
  19656. last_modified = res1->get_header_value("Last-Modified");
  19657. }
  19658. if (set_negative) {
  19659. // If we successfully set a negative mtime, ensure server returns a
  19660. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  19661. // with an old date and ensure server handles it without crash.
  19662. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  19663. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  19664. ASSERT_TRUE(res2);
  19665. // Behavior may vary; at minimum ensure server responds (200 or 304).
  19666. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  19667. } else {
  19668. // Could not set negative mtime on this platform; fall back to verifying
  19669. // that normal invalid/malformed dates are treated safely (non-304).
  19670. Headers h_bad_date = {
  19671. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19672. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  19673. ASSERT_TRUE(res_bad);
  19674. EXPECT_EQ(200, res_bad->status);
  19675. }
  19676. svr.stop();
  19677. t.join();
  19678. std::remove(fname);
  19679. }
  19680. //==============================================================================
  19681. // Integration Tests with Server
  19682. //==============================================================================
  19683. class SSEIntegrationTest : public ::testing::Test {
  19684. protected:
  19685. void SetUp() override {
  19686. stop_server_.store(false);
  19687. events_.clear();
  19688. server_ = httplib::detail::make_unique<Server>();
  19689. setup_server();
  19690. start_server();
  19691. }
  19692. void TearDown() override {
  19693. stop_server_.store(true);
  19694. event_cv_.notify_all();
  19695. server_->stop();
  19696. if (server_thread_.joinable()) { server_thread_.join(); }
  19697. }
  19698. void setup_server() {
  19699. // Simple SSE endpoint
  19700. server_->Get("/events", [this](const Request &req, Response &res) {
  19701. auto last_id = req.get_header_value("Last-Event-ID");
  19702. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  19703. res.set_chunked_content_provider(
  19704. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  19705. std::unique_lock<std::mutex> lock(event_mutex_);
  19706. if (event_cv_.wait_for(
  19707. lock, std::chrono::milliseconds(200), [this] {
  19708. return !events_.empty() || stop_server_.load();
  19709. })) {
  19710. if (stop_server_.load()) { return false; }
  19711. if (!events_.empty()) {
  19712. std::string event = events_.front();
  19713. events_.erase(events_.begin());
  19714. sink.write(event.data(), event.size());
  19715. return true;
  19716. }
  19717. }
  19718. return !stop_server_.load();
  19719. });
  19720. });
  19721. // Endpoint that returns error
  19722. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  19723. res.status = 500;
  19724. res.set_content("Internal Server Error", "text/plain");
  19725. });
  19726. // Endpoint for custom event types
  19727. server_->Get("/custom-events", [](const Request &, Response &res) {
  19728. res.set_chunked_content_provider(
  19729. "text/event-stream", [](size_t offset, DataSink &sink) {
  19730. if (offset == 0) {
  19731. std::string event = "event: update\ndata: updated\n\n"
  19732. "event: delete\ndata: deleted\n\n";
  19733. sink.write(event.data(), event.size());
  19734. }
  19735. return false; // End stream after sending
  19736. });
  19737. });
  19738. }
  19739. void start_server() {
  19740. port_ = server_->bind_to_any_port(HOST);
  19741. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19742. // Wait for server to start
  19743. while (!server_->is_running()) {
  19744. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19745. }
  19746. }
  19747. int get_port() const { return port_; }
  19748. void send_event(const std::string &event) {
  19749. std::lock_guard<std::mutex> lock(event_mutex_);
  19750. events_.push_back(event);
  19751. event_cv_.notify_all();
  19752. }
  19753. std::unique_ptr<Server> server_;
  19754. std::thread server_thread_;
  19755. std::mutex event_mutex_;
  19756. std::condition_variable event_cv_;
  19757. std::vector<std::string> events_;
  19758. std::atomic<bool> stop_server_{false};
  19759. std::string last_received_event_id_;
  19760. int port_ = 0;
  19761. };
  19762. //==============================================================================
  19763. // SSE Parsing Tests
  19764. //==============================================================================
  19765. class SSEParsingTest : public SSEIntegrationTest {
  19766. protected:
  19767. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  19768. // A trailing sentinel event tells when the whole stream has been parsed.
  19769. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  19770. auto body = stream + "event: end\ndata: end\n\n";
  19771. server_->Get("/parse", [body](const Request &, Response &res) {
  19772. res.set_content(body, "text/event-stream");
  19773. });
  19774. return collect("/parse");
  19775. }
  19776. // Runs SSEClient against path until an "end" event arrives and returns the
  19777. // messages dispatched before it
  19778. std::vector<sse::SSEMessage> collect(const std::string &path) {
  19779. Client client(HOST, get_port());
  19780. sse::SSEClient sse(client, path);
  19781. std::mutex mutex;
  19782. std::condition_variable cv;
  19783. std::vector<sse::SSEMessage> messages;
  19784. auto done = false;
  19785. sse.on_message([&](const sse::SSEMessage &msg) {
  19786. std::lock_guard<std::mutex> lock(mutex);
  19787. // Ignore a replay from a reconnect that races with stop()
  19788. if (!done) { messages.push_back(msg); }
  19789. });
  19790. sse.on_event("end", [&](const sse::SSEMessage &) {
  19791. std::lock_guard<std::mutex> lock(mutex);
  19792. done = true;
  19793. cv.notify_all();
  19794. });
  19795. sse.set_reconnect_interval(100);
  19796. sse.start_async();
  19797. {
  19798. std::unique_lock<std::mutex> lock(mutex);
  19799. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  19800. }
  19801. sse.stop();
  19802. EXPECT_TRUE(done);
  19803. return messages;
  19804. }
  19805. };
  19806. TEST_F(SSEParsingTest, SingleLineData) {
  19807. auto msgs = parse("data: hello\n\n");
  19808. ASSERT_EQ(msgs.size(), 1u);
  19809. EXPECT_EQ(msgs[0].data, "hello");
  19810. EXPECT_EQ(msgs[0].event, "message");
  19811. }
  19812. TEST_F(SSEParsingTest, MultiLineData) {
  19813. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  19814. ASSERT_EQ(msgs.size(), 1u);
  19815. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  19816. }
  19817. TEST_F(SSEParsingTest, CustomEventType) {
  19818. auto msgs = parse("event: update\ndata: payload\n\n");
  19819. ASSERT_EQ(msgs.size(), 1u);
  19820. EXPECT_EQ(msgs[0].event, "update");
  19821. EXPECT_EQ(msgs[0].data, "payload");
  19822. }
  19823. TEST_F(SSEParsingTest, EventIdHandling) {
  19824. auto msgs = parse("id: 12345\ndata: test\n\n");
  19825. ASSERT_EQ(msgs.size(), 1u);
  19826. EXPECT_EQ(msgs[0].id, "12345");
  19827. }
  19828. TEST_F(SSEParsingTest, EmptyEventId) {
  19829. auto msgs = parse("id:\ndata: test\n\n");
  19830. ASSERT_EQ(msgs.size(), 1u);
  19831. EXPECT_EQ(msgs[0].id, "");
  19832. }
  19833. TEST_F(SSEParsingTest, CommentsIgnored) {
  19834. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  19835. ASSERT_EQ(msgs.size(), 1u);
  19836. EXPECT_EQ(msgs[0].data, "hello");
  19837. EXPECT_EQ(msgs[0].event, "message");
  19838. }
  19839. TEST_F(SSEParsingTest, ColonInValue) {
  19840. auto msgs = parse("data: hello:world:test\n\n");
  19841. ASSERT_EQ(msgs.size(), 1u);
  19842. EXPECT_EQ(msgs[0].data, "hello:world:test");
  19843. }
  19844. TEST_F(SSEParsingTest, FieldNameOnly) {
  19845. // A line without a colon is a field name with an empty value
  19846. auto msgs = parse("data\n\n");
  19847. ASSERT_EQ(msgs.size(), 1u);
  19848. EXPECT_EQ(msgs[0].data, "");
  19849. }
  19850. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  19851. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  19852. ASSERT_EQ(msgs.size(), 1u);
  19853. EXPECT_EQ(msgs[0].event, "update");
  19854. EXPECT_EQ(msgs[0].data, "hello");
  19855. }
  19856. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  19857. auto msgs = parse("data\r\n\r\n");
  19858. ASSERT_EQ(msgs.size(), 1u);
  19859. EXPECT_EQ(msgs[0].data, "");
  19860. }
  19861. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  19862. auto msgs = parse("event: update\rdata: hello\r\r");
  19863. ASSERT_EQ(msgs.size(), 1u);
  19864. EXPECT_EQ(msgs[0].event, "update");
  19865. EXPECT_EQ(msgs[0].data, "hello");
  19866. }
  19867. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  19868. // Chunk boundaries fall inside every \r\n and right before the first one
  19869. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  19870. "\n\r", "\nevent: end\ndata: end\n\n"};
  19871. server_->Get("/split", [chunks](const Request &, Response &res) {
  19872. auto i = std::make_shared<size_t>(0);
  19873. res.set_chunked_content_provider(
  19874. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  19875. if (*i == chunks.size()) {
  19876. sink.done();
  19877. } else {
  19878. sink.write(chunks[*i].data(), chunks[*i].size());
  19879. (*i)++;
  19880. }
  19881. return true;
  19882. });
  19883. });
  19884. auto msgs = collect("/split");
  19885. ASSERT_EQ(msgs.size(), 1u);
  19886. EXPECT_EQ(msgs[0].event, "update");
  19887. EXPECT_EQ(msgs[0].data, "hello");
  19888. }
  19889. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  19890. // Only a BOM at the start of the stream is ignored
  19891. auto msgs = parse("\xEF\xBB\xBF"
  19892. "data: first\n\n"
  19893. "\xEF\xBB\xBF"
  19894. "data: second\n\n");
  19895. ASSERT_EQ(msgs.size(), 1u);
  19896. EXPECT_EQ(msgs[0].data, "first");
  19897. }
  19898. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  19899. auto msgs = parse("unknown: value\ndata: hello\n\n");
  19900. ASSERT_EQ(msgs.size(), 1u);
  19901. EXPECT_EQ(msgs[0].data, "hello");
  19902. EXPECT_EQ(msgs[0].event, "message");
  19903. }
  19904. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  19905. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  19906. ASSERT_EQ(msgs.size(), 2u);
  19907. EXPECT_EQ(msgs[0].data, "hello");
  19908. EXPECT_EQ(msgs[1].data, "hello");
  19909. }
  19910. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  19911. // An event without data is not dispatched, and its type must not leak
  19912. // into the next event
  19913. auto msgs = parse("event: update\n\ndata: hello\n\n");
  19914. ASSERT_EQ(msgs.size(), 1u);
  19915. EXPECT_EQ(msgs[0].event, "message");
  19916. EXPECT_EQ(msgs[0].data, "hello");
  19917. }
  19918. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  19919. // The first connection sends only an id; the second echoes back the
  19920. // Last-Event-ID it was reconnected with
  19921. std::atomic<int> connection_count{0};
  19922. server_->Get("/id-only", [&](const Request &req, Response &res) {
  19923. if (connection_count++ == 0) {
  19924. res.set_content("id: 42\n\n", "text/event-stream");
  19925. } else {
  19926. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19927. "\n\nevent: end\ndata: end\n\n",
  19928. "text/event-stream");
  19929. }
  19930. });
  19931. auto msgs = collect("/id-only");
  19932. ASSERT_EQ(msgs.size(), 1u);
  19933. EXPECT_EQ(msgs[0].data, "42");
  19934. }
  19935. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  19936. // The first connection sets an id and then clears it with an empty one; the
  19937. // second reports whether it was reconnected with a Last-Event-ID
  19938. std::atomic<int> connection_count{0};
  19939. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  19940. if (connection_count++ == 0) {
  19941. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  19942. "text/event-stream");
  19943. } else {
  19944. res.set_content(
  19945. std::string("data: ") +
  19946. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  19947. "\n\nevent: end\ndata: end\n\n",
  19948. "text/event-stream");
  19949. }
  19950. });
  19951. auto msgs = collect("/id-clear");
  19952. ASSERT_EQ(msgs.size(), 3u);
  19953. EXPECT_EQ(msgs[0].id, "1");
  19954. EXPECT_EQ(msgs[1].id, "");
  19955. EXPECT_EQ(msgs[2].data, "not sent");
  19956. }
  19957. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  19958. // The first connection sets an id and then sends ids that cannot be carried
  19959. // in a header; the second echoes back the Last-Event-ID it was reconnected
  19960. // with
  19961. std::atomic<int> connection_count{0};
  19962. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  19963. if (connection_count++ == 0) {
  19964. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  19965. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  19966. "text/event-stream");
  19967. } else {
  19968. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19969. "\n\nevent: end\ndata: end\n\n",
  19970. "text/event-stream");
  19971. }
  19972. });
  19973. auto msgs = collect("/id-unsendable");
  19974. ASSERT_EQ(msgs.size(), 1u);
  19975. EXPECT_EQ(msgs[0].data, "42");
  19976. }
  19977. TEST_F(SSEParsingTest, CompleteEventParsing) {
  19978. auto msgs = parse("event: notification\nid: evt-42\n"
  19979. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  19980. ASSERT_EQ(msgs.size(), 1u);
  19981. EXPECT_EQ(msgs[0].event, "notification");
  19982. EXPECT_EQ(msgs[0].id, "evt-42");
  19983. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  19984. }
  19985. TEST(SSEMessageTest, Clear) {
  19986. sse::SSEMessage msg;
  19987. msg.event = "custom";
  19988. msg.data = "some data";
  19989. msg.id = "123";
  19990. msg.clear();
  19991. EXPECT_EQ(msg.event, "message");
  19992. EXPECT_EQ(msg.data, "");
  19993. EXPECT_EQ(msg.id, "");
  19994. }
  19995. //==============================================================================
  19996. // SSE Integration Tests
  19997. //==============================================================================
  19998. // Test: Successful connection and on_open callback
  19999. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  20000. // Add a simple endpoint that sends one event and closes
  20001. server_->Get("/simple-event", [](const Request &, Response &res) {
  20002. res.set_chunked_content_provider(
  20003. "text/event-stream", [](size_t offset, DataSink &sink) {
  20004. if (offset == 0) {
  20005. std::string event = "data: hello\n\n";
  20006. sink.write(event.data(), event.size());
  20007. }
  20008. return false; // Close stream after sending
  20009. });
  20010. });
  20011. Client client("localhost", get_port());
  20012. sse::SSEClient sse(client, "/simple-event");
  20013. std::atomic<bool> open_called{false};
  20014. std::atomic<bool> message_received{false};
  20015. sse.on_open([&open_called]() { open_called.store(true); });
  20016. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  20017. if (msg.data == "hello") { message_received.store(true); }
  20018. });
  20019. sse.set_reconnect_interval(100);
  20020. sse.set_max_reconnect_attempts(1);
  20021. // Start async
  20022. sse.start_async();
  20023. // Wait for message to be processed
  20024. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20025. sse.stop();
  20026. EXPECT_TRUE(open_called.load());
  20027. EXPECT_TRUE(message_received.load());
  20028. }
  20029. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  20030. // A data line that never ends.
  20031. server_->Get("/endless-line", [](const Request &, Response &res) {
  20032. res.set_chunked_content_provider(
  20033. "text/event-stream", [](size_t offset, DataSink &sink) {
  20034. if (offset == 0) { sink.write("data: ", 6); }
  20035. std::string chunk(64 * 1024, 'A');
  20036. return sink.write(chunk.data(), chunk.size());
  20037. });
  20038. });
  20039. Client client("localhost", get_port());
  20040. // A stream that may run forever, so that only the event is bounded.
  20041. client.set_payload_max_length(0);
  20042. sse::SSEClient sse(client, "/endless-line");
  20043. std::atomic<bool> too_long{false};
  20044. sse.on_error([&](Error err) {
  20045. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  20046. });
  20047. sse.set_max_reconnect_attempts(1);
  20048. sse.start_async();
  20049. for (int i = 0; i < 500 && !too_long; i++) {
  20050. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20051. }
  20052. sse.stop();
  20053. EXPECT_TRUE(too_long);
  20054. }
  20055. // Test: on_message callback
  20056. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  20057. // Endpoint that sends multiple events then closes
  20058. server_->Get("/multi-event", [](const Request &, Response &res) {
  20059. res.set_chunked_content_provider(
  20060. "text/event-stream", [](size_t offset, DataSink &sink) {
  20061. if (offset == 0) {
  20062. std::string events = "data: message1\n\ndata: message2\n\n";
  20063. sink.write(events.data(), events.size());
  20064. }
  20065. return false;
  20066. });
  20067. });
  20068. Client client("localhost", get_port());
  20069. sse::SSEClient sse(client, "/multi-event");
  20070. std::vector<std::string> received_messages;
  20071. std::mutex messages_mutex;
  20072. sse.on_message([&](const sse::SSEMessage &msg) {
  20073. std::lock_guard<std::mutex> lock(messages_mutex);
  20074. received_messages.push_back(msg.data);
  20075. });
  20076. sse.set_reconnect_interval(100);
  20077. sse.set_max_reconnect_attempts(1);
  20078. sse.start_async();
  20079. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20080. sse.stop();
  20081. std::lock_guard<std::mutex> lock(messages_mutex);
  20082. EXPECT_GE(received_messages.size(), 2u);
  20083. if (received_messages.size() >= 2) {
  20084. EXPECT_EQ(received_messages[0], "message1");
  20085. EXPECT_EQ(received_messages[1], "message2");
  20086. }
  20087. }
  20088. // Test: on_event for specific types
  20089. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  20090. Client client("localhost", get_port());
  20091. sse::SSEClient sse(client, "/custom-events");
  20092. std::atomic<bool> update_received{false};
  20093. std::atomic<bool> delete_received{false};
  20094. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  20095. if (msg.data == "updated") { update_received.store(true); }
  20096. });
  20097. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  20098. if (msg.data == "deleted") { delete_received.store(true); }
  20099. });
  20100. sse.set_max_reconnect_attempts(1);
  20101. sse.start_async();
  20102. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  20103. sse.stop();
  20104. EXPECT_TRUE(update_received.load());
  20105. EXPECT_TRUE(delete_received.load());
  20106. }
  20107. // Test: on_error callback on connection failure
  20108. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  20109. // Connect to a non-existent port
  20110. Client client("localhost", 59999);
  20111. sse::SSEClient sse(client, "/events");
  20112. std::atomic<bool> error_called{false};
  20113. Error received_error = Error::Success;
  20114. sse.on_error([&](Error err) {
  20115. error_called.store(true);
  20116. received_error = err;
  20117. });
  20118. sse.set_reconnect_interval(50);
  20119. sse.set_max_reconnect_attempts(1);
  20120. sse.start_async();
  20121. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20122. sse.stop();
  20123. EXPECT_TRUE(error_called.load());
  20124. EXPECT_NE(received_error, Error::Success);
  20125. }
  20126. // Test: Last-Event-ID header sent on reconnect
  20127. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  20128. // Endpoint that sends event with ID
  20129. server_->Get("/event-with-id", [](const Request &, Response &res) {
  20130. res.set_chunked_content_provider(
  20131. "text/event-stream", [](size_t offset, DataSink &sink) {
  20132. if (offset == 0) {
  20133. std::string event = "id: evt-123\ndata: test\n\n";
  20134. sink.write(event.data(), event.size());
  20135. }
  20136. return false;
  20137. });
  20138. });
  20139. Client client("localhost", get_port());
  20140. sse::SSEClient sse(client, "/event-with-id");
  20141. std::atomic<bool> id_received{false};
  20142. sse.on_message([&](const sse::SSEMessage &msg) {
  20143. if (!msg.id.empty()) { id_received.store(true); }
  20144. });
  20145. sse.set_reconnect_interval(100);
  20146. sse.set_max_reconnect_attempts(1);
  20147. sse.start_async();
  20148. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20149. sse.stop();
  20150. EXPECT_TRUE(id_received.load());
  20151. EXPECT_EQ(sse.last_event_id(), "evt-123");
  20152. }
  20153. // Test: Manual stop
  20154. TEST_F(SSEIntegrationTest, ManualStop) {
  20155. // Endpoint that sends one event and stays open briefly
  20156. std::atomic<bool> handler_running{true};
  20157. server_->Get("/stay-open", [&handler_running](const Request &,
  20158. Response &res) {
  20159. res.set_chunked_content_provider(
  20160. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  20161. if (offset == 0) {
  20162. std::string event = "data: connected\n\n";
  20163. sink.write(event.data(), event.size());
  20164. }
  20165. // Keep connection open while handler_running is true
  20166. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  20167. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20168. }
  20169. return false;
  20170. });
  20171. });
  20172. Client client("localhost", get_port());
  20173. sse::SSEClient sse(client, "/stay-open");
  20174. std::atomic<bool> connected{false};
  20175. sse.on_open([&connected]() { connected.store(true); });
  20176. sse.set_reconnect_interval(100);
  20177. sse.set_max_reconnect_attempts(1);
  20178. sse.start_async();
  20179. // Wait for connection to establish
  20180. for (int i = 0; i < 20 && !connected.load(); ++i) {
  20181. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20182. }
  20183. EXPECT_TRUE(connected.load());
  20184. EXPECT_TRUE(sse.is_connected());
  20185. // Signal handler to stop
  20186. handler_running.store(false);
  20187. // Stop SSE client
  20188. sse.stop();
  20189. EXPECT_FALSE(sse.is_connected());
  20190. }
  20191. // Test: SSEClient with custom headers
  20192. TEST_F(SSEIntegrationTest, CustomHeaders) {
  20193. // Setup a server endpoint that checks for custom header
  20194. std::atomic<bool> header_received{false};
  20195. server_->Get("/header-check", [&](const Request &req, Response &res) {
  20196. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  20197. header_received.store(true);
  20198. }
  20199. res.set_chunked_content_provider("text/event-stream",
  20200. [](size_t, DataSink &) { return false; });
  20201. });
  20202. Client client("localhost", get_port());
  20203. Headers headers = {{"X-Custom-Header", "custom-value"}};
  20204. sse::SSEClient sse(client, "/header-check", headers);
  20205. sse.set_max_reconnect_attempts(1);
  20206. sse.start_async();
  20207. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20208. sse.stop();
  20209. EXPECT_TRUE(header_received.load());
  20210. }
  20211. // Test: Reconnect interval configuration
  20212. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  20213. Client client("localhost", get_port());
  20214. sse::SSEClient sse(client, "/events");
  20215. auto &result = sse.set_reconnect_interval(500);
  20216. // Builder pattern should return reference to self
  20217. EXPECT_EQ(&result, &sse);
  20218. }
  20219. // Test: Max reconnect attempts
  20220. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  20221. // Connect to non-existent port to force reconnects
  20222. Client client("localhost", 59998);
  20223. sse::SSEClient sse(client, "/events");
  20224. std::atomic<int> error_count{0};
  20225. sse.on_error([&](Error) { error_count.fetch_add(1); });
  20226. sse.set_reconnect_interval(50);
  20227. sse.set_max_reconnect_attempts(2);
  20228. auto start = std::chrono::steady_clock::now();
  20229. sse.start(); // Blocking call
  20230. auto end = std::chrono::steady_clock::now();
  20231. // Should have stopped after 2 failed attempts
  20232. EXPECT_GE(error_count.load(), 2);
  20233. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  20234. auto duration =
  20235. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  20236. #ifdef _WIN32
  20237. // Windows is much slower for socket connection failures
  20238. EXPECT_LT(duration.count(), 7000);
  20239. #else
  20240. EXPECT_LT(duration.count(), 1000);
  20241. #endif
  20242. }
  20243. // Test: Multi-line data in integration
  20244. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  20245. // Endpoint with multi-line data
  20246. server_->Get("/multiline-data", [](const Request &, Response &res) {
  20247. res.set_chunked_content_provider(
  20248. "text/event-stream", [](size_t offset, DataSink &sink) {
  20249. if (offset == 0) {
  20250. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  20251. sink.write(event.data(), event.size());
  20252. }
  20253. return false;
  20254. });
  20255. });
  20256. Client client("localhost", get_port());
  20257. sse::SSEClient sse(client, "/multiline-data");
  20258. std::string received_data;
  20259. std::mutex data_mutex;
  20260. sse.on_message([&](const sse::SSEMessage &msg) {
  20261. std::lock_guard<std::mutex> lock(data_mutex);
  20262. received_data = msg.data;
  20263. });
  20264. sse.set_reconnect_interval(100);
  20265. sse.set_max_reconnect_attempts(1);
  20266. sse.start_async();
  20267. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20268. sse.stop();
  20269. std::lock_guard<std::mutex> lock(data_mutex);
  20270. EXPECT_EQ(received_data, "line1\nline2\nline3");
  20271. }
  20272. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  20273. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  20274. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  20275. DataSink &sink) {
  20276. if (offset == 0) {
  20277. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  20278. sink.write(events.data(), events.size());
  20279. }
  20280. return false;
  20281. });
  20282. });
  20283. Client client("localhost", get_port());
  20284. sse::SSEClient sse(client, "/empty-data-lines");
  20285. std::mutex mutex;
  20286. std::condition_variable cv;
  20287. std::vector<std::string> received;
  20288. sse.on_message([&](const sse::SSEMessage &msg) {
  20289. std::lock_guard<std::mutex> lock(mutex);
  20290. received.push_back(msg.data);
  20291. cv.notify_all();
  20292. });
  20293. sse.set_max_reconnect_attempts(1);
  20294. sse.start_async();
  20295. {
  20296. std::unique_lock<std::mutex> lock(mutex);
  20297. cv.wait_for(lock, std::chrono::seconds(2),
  20298. [&] { return received.size() >= 3; });
  20299. }
  20300. sse.stop();
  20301. ASSERT_GE(received.size(), 3u);
  20302. EXPECT_EQ(received[0], "");
  20303. EXPECT_EQ(received[1], "\nhello");
  20304. EXPECT_EQ(received[2], "");
  20305. }
  20306. // Test: Auto-reconnect after server disconnection
  20307. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  20308. std::atomic<int> connection_count{0};
  20309. std::atomic<int> message_count{0};
  20310. // Endpoint that sends one event and closes, forcing reconnect
  20311. server_->Get("/reconnect-test",
  20312. [&connection_count](const Request &, Response &res) {
  20313. connection_count.fetch_add(1);
  20314. res.set_chunked_content_provider(
  20315. "text/event-stream", [](size_t offset, DataSink &sink) {
  20316. if (offset == 0) {
  20317. std::string event = "data: hello\n\n";
  20318. sink.write(event.data(), event.size());
  20319. }
  20320. return false; // Close connection after sending
  20321. });
  20322. });
  20323. Client client("localhost", get_port());
  20324. sse::SSEClient sse(client, "/reconnect-test");
  20325. sse.on_message([&message_count](const sse::SSEMessage &) {
  20326. message_count.fetch_add(1);
  20327. });
  20328. sse.set_reconnect_interval(100);
  20329. sse.set_max_reconnect_attempts(3);
  20330. sse.start_async();
  20331. // Wait long enough for multiple reconnects
  20332. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20333. sse.stop();
  20334. // Should have connected multiple times (initial + reconnects)
  20335. EXPECT_GE(connection_count.load(), 2);
  20336. // Should have received messages from multiple connections
  20337. EXPECT_GE(message_count.load(), 2);
  20338. }
  20339. // Test: A retry field that is not all ASCII digits is ignored
  20340. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  20341. std::atomic<int> connection_count{0};
  20342. server_->Get("/bad-retry",
  20343. [&connection_count](const Request &, Response &res) {
  20344. connection_count.fetch_add(1);
  20345. res.set_chunked_content_provider(
  20346. "text/event-stream", [](size_t offset, DataSink &sink) {
  20347. if (offset == 0) {
  20348. std::string event = "retry: -1\ndata: hello\n\n";
  20349. sink.write(event.data(), event.size());
  20350. }
  20351. return false;
  20352. });
  20353. });
  20354. Client client("localhost", get_port());
  20355. sse::SSEClient sse(client, "/bad-retry");
  20356. sse.set_reconnect_interval(10000);
  20357. sse.start_async();
  20358. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20359. sse.stop();
  20360. EXPECT_EQ(connection_count.load(), 1);
  20361. }
  20362. // Test: A retry field of all ASCII digits sets the reconnection time
  20363. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  20364. std::mutex mutex;
  20365. std::condition_variable cv;
  20366. std::vector<std::chrono::steady_clock::time_point> connected_at;
  20367. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  20368. {
  20369. std::lock_guard<std::mutex> lock(mutex);
  20370. connected_at.push_back(std::chrono::steady_clock::now());
  20371. cv.notify_all();
  20372. }
  20373. res.set_chunked_content_provider(
  20374. "text/event-stream", [](size_t offset, DataSink &sink) {
  20375. if (offset == 0) {
  20376. std::string event = "retry: 0\ndata: hello\n\n";
  20377. sink.write(event.data(), event.size());
  20378. }
  20379. return false;
  20380. });
  20381. });
  20382. Client client("localhost", get_port());
  20383. sse::SSEClient sse(client, "/zero-retry");
  20384. sse.set_reconnect_interval(10000);
  20385. sse.start_async();
  20386. {
  20387. std::unique_lock<std::mutex> lock(mutex);
  20388. cv.wait_for(lock, std::chrono::seconds(5),
  20389. [&] { return connected_at.size() >= 2; });
  20390. }
  20391. sse.stop();
  20392. // The server-supplied interval is applied, but never below 100ms, so
  20393. // "retry: 0" does not cause a busy reconnect loop
  20394. std::lock_guard<std::mutex> lock(mutex);
  20395. ASSERT_GE(connected_at.size(), 2u);
  20396. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  20397. connected_at[1] - connected_at[0])
  20398. .count();
  20399. EXPECT_GE(interval_ms, 100);
  20400. }
  20401. // Test: Last-Event-ID sent on reconnect
  20402. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  20403. std::atomic<int> connection_count{0};
  20404. std::vector<std::string> received_last_event_ids;
  20405. std::mutex id_mutex;
  20406. // Endpoint that checks Last-Event-ID header and sends event with ID
  20407. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  20408. int conn = connection_count.fetch_add(1);
  20409. // Capture the Last-Event-ID header from each connection
  20410. {
  20411. std::lock_guard<std::mutex> lock(id_mutex);
  20412. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  20413. }
  20414. res.set_chunked_content_provider(
  20415. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  20416. if (offset == 0) {
  20417. std::string event =
  20418. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  20419. sink.write(event.data(), event.size());
  20420. }
  20421. return false;
  20422. });
  20423. });
  20424. Client client("localhost", get_port());
  20425. sse::SSEClient sse(client, "/reconnect-with-id");
  20426. sse.set_reconnect_interval(100);
  20427. sse.set_max_reconnect_attempts(3);
  20428. sse.start_async();
  20429. // Wait for at least 2 connections
  20430. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20431. sse.stop();
  20432. // Verify behavior
  20433. std::lock_guard<std::mutex> lock(id_mutex);
  20434. EXPECT_GE(received_last_event_ids.size(), 2u);
  20435. // First connection should have no Last-Event-ID
  20436. if (!received_last_event_ids.empty()) {
  20437. EXPECT_EQ(received_last_event_ids[0], "");
  20438. }
  20439. // Second connection should have Last-Event-ID from first connection
  20440. if (received_last_event_ids.size() >= 2) {
  20441. EXPECT_EQ(received_last_event_ids[1], "event-0");
  20442. }
  20443. }
  20444. // Test: set_headers updates headers used on reconnect
  20445. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  20446. std::vector<std::string> received_tokens;
  20447. std::mutex token_mutex;
  20448. // Endpoint that captures Authorization header
  20449. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  20450. {
  20451. std::lock_guard<std::mutex> lock(token_mutex);
  20452. received_tokens.push_back(req.get_header_value("Authorization"));
  20453. }
  20454. res.set_chunked_content_provider(
  20455. "text/event-stream", [](size_t offset, DataSink &sink) {
  20456. if (offset == 0) {
  20457. std::string event = "data: hello\n\n";
  20458. sink.write(event.data(), event.size());
  20459. }
  20460. return false; // Close connection to trigger reconnect
  20461. });
  20462. });
  20463. Client client("localhost", get_port());
  20464. Headers headers = {{"Authorization", "Bearer old-token"}};
  20465. sse::SSEClient sse(client, "/auth-check", headers);
  20466. // Update headers on each successful connection
  20467. sse.on_open(
  20468. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  20469. sse.set_reconnect_interval(100);
  20470. sse.set_max_reconnect_attempts(3);
  20471. sse.start_async();
  20472. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20473. sse.stop();
  20474. std::lock_guard<std::mutex> lock(token_mutex);
  20475. ASSERT_GE(received_tokens.size(), 2u);
  20476. // First connection uses original header
  20477. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  20478. // Second connection uses updated header from set_headers
  20479. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  20480. }
  20481. // Test: 401 allows reconnection (so on_error can refresh headers)
  20482. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  20483. std::atomic<int> connection_count{0};
  20484. // Endpoint: returns 401 on first attempt, 200 on second
  20485. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  20486. int conn = connection_count.fetch_add(1);
  20487. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  20488. res.status = StatusCode::Unauthorized_401;
  20489. res.set_content("Unauthorized", "text/plain");
  20490. return;
  20491. }
  20492. res.set_chunked_content_provider(
  20493. "text/event-stream", [](size_t offset, DataSink &sink) {
  20494. if (offset == 0) {
  20495. std::string event = "data: authenticated\n\n";
  20496. sink.write(event.data(), event.size());
  20497. }
  20498. return false;
  20499. });
  20500. });
  20501. Client client("localhost", get_port());
  20502. Headers headers = {{"Authorization", "Bearer expired"}};
  20503. sse::SSEClient sse(client, "/auth-retry", headers);
  20504. std::atomic<bool> message_received{false};
  20505. // Refresh token on error
  20506. sse.on_error(
  20507. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  20508. sse.on_message([&](const sse::SSEMessage &msg) {
  20509. if (msg.data == "authenticated") { message_received.store(true); }
  20510. });
  20511. sse.set_reconnect_interval(100);
  20512. sse.set_max_reconnect_attempts(3);
  20513. sse.start_async();
  20514. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20515. sse.stop();
  20516. // Should have reconnected after 401 and succeeded with new token
  20517. EXPECT_GE(connection_count.load(), 2);
  20518. EXPECT_TRUE(message_received.load());
  20519. }
  20520. TEST(Issue2318Test, EmptyHostString) {
  20521. {
  20522. httplib::Client cli_empty("", PORT);
  20523. auto res = cli_empty.Get("/");
  20524. ASSERT_FALSE(res);
  20525. EXPECT_EQ(httplib::Error::Connection, res.error());
  20526. }
  20527. {
  20528. httplib::Client cli(" ", PORT);
  20529. auto res = cli.Get("/");
  20530. ASSERT_FALSE(res);
  20531. EXPECT_EQ(httplib::Error::Connection, res.error());
  20532. }
  20533. }
  20534. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20535. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  20536. Server svr;
  20537. // Set a small payload limit (1KB)
  20538. svr.set_payload_max_length(1024);
  20539. svr.Post("/test", [&](const Request &req, Response &res) {
  20540. res.set_content("Body size: " + std::to_string(req.body.size()),
  20541. "text/plain");
  20542. });
  20543. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  20544. auto se = detail::scope_exit([&] {
  20545. svr.stop();
  20546. listen_thread.join();
  20547. });
  20548. svr.wait_until_ready();
  20549. // Create data that compresses well but exceeds limit when decompressed
  20550. // 8KB of repeated null bytes compresses to a very small size
  20551. std::string original_data(8 * 1024, '\0');
  20552. // Compress the data using gzip
  20553. std::string compressed_data;
  20554. detail::gzip_compressor compressor;
  20555. compressor.compress(original_data.data(), original_data.size(), true,
  20556. [&](const char *data, size_t size) {
  20557. compressed_data.append(data, size);
  20558. return true;
  20559. });
  20560. // Verify compression worked (compressed should be much smaller)
  20561. ASSERT_LT(compressed_data.size(), original_data.size());
  20562. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  20563. // Send compressed data with Content-Encoding: gzip
  20564. Client cli(HOST, PORT);
  20565. Headers headers = {{"Content-Encoding", "gzip"}};
  20566. auto res =
  20567. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  20568. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  20569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20570. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  20571. }
  20572. #endif
  20573. // ============================================================================
  20574. // OpenSSL-Specific Tests
  20575. // ============================================================================
  20576. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  20577. X509 *readCertificate(const std::string &strFileName) {
  20578. std::ifstream inStream(strFileName);
  20579. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  20580. std::istreambuf_iterator<char>());
  20581. if (strCertPEM.empty()) return (nullptr);
  20582. BIO *pbCert = BIO_new(BIO_s_mem());
  20583. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  20584. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  20585. BIO_free(pbCert);
  20586. return (pCert);
  20587. }
  20588. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  20589. std::ifstream inStream(strFileName);
  20590. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  20591. std::istreambuf_iterator<char>());
  20592. if (strPrivateKeyPEM.empty()) return (nullptr);
  20593. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  20594. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  20595. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  20596. BIO_free(pbPrivKey);
  20597. return (pPrivateKey);
  20598. }
  20599. TEST(BindServerTest, UpdateCerts) {
  20600. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20601. int port = svr.bind_to_any_port("0.0.0.0");
  20602. ASSERT_TRUE(svr.is_valid());
  20603. ASSERT_TRUE(port > 0);
  20604. X509 *cert = readCertificate(SERVER_CERT_FILE);
  20605. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  20606. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  20607. ASSERT_TRUE(cert != nullptr);
  20608. ASSERT_TRUE(ca_cert != nullptr);
  20609. ASSERT_TRUE(key != nullptr);
  20610. X509_STORE *cert_store = X509_STORE_new();
  20611. X509_STORE_add_cert(cert_store, ca_cert);
  20612. // svr.update_certs(cert, key, cert_store); // deprecated
  20613. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  20614. CLIENT_CA_CERT_FILE);
  20615. ASSERT_TRUE(svr.is_valid());
  20616. svr.stop();
  20617. X509_STORE_free(cert_store);
  20618. X509_free(cert);
  20619. X509_free(ca_cert);
  20620. EVP_PKEY_free(key);
  20621. }
  20622. // Test that update_certs() updates client CA list correctly
  20623. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  20624. // Start with file-based constructor
  20625. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20626. ASSERT_TRUE(svr.is_valid());
  20627. // Initially no client CA list should be set
  20628. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20629. ASSERT_TRUE(ssl_ctx != nullptr);
  20630. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  20631. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  20632. EXPECT_EQ(0, count_before);
  20633. // Now update with client CA (PEM string)
  20634. std::string cert_pem, key_pem, ca_pem;
  20635. read_file(SERVER_CERT_FILE, cert_pem);
  20636. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  20637. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  20638. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  20639. ASSERT_TRUE(svr.is_valid());
  20640. // Now client CA list should be set
  20641. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  20642. ASSERT_TRUE(ca_list_after != nullptr);
  20643. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  20644. }
  20645. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  20646. // Test that the file-path SSLServer constructor properly sets the client CA
  20647. // list that is sent to clients during the TLS handshake (CertificateRequest)
  20648. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20649. ASSERT_TRUE(svr.is_valid());
  20650. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20651. ASSERT_TRUE(ssl_ctx != nullptr);
  20652. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  20653. ASSERT_TRUE(ca_list != nullptr);
  20654. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  20655. }
  20656. #endif
  20657. // ============================================================================
  20658. // MbedTLS-Specific Tests
  20659. // ============================================================================
  20660. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  20661. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  20662. using namespace httplib::tls;
  20663. // Track if callback was invoked
  20664. bool callback_invoked = false;
  20665. // The callback receives void* ctx which is actually MbedTlsContext*
  20666. // We can access the mbedtls_ssl_config via the context
  20667. auto setup_callback = [&callback_invoked](void *ctx) {
  20668. callback_invoked = true;
  20669. // Cast to MbedTlsContext* to access the ssl config
  20670. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  20671. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  20672. // Use static variables to hold certificate data (simplified for test)
  20673. static mbedtls_x509_crt own_cert;
  20674. static mbedtls_pk_context own_key;
  20675. static mbedtls_x509_crt ca_chain;
  20676. static bool initialized = false;
  20677. if (!initialized) {
  20678. mbedtls_x509_crt_init(&own_cert);
  20679. mbedtls_pk_init(&own_key);
  20680. mbedtls_x509_crt_init(&ca_chain);
  20681. // Load server certificate
  20682. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  20683. return false;
  20684. }
  20685. // Load server private key.
  20686. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  20687. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  20688. #if MBEDTLS_VERSION_MAJOR == 3
  20689. ,
  20690. mbedtls_ctr_drbg_random, nullptr
  20691. #endif
  20692. ) != 0) {
  20693. return false;
  20694. }
  20695. // Load CA chain for client verification
  20696. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  20697. return false;
  20698. }
  20699. initialized = true;
  20700. }
  20701. // Configure the SSL config
  20702. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  20703. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  20704. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  20705. // Set minimum TLS version using mbedTLS native API
  20706. #if MBEDTLS_VERSION_MAJOR >= 3
  20707. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  20708. #else
  20709. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  20710. MBEDTLS_SSL_MINOR_VERSION_3);
  20711. #endif
  20712. return true;
  20713. };
  20714. SSLServer svr(setup_callback);
  20715. ASSERT_TRUE(svr.is_valid());
  20716. ASSERT_TRUE(callback_invoked);
  20717. svr.Get("/test", [&](const Request &req, Response &res) {
  20718. res.set_content("test", "text/plain");
  20719. auto cert = req.peer_cert();
  20720. ASSERT_TRUE(static_cast<bool>(cert));
  20721. auto common_name = cert.subject_cn();
  20722. EXPECT_EQ("Common Name", common_name);
  20723. });
  20724. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20725. auto se = detail::scope_exit([&] {
  20726. svr.stop();
  20727. t.join();
  20728. ASSERT_FALSE(svr.is_running());
  20729. });
  20730. svr.wait_until_ready();
  20731. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  20732. cli.enable_server_certificate_verification(false);
  20733. cli.set_connection_timeout(30);
  20734. auto res = cli.Get("/test");
  20735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20736. ASSERT_EQ(StatusCode::OK_200, res->status);
  20737. }
  20738. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  20739. // context (owning mbedtls_ssl_config) before shutting down a still-open
  20740. // keep-alive SSL session, which reads through that config in
  20741. // mbedtls_ssl_close_notify.
  20742. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  20743. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20744. ASSERT_TRUE(svr.is_valid());
  20745. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  20746. res.set_content("test", "text/plain");
  20747. });
  20748. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20749. auto se = detail::scope_exit([&] {
  20750. svr.stop();
  20751. t.join();
  20752. ASSERT_FALSE(svr.is_running());
  20753. });
  20754. svr.wait_until_ready();
  20755. {
  20756. SSLClient cli(HOST, PORT);
  20757. cli.enable_server_certificate_verification(false);
  20758. cli.set_keep_alive(true);
  20759. auto res = cli.Get("/test");
  20760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20761. ASSERT_EQ(StatusCode::OK_200, res->status);
  20762. // cli is destructed here with the keep-alive SSL session still open.
  20763. }
  20764. }
  20765. #endif
  20766. // WebSocket Tests
  20767. TEST(WebSocketTest, RSVBitsMustBeZero) {
  20768. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  20769. // defining the meaning of these bits has been negotiated.
  20770. auto make_frame = [](uint8_t first_byte) {
  20771. std::string frame;
  20772. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  20773. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  20774. frame += "Hello";
  20775. return frame;
  20776. };
  20777. // RSV1 set (0x40)
  20778. {
  20779. detail::BufferStream strm;
  20780. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  20781. ws::Opcode opcode;
  20782. std::string payload;
  20783. bool fin;
  20784. EXPECT_EQ(
  20785. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20786. ws::impl::FrameRead::Fail);
  20787. }
  20788. // RSV2 set (0x20)
  20789. {
  20790. detail::BufferStream strm;
  20791. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  20792. ws::Opcode opcode;
  20793. std::string payload;
  20794. bool fin;
  20795. EXPECT_EQ(
  20796. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20797. ws::impl::FrameRead::Fail);
  20798. }
  20799. // RSV3 set (0x10)
  20800. {
  20801. detail::BufferStream strm;
  20802. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  20803. ws::Opcode opcode;
  20804. std::string payload;
  20805. bool fin;
  20806. EXPECT_EQ(
  20807. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20808. ws::impl::FrameRead::Fail);
  20809. }
  20810. // No RSV bits set - should succeed
  20811. {
  20812. detail::BufferStream strm;
  20813. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  20814. ws::Opcode opcode;
  20815. std::string payload;
  20816. bool fin;
  20817. EXPECT_EQ(
  20818. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20819. ws::impl::FrameRead::Ok);
  20820. EXPECT_EQ(ws::Opcode::Text, opcode);
  20821. EXPECT_EQ("Hello", payload);
  20822. EXPECT_TRUE(fin);
  20823. }
  20824. }
  20825. TEST(WebSocketTest, ControlFrameValidation) {
  20826. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  20827. // payload length <= 125.
  20828. // Ping with FIN=0 - must be rejected
  20829. {
  20830. detail::BufferStream strm;
  20831. std::string frame;
  20832. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  20833. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20834. strm.write(frame.data(), frame.size());
  20835. ws::Opcode opcode;
  20836. std::string payload;
  20837. bool fin;
  20838. EXPECT_EQ(
  20839. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20840. ws::impl::FrameRead::Fail);
  20841. }
  20842. // Close with FIN=0 - must be rejected
  20843. {
  20844. detail::BufferStream strm;
  20845. std::string frame;
  20846. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  20847. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20848. strm.write(frame.data(), frame.size());
  20849. ws::Opcode opcode;
  20850. std::string payload;
  20851. bool fin;
  20852. EXPECT_EQ(
  20853. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20854. ws::impl::FrameRead::Fail);
  20855. }
  20856. // Ping with payload_len=126 (extended length) - must be rejected
  20857. {
  20858. detail::BufferStream strm;
  20859. std::string frame;
  20860. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20861. frame += static_cast<char>(126); // payload_len=126 (>125)
  20862. frame += static_cast<char>(0x00); // extended length high byte
  20863. frame += static_cast<char>(126); // extended length low byte
  20864. frame += std::string(126, 'x');
  20865. strm.write(frame.data(), frame.size());
  20866. ws::Opcode opcode;
  20867. std::string payload;
  20868. bool fin;
  20869. EXPECT_EQ(
  20870. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20871. ws::impl::FrameRead::Fail);
  20872. }
  20873. // Ping with FIN=1 and payload_len=125 - should succeed
  20874. {
  20875. detail::BufferStream strm;
  20876. std::string frame;
  20877. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20878. frame += static_cast<char>(125); // payload_len=125
  20879. frame += std::string(125, 'x');
  20880. strm.write(frame.data(), frame.size());
  20881. ws::Opcode opcode;
  20882. std::string payload;
  20883. bool fin;
  20884. EXPECT_EQ(
  20885. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20886. ws::impl::FrameRead::Ok);
  20887. EXPECT_EQ(ws::Opcode::Ping, opcode);
  20888. EXPECT_EQ(125u, payload.size());
  20889. EXPECT_TRUE(fin);
  20890. }
  20891. }
  20892. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  20893. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  20894. // length MUST be 0.
  20895. // MSB set - must be rejected
  20896. {
  20897. detail::BufferStream strm;
  20898. std::string frame;
  20899. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20900. frame += static_cast<char>(127); // 64-bit extended length
  20901. frame += static_cast<char>(0x80); // MSB set (invalid)
  20902. frame += std::string(7, '\0'); // remaining 7 bytes of length
  20903. strm.write(frame.data(), frame.size());
  20904. ws::Opcode opcode;
  20905. std::string payload;
  20906. bool fin;
  20907. EXPECT_EQ(
  20908. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20909. ws::impl::FrameRead::Fail);
  20910. }
  20911. // MSB clear - should pass length parsing (will be rejected by max_len,
  20912. // but that's a different check; use a small length to verify)
  20913. {
  20914. detail::BufferStream strm;
  20915. std::string frame;
  20916. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20917. frame += static_cast<char>(127); // 64-bit extended length
  20918. frame += std::string(7, '\0'); // high bytes = 0
  20919. frame += static_cast<char>(0x03); // length = 3
  20920. frame += "abc";
  20921. strm.write(frame.data(), frame.size());
  20922. ws::Opcode opcode;
  20923. std::string payload;
  20924. bool fin;
  20925. EXPECT_EQ(
  20926. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20927. ws::impl::FrameRead::Ok);
  20928. EXPECT_EQ(ws::Opcode::Text, opcode);
  20929. EXPECT_EQ("abc", payload);
  20930. }
  20931. }
  20932. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  20933. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  20934. // Valid UTF-8
  20935. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  20936. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  20937. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  20938. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  20939. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  20940. // Invalid UTF-8
  20941. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  20942. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  20943. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  20944. EXPECT_FALSE(
  20945. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  20946. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  20947. }
  20948. TEST(WebSocketTest, ConnectAndDisconnect) {
  20949. Server svr;
  20950. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20951. std::string msg;
  20952. while (ws.read(msg)) {}
  20953. });
  20954. auto port = svr.bind_to_any_port(HOST);
  20955. std::thread t([&]() { svr.listen_after_bind(); });
  20956. svr.wait_until_ready();
  20957. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20958. auto res = client.connect();
  20959. ASSERT_TRUE(res);
  20960. EXPECT_EQ(Error::Success, res.error());
  20961. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  20962. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  20963. EXPECT_TRUE(client.is_open());
  20964. client.close();
  20965. EXPECT_FALSE(client.is_open());
  20966. svr.stop();
  20967. t.join();
  20968. }
  20969. TEST(WebSocketTest, ValidURL) {
  20970. ws::WebSocketClient ws1("ws://localhost:8080/path");
  20971. EXPECT_TRUE(ws1.is_valid());
  20972. ws::WebSocketClient ws2("ws://example.com/path");
  20973. EXPECT_TRUE(ws2.is_valid());
  20974. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  20975. EXPECT_TRUE(ws3.is_valid());
  20976. #ifdef CPPHTTPLIB_SSL_ENABLED
  20977. ws::WebSocketClient wss1("wss://example.com/path");
  20978. EXPECT_TRUE(wss1.is_valid());
  20979. ws::WebSocketClient wss2("wss://example.com:443/path");
  20980. EXPECT_TRUE(wss2.is_valid());
  20981. #endif
  20982. }
  20983. TEST(WebSocketTest, InvalidURL) {
  20984. // No scheme
  20985. ws::WebSocketClient ws1("localhost:8080/path");
  20986. EXPECT_FALSE(ws1.is_valid());
  20987. // No path
  20988. ws::WebSocketClient ws2("ws://localhost:8080");
  20989. EXPECT_FALSE(ws2.is_valid());
  20990. // Empty string
  20991. ws::WebSocketClient ws3("");
  20992. EXPECT_FALSE(ws3.is_valid());
  20993. // Missing host
  20994. ws::WebSocketClient ws4("ws://:8080/path");
  20995. EXPECT_FALSE(ws4.is_valid());
  20996. // Port number overflow — should not crash
  20997. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  20998. EXPECT_FALSE(ws5.is_valid());
  20999. // Port out of range
  21000. ws::WebSocketClient ws6("ws://localhost:99999/path");
  21001. EXPECT_FALSE(ws6.is_valid());
  21002. }
  21003. TEST(WebSocketTest, UnsupportedScheme) {
  21004. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  21005. ws::WebSocketClient ws1("http://localhost:8080/path");
  21006. EXPECT_FALSE(ws1.is_valid());
  21007. ws::WebSocketClient ws2("https://localhost:8080/path");
  21008. EXPECT_FALSE(ws2.is_valid());
  21009. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  21010. EXPECT_FALSE(ws3.is_valid());
  21011. #else
  21012. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  21013. std::invalid_argument);
  21014. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  21015. std::invalid_argument);
  21016. #endif
  21017. }
  21018. TEST(WebSocketTest, ConnectWhenInvalid) {
  21019. ws::WebSocketClient ws("not a valid url");
  21020. EXPECT_FALSE(ws.is_valid());
  21021. auto res = ws.connect();
  21022. EXPECT_FALSE(res);
  21023. EXPECT_EQ(Error::Connection, res.error());
  21024. EXPECT_EQ(-1, res.status());
  21025. }
  21026. TEST(WebSocketTest, ConnectRefusedReportsError) {
  21027. // Grab a port that is free, then close it again so nothing listens there
  21028. Server svr;
  21029. auto port = svr.bind_to_any_port(HOST);
  21030. svr.stop();
  21031. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21032. auto res = client.connect();
  21033. ASSERT_FALSE(res);
  21034. EXPECT_EQ(Error::Connection, res.error());
  21035. EXPECT_EQ(-1, res.status());
  21036. }
  21037. TEST(WebSocketTest, DefaultPort) {
  21038. ws::WebSocketClient ws1("ws://example.com/path");
  21039. EXPECT_TRUE(ws1.is_valid());
  21040. // ws:// defaults to port 80 (verified by successful parse)
  21041. #ifdef CPPHTTPLIB_SSL_ENABLED
  21042. ws::WebSocketClient ws2("wss://example.com/path");
  21043. EXPECT_TRUE(ws2.is_valid());
  21044. // wss:// defaults to port 443 (verified by successful parse)
  21045. #endif
  21046. }
  21047. TEST(WebSocketTest, IPv6LiteralAddress) {
  21048. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  21049. EXPECT_TRUE(ws1.is_valid());
  21050. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  21051. EXPECT_TRUE(ws2.is_valid());
  21052. }
  21053. TEST(WebSocketTest, ComplexPath) {
  21054. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  21055. EXPECT_TRUE(ws1.is_valid());
  21056. ws::WebSocketClient ws2("ws://localhost:8080/");
  21057. EXPECT_TRUE(ws2.is_valid());
  21058. }
  21059. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  21060. Server svr;
  21061. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21062. std::string msg;
  21063. while (ws.read(msg)) {}
  21064. });
  21065. auto port = svr.bind_to_any_port(HOST);
  21066. std::thread t([&]() { svr.listen_after_bind(); });
  21067. svr.wait_until_ready();
  21068. auto another_host = "example.com";
  21069. auto wrong_ip = "192.0.2.1";
  21070. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21071. client.set_hostname_addr_map({{another_host, wrong_ip}});
  21072. ASSERT_TRUE(client.connect());
  21073. EXPECT_TRUE(client.is_open());
  21074. client.close();
  21075. svr.stop();
  21076. t.join();
  21077. }
  21078. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  21079. Server svr;
  21080. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21081. std::string msg;
  21082. while (ws.read(msg)) {}
  21083. });
  21084. auto port = svr.bind_to_any_port(HOST);
  21085. std::thread t([&]() { svr.listen_after_bind(); });
  21086. svr.wait_until_ready();
  21087. auto wrong_ip = "192.0.2.1";
  21088. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21089. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  21090. client.set_connection_timeout(1);
  21091. client.set_read_timeout(1);
  21092. client.set_write_timeout(1);
  21093. EXPECT_FALSE(client.connect());
  21094. EXPECT_FALSE(client.is_open());
  21095. svr.stop();
  21096. t.join();
  21097. }
  21098. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  21099. // A mapped value that is not an IP literal must be resolved. HOST resolves
  21100. // from the hosts file, so this test needs no external DNS. "target.invalid"
  21101. // (RFC 6761) is only a map key and the Host header value.
  21102. auto host = "target.invalid";
  21103. Server svr;
  21104. std::string received_host;
  21105. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21106. received_host = req.get_header_value("Host");
  21107. std::string msg;
  21108. while (ws.read(msg)) {}
  21109. });
  21110. auto port = svr.bind_to_any_port(HOST);
  21111. std::thread t([&]() { svr.listen_after_bind(); });
  21112. // ASSERT_* below returns from the test body, which would leave t joinable
  21113. // and make ~thread call std::terminate.
  21114. auto se = detail::scope_exit([&] {
  21115. svr.stop();
  21116. if (t.joinable()) { t.join(); }
  21117. });
  21118. svr.wait_until_ready();
  21119. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  21120. std::to_string(port) + "/ws");
  21121. client.set_hostname_addr_map({{host, HOST}});
  21122. ASSERT_TRUE(client.connect());
  21123. EXPECT_TRUE(client.is_open());
  21124. client.close();
  21125. svr.stop();
  21126. t.join();
  21127. // The mapping only redirects the connection; the identity stays host_.
  21128. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  21129. }
  21130. class WebSocketIntegrationTest : public ::testing::Test {
  21131. protected:
  21132. void SetUp() override {
  21133. server_ = httplib::detail::make_unique<Server>();
  21134. setup_server();
  21135. start_server();
  21136. }
  21137. void TearDown() override {
  21138. server_->stop();
  21139. if (server_thread_.joinable()) { server_thread_.join(); }
  21140. }
  21141. void setup_server() {
  21142. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21143. std::string msg;
  21144. ws::ReadResult ret;
  21145. while ((ret = ws.read(msg))) {
  21146. if (ret == ws::Binary) {
  21147. ws.send(msg.data(), msg.size());
  21148. } else {
  21149. ws.send(msg);
  21150. }
  21151. }
  21152. });
  21153. server_->WebSocket("/ws-echo-string",
  21154. [](const Request &, ws::WebSocket &ws) {
  21155. std::string msg;
  21156. while (ws.read(msg)) {
  21157. ws.send("echo: " + msg);
  21158. }
  21159. });
  21160. server_->WebSocket(
  21161. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  21162. // Echo back request metadata
  21163. ws.send("path:" + req.path);
  21164. ws.send("header:" + req.get_header_value("X-Test-Header"));
  21165. std::string msg;
  21166. while (ws.read(msg)) {}
  21167. });
  21168. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  21169. std::string msg;
  21170. ws.read(msg); // wait for a message
  21171. ws.close();
  21172. });
  21173. server_->WebSocket("/ws-close-status",
  21174. [](const Request &, ws::WebSocket &ws) {
  21175. std::string msg;
  21176. ws.read(msg); // wait for a message
  21177. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  21178. });
  21179. server_->WebSocket(
  21180. "/ws-subprotocol",
  21181. [](const Request &, ws::WebSocket &ws) {
  21182. std::string msg;
  21183. while (ws.read(msg)) {
  21184. ws.send(msg);
  21185. }
  21186. },
  21187. [](const std::vector<std::string> &protocols) -> std::string {
  21188. for (const auto &p : protocols) {
  21189. if (p == "graphql-ws") { return p; }
  21190. }
  21191. return "";
  21192. });
  21193. server_->WebSocket(
  21194. "/ws-subprotocol-unoffered",
  21195. [](const Request &, ws::WebSocket &ws) {
  21196. std::string msg;
  21197. while (ws.read(msg)) {
  21198. ws.send(msg);
  21199. }
  21200. },
  21201. [](const std::vector<std::string> &) -> std::string {
  21202. return "admin";
  21203. });
  21204. }
  21205. void start_server() {
  21206. port_ = server_->bind_to_any_port(HOST);
  21207. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21208. server_->wait_until_ready();
  21209. }
  21210. std::unique_ptr<Server> server_;
  21211. std::thread server_thread_;
  21212. int port_ = 0;
  21213. };
  21214. TEST_F(WebSocketIntegrationTest, TextEcho) {
  21215. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21216. "/ws-echo");
  21217. ASSERT_TRUE(client.connect());
  21218. ASSERT_TRUE(client.is_open());
  21219. ASSERT_TRUE(client.send("Hello WebSocket"));
  21220. std::string msg;
  21221. EXPECT_EQ(ws::Text, client.read(msg));
  21222. EXPECT_EQ("Hello WebSocket", msg);
  21223. client.close();
  21224. }
  21225. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  21226. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21227. "/ws-echo");
  21228. ASSERT_TRUE(client.connect());
  21229. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  21230. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  21231. std::string msg;
  21232. EXPECT_EQ(ws::Binary, client.read(msg));
  21233. EXPECT_EQ(binary_data, msg);
  21234. client.close();
  21235. }
  21236. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  21237. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21238. "/ws-echo");
  21239. ASSERT_TRUE(client.connect());
  21240. for (int i = 0; i < 10; i++) {
  21241. auto text = "message " + std::to_string(i);
  21242. ASSERT_TRUE(client.send(text));
  21243. std::string msg;
  21244. ASSERT_TRUE(client.read(msg));
  21245. EXPECT_EQ(text, msg);
  21246. }
  21247. client.close();
  21248. }
  21249. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  21250. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21251. "/ws-close");
  21252. ASSERT_TRUE(client.connect());
  21253. // Send a message to trigger the server to close
  21254. ASSERT_TRUE(client.send("trigger close"));
  21255. // The server will close, so read should return false
  21256. std::string msg;
  21257. EXPECT_FALSE(client.read(msg));
  21258. EXPECT_FALSE(client.is_open());
  21259. }
  21260. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  21261. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21262. "/ws-echo");
  21263. ASSERT_TRUE(client.connect());
  21264. // 128KB message
  21265. std::string large_data(128 * 1024, 'X');
  21266. ASSERT_TRUE(client.send(large_data));
  21267. std::string msg;
  21268. ASSERT_TRUE(client.read(msg));
  21269. EXPECT_EQ(large_data, msg);
  21270. client.close();
  21271. }
  21272. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  21273. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21274. "/ws-echo");
  21275. ASSERT_TRUE(client.connect());
  21276. const int num_threads = 4;
  21277. std::vector<std::thread> threads;
  21278. std::atomic<int> send_count{0};
  21279. for (int t = 0; t < num_threads; t++) {
  21280. threads.emplace_back([&client, &send_count, t]() {
  21281. for (int i = 0; i < 5; i++) {
  21282. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  21283. if (client.send(text)) { send_count++; }
  21284. }
  21285. });
  21286. }
  21287. for (auto &th : threads) {
  21288. th.join();
  21289. }
  21290. int received = 0;
  21291. std::string msg;
  21292. while (received < send_count.load()) {
  21293. if (!client.read(msg)) { break; }
  21294. received++;
  21295. }
  21296. EXPECT_EQ(send_count.load(), received);
  21297. client.close();
  21298. }
  21299. TEST_F(WebSocketIntegrationTest, ReadString) {
  21300. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21301. "/ws-echo-string");
  21302. ASSERT_TRUE(client.connect());
  21303. ASSERT_TRUE(client.send("hello"));
  21304. std::string msg;
  21305. ASSERT_TRUE(client.read(msg));
  21306. EXPECT_EQ("echo: hello", msg);
  21307. ASSERT_TRUE(client.send("world"));
  21308. ASSERT_TRUE(client.read(msg));
  21309. EXPECT_EQ("echo: world", msg);
  21310. client.close();
  21311. }
  21312. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  21313. Headers headers = {{"X-Test-Header", "test-value"}};
  21314. ws::WebSocketClient client(
  21315. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  21316. ASSERT_TRUE(client.connect());
  21317. std::string msg;
  21318. ASSERT_TRUE(client.read(msg));
  21319. EXPECT_EQ("path:/ws-request-info", msg);
  21320. ASSERT_TRUE(client.read(msg));
  21321. EXPECT_EQ("header:test-value", msg);
  21322. client.close();
  21323. }
  21324. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  21325. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21326. "/ws-echo");
  21327. client.set_read_timeout(1, 0); // 1 second
  21328. ASSERT_TRUE(client.connect());
  21329. // Don't send anything — server echo handler waits for a message, so read()
  21330. // should time out. The connection survives it: nothing was consumed.
  21331. std::string msg;
  21332. EXPECT_EQ(client.read(msg), ws::Timeout);
  21333. EXPECT_TRUE(client.is_open());
  21334. // And it is still usable afterwards.
  21335. EXPECT_TRUE(client.send("after timeout"));
  21336. EXPECT_EQ(client.read(msg), ws::Text);
  21337. EXPECT_EQ(msg, "after timeout");
  21338. }
  21339. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  21340. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21341. "/ws-echo");
  21342. client.set_read_timeout(1, 0);
  21343. ASSERT_TRUE(client.connect());
  21344. ASSERT_TRUE(client.send("first"));
  21345. std::string msg;
  21346. ASSERT_EQ(client.read(msg), ws::Text);
  21347. ASSERT_EQ(msg, "first");
  21348. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  21349. // not be used with a read timeout: it would reprocess the previous message.
  21350. EXPECT_EQ(client.read(msg), ws::Timeout);
  21351. EXPECT_EQ(msg, "first");
  21352. }
  21353. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  21354. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21355. "/ws-echo");
  21356. ASSERT_TRUE(client.connect());
  21357. // Setting it once the connection is open reaches the live stream, not just
  21358. // the seed for the next connect().
  21359. client.set_read_timeout(1, 0);
  21360. std::string msg;
  21361. EXPECT_EQ(client.read(msg), ws::Timeout);
  21362. EXPECT_TRUE(client.is_open());
  21363. }
  21364. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  21365. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21366. "/ws-echo");
  21367. client.set_read_timeout(5, 0);
  21368. ASSERT_TRUE(client.connect());
  21369. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21370. // The server should reject it and close the connection.
  21371. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  21372. client.send(oversized);
  21373. // The server's read() should have failed due to payload limit,
  21374. // so our read() should return false (connection closed).
  21375. std::string msg;
  21376. EXPECT_FALSE(client.read(msg));
  21377. }
  21378. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  21379. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21380. "/ws-echo");
  21381. client.set_read_timeout(10, 0);
  21382. ASSERT_TRUE(client.connect());
  21383. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21384. // This should succeed.
  21385. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  21386. ASSERT_TRUE(client.send(at_limit));
  21387. std::string msg;
  21388. ASSERT_TRUE(client.read(msg));
  21389. EXPECT_EQ(at_limit.size(), msg.size());
  21390. client.close();
  21391. }
  21392. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  21393. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21394. "/nonexistent");
  21395. auto res = client.connect();
  21396. EXPECT_FALSE(res);
  21397. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21398. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  21399. EXPECT_FALSE(client.is_open());
  21400. }
  21401. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  21402. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21403. "/ws-echo");
  21404. ASSERT_TRUE(client.connect());
  21405. ASSERT_TRUE(client.send(""));
  21406. std::string msg;
  21407. EXPECT_EQ(ws::Text, client.read(msg));
  21408. EXPECT_EQ("", msg);
  21409. client.close();
  21410. }
  21411. TEST_F(WebSocketIntegrationTest, Reconnect) {
  21412. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21413. "/ws-echo");
  21414. // First connection
  21415. ASSERT_TRUE(client.connect());
  21416. ASSERT_TRUE(client.send("first"));
  21417. std::string msg;
  21418. ASSERT_TRUE(client.read(msg));
  21419. EXPECT_EQ("first", msg);
  21420. client.close();
  21421. EXPECT_FALSE(client.is_open());
  21422. // Reconnect using the same client object
  21423. ASSERT_TRUE(client.connect());
  21424. ASSERT_TRUE(client.is_open());
  21425. ASSERT_TRUE(client.send("second"));
  21426. ASSERT_TRUE(client.read(msg));
  21427. EXPECT_EQ("second", msg);
  21428. client.close();
  21429. }
  21430. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  21431. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21432. "/ws-close-status");
  21433. ASSERT_TRUE(client.connect());
  21434. // Trigger the server to close with GoingAway status
  21435. ASSERT_TRUE(client.send("trigger"));
  21436. // read() should return false after receiving the close frame
  21437. std::string msg;
  21438. EXPECT_FALSE(client.read(msg));
  21439. EXPECT_FALSE(client.is_open());
  21440. }
  21441. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  21442. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21443. "/ws-echo");
  21444. ASSERT_TRUE(client.connect());
  21445. client.close(ws::CloseStatus::GoingAway, "client leaving");
  21446. EXPECT_FALSE(client.is_open());
  21447. }
  21448. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  21449. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  21450. ws::WebSocketClient client(
  21451. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21452. ASSERT_TRUE(client.connect());
  21453. // Server should have selected graphql-ws
  21454. EXPECT_EQ("graphql-ws", client.subprotocol());
  21455. client.close();
  21456. }
  21457. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  21458. Headers headers;
  21459. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  21460. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  21461. ws::WebSocketClient client(
  21462. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21463. ASSERT_TRUE(client.connect());
  21464. // The offer on the second field line counts too, so graphql-ws is selected
  21465. EXPECT_EQ("graphql-ws", client.subprotocol());
  21466. client.close();
  21467. }
  21468. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  21469. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  21470. ws::WebSocketClient client(
  21471. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21472. ASSERT_TRUE(client.connect());
  21473. // Server should not have selected any subprotocol
  21474. EXPECT_TRUE(client.subprotocol().empty());
  21475. client.close();
  21476. }
  21477. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  21478. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21479. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21480. "/ws-subprotocol-unoffered",
  21481. headers);
  21482. ASSERT_TRUE(client.connect());
  21483. EXPECT_TRUE(client.subprotocol().empty());
  21484. client.close();
  21485. }
  21486. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  21487. // Connect without requesting any subprotocol
  21488. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21489. "/ws-subprotocol");
  21490. ASSERT_TRUE(client.connect());
  21491. EXPECT_TRUE(client.subprotocol().empty());
  21492. client.close();
  21493. }
  21494. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  21495. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21496. "/ws-echo");
  21497. client.set_tcp_nodelay(true);
  21498. client.set_connection_timeout(3, 0);
  21499. bool socket_options_called = false;
  21500. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  21501. ASSERT_TRUE(client.connect());
  21502. ASSERT_TRUE(client.is_open());
  21503. EXPECT_TRUE(socket_options_called);
  21504. ASSERT_TRUE(client.send("hello"));
  21505. std::string msg;
  21506. auto result = client.read(msg);
  21507. EXPECT_EQ(result, ws::ReadResult::Text);
  21508. EXPECT_EQ(msg, "hello");
  21509. client.close();
  21510. }
  21511. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  21512. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21513. "/ws-echo");
  21514. client.set_connection_timeout(std::chrono::seconds(3));
  21515. client.set_write_timeout(std::chrono::seconds(3));
  21516. // A sub-second remainder exercises the seconds/microseconds split.
  21517. client.set_read_timeout(std::chrono::milliseconds(1500));
  21518. ASSERT_TRUE(client.connect());
  21519. auto start = std::chrono::steady_clock::now();
  21520. std::string msg;
  21521. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  21522. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  21523. std::chrono::steady_clock::now() - start)
  21524. .count();
  21525. // Above 1s so that dropping the microseconds half of the split fails here.
  21526. // Ignoring the setter altogether would not reach this line at all: a client
  21527. // waits forever by default.
  21528. EXPECT_GE(elapsed, 1400);
  21529. EXPECT_LT(elapsed, 30000);
  21530. }
  21531. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  21532. Server svr;
  21533. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  21534. if (!req.has_header("Authorization")) {
  21535. res.status = StatusCode::Unauthorized_401;
  21536. res.set_content("Unauthorized", "text/plain");
  21537. return Server::HandlerResponse::Handled;
  21538. }
  21539. return Server::HandlerResponse::Unhandled;
  21540. });
  21541. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21542. std::string msg;
  21543. while (ws.read(msg)) {
  21544. ws.send(msg);
  21545. }
  21546. });
  21547. auto port = svr.bind_to_any_port("localhost");
  21548. std::thread t([&]() { svr.listen_after_bind(); });
  21549. svr.wait_until_ready();
  21550. // Without Authorization header - should be rejected before upgrade
  21551. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  21552. EXPECT_FALSE(client1.connect());
  21553. // The rejection is framed like any other HTTP response
  21554. {
  21555. Client cli("localhost", port);
  21556. Headers headers = {{"Upgrade", "websocket"},
  21557. {"Connection", "Upgrade"},
  21558. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21559. {"Sec-WebSocket-Version", "13"}};
  21560. auto res = cli.Get("/ws", headers);
  21561. ASSERT_TRUE(res);
  21562. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21563. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21564. EXPECT_EQ("Unauthorized", res->body);
  21565. }
  21566. // With Authorization header - should succeed
  21567. Headers headers = {{"Authorization", "Bearer token123"}};
  21568. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  21569. headers);
  21570. ASSERT_TRUE(client2.connect());
  21571. ASSERT_TRUE(client2.send("hello"));
  21572. std::string msg;
  21573. ASSERT_TRUE(client2.read(msg));
  21574. EXPECT_EQ("hello", msg);
  21575. client2.close();
  21576. svr.stop();
  21577. t.join();
  21578. }
  21579. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  21580. Server svr;
  21581. std::atomic<int> pre_request_calls{0};
  21582. std::atomic<bool> route_matched{false};
  21583. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  21584. pre_request_calls++;
  21585. if (req.matched_route == "/ws/:id") { route_matched = true; }
  21586. if (req.get_header_value("Authorization") != "Bearer token123") {
  21587. res.status = StatusCode::Unauthorized_401;
  21588. res.set_content("Unauthorized", "text/plain");
  21589. return Server::HandlerResponse::Handled;
  21590. }
  21591. return Server::HandlerResponse::Unhandled;
  21592. });
  21593. std::atomic<bool> handler_called{false};
  21594. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  21595. handler_called = true;
  21596. ws.send(req.matched_route + " " + req.path_params.at("id"));
  21597. });
  21598. auto port = svr.bind_to_any_port("localhost");
  21599. std::thread t([&]() { svr.listen_after_bind(); });
  21600. svr.wait_until_ready();
  21601. // Without Authorization header - should be rejected before upgrade
  21602. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  21603. "/ws/1");
  21604. EXPECT_FALSE(client1.connect());
  21605. EXPECT_FALSE(handler_called);
  21606. EXPECT_EQ(1, pre_request_calls);
  21607. EXPECT_TRUE(route_matched);
  21608. // The rejection is an ordinary HTTP response, not a protocol switch
  21609. {
  21610. Client cli("localhost", port);
  21611. Headers headers = {{"Upgrade", "websocket"},
  21612. {"Connection", "Upgrade"},
  21613. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21614. {"Sec-WebSocket-Version", "13"}};
  21615. auto res = cli.Get("/ws/1", headers);
  21616. ASSERT_TRUE(res);
  21617. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21618. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21619. EXPECT_EQ("Unauthorized", res->body);
  21620. }
  21621. EXPECT_FALSE(handler_called);
  21622. // With Authorization header - should succeed
  21623. Headers headers = {{"Authorization", "Bearer token123"}};
  21624. ws::WebSocketClient client2(
  21625. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  21626. ASSERT_TRUE(client2.connect());
  21627. std::string msg;
  21628. ASSERT_TRUE(client2.read(msg));
  21629. EXPECT_EQ("/ws/:id 2", msg);
  21630. EXPECT_TRUE(handler_called);
  21631. client2.close();
  21632. svr.stop();
  21633. t.join();
  21634. }
  21635. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  21636. Server svr;
  21637. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21638. // A read timeout is how a handler gets control back. Without it, a handler
  21639. // parked in read() can never write on the connection it is reading.
  21640. ws.set_read_timeout(std::chrono::milliseconds(100));
  21641. std::string msg;
  21642. while (ws.is_open()) {
  21643. auto r = ws.read(msg);
  21644. if (r == httplib::ws::Timeout) {
  21645. ws.send("tick");
  21646. continue;
  21647. }
  21648. if (r == httplib::ws::Fail) { break; }
  21649. ws.send(msg);
  21650. }
  21651. });
  21652. auto port = svr.bind_to_any_port("localhost");
  21653. std::thread t([&]() { svr.listen_after_bind(); });
  21654. svr.wait_until_ready();
  21655. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21656. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  21657. ASSERT_TRUE(client.connect());
  21658. // The client sends nothing, so anything it receives came out of the
  21659. // handler's timeout path.
  21660. std::string msg;
  21661. ASSERT_EQ(client.read(msg), ws::Text);
  21662. EXPECT_EQ("tick", msg);
  21663. client.close();
  21664. svr.stop();
  21665. t.join();
  21666. }
  21667. // Stream::read may return fewer bytes than asked for. This is that contract at
  21668. // its worst -- one byte per call -- which is what a frame header straddling a
  21669. // read buffer's boundary looks like to the frame parser.
  21670. class WsByteAtATimeStream : public Stream {
  21671. public:
  21672. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  21673. bool is_readable() const override { return true; }
  21674. bool wait_readable() const override { return true; }
  21675. bool wait_writable() const override { return true; }
  21676. ssize_t read(char *ptr, size_t size) override {
  21677. if (size == 0 || pos_ >= data_.size()) { return 0; }
  21678. *ptr = data_[pos_++];
  21679. return 1;
  21680. }
  21681. ssize_t write(const char *, size_t size) override {
  21682. return static_cast<ssize_t>(size);
  21683. }
  21684. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  21685. ip = "127.0.0.1";
  21686. port = 0;
  21687. }
  21688. void get_local_ip_and_port(std::string &ip, int &port) const override {
  21689. ip = "127.0.0.1";
  21690. port = 0;
  21691. }
  21692. socket_t socket() const override { return INVALID_SOCKET; }
  21693. time_t duration() const override { return 0; }
  21694. private:
  21695. std::string data_;
  21696. size_t pos_ = 0;
  21697. };
  21698. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  21699. // The payload uses the 16-bit extended length, so the header, the length
  21700. // and the mask key are all multi-byte fields here. Each used to be read
  21701. // with a single read() call, which fails as soon as one is split. The
  21702. // payload is also a little over one read chunk, so it is read in two.
  21703. std::string body;
  21704. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  21705. body += static_cast<char>(i % 251);
  21706. }
  21707. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  21708. std::string frame;
  21709. frame += static_cast<char>(0x81); // FIN + Text
  21710. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  21711. frame += static_cast<char>(body.size() >> 8);
  21712. frame += static_cast<char>(body.size() & 0xff);
  21713. for (size_t i = 0; i < 4; i++) {
  21714. frame += static_cast<char>(mask[i]);
  21715. }
  21716. for (size_t i = 0; i < body.size(); i++) {
  21717. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  21718. }
  21719. WsByteAtATimeStream strm(frame);
  21720. ws::Opcode opcode;
  21721. std::string payload;
  21722. bool fin = false;
  21723. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  21724. /*expect_masked=*/true, body.size()),
  21725. ws::impl::FrameRead::Ok);
  21726. EXPECT_TRUE(fin);
  21727. EXPECT_EQ(opcode, ws::Opcode::Text);
  21728. EXPECT_EQ(payload, body);
  21729. }
  21730. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  21731. std::string body(2000, 'x');
  21732. std::string frame;
  21733. frame += static_cast<char>(0x82); // FIN + Binary
  21734. frame += static_cast<char>(126); // 16-bit length follows
  21735. frame += static_cast<char>(body.size() >> 8);
  21736. frame += static_cast<char>(body.size() & 0xff);
  21737. frame += body;
  21738. detail::BufferStream strm;
  21739. strm.write(frame.data(), frame.size());
  21740. ws::Opcode opcode;
  21741. std::string payload;
  21742. bool fin;
  21743. EXPECT_EQ(
  21744. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  21745. ws::impl::FrameRead::Ok);
  21746. EXPECT_EQ(body, payload);
  21747. }
  21748. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  21749. // The header announces the largest payload allowed, and only 3 bytes of it
  21750. // ever arrive.
  21751. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  21752. std::string frame;
  21753. frame += static_cast<char>(0x82); // FIN + Binary
  21754. frame += static_cast<char>(127); // 64-bit length follows
  21755. for (int shift = 56; shift >= 0; shift -= 8) {
  21756. frame += static_cast<char>((len >> shift) & 0xff);
  21757. }
  21758. frame += "abc";
  21759. detail::BufferStream strm;
  21760. strm.write(frame.data(), frame.size());
  21761. ws::Opcode opcode;
  21762. std::string payload;
  21763. bool fin;
  21764. EXPECT_EQ(
  21765. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  21766. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  21767. ws::impl::FrameRead::Fail);
  21768. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  21769. }
  21770. TEST(WebSocketTest, QueryStringInHandshake) {
  21771. Server svr;
  21772. std::mutex mtx;
  21773. std::string received_target;
  21774. std::string received_token;
  21775. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21776. {
  21777. std::lock_guard<std::mutex> lock(mtx);
  21778. received_target = req.target;
  21779. if (req.has_param("token")) {
  21780. received_token = req.get_param_value("token");
  21781. }
  21782. }
  21783. std::string msg;
  21784. while (ws.read(msg)) {
  21785. ws.send(msg);
  21786. }
  21787. });
  21788. auto port = svr.bind_to_any_port("localhost");
  21789. std::thread t([&]() { svr.listen_after_bind(); });
  21790. svr.wait_until_ready();
  21791. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  21792. "/ws?token=ABC&session=123");
  21793. ASSERT_TRUE(client.connect());
  21794. // Round-trip ensures the handler has run and captured the request.
  21795. ASSERT_TRUE(client.send("hello"));
  21796. std::string msg;
  21797. ASSERT_TRUE(client.read(msg));
  21798. EXPECT_EQ("hello", msg);
  21799. client.close();
  21800. {
  21801. std::lock_guard<std::mutex> lock(mtx);
  21802. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  21803. EXPECT_EQ("ABC", received_token);
  21804. }
  21805. svr.stop();
  21806. t.join();
  21807. }
  21808. // Run a handshake against a throwaway server and hand the request the server
  21809. // received back to the caller, so tests can assert on the headers the client
  21810. // actually put on the wire.
  21811. static void capture_websocket_handshake_request(
  21812. const Headers &client_headers,
  21813. std::function<void(const Request &, int port)> verify) {
  21814. Server svr;
  21815. std::mutex mtx;
  21816. Request received;
  21817. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21818. {
  21819. std::lock_guard<std::mutex> lock(mtx);
  21820. received = req;
  21821. }
  21822. std::string msg;
  21823. while (ws.read(msg)) {
  21824. ws.send(msg);
  21825. }
  21826. });
  21827. auto port = svr.bind_to_any_port("localhost");
  21828. std::thread t([&]() { svr.listen_after_bind(); });
  21829. auto se = detail::scope_exit([&] {
  21830. svr.stop();
  21831. t.join();
  21832. });
  21833. svr.wait_until_ready();
  21834. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  21835. client_headers);
  21836. ASSERT_TRUE(client.connect());
  21837. ASSERT_TRUE(client.send("hello"));
  21838. std::string msg;
  21839. ASSERT_TRUE(client.read(msg));
  21840. client.close();
  21841. {
  21842. std::lock_guard<std::mutex> lock(mtx);
  21843. verify(received, port);
  21844. }
  21845. }
  21846. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  21847. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  21848. // Non-default port must be present in the Host header. Default ports
  21849. // (80/443) are omitted; that logic is covered by
  21850. // MakeHostAndPortStringTest.
  21851. EXPECT_EQ("localhost:" + std::to_string(port),
  21852. req.get_header_value("Host"));
  21853. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  21854. req.get_header_value("User-Agent"));
  21855. EXPECT_FALSE(req.has_header("Accept"));
  21856. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  21857. EXPECT_FALSE(req.has_header("Content-Length"));
  21858. });
  21859. }
  21860. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  21861. capture_websocket_handshake_request(
  21862. {{"Host", "example.com"},
  21863. {"User-Agent", "custom-agent"},
  21864. {"X-Custom", "value"}},
  21865. [](const Request &req, int) {
  21866. EXPECT_EQ("example.com", req.get_header_value("Host"));
  21867. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  21868. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  21869. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  21870. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  21871. });
  21872. }
  21873. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  21874. capture_websocket_handshake_request(
  21875. {{"Upgrade", "bogus"},
  21876. {"Connection", "close"},
  21877. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  21878. {"Sec-WebSocket-Version", "8"}},
  21879. [](const Request &req, int) {
  21880. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  21881. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  21882. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  21883. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  21884. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  21885. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  21886. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  21887. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  21888. req.get_header_value("Sec-WebSocket-Key"));
  21889. });
  21890. }
  21891. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  21892. // A header the client refuses to send must abort the handshake before any
  21893. // part of it reaches the wire; a lone request line would otherwise sit in
  21894. // the peer's buffer as a truncated request.
  21895. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21896. ASSERT_NE(INVALID_SOCKET, srv);
  21897. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  21898. sockaddr_in addr{};
  21899. addr.sin_family = AF_INET;
  21900. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  21901. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21902. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  21903. ASSERT_EQ(0, ::listen(srv, 1));
  21904. sockaddr_in bound{};
  21905. socklen_t bound_len = sizeof(bound);
  21906. ASSERT_EQ(
  21907. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  21908. auto port = ntohs(bound.sin_port);
  21909. ssize_t received = -1;
  21910. std::thread t([&] {
  21911. // Bound every blocking call so a regression fails the test with a bad
  21912. // value instead of hanging the suite.
  21913. fd_set rfds;
  21914. FD_ZERO(&rfds);
  21915. FD_SET(srv, &rfds);
  21916. timeval tv{5, 0};
  21917. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  21918. 0) {
  21919. return;
  21920. }
  21921. sockaddr_in cli_addr{};
  21922. socklen_t cli_len = sizeof(cli_addr);
  21923. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  21924. if (cli == INVALID_SOCKET) { return; }
  21925. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  21926. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21927. char buf[4096];
  21928. received = ::recv(cli, buf, sizeof(buf), 0);
  21929. });
  21930. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  21931. // connect() has already shut the socket down by the time it returns false,
  21932. // so the peer sees EOF without waiting for the client to be destroyed.
  21933. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  21934. {{"X-Bad", "a\r\nInjected: 1"}});
  21935. EXPECT_FALSE(client.connect());
  21936. t.join();
  21937. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  21938. EXPECT_EQ(0, received);
  21939. }
  21940. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  21941. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  21942. // contains "upgrade" as a substring is a different token and must not
  21943. // start a WebSocket handshake.
  21944. auto make_request = [](const std::vector<std::string> &connection_values) {
  21945. Request req;
  21946. req.method = "GET";
  21947. req.headers.emplace("Upgrade", "websocket");
  21948. for (const auto &value : connection_values) {
  21949. req.headers.emplace("Connection", value);
  21950. }
  21951. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21952. req.headers.emplace("Sec-WebSocket-Version", "13");
  21953. return req;
  21954. };
  21955. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  21956. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  21957. EXPECT_TRUE(
  21958. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  21959. EXPECT_TRUE(
  21960. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  21961. EXPECT_TRUE(
  21962. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  21963. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  21964. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  21965. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  21966. EXPECT_FALSE(
  21967. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  21968. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  21969. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21970. }
  21971. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  21972. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  21973. // asks recipients to match each protocol-name case-insensitively, and RFC
  21974. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  21975. // client naming websocket alongside another protocol, or on a second field
  21976. // line, is offering websocket; a value that merely contains "websocket" as a
  21977. // substring is a different protocol name and is not.
  21978. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  21979. Request req;
  21980. req.method = "GET";
  21981. for (const auto &value : upgrade_values) {
  21982. req.headers.emplace("Upgrade", value);
  21983. }
  21984. req.headers.emplace("Connection", "Upgrade");
  21985. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21986. req.headers.emplace("Sec-WebSocket-Version", "13");
  21987. return req;
  21988. };
  21989. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  21990. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  21991. EXPECT_TRUE(
  21992. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  21993. EXPECT_TRUE(
  21994. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  21995. EXPECT_TRUE(
  21996. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  21997. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  21998. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  21999. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  22000. EXPECT_FALSE(
  22001. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  22002. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  22003. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22004. }
  22005. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  22006. Server svr;
  22007. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  22008. auto port = svr.bind_to_any_port("localhost");
  22009. std::thread t([&]() { svr.listen_after_bind(); });
  22010. auto se = detail::scope_exit([&] {
  22011. svr.stop();
  22012. t.join();
  22013. });
  22014. svr.wait_until_ready();
  22015. Headers headers = {{"Upgrade", "websocket"},
  22016. {"Connection", "notupgrade"},
  22017. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22018. {"Sec-WebSocket-Version", "13"}};
  22019. Client cli("localhost", port);
  22020. auto res = cli.Get("/ws", headers);
  22021. // The route exists only as a WebSocket route, so a request that fails the
  22022. // handshake check falls through to ordinary routing.
  22023. ASSERT_TRUE(res);
  22024. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  22025. }
  22026. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  22027. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  22028. // Connection value is the only thing left for the client to reject.
  22029. Server svr;
  22030. svr.Get("/ws", [](const Request &req, Response &res) {
  22031. res.status = StatusCode::SwitchingProtocol_101;
  22032. res.set_header("Upgrade", "websocket");
  22033. res.set_header("Connection", "notupgrade");
  22034. res.set_header("Sec-WebSocket-Accept",
  22035. detail::websocket_accept_key(
  22036. req.get_header_value("Sec-WebSocket-Key")));
  22037. });
  22038. auto port = svr.bind_to_any_port("localhost");
  22039. std::thread t([&]() { svr.listen_after_bind(); });
  22040. auto se = detail::scope_exit([&] {
  22041. svr.stop();
  22042. t.join();
  22043. });
  22044. svr.wait_until_ready();
  22045. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22046. auto res = client.connect();
  22047. EXPECT_FALSE(res);
  22048. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22049. EXPECT_FALSE(client.is_open());
  22050. }
  22051. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  22052. Server svr;
  22053. svr.Get("/ws", [](const Request &req, Response &res) {
  22054. res.status = StatusCode::SwitchingProtocol_101;
  22055. res.set_header("Upgrade", "websocket");
  22056. res.set_header("Connection", "Upgrade");
  22057. res.set_header("Sec-WebSocket-Accept",
  22058. detail::websocket_accept_key(
  22059. req.get_header_value("Sec-WebSocket-Key")));
  22060. res.set_header("Sec-WebSocket-Protocol", "admin");
  22061. });
  22062. auto port = svr.bind_to_any_port("localhost");
  22063. std::thread t([&]() { svr.listen_after_bind(); });
  22064. auto se = detail::scope_exit([&] {
  22065. svr.stop();
  22066. t.join();
  22067. });
  22068. svr.wait_until_ready();
  22069. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  22070. // Server selects a subprotocol the client never offered
  22071. {
  22072. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22073. ws::WebSocketClient client(url, headers);
  22074. auto res = client.connect();
  22075. EXPECT_FALSE(res);
  22076. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22077. EXPECT_FALSE(client.is_open());
  22078. EXPECT_TRUE(client.subprotocol().empty());
  22079. }
  22080. // Client offered none but the server named one anyway
  22081. {
  22082. ws::WebSocketClient client(url);
  22083. auto res = client.connect();
  22084. EXPECT_FALSE(res);
  22085. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22086. EXPECT_FALSE(client.is_open());
  22087. EXPECT_TRUE(client.subprotocol().empty());
  22088. }
  22089. }
  22090. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  22091. // The socket path doubles as the URL host, so it must not contain '/'.
  22092. const char *shard = getenv("GTEST_SHARD_INDEX");
  22093. const std::string sock_path =
  22094. shard ? std::string("httplib-ws-") + shard + ".sock"
  22095. : std::string("httplib-ws.sock");
  22096. std::remove(sock_path.c_str());
  22097. Server svr;
  22098. std::mutex mtx;
  22099. std::string received_host;
  22100. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22101. {
  22102. std::lock_guard<std::mutex> lock(mtx);
  22103. received_host = req.get_header_value("Host");
  22104. }
  22105. std::string msg;
  22106. while (ws.read(msg)) {
  22107. ws.send(msg);
  22108. }
  22109. });
  22110. svr.set_address_family(AF_UNIX);
  22111. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  22112. auto se = detail::scope_exit([&] {
  22113. svr.stop();
  22114. t.join();
  22115. std::remove(sock_path.c_str());
  22116. });
  22117. svr.wait_until_ready();
  22118. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  22119. client.set_address_family(AF_UNIX);
  22120. ASSERT_TRUE(client.connect());
  22121. ASSERT_TRUE(client.send("hello"));
  22122. std::string msg;
  22123. ASSERT_TRUE(client.read(msg));
  22124. client.close();
  22125. {
  22126. std::lock_guard<std::mutex> lock(mtx);
  22127. // There is no host:port for a Unix socket, so the same "localhost"
  22128. // placeholder the HTTP client uses is expected.
  22129. EXPECT_EQ("localhost", received_host);
  22130. }
  22131. }
  22132. // Two threads must never parse WebSocket frames from the same stream.
  22133. // close() used to read the peer's Close reply with its own frame read, so it
  22134. // raced a reader thread that was in the middle of a payload: the payload loop
  22135. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  22136. // so bytes taken by close() were replaced with bytes from further along the
  22137. // stream. The message kept its length and silently changed content.
  22138. //
  22139. // The raw peer below sends a frame header plus part of the payload, waits for
  22140. // the handler to call close(), and only then sends the rest. Whichever thread
  22141. // would win the race for those bytes, the message must arrive intact, because
  22142. // close() must not touch the stream while read() owns it.
  22143. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  22144. #ifndef _WIN32
  22145. signal(SIGPIPE, SIG_IGN);
  22146. #endif
  22147. const size_t payload_len = 120; // fits the 7-bit length field
  22148. const size_t prefix_len = 8;
  22149. const int attempts = 8;
  22150. std::string expected(payload_len, '\0');
  22151. for (size_t i = 0; i < payload_len; i++) {
  22152. expected[i] = static_cast<char>('a' + i % 26);
  22153. }
  22154. std::atomic<bool> peer_stalled{false};
  22155. std::atomic<bool> handler_done{false};
  22156. std::mutex received_mutex;
  22157. std::vector<std::string> received;
  22158. // Bound every wait, so a regression fails the test instead of hanging the
  22159. // suite.
  22160. auto wait_for = [](const std::atomic<bool> &flag) {
  22161. for (int i = 0; i < 500 && !flag; i++) {
  22162. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22163. }
  22164. };
  22165. Server svr;
  22166. svr.set_websocket_ping_interval(0);
  22167. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22168. std::thread reader([&]() {
  22169. std::string msg;
  22170. while (ws.read(msg)) {
  22171. std::lock_guard<std::mutex> guard(received_mutex);
  22172. received.push_back(msg);
  22173. }
  22174. });
  22175. // Wait until the peer stalls mid-payload, so the reader thread is parked
  22176. // inside read_websocket_frame() when close() runs.
  22177. wait_for(peer_stalled);
  22178. ws.close();
  22179. reader.join();
  22180. handler_done = true;
  22181. });
  22182. auto port = svr.bind_to_any_port("127.0.0.1");
  22183. std::thread t([&]() { svr.listen_after_bind(); });
  22184. auto se = detail::scope_exit([&] {
  22185. svr.stop();
  22186. t.join();
  22187. });
  22188. svr.wait_until_ready();
  22189. auto send_bytes = [](socket_t s, const std::string &data) {
  22190. #ifdef _WIN32
  22191. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  22192. #else
  22193. auto n = ::send(s, data.data(), data.size(), 0);
  22194. #endif
  22195. return n == static_cast<decltype(n)>(data.size());
  22196. };
  22197. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  22198. // Every length used here fits the 7-bit length field.
  22199. auto masked_header = [](uint8_t first_byte, size_t len) {
  22200. std::string h;
  22201. h += static_cast<char>(first_byte);
  22202. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  22203. h.append(4, '\0'); // mask key
  22204. return h;
  22205. };
  22206. for (int attempt = 0; attempt < attempts; attempt++) {
  22207. peer_stalled = false;
  22208. handler_done = false;
  22209. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22210. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  22211. auto se_sock = detail::scope_exit([&] {
  22212. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  22213. });
  22214. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22215. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  22216. sockaddr_in addr{};
  22217. addr.sin_family = AF_INET;
  22218. addr.sin_port = htons(static_cast<uint16_t>(port));
  22219. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22220. ASSERT_EQ(
  22221. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  22222. << "attempt " << attempt;
  22223. ASSERT_TRUE(send_bytes(sock,
  22224. "GET /ws HTTP/1.1\r\n"
  22225. "Host: 127.0.0.1\r\n"
  22226. "Upgrade: websocket\r\n"
  22227. "Connection: Upgrade\r\n"
  22228. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22229. "Sec-WebSocket-Version: 13\r\n"
  22230. "\r\n"))
  22231. << "attempt " << attempt;
  22232. std::string response;
  22233. while (response.find("\r\n\r\n") == std::string::npos) {
  22234. char buf[512];
  22235. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  22236. if (n <= 0) { break; }
  22237. response.append(buf, static_cast<size_t>(n));
  22238. }
  22239. ASSERT_NE(std::string::npos, response.find(" 101 "))
  22240. << "attempt " << attempt;
  22241. // Send the header of a Binary message but only the first prefix_len bytes
  22242. // of its payload, leaving the reader thread stalled inside the payload.
  22243. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  22244. expected.substr(0, prefix_len)))
  22245. << "attempt " << attempt;
  22246. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22247. peer_stalled = true;
  22248. // Let close() send its Close frame and park in its own read before the
  22249. // rest of the payload arrives, so both threads are waiting for it.
  22250. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22251. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  22252. close_frame += static_cast<char>(0x03); // status 1000
  22253. close_frame += static_cast<char>(0xE8);
  22254. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  22255. << "attempt " << attempt;
  22256. // Closing the peer releases the reader thread even on the buggy path,
  22257. // where it waits for bytes another thread already consumed.
  22258. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22259. detail::close_socket(sock);
  22260. sock = INVALID_SOCKET;
  22261. wait_for(handler_done);
  22262. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  22263. }
  22264. std::lock_guard<std::mutex> guard(received_mutex);
  22265. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  22266. << "a message in flight when close() ran was dropped";
  22267. for (size_t i = 0; i < received.size(); i++) {
  22268. EXPECT_EQ(expected, received[i]) << "message " << i;
  22269. }
  22270. }
  22271. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  22272. std::atomic<bool> done{false};
  22273. std::string received;
  22274. Server svr;
  22275. svr.set_websocket_ping_interval(0);
  22276. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22277. std::string msg;
  22278. if (ws.read(msg) == ws::Binary) { received = msg; }
  22279. done = true;
  22280. });
  22281. auto port = svr.bind_to_any_port("127.0.0.1");
  22282. std::thread t([&]() { svr.listen_after_bind(); });
  22283. auto se = detail::scope_exit([&] {
  22284. svr.stop();
  22285. t.join();
  22286. });
  22287. svr.wait_until_ready();
  22288. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22289. ASSERT_NE(INVALID_SOCKET, sock);
  22290. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  22291. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22292. sockaddr_in addr{};
  22293. addr.sin_family = AF_INET;
  22294. addr.sin_port = htons(static_cast<uint16_t>(port));
  22295. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22296. ASSERT_EQ(0,
  22297. ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  22298. // Frames with an all-zero mask key, so the payload goes out verbatim.
  22299. auto frame = [](uint8_t first_byte, const std::string &payload) {
  22300. std::string f;
  22301. f += static_cast<char>(first_byte);
  22302. f += static_cast<char>(0x80 | payload.size());
  22303. f.append(4, '\0');
  22304. return f + payload;
  22305. };
  22306. std::string data = "GET /ws HTTP/1.1\r\n"
  22307. "Host: 127.0.0.1\r\n"
  22308. "Upgrade: websocket\r\n"
  22309. "Connection: Upgrade\r\n"
  22310. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22311. "Sec-WebSocket-Version: 13\r\n"
  22312. "\r\n";
  22313. data += frame(0x02, "Hel"); // Binary, more to come
  22314. data += frame(0x89, "p"); // FIN + Ping
  22315. data += frame(0x80, "lo"); // FIN + Continuation
  22316. #ifdef _WIN32
  22317. ::send(sock, data.data(), static_cast<int>(data.size()), 0);
  22318. #else
  22319. ::send(sock, data.data(), data.size(), 0);
  22320. #endif
  22321. for (int i = 0; i < 500 && !done; i++) {
  22322. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22323. }
  22324. ASSERT_TRUE(done);
  22325. EXPECT_EQ("Hello", received);
  22326. }
  22327. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22328. class WebSocketSSLIntegrationTest : public ::testing::Test {
  22329. protected:
  22330. void SetUp() override {
  22331. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  22332. SERVER_PRIVATE_KEY_FILE);
  22333. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22334. std::string msg;
  22335. ws::ReadResult ret;
  22336. while ((ret = ws.read(msg))) {
  22337. if (ret == ws::Binary) {
  22338. ws.send(msg.data(), msg.size());
  22339. } else {
  22340. ws.send(msg);
  22341. }
  22342. }
  22343. });
  22344. port_ = server_->bind_to_any_port(HOST);
  22345. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22346. server_->wait_until_ready();
  22347. }
  22348. void TearDown() override {
  22349. server_->stop();
  22350. if (server_thread_.joinable()) { server_thread_.join(); }
  22351. }
  22352. std::unique_ptr<SSLServer> server_;
  22353. std::thread server_thread_;
  22354. int port_ = 0;
  22355. };
  22356. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  22357. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22358. "/ws-echo");
  22359. client.enable_server_certificate_verification(false);
  22360. ASSERT_TRUE(client.connect());
  22361. ASSERT_TRUE(client.is_open());
  22362. ASSERT_TRUE(client.send("Hello WSS"));
  22363. std::string msg;
  22364. EXPECT_EQ(ws::Text, client.read(msg));
  22365. EXPECT_EQ("Hello WSS", msg);
  22366. client.close();
  22367. }
  22368. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  22369. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  22370. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  22371. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  22372. // client (without calling close() first) is the only path that runs
  22373. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  22374. // bug exactly.
  22375. //
  22376. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  22377. // when linked against an instrumented libssl; run under Valgrind to catch it
  22378. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  22379. // suite (the freed session otherwise stalls on the close handshake) — this test
  22380. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  22381. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  22382. {
  22383. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22384. "/ws-echo");
  22385. client.enable_server_certificate_verification(false);
  22386. client.set_read_timeout(2, 0);
  22387. client.set_write_timeout(2, 0);
  22388. ASSERT_TRUE(client.connect());
  22389. ASSERT_TRUE(client.is_open());
  22390. ASSERT_TRUE(client.send("still open"));
  22391. // Intentionally do NOT call client.close(): leaving scope runs
  22392. // shutdown_and_close() with the WebSocket still open, which must send the
  22393. // close frame while the TLS session is still alive.
  22394. }
  22395. }
  22396. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  22397. // shutdown_and_close() at the start of connect(), reproducing the same
  22398. // use-after-free within the test body rather than at scope exit. The second
  22399. // connect must succeed and echo, proving the close handshake ran over a live
  22400. // session. See the note above about memory-tool requirements.
  22401. TEST_F(WebSocketSSLIntegrationTest,
  22402. ReconnectWhileOpenSendsCloseOverLiveSession) {
  22403. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22404. "/ws-echo");
  22405. client.enable_server_certificate_verification(false);
  22406. client.set_read_timeout(2, 0);
  22407. client.set_write_timeout(2, 0);
  22408. ASSERT_TRUE(client.connect());
  22409. ASSERT_TRUE(client.is_open());
  22410. ASSERT_TRUE(client.send("still open"));
  22411. // Reconnect without closing first: connect() calls shutdown_and_close() on
  22412. // the still-open connection, which must not touch a freed TLS session.
  22413. ASSERT_TRUE(client.connect());
  22414. ASSERT_TRUE(client.is_open());
  22415. ASSERT_TRUE(client.send("after reconnect"));
  22416. std::string msg;
  22417. EXPECT_EQ(ws::Text, client.read(msg));
  22418. EXPECT_EQ("after reconnect", msg);
  22419. client.close();
  22420. }
  22421. #endif
  22422. #ifdef CPPHTTPLIB_SSL_ENABLED
  22423. class WebSocketSSLCATest : public ::testing::Test {
  22424. protected:
  22425. void SetUp() override {
  22426. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  22427. SERVER_PRIVATE_KEY_FILE);
  22428. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22429. std::string msg;
  22430. while (ws.read(msg)) {
  22431. ws.send(msg);
  22432. }
  22433. });
  22434. port_ = server_->bind_to_any_port("127.0.0.1");
  22435. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22436. server_->wait_until_ready();
  22437. }
  22438. void TearDown() override {
  22439. server_->stop();
  22440. if (server_thread_.joinable()) { server_thread_.join(); }
  22441. }
  22442. std::string url() const {
  22443. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  22444. }
  22445. std::unique_ptr<SSLServer> server_;
  22446. std::thread server_thread_;
  22447. int port_ = 0;
  22448. };
  22449. // A custom CA loaded as PEM verifies the server with full certificate
  22450. // verification enabled
  22451. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  22452. ws::WebSocketClient client(url());
  22453. std::string cert;
  22454. read_file(SERVER_CERT2_FILE, cert);
  22455. client.load_ca_cert_store(cert.c_str(), cert.size());
  22456. ASSERT_TRUE(client.connect());
  22457. ASSERT_TRUE(client.send("hello"));
  22458. std::string msg;
  22459. EXPECT_EQ(ws::Text, client.read(msg));
  22460. EXPECT_EQ("hello", msg);
  22461. client.close();
  22462. }
  22463. // A custom CA that does not cover the server must fail verification (the
  22464. // custom CA is exclusive; system certs are not loaded alongside it)
  22465. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  22466. ws::WebSocketClient client(url());
  22467. std::string cert;
  22468. read_file(CLIENT_CA_CERT_FILE, cert);
  22469. client.load_ca_cert_store(cert.c_str(), cert.size());
  22470. auto res = client.connect();
  22471. ASSERT_FALSE(res);
  22472. EXPECT_EQ(Error::SSLServerVerification, res.error());
  22473. EXPECT_EQ(-1, res.status());
  22474. EXPECT_NE(0u, res.ssl_backend_error());
  22475. }
  22476. // The same CA as a file path rather than PEM in memory
  22477. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  22478. ws::WebSocketClient client(url());
  22479. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22480. ASSERT_TRUE(client.connect());
  22481. ASSERT_TRUE(client.send("hello"));
  22482. std::string msg;
  22483. EXPECT_EQ(ws::Text, client.read(msg));
  22484. EXPECT_EQ("hello", msg);
  22485. client.close();
  22486. }
  22487. // ...and a CA file that does not cover the server still fails, so it is the
  22488. // path above that decides the outcome
  22489. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  22490. ws::WebSocketClient client(url());
  22491. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22492. ASSERT_FALSE(client.connect());
  22493. }
  22494. // Regression test: reconnecting with a native custom CA store used to reuse
  22495. // a store handle the previous TLS context had already freed (use-after-free
  22496. // under the OpenSSL backend). The context now lives as long as the client.
  22497. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  22498. ws::WebSocketClient client(url());
  22499. std::string cert;
  22500. read_file(SERVER_CERT2_FILE, cert);
  22501. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  22502. ASSERT_TRUE(client.connect());
  22503. client.close();
  22504. ASSERT_TRUE(client.connect());
  22505. ASSERT_TRUE(client.send("again"));
  22506. std::string msg;
  22507. EXPECT_EQ(ws::Text, client.read(msg));
  22508. EXPECT_EQ("again", msg);
  22509. client.close();
  22510. }
  22511. // Regression test: a certificate with a trusted chain but no identity match
  22512. // for the server IP must be rejected. The Mbed TLS backend used to skip
  22513. // verification entirely for IP hosts, so this connection succeeded there.
  22514. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  22515. // chain verification while the identity check must still fail.
  22516. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  22517. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22518. ASSERT_TRUE(svr.is_valid());
  22519. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22520. std::string msg;
  22521. while (ws.read(msg)) {
  22522. ws.send(msg);
  22523. }
  22524. });
  22525. auto port = svr.bind_to_any_port("127.0.0.1");
  22526. auto t = std::thread([&]() { svr.listen_after_bind(); });
  22527. auto se = detail::scope_exit([&] {
  22528. svr.stop();
  22529. t.join();
  22530. });
  22531. svr.wait_until_ready();
  22532. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  22533. "/echo");
  22534. std::string cert;
  22535. read_file(SERVER_CERT_FILE, cert);
  22536. client.load_ca_cert_store(cert.c_str(), cert.size());
  22537. ASSERT_FALSE(client.connect());
  22538. }
  22539. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  22540. // SNI, so nothing binds the host name to the TLS session. These bind the
  22541. // server to "localhost" instead, the only shape that exercises the SNI and
  22542. // hostname-verification path with certificate verification left enabled.
  22543. class WebSocketSSLDnsHostTest : public ::testing::Test {
  22544. protected:
  22545. void Start(const char *cert_file) {
  22546. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  22547. SERVER_PRIVATE_KEY_FILE);
  22548. ASSERT_TRUE(server_->is_valid());
  22549. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22550. std::string msg;
  22551. while (ws.read(msg)) {
  22552. ws.send(msg);
  22553. }
  22554. });
  22555. port_ = server_->bind_to_any_port("localhost");
  22556. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22557. server_->wait_until_ready();
  22558. }
  22559. void TearDown() override {
  22560. if (server_) { server_->stop(); }
  22561. if (server_thread_.joinable()) { server_thread_.join(); }
  22562. }
  22563. std::string url() const {
  22564. return "wss://localhost:" + std::to_string(port_) + "/echo";
  22565. }
  22566. std::unique_ptr<SSLServer> server_;
  22567. std::thread server_thread_;
  22568. int port_ = 0;
  22569. };
  22570. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  22571. // out and the connection is usable
  22572. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  22573. Start(SERVER_CERT2_FILE);
  22574. ws::WebSocketClient client(url());
  22575. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22576. ASSERT_TRUE(client.connect());
  22577. ASSERT_TRUE(client.send("hello"));
  22578. std::string msg;
  22579. EXPECT_EQ(ws::Text, client.read(msg));
  22580. EXPECT_EQ("hello", msg);
  22581. client.close();
  22582. }
  22583. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  22584. // while the identity check must still reject "localhost"
  22585. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  22586. Start(SERVER_CERT_FILE);
  22587. ws::WebSocketClient client(url());
  22588. client.set_ca_cert_path(SERVER_CERT_FILE);
  22589. auto res = client.connect();
  22590. ASSERT_FALSE(res);
  22591. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  22592. EXPECT_EQ(-1, res.status());
  22593. }
  22594. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  22595. // disabled: the chain is still checked, only the identity check is skipped
  22596. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  22597. Start(SERVER_CERT_FILE);
  22598. ws::WebSocketClient client(url());
  22599. client.set_ca_cert_path(SERVER_CERT_FILE);
  22600. client.enable_server_hostname_verification(false);
  22601. ASSERT_TRUE(client.connect());
  22602. ASSERT_TRUE(client.send("hello"));
  22603. std::string msg;
  22604. EXPECT_EQ(ws::Text, client.read(msg));
  22605. EXPECT_EQ("hello", msg);
  22606. client.close();
  22607. }
  22608. // A CA that did not sign the server certificate fails the chain, even though
  22609. // the name would match
  22610. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  22611. Start(SERVER_CERT2_FILE);
  22612. ws::WebSocketClient client(url());
  22613. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22614. ASSERT_FALSE(client.connect());
  22615. }
  22616. // With verification disabled, neither the chain nor the name is checked
  22617. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  22618. Start(SERVER_CERT_FILE);
  22619. ws::WebSocketClient client(url());
  22620. client.enable_server_certificate_verification(false);
  22621. ASSERT_TRUE(client.connect());
  22622. ASSERT_TRUE(client.send("hello"));
  22623. std::string msg;
  22624. EXPECT_EQ(ws::Text, client.read(msg));
  22625. EXPECT_EQ("hello", msg);
  22626. client.close();
  22627. }
  22628. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  22629. protected:
  22630. void SetUp() override {
  22631. server_ = httplib::detail::make_unique<SSLServer>(
  22632. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22633. ASSERT_TRUE(server_->is_valid());
  22634. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22635. std::string msg;
  22636. while (ws.read(msg)) {
  22637. ws.send(msg);
  22638. }
  22639. });
  22640. port_ = server_->bind_to_any_port("localhost");
  22641. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22642. server_->wait_until_ready();
  22643. }
  22644. void TearDown() override {
  22645. server_->stop();
  22646. if (server_thread_.joinable()) { server_thread_.join(); }
  22647. }
  22648. std::string url() const {
  22649. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  22650. }
  22651. void ConnectWithClientCert(const std::string &client_cert_file,
  22652. const std::string &client_private_key_file,
  22653. const char *private_key_password) {
  22654. std::string cert_pem, key_pem;
  22655. read_file(client_cert_file, cert_pem);
  22656. read_file(client_private_key_file, key_pem);
  22657. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  22658. key_pem.c_str(), key_pem.size(),
  22659. private_key_password};
  22660. ws::WebSocketClient client(url(), pem);
  22661. ASSERT_TRUE(client.is_valid());
  22662. client.enable_server_certificate_verification(false);
  22663. ASSERT_TRUE(client.connect());
  22664. ASSERT_TRUE(client.send("hello"));
  22665. std::string msg;
  22666. EXPECT_EQ(ws::Text, client.read(msg));
  22667. EXPECT_EQ("hello", msg);
  22668. client.close();
  22669. }
  22670. std::unique_ptr<SSLServer> server_;
  22671. std::thread server_thread_;
  22672. int port_ = 0;
  22673. };
  22674. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  22675. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  22676. }
  22677. // Control for the tests above: the fixture's server really does require a
  22678. // client certificate, so it is the PEM the constructor installed that decides
  22679. // the outcome.
  22680. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  22681. ws::WebSocketClient client(url());
  22682. ASSERT_TRUE(client.is_valid());
  22683. client.enable_server_certificate_verification(false);
  22684. EXPECT_FALSE(client.connect());
  22685. }
  22686. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  22687. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  22688. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  22689. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  22690. }
  22691. #endif
  22692. #if !defined(_WIN32)
  22693. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  22694. auto secret_dir = std::string("./symlink_test_secret");
  22695. auto served_dir = std::string("./symlink_test_served");
  22696. auto secret_file = secret_dir + "/secret.txt";
  22697. auto symlink_path = served_dir + "/escape";
  22698. // Setup: create directories and files
  22699. mkdir(secret_dir.c_str(), 0755);
  22700. mkdir(served_dir.c_str(), 0755);
  22701. {
  22702. std::ofstream ofs(secret_file);
  22703. ofs << "SECRET_DATA";
  22704. }
  22705. // Create symlink using absolute path so it resolves correctly
  22706. #ifdef PATH_MAX
  22707. char abs_secret[PATH_MAX];
  22708. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  22709. #else
  22710. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  22711. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  22712. ASSERT_NE(nullptr, abs_secret);
  22713. #endif
  22714. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  22715. auto se = detail::scope_exit([&] {
  22716. unlink(symlink_path.c_str());
  22717. unlink(secret_file.c_str());
  22718. rmdir(served_dir.c_str());
  22719. rmdir(secret_dir.c_str());
  22720. });
  22721. Server svr;
  22722. svr.set_mount_point("/", served_dir);
  22723. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  22724. auto se2 = detail::scope_exit([&] {
  22725. svr.stop();
  22726. listen_thread.join();
  22727. });
  22728. svr.wait_until_ready();
  22729. Client cli("localhost", PORT);
  22730. // Symlink pointing outside base dir should be blocked
  22731. auto res = cli.Get("/escape/secret.txt");
  22732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22733. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  22734. }
  22735. #endif
  22736. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  22737. // "GET /smuggled" request), reads the first response, and only then sends the
  22738. // embedded request as the body. Returns how many times /smuggled ran.
  22739. //
  22740. // The body is sent AFTER receiving the first response (as in the original
  22741. // PoC) so that the stream_line_reader cannot buffer it together with the
  22742. // headers of the first request.
  22743. static int count_smuggled_requests(const std::string &outer_head,
  22744. std::string &first_response) {
  22745. Server svr;
  22746. svr.set_mount_point("/", "./www");
  22747. std::atomic<int> smuggled_count(0);
  22748. svr.Get("/smuggled", [&](const Request &, Response &res) {
  22749. smuggled_count++;
  22750. res.set_content("oops", "text/plain");
  22751. });
  22752. svr.Post("/post", [&](const Request &req, Response &res) {
  22753. res.set_content(req.body, "text/plain");
  22754. });
  22755. auto port = svr.bind_to_any_port("localhost");
  22756. thread t = thread([&] { svr.listen_after_bind(); });
  22757. auto se = detail::scope_exit([&] {
  22758. svr.stop();
  22759. t.join();
  22760. });
  22761. svr.wait_until_ready();
  22762. auto error = Error::Success;
  22763. auto sock = detail::create_client_socket(
  22764. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  22765. /*connection_timeout_sec=*/2, 0,
  22766. /*read_timeout_sec=*/2, 0,
  22767. /*write_timeout_sec=*/2, 0, std::string(), error);
  22768. EXPECT_NE(INVALID_SOCKET, sock);
  22769. if (sock == INVALID_SOCKET) { return -1; }
  22770. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22771. // The "smuggled" request will be sent as the body of the outer request
  22772. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  22773. "Host: localhost\r\n"
  22774. "Connection: close\r\n"
  22775. "\r\n";
  22776. auto head = outer_head;
  22777. auto len = std::to_string(smuggled.size());
  22778. for (auto pos = head.find("{len}"); pos != std::string::npos;
  22779. pos = head.find("{len}", pos + len.size())) {
  22780. head.replace(pos, 5, len);
  22781. }
  22782. // Step 1: Send only the outer request headers (no body yet)
  22783. auto sent = send(sock, head.data(), head.size(), 0);
  22784. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  22785. // Step 2: Read the first response
  22786. char buf[4096];
  22787. for (;;) {
  22788. auto n = recv(sock, buf, sizeof(buf), 0);
  22789. if (n <= 0) break;
  22790. first_response.append(buf, static_cast<size_t>(n));
  22791. // Stop once we have a complete response (headers + body)
  22792. auto hdr_end = first_response.find("\r\n\r\n");
  22793. if (hdr_end != std::string::npos) {
  22794. // Check for Content-Length to know when the body is complete
  22795. auto cl_pos = first_response.find("Content-Length:");
  22796. if (cl_pos != std::string::npos) {
  22797. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  22798. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  22799. auto cl = std::stoul(
  22800. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  22801. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  22802. } else {
  22803. break; // No Content-Length, assume headers-only response
  22804. }
  22805. }
  22806. }
  22807. // Step 3: Now send the body, which looks like a new HTTP request. On a
  22808. // vulnerable server the keep-alive loop reads this as a second request. The
  22809. // server may already have closed the connection, so the result is ignored.
  22810. send(sock, smuggled.data(), smuggled.size(), 0);
  22811. // Half-close so that a server which drained the body sees EOF and closes,
  22812. // instead of the read below waiting for the read timeout.
  22813. #ifdef _WIN32
  22814. ::shutdown(sock, SD_SEND);
  22815. #else
  22816. ::shutdown(sock, SHUT_WR);
  22817. #endif
  22818. // Step 4: Read until the server closes the connection
  22819. for (;;) {
  22820. auto n = recv(sock, buf, sizeof(buf), 0);
  22821. if (n <= 0) break;
  22822. }
  22823. return smuggled_count.load();
  22824. }
  22825. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  22826. // A GET request with Content-Length to a static file handler must have its
  22827. // body drained before the keep-alive connection is reused. Otherwise the
  22828. // unread body bytes are interpreted as the next HTTP request.
  22829. std::string first_response;
  22830. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22831. "Host: localhost\r\n"
  22832. "Content-Length: {len}\r\n"
  22833. "\r\n",
  22834. first_response));
  22835. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  22836. }
  22837. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  22838. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  22839. // be answered with 400 and the connection closed. Treating it as "no body"
  22840. // leaves the body to be parsed as the next request.
  22841. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  22842. const char *targets[] = {
  22843. "GET /file", // handler that never reads the body
  22844. "GET /not-found", // no handler matches (404)
  22845. "POST /post", // handler that reads the body
  22846. };
  22847. for (auto target : targets) {
  22848. for (auto value : values) {
  22849. std::string first_response;
  22850. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  22851. " HTTP/1.1\r\n"
  22852. "Host: localhost\r\n"
  22853. "Content-Length: " +
  22854. value + "\r\n\r\n",
  22855. first_response))
  22856. << target << " with Content-Length: " << value;
  22857. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  22858. << target << " with Content-Length: " << value;
  22859. }
  22860. }
  22861. }
  22862. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  22863. // A 400 for an unparseable request line leaves the rest of the message
  22864. // unread, so the connection must be closed rather than reused.
  22865. std::string first_response;
  22866. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  22867. "Host: localhost\r\n"
  22868. "Content-Length: {len}\r\n"
  22869. "\r\n",
  22870. first_response));
  22871. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22872. }
  22873. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  22874. // Same as above for a header block that fails to parse.
  22875. std::string first_response;
  22876. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22877. "Host: localhost\r\n"
  22878. "Bad Header\r\n"
  22879. "Content-Length: {len}\r\n"
  22880. "\r\n",
  22881. first_response));
  22882. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22883. }
  22884. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  22885. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  22886. // server must not read another request on that connection, even when the
  22887. // request had no body to drain.
  22888. std::string first_response;
  22889. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  22890. "Host: localhost\r\n"
  22891. "\r\n",
  22892. first_response));
  22893. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  22894. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  22895. }
  22896. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  22897. // A content reader that stops early leaves the stream inside the body.
  22898. // Draining the whole Content-Length from there, or reading the body again,
  22899. // reads into the next request, and whatever follows is parsed as a request
  22900. // of its own.
  22901. Server svr;
  22902. std::atomic<int> smuggled_count(0);
  22903. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  22904. svr.Post("/upload", [](const Request &req, Response &res,
  22905. const ContentReader &content_reader) {
  22906. // Stop at the last chunk, so the whole body has been read however it
  22907. // arrives.
  22908. auto length = req.get_header_value_u64("Content-Length");
  22909. size_t total = 0;
  22910. auto consumed = content_reader([&](const char *, size_t n) {
  22911. total += n;
  22912. return total < length;
  22913. });
  22914. EXPECT_FALSE(consumed);
  22915. if (req.has_param("retry")) {
  22916. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  22917. }
  22918. // Replace the 400 the aborted read set, which would close the connection.
  22919. res.set_redirect("/done");
  22920. });
  22921. auto port = svr.bind_to_any_port(HOST);
  22922. thread t = thread([&] { svr.listen_after_bind(); });
  22923. auto se = detail::scope_exit([&] {
  22924. svr.stop();
  22925. t.join();
  22926. });
  22927. svr.wait_until_ready();
  22928. // A front end sees the second request as a POST whose body is the GET. The
  22929. // first body is as long as the POST's headers, so draining it again reads
  22930. // exactly those and leaves the GET to be parsed next.
  22931. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  22932. "Host: localhost\r\n"
  22933. "\r\n";
  22934. std::string second_head = "POST /post HTTP/1.1\r\n"
  22935. "Host: localhost\r\n"
  22936. "Content-Length: " +
  22937. std::to_string(inner.size()) +
  22938. "\r\n"
  22939. "\r\n";
  22940. for (auto target : {"/upload", "/upload?retry"}) {
  22941. smuggled_count = 0;
  22942. std::string request = "POST " + std::string(target) +
  22943. " HTTP/1.1\r\n"
  22944. "Host: localhost\r\n"
  22945. "Content-Length: " +
  22946. std::to_string(second_head.size()) +
  22947. "\r\n"
  22948. "\r\n" +
  22949. std::string(second_head.size(), 'A') + second_head +
  22950. inner;
  22951. std::string response;
  22952. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  22953. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  22954. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  22955. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  22956. EXPECT_EQ(0, smuggled_count.load()) << target;
  22957. }
  22958. }
  22959. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  22960. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  22961. // must be rejected with 400 Bad Request.
  22962. Server svr;
  22963. svr.Post("/test", [&](const Request &, Response &res) {
  22964. res.set_content("ok", "text/plain");
  22965. });
  22966. thread t = thread([&] { svr.listen(HOST, PORT); });
  22967. auto se = detail::scope_exit([&] {
  22968. svr.stop();
  22969. t.join();
  22970. ASSERT_FALSE(svr.is_running());
  22971. });
  22972. svr.wait_until_ready();
  22973. // Exact "chunked"
  22974. {
  22975. auto req = "POST /test HTTP/1.1\r\n"
  22976. "Host: localhost\r\n"
  22977. "Content-Length: 5\r\n"
  22978. "Transfer-Encoding: chunked\r\n"
  22979. "Connection: close\r\n"
  22980. "\r\n"
  22981. "hello";
  22982. std::string response;
  22983. ASSERT_TRUE(send_request(1, req, &response));
  22984. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22985. response.substr(0, response.find("\r\n")));
  22986. }
  22987. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  22988. {
  22989. auto req = "POST /test HTTP/1.1\r\n"
  22990. "Host: localhost\r\n"
  22991. "Content-Length: 5\r\n"
  22992. "Transfer-Encoding: gzip, chunked\r\n"
  22993. "Connection: close\r\n"
  22994. "\r\n"
  22995. "hello";
  22996. std::string response;
  22997. ASSERT_TRUE(send_request(1, req, &response));
  22998. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22999. response.substr(0, response.find("\r\n")));
  23000. }
  23001. }
  23002. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  23003. Server svr;
  23004. svr.Post("/test", [&](const Request &, Response &res) {
  23005. res.set_content("ok", "text/plain");
  23006. });
  23007. thread t = thread([&] { svr.listen(HOST, PORT); });
  23008. auto se = detail::scope_exit([&] {
  23009. svr.stop();
  23010. t.join();
  23011. ASSERT_FALSE(svr.is_running());
  23012. });
  23013. svr.wait_until_ready();
  23014. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  23015. // length cannot be determined, so the server must answer 400 and close
  23016. // rather than treat the request as bodyless and leave the body in the
  23017. // socket for the next request to pick up.
  23018. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  23019. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  23020. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  23021. std::string response;
  23022. ASSERT_TRUE(send_request(1, req, &response));
  23023. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23024. response.substr(0, response.find("\r\n")))
  23025. << transfer_encoding;
  23026. }
  23027. // RFC 9110 5.3: the codings may also be split across several
  23028. // Transfer-Encoding lines, which combine in the order they were received.
  23029. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  23030. // just like the single-line "chunked, gzip" above.
  23031. {
  23032. auto req = "POST /test HTTP/1.1\r\n"
  23033. "Host: localhost\r\n"
  23034. "Transfer-Encoding: chunked\r\n"
  23035. "Transfer-Encoding: gzip\r\n"
  23036. "\r\n"
  23037. "0\r\n\r\n";
  23038. std::string response;
  23039. ASSERT_TRUE(send_request(1, req, &response));
  23040. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23041. response.substr(0, response.find("\r\n")));
  23042. }
  23043. // A sequence ending in chunked stays valid.
  23044. auto req = "POST /test HTTP/1.1\r\n"
  23045. "Host: localhost\r\n"
  23046. "Transfer-Encoding: gzip, chunked\r\n"
  23047. "Connection: close\r\n"
  23048. "\r\n"
  23049. "0\r\n\r\n";
  23050. std::string response;
  23051. ASSERT_TRUE(send_request(1, req, &response));
  23052. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  23053. // ...including when it is spread over several lines.
  23054. auto split_req = "POST /test HTTP/1.1\r\n"
  23055. "Host: localhost\r\n"
  23056. "Transfer-Encoding: gzip\r\n"
  23057. "Transfer-Encoding: chunked\r\n"
  23058. "Connection: close\r\n"
  23059. "\r\n"
  23060. "0\r\n\r\n";
  23061. std::string split_response;
  23062. ASSERT_TRUE(send_request(1, split_req, &split_response));
  23063. EXPECT_EQ("HTTP/1.1 200 OK",
  23064. split_response.substr(0, split_response.find("\r\n")));
  23065. }
  23066. // Regression for issue #2450: a DELETE without Content-Length on a
  23067. // keep-alive connection must not let the post-response drain consume the
  23068. // next request's bytes.
  23069. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  23070. Server svr;
  23071. std::atomic<int> delete_count(0);
  23072. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  23073. delete_count++;
  23074. res.status = StatusCode::NoContent_204;
  23075. });
  23076. auto port = svr.bind_to_any_port(HOST);
  23077. thread t = thread([&] { svr.listen_after_bind(); });
  23078. auto se = detail::scope_exit([&] {
  23079. svr.stop();
  23080. t.join();
  23081. });
  23082. svr.wait_until_ready();
  23083. auto error = Error::Success;
  23084. auto sock = detail::create_client_socket(
  23085. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23086. /*connection_timeout_sec=*/2, 0,
  23087. /*read_timeout_sec=*/2, 0,
  23088. /*write_timeout_sec=*/2, 0, std::string(), error);
  23089. ASSERT_NE(INVALID_SOCKET, sock);
  23090. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23091. auto send_request_and_read_response = [&](const std::string &req,
  23092. std::string &out) -> bool {
  23093. auto sent = send(sock, req.data(), req.size(), 0);
  23094. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  23095. char buf[4096];
  23096. for (;;) {
  23097. auto n = recv(sock, buf, sizeof(buf), 0);
  23098. if (n <= 0) { return !out.empty(); }
  23099. out.append(buf, static_cast<size_t>(n));
  23100. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  23101. }
  23102. };
  23103. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  23104. "Host: localhost\r\n"
  23105. "\r\n";
  23106. std::string resp1;
  23107. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  23108. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  23109. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  23110. "Host: localhost\r\n"
  23111. "Connection: close\r\n"
  23112. "\r\n";
  23113. std::string resp2;
  23114. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  23115. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  23116. EXPECT_EQ(2, delete_count.load());
  23117. }
  23118. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  23119. Server svr;
  23120. svr.Post("/ingest", [&](const Request &, Response &res,
  23121. const ContentReader &content_reader) {
  23122. auto consumed = content_reader([](const char *, size_t) { return false; });
  23123. EXPECT_FALSE(consumed);
  23124. res.status = StatusCode::Conflict_409;
  23125. res.set_header("Connection", "close");
  23126. });
  23127. auto port = svr.bind_to_any_port(HOST);
  23128. thread t = thread([&] { svr.listen_after_bind(); });
  23129. auto se = detail::scope_exit([&] {
  23130. svr.stop();
  23131. t.join();
  23132. });
  23133. svr.wait_until_ready();
  23134. auto error = Error::Success;
  23135. auto sock = detail::create_client_socket(
  23136. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23137. /*connection_timeout_sec=*/2, 0,
  23138. /*read_timeout_sec=*/1, 0,
  23139. /*write_timeout_sec=*/2, 0, std::string(), error);
  23140. ASSERT_NE(INVALID_SOCKET, sock);
  23141. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23142. std::string request = "POST /ingest HTTP/1.1\r\n"
  23143. "Host: localhost\r\n"
  23144. "Transfer-Encoding: chunked\r\n"
  23145. "\r\n"
  23146. "4\r\n"
  23147. "data\r\n";
  23148. auto sent = send(sock, request.data(), request.size(), 0);
  23149. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  23150. std::string response;
  23151. ssize_t received = 0;
  23152. do {
  23153. char buf[4096];
  23154. received = recv(sock, buf, sizeof(buf), 0);
  23155. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  23156. } while (received > 0);
  23157. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  23158. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  23159. EXPECT_EQ(0, received);
  23160. }
  23161. namespace no_proxy_test {
  23162. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  23163. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  23164. // calling listen().
  23165. class ScopedServer {
  23166. public:
  23167. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  23168. ~ScopedServer() {
  23169. svr_.stop();
  23170. if (th_.joinable()) { th_.join(); }
  23171. }
  23172. Server &svr() { return svr_; }
  23173. int port() const { return port_; }
  23174. void listen() {
  23175. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23176. svr_.wait_until_ready();
  23177. }
  23178. private:
  23179. Server svr_;
  23180. std::thread th_;
  23181. int port_ = 0;
  23182. };
  23183. class ProxyAndTargetServers {
  23184. public:
  23185. ProxyAndTargetServers() {
  23186. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  23187. proxy_hits_++;
  23188. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23189. res.set_content("via-proxy", "text/plain");
  23190. });
  23191. target_.Get(".*", [this](const Request &req, Response &res) {
  23192. target_hits_++;
  23193. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23194. res.set_content("direct", "text/plain");
  23195. });
  23196. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  23197. target_port_ = target_.bind_to_any_port("127.0.0.1");
  23198. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  23199. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  23200. proxy_mock_.wait_until_ready();
  23201. target_.wait_until_ready();
  23202. }
  23203. ~ProxyAndTargetServers() {
  23204. proxy_mock_.stop();
  23205. target_.stop();
  23206. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  23207. if (target_thread_.joinable()) { target_thread_.join(); }
  23208. }
  23209. Server &proxy_mock() { return proxy_mock_; }
  23210. Server &target() { return target_; }
  23211. int proxy_port() const { return proxy_port_; }
  23212. int target_port() const { return target_port_; }
  23213. int proxy_hits() const { return proxy_hits_.load(); }
  23214. int target_hits() const { return target_hits_.load(); }
  23215. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  23216. void reset_counters() {
  23217. proxy_hits_ = 0;
  23218. target_hits_ = 0;
  23219. last_had_proxy_authz_ = false;
  23220. }
  23221. private:
  23222. Server proxy_mock_;
  23223. Server target_;
  23224. std::thread proxy_thread_;
  23225. std::thread target_thread_;
  23226. int proxy_port_ = 0;
  23227. int target_port_ = 0;
  23228. std::atomic<int> proxy_hits_{0};
  23229. std::atomic<int> target_hits_{0};
  23230. std::atomic<bool> last_had_proxy_authz_{false};
  23231. };
  23232. inline std::unique_ptr<Client> make_client(const std::string &host,
  23233. ProxyAndTargetServers &s) {
  23234. auto cli = detail::make_unique<Client>(host, s.target_port());
  23235. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  23236. cli->set_proxy("127.0.0.1", s.proxy_port());
  23237. return cli;
  23238. }
  23239. } // namespace no_proxy_test
  23240. using no_proxy_test::make_client;
  23241. using no_proxy_test::ProxyAndTargetServers;
  23242. TEST(NoProxyTest, ExactHostnameBypasses) {
  23243. ProxyAndTargetServers s;
  23244. auto cli = make_client("example.com", s);
  23245. cli->set_no_proxy({"example.com"});
  23246. auto res = cli->Get("/");
  23247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23248. EXPECT_EQ(0, s.proxy_hits());
  23249. EXPECT_EQ(1, s.target_hits());
  23250. }
  23251. TEST(NoProxyTest, SubdomainBypasses) {
  23252. ProxyAndTargetServers s;
  23253. auto cli = make_client("foo.example.com", s);
  23254. cli->set_no_proxy({"example.com"});
  23255. auto res = cli->Get("/");
  23256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23257. EXPECT_EQ(0, s.proxy_hits());
  23258. EXPECT_EQ(1, s.target_hits());
  23259. }
  23260. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  23261. // Regression guard: "evilexample.com" must not be considered a subdomain
  23262. // of "example.com". Without the dot-boundary rule, a naive endsWith
  23263. // check would let traffic bypass the proxy and leak credentials direct
  23264. // to the attacker host.
  23265. ProxyAndTargetServers s;
  23266. auto cli = make_client("evilexample.com", s);
  23267. cli->set_no_proxy({"example.com"});
  23268. auto res = cli->Get("/");
  23269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23270. EXPECT_GE(s.proxy_hits(), 1);
  23271. EXPECT_EQ(0, s.target_hits());
  23272. }
  23273. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  23274. ProxyAndTargetServers s;
  23275. auto cli = make_client("example.com.evil.com", s);
  23276. cli->set_no_proxy({"example.com"});
  23277. auto res = cli->Get("/");
  23278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23279. EXPECT_GE(s.proxy_hits(), 1);
  23280. EXPECT_EQ(0, s.target_hits());
  23281. }
  23282. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  23283. ProxyAndTargetServers s;
  23284. auto cli = make_client("example.com", s);
  23285. cli->set_no_proxy({".example.com"});
  23286. auto res = cli->Get("/");
  23287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23288. EXPECT_EQ(0, s.proxy_hits());
  23289. EXPECT_EQ(1, s.target_hits());
  23290. }
  23291. TEST(NoProxyTest, CaseInsensitiveHostname) {
  23292. ProxyAndTargetServers s;
  23293. auto cli = make_client("Example.COM", s);
  23294. cli->set_no_proxy({"EXAMPLE.com"});
  23295. auto res = cli->Get("/");
  23296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23297. EXPECT_EQ(0, s.proxy_hits());
  23298. EXPECT_EQ(1, s.target_hits());
  23299. }
  23300. TEST(NoProxyTest, TrailingDotIsNormalized) {
  23301. ProxyAndTargetServers s;
  23302. auto cli = make_client("example.com.", s);
  23303. cli->set_no_proxy({"example.com"});
  23304. auto res = cli->Get("/");
  23305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23306. EXPECT_EQ(0, s.proxy_hits());
  23307. EXPECT_EQ(1, s.target_hits());
  23308. }
  23309. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  23310. // Trailing dots must be normalized on BOTH sides — host and entry.
  23311. // An implementation that only strips the host-side trailing dot would
  23312. // fail to match host "example.com" against entry "example.com." because
  23313. // a literal substring search would compare 11 chars against 12.
  23314. ProxyAndTargetServers s;
  23315. auto cli = make_client("example.com", s);
  23316. cli->set_no_proxy({"example.com."});
  23317. auto res = cli->Get("/");
  23318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23319. EXPECT_EQ(0, s.proxy_hits());
  23320. EXPECT_EQ(1, s.target_hits());
  23321. }
  23322. TEST(NoProxyTest, WildcardBypassesEverything) {
  23323. ProxyAndTargetServers s;
  23324. auto cli = make_client("anything.invalid.test", s);
  23325. cli->set_no_proxy({"*"});
  23326. auto res = cli->Get("/");
  23327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23328. EXPECT_EQ(0, s.proxy_hits());
  23329. EXPECT_EQ(1, s.target_hits());
  23330. }
  23331. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  23332. ProxyAndTargetServers s;
  23333. Client cli("127.0.0.1", s.target_port());
  23334. cli.set_proxy("127.0.0.1", s.proxy_port());
  23335. cli.set_no_proxy({"127.0.0.1"});
  23336. auto res = cli.Get("/");
  23337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23338. EXPECT_EQ(0, s.proxy_hits());
  23339. EXPECT_EQ(1, s.target_hits());
  23340. }
  23341. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  23342. ProxyAndTargetServers s;
  23343. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  23344. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  23345. cli.set_proxy("127.0.0.1", s.proxy_port());
  23346. cli.set_no_proxy({"::1"});
  23347. auto res = cli.Get("/");
  23348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23349. EXPECT_EQ(0, s.proxy_hits());
  23350. EXPECT_EQ(1, s.target_hits());
  23351. }
  23352. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  23353. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  23354. // must still be recognized as IPv6 for CIDR matching. Implementations
  23355. // that detect IPv6 only when the host begins with '[' would parse the
  23356. // host as a hostname and miss the match.
  23357. ProxyAndTargetServers s;
  23358. Client cli("fe80::1", s.target_port());
  23359. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23360. cli.set_proxy("127.0.0.1", s.proxy_port());
  23361. cli.set_no_proxy({"fe80::/10"});
  23362. auto res = cli.Get("/");
  23363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23364. EXPECT_EQ(0, s.proxy_hits());
  23365. EXPECT_EQ(1, s.target_hits());
  23366. }
  23367. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  23368. ProxyAndTargetServers s;
  23369. Client cli("::1", s.target_port());
  23370. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  23371. cli.set_proxy("127.0.0.1", s.proxy_port());
  23372. cli.set_no_proxy({"[::1]"});
  23373. auto res = cli.Get("/");
  23374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23375. EXPECT_EQ(0, s.proxy_hits());
  23376. EXPECT_EQ(1, s.target_hits());
  23377. }
  23378. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  23379. ProxyAndTargetServers s;
  23380. Client cli("fe80::1", s.target_port());
  23381. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23382. cli.set_proxy("127.0.0.1", s.proxy_port());
  23383. cli.set_no_proxy({"[fe80::]/10"});
  23384. auto res = cli.Get("/");
  23385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23386. EXPECT_EQ(0, s.proxy_hits());
  23387. EXPECT_EQ(1, s.target_hits());
  23388. }
  23389. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  23390. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  23391. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  23392. // tricks via address-family conversion.
  23393. ProxyAndTargetServers s;
  23394. Client cli("::ffff:127.0.0.1", s.target_port());
  23395. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  23396. cli.set_proxy("127.0.0.1", s.proxy_port());
  23397. cli.set_no_proxy({"127.0.0.1"});
  23398. auto res = cli.Get("/");
  23399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23400. EXPECT_GE(s.proxy_hits(), 1);
  23401. EXPECT_EQ(0, s.target_hits());
  23402. }
  23403. TEST(NoProxyTest, IPv4CidrMatch) {
  23404. ProxyAndTargetServers s;
  23405. Client cli("127.0.0.1", s.target_port());
  23406. cli.set_proxy("127.0.0.1", s.proxy_port());
  23407. cli.set_no_proxy({"127.0.0.0/8"});
  23408. auto res = cli.Get("/");
  23409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23410. EXPECT_EQ(0, s.proxy_hits());
  23411. EXPECT_EQ(1, s.target_hits());
  23412. }
  23413. TEST(NoProxyTest, IPv4CidrNonMatch) {
  23414. ProxyAndTargetServers s;
  23415. Client cli("127.0.0.1", s.target_port());
  23416. cli.set_proxy("127.0.0.1", s.proxy_port());
  23417. cli.set_no_proxy({"10.0.0.0/8"});
  23418. auto res = cli.Get("/");
  23419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23420. EXPECT_GE(s.proxy_hits(), 1);
  23421. EXPECT_EQ(0, s.target_hits());
  23422. }
  23423. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  23424. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  23425. // IPv4 target matches.
  23426. ProxyAndTargetServers s;
  23427. Client cli("127.0.0.1", s.target_port());
  23428. cli.set_proxy("127.0.0.1", s.proxy_port());
  23429. cli.set_no_proxy({"0.0.0.0/0"});
  23430. auto res = cli.Get("/");
  23431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23432. EXPECT_EQ(0, s.proxy_hits());
  23433. EXPECT_EQ(1, s.target_hits());
  23434. }
  23435. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  23436. ProxyAndTargetServers s;
  23437. Client cli("127.0.0.1", s.target_port());
  23438. cli.set_proxy("127.0.0.1", s.proxy_port());
  23439. cli.set_no_proxy({"127.0.0.1"});
  23440. auto res = cli.Get("/");
  23441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23442. EXPECT_EQ(0, s.proxy_hits());
  23443. EXPECT_EQ(1, s.target_hits());
  23444. }
  23445. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  23446. ProxyAndTargetServers s;
  23447. Client cli("127.0.0.1", s.target_port());
  23448. cli.set_proxy("127.0.0.1", s.proxy_port());
  23449. cli.set_no_proxy({"127.0.0.0/33"});
  23450. auto res = cli.Get("/");
  23451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23452. EXPECT_GE(s.proxy_hits(), 1);
  23453. EXPECT_EQ(0, s.target_hits());
  23454. }
  23455. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  23456. // Empty prefix after the slash must be rejected, not silently treated as /32.
  23457. ProxyAndTargetServers s;
  23458. Client cli("127.0.0.1", s.target_port());
  23459. cli.set_proxy("127.0.0.1", s.proxy_port());
  23460. cli.set_no_proxy({"127.0.0.1/"});
  23461. auto res = cli.Get("/");
  23462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23463. EXPECT_GE(s.proxy_hits(), 1);
  23464. EXPECT_EQ(0, s.target_hits());
  23465. }
  23466. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  23467. ProxyAndTargetServers s;
  23468. auto cli = make_client("internal.corp", s);
  23469. cli->set_proxy_basic_auth("u", "p");
  23470. cli->set_no_proxy({"internal.corp"});
  23471. auto res = cli->Get("/");
  23472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23473. EXPECT_EQ(1, s.target_hits());
  23474. EXPECT_EQ(0, s.proxy_hits());
  23475. EXPECT_FALSE(s.last_had_proxy_authz())
  23476. << "Proxy-Authorization must not be sent direct to the target";
  23477. }
  23478. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  23479. ProxyAndTargetServers s;
  23480. auto cli = make_client("public.example", s);
  23481. cli->set_proxy_basic_auth("u", "p");
  23482. cli->set_no_proxy({"internal.corp"}); // does not match
  23483. auto res = cli->Get("/");
  23484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23485. EXPECT_GE(s.proxy_hits(), 1);
  23486. EXPECT_TRUE(s.last_had_proxy_authz());
  23487. }
  23488. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  23489. std::atomic<int> hits{0};
  23490. std::atomic<int> hits_with_authz{0};
  23491. no_proxy_test::ScopedServer proxy_mock;
  23492. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23493. hits++;
  23494. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  23495. if (req.target.find("/redir") != std::string::npos) {
  23496. res.set_redirect("http://other.example/landed");
  23497. } else {
  23498. res.set_content("via-proxy", "text/plain");
  23499. }
  23500. });
  23501. proxy_mock.listen();
  23502. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  23503. hits = 0;
  23504. hits_with_authz = 0;
  23505. Client cli("public.example", 80);
  23506. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23507. cli.set_proxy_basic_auth(c.first, c.second);
  23508. cli.set_follow_location(true);
  23509. // The redirect to another host goes through the proxy as well
  23510. auto res = cli.Get("/redir");
  23511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23512. EXPECT_EQ(2, hits.load());
  23513. EXPECT_EQ(2, hits_with_authz.load());
  23514. }
  23515. }
  23516. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  23517. ProxyAndTargetServers s;
  23518. auto cli = make_client("anything.test", s);
  23519. auto res = cli->Get("/");
  23520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23521. EXPECT_GE(s.proxy_hits(), 1);
  23522. EXPECT_EQ(0, s.target_hits());
  23523. }
  23524. TEST(NoProxyTest, PortSpecificEntryRejected) {
  23525. ProxyAndTargetServers s;
  23526. auto cli = make_client("example.com", s);
  23527. cli->set_no_proxy({"example.com:8080"});
  23528. auto res = cli->Get("/");
  23529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23530. EXPECT_GE(s.proxy_hits(), 1);
  23531. EXPECT_EQ(0, s.target_hits());
  23532. }
  23533. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  23534. ProxyAndTargetServers s;
  23535. auto cli = make_client("anything.test", s);
  23536. cli->set_no_proxy({"", " ", "\t"});
  23537. auto res = cli->Get("/");
  23538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23539. EXPECT_GE(s.proxy_hits(), 1);
  23540. EXPECT_EQ(0, s.target_hits());
  23541. }
  23542. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  23543. // An entry with leading/trailing whitespace must still match — env-style
  23544. // values are commonly pasted with stray spaces and an implementation
  23545. // that feeds the raw token directly to inet_pton would fail to match
  23546. // valid CIDRs because of the spaces.
  23547. ProxyAndTargetServers s;
  23548. Client cli("127.0.0.1", s.target_port());
  23549. cli.set_proxy("127.0.0.1", s.proxy_port());
  23550. cli.set_no_proxy({" 127.0.0.0/8 "});
  23551. auto res = cli.Get("/");
  23552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23553. EXPECT_EQ(0, s.proxy_hits());
  23554. EXPECT_EQ(1, s.target_hits());
  23555. }
  23556. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  23557. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  23558. // go direct and must NOT carry Proxy-Authorization.
  23559. std::atomic<int> proxy_hits{0};
  23560. std::atomic<int> target_hits{0};
  23561. std::atomic<bool> target_saw_authz{false};
  23562. no_proxy_test::ScopedServer proxy_mock, target;
  23563. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23564. proxy_hits++;
  23565. res.status = 302;
  23566. res.set_header("Location", "http://127.0.0.1:" +
  23567. std::to_string(target.port()) + "/landed");
  23568. });
  23569. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23570. target_hits++;
  23571. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  23572. res.set_content("direct", "text/plain");
  23573. });
  23574. proxy_mock.listen();
  23575. target.listen();
  23576. Client cli("public.example", target.port());
  23577. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23578. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23579. cli.set_proxy_basic_auth("u", "p");
  23580. cli.set_no_proxy({"127.0.0.1"});
  23581. cli.set_follow_location(true);
  23582. auto res = cli.Get("/redir");
  23583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23584. EXPECT_GE(proxy_hits.load(), 1);
  23585. EXPECT_GE(target_hits.load(), 1);
  23586. EXPECT_FALSE(target_saw_authz.load());
  23587. }
  23588. #ifdef CPPHTTPLIB_SSL_ENABLED
  23589. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  23590. // Direct origin replying 407 must not trigger the digest retry; otherwise
  23591. // proxy creds would be sent to the (possibly hostile) origin.
  23592. std::atomic<int> target_hits{0};
  23593. std::atomic<bool> target_saw_proxy_authz{false};
  23594. no_proxy_test::ScopedServer target;
  23595. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23596. target_hits++;
  23597. if (req.has_header("Proxy-Authorization")) {
  23598. target_saw_proxy_authz = true;
  23599. }
  23600. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23601. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  23602. "nonce=\"abc\", algorithm=MD5");
  23603. });
  23604. target.listen();
  23605. // The proxy address is set to the target's port: the bypass MUST kick in;
  23606. // if it doesn't, the test still routes "via proxy" to the same server and
  23607. // the Proxy-Authorization assertion below catches the leak.
  23608. Client cli("evil.example", target.port());
  23609. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  23610. cli.set_proxy("127.0.0.1", target.port());
  23611. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23612. cli.set_no_proxy({"evil.example"});
  23613. auto res = cli.Get("/x");
  23614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23615. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23616. EXPECT_EQ(1, target_hits.load());
  23617. EXPECT_FALSE(target_saw_proxy_authz.load());
  23618. }
  23619. #endif
  23620. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  23621. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  23622. std::atomic<int> proxy_hits{0};
  23623. std::atomic<int> bypass_hits{0};
  23624. std::atomic<bool> proxy_saw_c_url{false};
  23625. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  23626. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23627. proxy_hits++;
  23628. if (req.path.find("/start") != std::string::npos) {
  23629. res.status = 302;
  23630. res.set_header("Location", "http://127.0.0.1:" +
  23631. std::to_string(bypass_server.port()) +
  23632. "/middle");
  23633. return;
  23634. }
  23635. if (req.path.find("/end") != std::string::npos) {
  23636. proxy_saw_c_url = true;
  23637. res.set_content("c-via-proxy", "text/plain");
  23638. return;
  23639. }
  23640. res.set_content("unexpected", "text/plain");
  23641. });
  23642. // public.example's "advertised" port is arbitrary (the request never lands
  23643. // there — it goes through the proxy), but use a dynamic value to stay
  23644. // friendly with sharded parallel runs.
  23645. int public_port = bypass_server.port();
  23646. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  23647. bypass_hits++;
  23648. res.status = 302;
  23649. res.set_header("Location", "http://public.example:" +
  23650. std::to_string(public_port) + "/end");
  23651. });
  23652. proxy_mock.listen();
  23653. bypass_server.listen();
  23654. Client cli("public.example", public_port);
  23655. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23656. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23657. cli.set_no_proxy({"127.0.0.1"});
  23658. cli.set_follow_location(true);
  23659. auto res = cli.Get("/start");
  23660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23661. EXPECT_EQ(StatusCode::OK_200, res->status);
  23662. EXPECT_EQ("c-via-proxy", res->body);
  23663. EXPECT_GE(proxy_hits.load(), 2);
  23664. EXPECT_GE(bypass_hits.load(), 1);
  23665. EXPECT_TRUE(proxy_saw_c_url.load());
  23666. }
  23667. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  23668. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  23669. // request reconnects to the correct endpoint.
  23670. std::atomic<int> proxy_hits{0};
  23671. std::atomic<int> target_hits{0};
  23672. no_proxy_test::ScopedServer proxy_mock, target;
  23673. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23674. proxy_hits++;
  23675. res.set_content("via-proxy", "text/plain");
  23676. });
  23677. target.svr().Get(".*", [&](const Request &, Response &res) {
  23678. target_hits++;
  23679. res.set_content("direct", "text/plain");
  23680. });
  23681. proxy_mock.listen();
  23682. target.listen();
  23683. Client cli("public.example", target.port());
  23684. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23685. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23686. cli.set_keep_alive(true);
  23687. auto res1 = cli.Get("/a");
  23688. ASSERT_TRUE(res1);
  23689. EXPECT_EQ("via-proxy", res1->body);
  23690. EXPECT_EQ(1, proxy_hits.load());
  23691. EXPECT_EQ(0, target_hits.load());
  23692. cli.set_no_proxy({"public.example"});
  23693. auto res2 = cli.Get("/b");
  23694. ASSERT_TRUE(res2);
  23695. EXPECT_EQ("direct", res2->body);
  23696. EXPECT_EQ(1, proxy_hits.load());
  23697. EXPECT_EQ(1, target_hits.load());
  23698. }
  23699. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  23700. namespace proxy_tunnel_test {
  23701. // SSLServer counterpart to no_proxy_test::ScopedServer.
  23702. class ScopedSSLServer {
  23703. public:
  23704. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  23705. port_ = svr_.bind_to_any_port("127.0.0.1");
  23706. }
  23707. ~ScopedSSLServer() {
  23708. svr_.stop();
  23709. if (th_.joinable()) { th_.join(); }
  23710. }
  23711. SSLServer &svr() { return svr_; }
  23712. int port() const { return port_; }
  23713. void listen() {
  23714. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23715. svr_.wait_until_ready();
  23716. }
  23717. private:
  23718. SSLServer svr_;
  23719. std::thread th_;
  23720. int port_ = 0;
  23721. };
  23722. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  23723. class ScopedConnectProxy {
  23724. public:
  23725. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  23726. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  23727. if (listen_fd_ < 0) { return; }
  23728. int yes = 1;
  23729. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  23730. sockaddr_in a{};
  23731. a.sin_family = AF_INET;
  23732. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23733. a.sin_port = 0;
  23734. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  23735. return;
  23736. }
  23737. socklen_t alen = sizeof(a);
  23738. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  23739. 0) {
  23740. return;
  23741. }
  23742. port_ = ntohs(a.sin_port);
  23743. if (::listen(listen_fd_, 1) != 0) { return; }
  23744. th_ = std::thread([this] { run(); });
  23745. }
  23746. ~ScopedConnectProxy() {
  23747. stop_ = true;
  23748. if (listen_fd_ >= 0) {
  23749. ::shutdown(listen_fd_, SHUT_RDWR);
  23750. ::close(listen_fd_);
  23751. }
  23752. if (th_.joinable()) { th_.join(); }
  23753. }
  23754. int port() const { return port_; }
  23755. int connect_hits() const { return connect_hits_.load(); }
  23756. // Head of the last CONNECT request, as the proxy saw it on the wire.
  23757. std::string connect_request() const {
  23758. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23759. return connect_request_;
  23760. }
  23761. private:
  23762. void run() {
  23763. while (!stop_.load()) {
  23764. fd_set rfds;
  23765. FD_ZERO(&rfds);
  23766. FD_SET(listen_fd_, &rfds);
  23767. timeval tv{0, 100 * 1000};
  23768. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  23769. if (sel <= 0) { continue; }
  23770. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  23771. if (client_fd < 0) { continue; }
  23772. std::string req;
  23773. char buf[2048];
  23774. while (req.find("\r\n\r\n") == std::string::npos) {
  23775. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  23776. if (n <= 0) { break; }
  23777. req.append(buf, static_cast<size_t>(n));
  23778. }
  23779. if (req.compare(0, 7, "CONNECT") != 0) {
  23780. ::close(client_fd);
  23781. continue;
  23782. }
  23783. connect_hits_++;
  23784. {
  23785. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23786. connect_request_ = req;
  23787. }
  23788. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  23789. ::send(client_fd, ok, std::strlen(ok), 0);
  23790. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  23791. sockaddr_in o{};
  23792. o.sin_family = AF_INET;
  23793. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23794. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  23795. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  23796. 0) {
  23797. ::close(client_fd);
  23798. ::close(origin_fd);
  23799. continue;
  23800. }
  23801. auto forward = [](int from, int to) {
  23802. char b[8192];
  23803. for (;;) {
  23804. ssize_t n = ::recv(from, b, sizeof(b), 0);
  23805. if (n <= 0) { break; }
  23806. ssize_t off = 0;
  23807. while (off < n) {
  23808. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  23809. if (s <= 0) {
  23810. off = n;
  23811. break;
  23812. }
  23813. off += s;
  23814. }
  23815. }
  23816. ::shutdown(to, SHUT_WR);
  23817. };
  23818. std::thread t1([&] { forward(client_fd, origin_fd); });
  23819. std::thread t2([&] { forward(origin_fd, client_fd); });
  23820. t1.join();
  23821. t2.join();
  23822. ::close(client_fd);
  23823. ::close(origin_fd);
  23824. }
  23825. }
  23826. int forward_port_ = -1;
  23827. int listen_fd_ = -1;
  23828. int port_ = 0;
  23829. std::thread th_;
  23830. std::atomic<bool> stop_{false};
  23831. std::atomic<int> connect_hits_{0};
  23832. mutable std::mutex connect_request_mutex_;
  23833. std::string connect_request_;
  23834. };
  23835. // Sends one request through the CONNECT proxy to the TLS origin with a
  23836. // credential configured for each hop, and checks that each credential reaches
  23837. // only the hop it was configured for: the proxy's on the CONNECT request, the
  23838. // origin's (every header in origin_headers) on the tunnelled request.
  23839. void CredentialsStayWithTheirHop(
  23840. const std::function<void(SSLClient &)> &set_credentials,
  23841. const std::string &scheme,
  23842. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  23843. std::atomic<int> origin_hits{0};
  23844. std::atomic<bool> origin_saw_proxy_authz{false};
  23845. std::atomic<bool> origin_saw_headers{false};
  23846. ScopedSSLServer origin;
  23847. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23848. origin_hits++;
  23849. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  23850. origin_saw_headers =
  23851. std::all_of(origin_headers.begin(), origin_headers.end(),
  23852. [&](const std::string &h) { return req.has_header(h); });
  23853. res.set_content("ok", "text/plain");
  23854. });
  23855. origin.listen();
  23856. ScopedConnectProxy proxy(origin.port());
  23857. ASSERT_NE(0, proxy.port());
  23858. // Pinned to 127.0.0.1 for the same reason as the test below.
  23859. SSLClient cli("127.0.0.1", origin.port());
  23860. cli.enable_server_certificate_verification(false);
  23861. cli.set_proxy("127.0.0.1", proxy.port());
  23862. set_credentials(cli);
  23863. auto res = cli.Get("/x");
  23864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23865. EXPECT_EQ(StatusCode::OK_200, res->status);
  23866. EXPECT_EQ(1, origin_hits.load());
  23867. EXPECT_EQ(1, proxy.connect_hits());
  23868. EXPECT_TRUE(origin_saw_headers.load());
  23869. EXPECT_FALSE(origin_saw_proxy_authz.load())
  23870. << "Proxy-Authorization must not be sent inside the tunnel";
  23871. auto connect_req = proxy.connect_request();
  23872. EXPECT_NE(std::string::npos,
  23873. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  23874. for (const auto &h : origin_headers) {
  23875. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  23876. << h << " must not be sent to the proxy on CONNECT";
  23877. }
  23878. }
  23879. } // namespace proxy_tunnel_test
  23880. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  23881. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23882. [](SSLClient &cli) {
  23883. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  23884. cli.set_basic_auth("origin-user", "origin-pass");
  23885. },
  23886. "Basic");
  23887. }
  23888. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  23889. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23890. [](SSLClient &cli) {
  23891. cli.set_proxy_bearer_token_auth("proxy-token");
  23892. cli.set_bearer_token_auth("origin-token");
  23893. },
  23894. "Bearer");
  23895. }
  23896. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  23897. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23898. [](SSLClient &cli) {
  23899. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  23900. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  23901. {"Cookie", "sid=origin-session"},
  23902. {"X-Api-Key", "origin-key"}});
  23903. },
  23904. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  23905. }
  23906. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  23907. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  23908. // retry; otherwise proxy creds would be sent to the origin.
  23909. std::atomic<int> origin_hits{0};
  23910. std::atomic<bool> origin_saw_proxy_authz{false};
  23911. proxy_tunnel_test::ScopedSSLServer origin;
  23912. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23913. origin_hits++;
  23914. if (req.has_header("Proxy-Authorization")) {
  23915. origin_saw_proxy_authz = true;
  23916. }
  23917. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23918. res.set_header("Proxy-Authenticate",
  23919. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  23920. "algorithm=MD5");
  23921. });
  23922. origin.listen();
  23923. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  23924. ASSERT_NE(0, proxy.port());
  23925. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  23926. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  23927. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  23928. // and answer with its own status, making this test flaky.
  23929. SSLClient cli("127.0.0.1", origin.port());
  23930. cli.enable_server_certificate_verification(false);
  23931. cli.set_proxy("127.0.0.1", proxy.port());
  23932. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23933. auto res = cli.Get("/x");
  23934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23935. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23936. EXPECT_EQ(1, origin_hits.load());
  23937. EXPECT_FALSE(origin_saw_proxy_authz.load());
  23938. EXPECT_EQ(1, proxy.connect_hits());
  23939. }
  23940. #endif