test.cc 923 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450
  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. };
  1577. for (const auto &c : cases) {
  1578. Params params;
  1579. detail::parse_disposition_params(c.value, params);
  1580. for (const auto &kv : c.expected) {
  1581. auto it = params.find(kv.first);
  1582. ASSERT_NE(it, params.end())
  1583. << "value: " << c.value << ", key: " << kv.first;
  1584. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1585. }
  1586. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1587. }
  1588. }
  1589. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1590. Server svr;
  1591. std::string filename;
  1592. std::string content;
  1593. svr.Post("/upload", [&](const Request &req, Response &) {
  1594. const auto &file = req.form.get_file("file");
  1595. filename = file.filename;
  1596. content = file.content;
  1597. });
  1598. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1599. auto se = detail::scope_exit([&] {
  1600. svr.stop();
  1601. thread.join();
  1602. ASSERT_FALSE(svr.is_running());
  1603. });
  1604. svr.wait_until_ready();
  1605. std::string body = "--B\r\n"
  1606. "Content-Disposition: form-data; name=\"file\"; "
  1607. "filename=\"a.txt\"\r\n"
  1608. "Content-Type: text/plain\r\n"
  1609. "\r\n"
  1610. "hello\r\n"
  1611. "--B--\r\n";
  1612. Client cli(HOST, PORT);
  1613. auto res = cli.Post(
  1614. "/upload",
  1615. [&](size_t offset, DataSink &sink) {
  1616. if (offset < body.size()) {
  1617. sink.write(&body[offset], 1);
  1618. } else {
  1619. sink.done();
  1620. }
  1621. return true;
  1622. },
  1623. "multipart/form-data; boundary=B");
  1624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1625. EXPECT_EQ(StatusCode::OK_200, res->status);
  1626. EXPECT_EQ("a.txt", filename);
  1627. EXPECT_EQ("hello", content);
  1628. }
  1629. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1630. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1631. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1632. Server svr;
  1633. std::string field_value, file_name, file_filename;
  1634. bool has_field = false, has_file = false;
  1635. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1636. has_field = req.form.has_field("x=y");
  1637. field_value = req.form.get_field("x=y");
  1638. has_file = req.form.has_file("file1");
  1639. const auto &file = req.form.get_file("file1");
  1640. file_name = file.name;
  1641. file_filename = file.filename;
  1642. res.set_content("ok", "text/plain");
  1643. });
  1644. auto port = svr.bind_to_any_port(HOST);
  1645. thread t = thread([&] { svr.listen_after_bind(); });
  1646. auto se = detail::scope_exit([&] {
  1647. svr.stop();
  1648. t.join();
  1649. ASSERT_FALSE(svr.is_running());
  1650. });
  1651. svr.wait_until_ready();
  1652. UploadFormDataItems items = {
  1653. {"x=y", "field-value", "", ""},
  1654. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1655. };
  1656. Client cli(HOST, port);
  1657. auto res = cli.Post("/quoted", items);
  1658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1659. ASSERT_EQ(StatusCode::OK_200, res->status);
  1660. EXPECT_TRUE(has_field);
  1661. EXPECT_EQ("field-value", field_value);
  1662. EXPECT_TRUE(has_file);
  1663. EXPECT_EQ("file1", file_name);
  1664. EXPECT_EQ("a;b=report.pdf", file_filename);
  1665. }
  1666. TEST(GetHeaderValueTest, DefaultValue) {
  1667. Headers headers = {{"Dummy", "Dummy"}};
  1668. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1669. EXPECT_STREQ("text/plain", val);
  1670. }
  1671. TEST(GetHeaderValueTest, DefaultValueInt) {
  1672. Headers headers = {{"Dummy", "Dummy"}};
  1673. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1674. EXPECT_EQ(100ull, val);
  1675. }
  1676. TEST(GetHeaderValueTest, RegularValue) {
  1677. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1678. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1679. EXPECT_STREQ("text/html", val);
  1680. }
  1681. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1682. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1683. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1684. EXPECT_STREQ("text/html", val);
  1685. }
  1686. TEST(GetHeaderValueTest, SetContent) {
  1687. Response res;
  1688. res.set_content("html", "text/html");
  1689. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1690. res.set_content("text", "text/plain");
  1691. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1692. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1693. }
  1694. TEST(GetHeaderValueTest, RegularValueInt) {
  1695. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1696. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1697. EXPECT_EQ(100ull, val);
  1698. }
  1699. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1700. Headers headers = {{"Content-Length", "x"}};
  1701. auto is_invalid_value = false;
  1702. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1703. is_invalid_value);
  1704. EXPECT_EQ(0ull, val);
  1705. EXPECT_TRUE(is_invalid_value);
  1706. }
  1707. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1708. // An all-digit value that overflows size_t must be reported as invalid, not
  1709. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1710. // a large length to a small one on 32-bit builds, leaving the framing length
  1711. // wrong while is_invalid_value stayed false.
  1712. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1713. auto is_invalid_value = false;
  1714. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1715. is_invalid_value);
  1716. EXPECT_TRUE(is_invalid_value);
  1717. // A well-formed length is unaffected.
  1718. Headers ok = {{"Content-Length", "1234"}};
  1719. is_invalid_value = false;
  1720. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1721. is_invalid_value);
  1722. EXPECT_EQ(1234ull, val);
  1723. EXPECT_FALSE(is_invalid_value);
  1724. }
  1725. TEST(GetHeaderValueTest, Range) {
  1726. {
  1727. Headers headers = {make_range_header({{1, -1}})};
  1728. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1729. EXPECT_STREQ("bytes=1-", val);
  1730. }
  1731. {
  1732. Headers headers = {make_range_header({{-1, 1}})};
  1733. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1734. EXPECT_STREQ("bytes=-1", val);
  1735. }
  1736. {
  1737. Headers headers = {make_range_header({{1, 10}})};
  1738. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1739. EXPECT_STREQ("bytes=1-10", val);
  1740. }
  1741. {
  1742. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1743. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1744. EXPECT_STREQ("bytes=1-10, 100-", val);
  1745. }
  1746. {
  1747. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1748. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1749. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1750. }
  1751. {
  1752. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1753. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1754. EXPECT_STREQ("bytes=0-0, -1", val);
  1755. }
  1756. }
  1757. TEST(BearerTokenAuthTest, SchemeValidation) {
  1758. // A value shorter than "Bearer " must not throw from the fixed-length
  1759. // substr, and a non-Bearer scheme must not be reported as a token.
  1760. struct {
  1761. const char *value;
  1762. const char *expected;
  1763. } cases[] = {
  1764. {"x", ""},
  1765. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1766. {"Bearer abc123", "abc123"},
  1767. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1768. };
  1769. for (const auto &c : cases) {
  1770. Request req;
  1771. req.set_header("Authorization", c.value);
  1772. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1773. }
  1774. }
  1775. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1776. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1777. // to depend on the standard library (libstdc++ handed back duplicates in
  1778. // reverse insertion order, libc++ in insertion order).
  1779. Request req;
  1780. req.set_header("Accept-Encoding", "gzip");
  1781. req.set_header("Accept-Encoding", "deflate");
  1782. req.set_header("Accept-Encoding", "br");
  1783. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1784. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1785. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1786. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1787. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1788. }
  1789. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1790. Request req;
  1791. req.set_header("X-Test", "only");
  1792. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1793. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1794. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1795. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1796. }
  1797. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1798. Request req;
  1799. req.set_header("X-First", "1");
  1800. req.set_header("X-Test", "2");
  1801. req.params.emplace("first", "1");
  1802. req.params.emplace("test", "2");
  1803. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1804. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1805. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1806. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1807. // The second one is negative when read as a signed value
  1808. const auto max_id = (std::numeric_limits<size_t>::max)();
  1809. for (auto id : {max_id / 2, max_id}) {
  1810. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1811. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1812. EXPECT_EQ("", req.get_param_value("test", id));
  1813. EXPECT_EQ("", req.form.get_field("test", id));
  1814. EXPECT_EQ("", req.form.get_file("test", id).content);
  1815. }
  1816. }
  1817. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1818. Headers headers;
  1819. headers.emplace("Host", "example.com");
  1820. headers.emplace("Accept-Encoding", "gzip");
  1821. headers.emplace("User-Agent", "test");
  1822. headers.emplace("Accept-Encoding", "deflate");
  1823. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1824. "Accept-Encoding=deflate ",
  1825. entries_to_string(headers));
  1826. }
  1827. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1828. Headers headers = {{"Content-Type", "text/html"},
  1829. {"CONTENT-TYPE", "text/xml"}};
  1830. EXPECT_EQ(2U, headers.count("content-type"));
  1831. auto it = headers.find("content-type");
  1832. ASSERT_TRUE(it != headers.end());
  1833. EXPECT_EQ("text/html", it->second);
  1834. }
  1835. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1836. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1837. // drop only those fields and leave everything positioned between them.
  1838. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1839. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1840. auto rng = headers.equal_range("a");
  1841. headers.erase(rng.first, rng.second);
  1842. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1843. }
  1844. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1845. Headers headers = {
  1846. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1847. EXPECT_EQ(3U, headers.erase("A"));
  1848. EXPECT_EQ(0U, headers.count("A"));
  1849. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1850. }
  1851. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1852. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1853. headers.emplace_front("Host", "example.com");
  1854. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1855. entries_to_string(headers));
  1856. }
  1857. TEST(ParseHeaderValueTest, Range) {
  1858. {
  1859. Ranges ranges;
  1860. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1861. EXPECT_TRUE(ret);
  1862. EXPECT_EQ(1u, ranges.size());
  1863. EXPECT_EQ(1u, ranges[0].first);
  1864. EXPECT_EQ(-1, ranges[0].second);
  1865. }
  1866. {
  1867. Ranges ranges;
  1868. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1869. EXPECT_TRUE(ret);
  1870. EXPECT_EQ(1u, ranges.size());
  1871. EXPECT_EQ(-1, ranges[0].first);
  1872. EXPECT_EQ(1u, ranges[0].second);
  1873. }
  1874. {
  1875. Ranges ranges;
  1876. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1877. EXPECT_TRUE(ret);
  1878. EXPECT_EQ(1u, ranges.size());
  1879. EXPECT_EQ(1u, ranges[0].first);
  1880. EXPECT_EQ(10u, ranges[0].second);
  1881. }
  1882. {
  1883. Ranges ranges;
  1884. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1885. EXPECT_FALSE(ret);
  1886. }
  1887. {
  1888. Ranges ranges;
  1889. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1890. EXPECT_TRUE(ret);
  1891. EXPECT_EQ(2u, ranges.size());
  1892. EXPECT_EQ(1u, ranges[0].first);
  1893. EXPECT_EQ(10u, ranges[0].second);
  1894. EXPECT_EQ(100u, ranges[1].first);
  1895. EXPECT_EQ(-1, ranges[1].second);
  1896. }
  1897. {
  1898. Ranges ranges;
  1899. auto ret =
  1900. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1901. EXPECT_TRUE(ret);
  1902. EXPECT_EQ(3u, ranges.size());
  1903. EXPECT_EQ(1u, ranges[0].first);
  1904. EXPECT_EQ(10u, ranges[0].second);
  1905. EXPECT_EQ(100u, ranges[1].first);
  1906. EXPECT_EQ(200u, ranges[1].second);
  1907. EXPECT_EQ(300u, ranges[2].first);
  1908. EXPECT_EQ(400u, ranges[2].second);
  1909. }
  1910. {
  1911. Ranges ranges;
  1912. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1913. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1914. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1915. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1916. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1917. EXPECT_FALSE(detail::parse_range_header("bytes=,", 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=a-b", ranges));
  1921. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1922. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1923. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1924. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1925. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1926. EXPECT_FALSE(
  1927. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1928. EXPECT_TRUE(ranges.empty());
  1929. }
  1930. {
  1931. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1932. // remainder of the representation, so it stays accepted.
  1933. Ranges ranges;
  1934. auto ret =
  1935. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1936. EXPECT_TRUE(ret);
  1937. ASSERT_EQ(1u, ranges.size());
  1938. EXPECT_EQ(0, ranges[0].first);
  1939. EXPECT_EQ(-1, ranges[0].second);
  1940. }
  1941. // RFC 9110 14.1: range unit names are case-insensitive.
  1942. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  1943. Ranges ranges;
  1944. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  1945. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  1946. }
  1947. }
  1948. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1949. Request req;
  1950. req.set_header("Accept-Encoding", "gzip");
  1951. Response res;
  1952. res.set_header("Content-Type", "text/plain");
  1953. auto ret = detail::encoding_type(req, res);
  1954. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1955. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1956. #else
  1957. EXPECT_TRUE(ret == detail::EncodingType::None);
  1958. #endif
  1959. }
  1960. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1961. Request req;
  1962. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1963. Response res;
  1964. res.set_header("Content-Type", "text/plain");
  1965. auto ret = detail::encoding_type(req, res);
  1966. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1967. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1968. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1969. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1970. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1971. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1972. #else
  1973. EXPECT_TRUE(ret == detail::EncodingType::None);
  1974. #endif
  1975. }
  1976. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1977. Request req;
  1978. req.set_header("Accept-Encoding",
  1979. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1980. Response res;
  1981. res.set_header("Content-Type", "text/plain");
  1982. auto ret = detail::encoding_type(req, res);
  1983. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1984. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1985. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1986. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1987. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1988. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1989. #else
  1990. EXPECT_TRUE(ret == detail::EncodingType::None);
  1991. #endif
  1992. }
  1993. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1994. // All supported encodings rejected with q=0 should return None
  1995. Request req;
  1996. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1997. Response res;
  1998. res.set_header("Content-Type", "text/plain");
  1999. auto ret = detail::encoding_type(req, res);
  2000. EXPECT_TRUE(ret == detail::EncodingType::None);
  2001. }
  2002. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2003. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2004. Request req;
  2005. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2006. Response res;
  2007. res.set_header("Content-Type", "text/plain");
  2008. auto ret = detail::encoding_type(req, res);
  2009. EXPECT_TRUE(ret == detail::EncodingType::None);
  2010. }
  2011. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2012. Request req;
  2013. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2014. Response res;
  2015. res.set_header("Content-Type", "text/plain");
  2016. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2017. }
  2018. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2019. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2020. Request req;
  2021. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2022. Response res;
  2023. res.set_header("Content-Type", "text/plain");
  2024. auto ret = detail::encoding_type(req, res);
  2025. EXPECT_TRUE(ret == detail::EncodingType::None);
  2026. }
  2027. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2028. // RFC 7231: Accept-Encoding values are case-insensitive
  2029. Request req;
  2030. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2031. Response res;
  2032. res.set_header("Content-Type", "text/plain");
  2033. auto ret = detail::encoding_type(req, res);
  2034. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2035. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2036. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2037. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2038. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2039. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2040. #else
  2041. EXPECT_TRUE(ret == detail::EncodingType::None);
  2042. #endif
  2043. }
  2044. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2045. // q value should determine priority, not hardcoded order
  2046. Request req;
  2047. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2048. Response res;
  2049. res.set_header("Content-Type", "text/plain");
  2050. auto ret = detail::encoding_type(req, res);
  2051. // gzip has highest q=1.0, so it should be selected even though
  2052. // br and zstd are also supported
  2053. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2054. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2055. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2056. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2057. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2058. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2059. #else
  2060. EXPECT_TRUE(ret == detail::EncodingType::None);
  2061. #endif
  2062. }
  2063. TEST(BufferStreamTest, read) {
  2064. detail::BufferStream strm1;
  2065. Stream &strm = strm1;
  2066. EXPECT_EQ(5, strm.write("hello"));
  2067. char buf[512];
  2068. EXPECT_EQ(2, strm.read(buf, 2));
  2069. EXPECT_EQ('h', buf[0]);
  2070. EXPECT_EQ('e', buf[1]);
  2071. EXPECT_EQ(2, strm.read(buf, 2));
  2072. EXPECT_EQ('l', buf[0]);
  2073. EXPECT_EQ('l', buf[1]);
  2074. EXPECT_EQ(1, strm.read(buf, 1));
  2075. EXPECT_EQ('o', buf[0]);
  2076. EXPECT_EQ(0, strm.read(buf, 1));
  2077. }
  2078. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2079. auto host = "www.httpwatch.com";
  2080. auto ip = hosted_at(host);
  2081. EXPECT_EQ("23.96.13.243", ip);
  2082. std::vector<std::string> addrs;
  2083. hosted_at(host, addrs);
  2084. EXPECT_EQ(1u, addrs.size());
  2085. }
  2086. #if 0 // It depends on each test environment...
  2087. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2088. auto host = "www.youtube.com";
  2089. std::vector<std::string> addrs;
  2090. hosted_at(host, addrs);
  2091. EXPECT_EQ(20u, addrs.size());
  2092. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2093. EXPECT_TRUE(it != addrs.end());
  2094. }
  2095. #endif
  2096. class ChunkedEncodingTest : public ::testing::Test {
  2097. protected:
  2098. ChunkedEncodingTest()
  2099. : cli_(HOST, PORT)
  2100. #ifdef CPPHTTPLIB_SSL_ENABLED
  2101. ,
  2102. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2103. #endif
  2104. {
  2105. cli_.set_connection_timeout(2);
  2106. #ifdef CPPHTTPLIB_SSL_ENABLED
  2107. cli_.enable_server_certificate_verification(false);
  2108. #endif
  2109. }
  2110. virtual void SetUp() {
  2111. read_file("./image.jpg", image_data_);
  2112. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2113. res.set_content("Hello World!", "text/plain");
  2114. });
  2115. svr_.Get(
  2116. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2117. res.set_chunked_content_provider(
  2118. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2119. size_t remaining = image_data_.size() - offset;
  2120. if (remaining == 0) {
  2121. sink.done();
  2122. } else {
  2123. constexpr size_t CHUNK_SIZE = 1024;
  2124. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2125. sink.write(&image_data_[offset], send_size);
  2126. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2127. }
  2128. return true;
  2129. });
  2130. });
  2131. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2132. svr_.wait_until_ready();
  2133. }
  2134. virtual void TearDown() {
  2135. svr_.stop();
  2136. if (!request_threads_.empty()) {
  2137. std::this_thread::sleep_for(std::chrono::seconds(1));
  2138. for (auto &t : request_threads_) {
  2139. t.join();
  2140. }
  2141. }
  2142. t_.join();
  2143. }
  2144. #ifdef CPPHTTPLIB_SSL_ENABLED
  2145. SSLClient cli_;
  2146. SSLServer svr_;
  2147. #else
  2148. Client cli_;
  2149. Server svr_;
  2150. #endif
  2151. thread t_;
  2152. std::vector<thread> request_threads_;
  2153. std::string image_data_;
  2154. };
  2155. TEST_F(ChunkedEncodingTest, NormalGet) {
  2156. auto res = cli_.Get("/chunked");
  2157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2158. std::string out;
  2159. read_file("./image.jpg", out);
  2160. EXPECT_EQ(StatusCode::OK_200, res->status);
  2161. EXPECT_EQ(out, res->body);
  2162. }
  2163. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2164. std::string body;
  2165. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2166. body.append(data, data_length);
  2167. return true;
  2168. });
  2169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2170. std::string out;
  2171. read_file("./image.jpg", out);
  2172. EXPECT_EQ(StatusCode::OK_200, res->status);
  2173. EXPECT_EQ(out, body);
  2174. }
  2175. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2176. std::string body;
  2177. auto res = cli_.Get(
  2178. "/chunked",
  2179. [&](const Response &response) {
  2180. EXPECT_EQ(StatusCode::OK_200, response.status);
  2181. return true;
  2182. },
  2183. [&](const char *data, size_t data_length) {
  2184. body.append(data, data_length);
  2185. return true;
  2186. });
  2187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2188. std::string out;
  2189. read_file("./image.jpg", out);
  2190. EXPECT_EQ(StatusCode::OK_200, res->status);
  2191. EXPECT_EQ(out, body);
  2192. }
  2193. TEST(RangeTest, FromHTTPBin_Online) {
  2194. auto host = "httpbingo.org";
  2195. auto path = std::string{"/range/32"};
  2196. #ifdef CPPHTTPLIB_SSL_ENABLED
  2197. auto port = 443;
  2198. SSLClient cli(host, port);
  2199. #else
  2200. auto port = 80;
  2201. Client cli(host, port);
  2202. #endif
  2203. cli.set_connection_timeout(5);
  2204. {
  2205. auto res = cli.Get(path);
  2206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2207. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2208. EXPECT_EQ(StatusCode::OK_200, res->status);
  2209. }
  2210. {
  2211. Headers headers = {make_range_header({{1, -1}})};
  2212. auto res = cli.Get(path, headers);
  2213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2214. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2215. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2216. }
  2217. {
  2218. Headers headers = {make_range_header({{1, 10}})};
  2219. auto res = cli.Get(path, headers);
  2220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2221. EXPECT_EQ("bcdefghijk", res->body);
  2222. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2223. }
  2224. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2225. // entire resource, while the original httpbin returned 200. Both are
  2226. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2227. {
  2228. Headers headers = {make_range_header({{0, 31}})};
  2229. auto res = cli.Get(path, headers);
  2230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2231. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2232. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2233. res->status == StatusCode::PartialContent_206);
  2234. }
  2235. {
  2236. Headers headers = {make_range_header({{0, -1}})};
  2237. auto res = cli.Get(path, headers);
  2238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2239. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2240. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2241. res->status == StatusCode::PartialContent_206);
  2242. }
  2243. // go-httpbin returns 206 with clamped range for over-range requests,
  2244. // while the original httpbin returned 416. Both behaviors are observed
  2245. // in real servers, so we only verify the request succeeds.
  2246. {
  2247. Headers headers = {make_range_header({{0, 32}})};
  2248. auto res = cli.Get(path, headers);
  2249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2250. }
  2251. }
  2252. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2253. auto host = "unresolvableaddress.local";
  2254. auto path = std::string{"/"};
  2255. #ifdef CPPHTTPLIB_SSL_ENABLED
  2256. auto port = 443;
  2257. SSLClient cli(host, port);
  2258. #else
  2259. auto port = 80;
  2260. Client cli(host, port);
  2261. #endif
  2262. cli.set_connection_timeout(1);
  2263. {
  2264. auto res = cli.Get(path);
  2265. ASSERT_FALSE(res);
  2266. }
  2267. std::this_thread::sleep_for(std::chrono::seconds(8));
  2268. }
  2269. #if defined(__linux__) && defined(__GLIBC__) && \
  2270. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2271. // Forward declaration: in split builds split.py strips `inline` and moves the
  2272. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2273. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2274. // against the symbol in both header-only and split builds.
  2275. namespace httplib {
  2276. namespace detail {
  2277. int getaddrinfo_with_timeout(const char *node, const char *service,
  2278. const struct addrinfo *hints,
  2279. struct addrinfo **res, time_t timeout_sec);
  2280. } // namespace detail
  2281. } // namespace httplib
  2282. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2283. //
  2284. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2285. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2286. // gai_suspend() call hits the connection timeout the function calls
  2287. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2288. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2289. // still alive and still references the now-destroyed stack frame.
  2290. //
  2291. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2292. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2293. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2294. // and runs them in a container.
  2295. namespace {
  2296. bool should_run_issue_2431_tests() {
  2297. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2298. return v && *v && std::string(v) != "0";
  2299. }
  2300. std::string unique_unresolvable_host(int n) {
  2301. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2302. // glibc still asks the configured nameserver — which is exactly the path
  2303. // we want to exercise. A unique label per call avoids the resolver cache.
  2304. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2305. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2306. std::to_string(n) + ".invalid";
  2307. }
  2308. } // namespace
  2309. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2310. if (!should_run_issue_2431_tests()) {
  2311. GTEST_SKIP()
  2312. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2313. }
  2314. for (int i = 0; i < 8; ++i) {
  2315. struct addrinfo hints;
  2316. memset(&hints, 0, sizeof(hints));
  2317. hints.ai_family = AF_UNSPEC;
  2318. hints.ai_socktype = SOCK_STREAM;
  2319. auto host = unique_unresolvable_host(i);
  2320. struct addrinfo *result = nullptr;
  2321. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2322. &result, /*timeout_sec=*/1);
  2323. if (rc == 0 && result) { freeaddrinfo(result); }
  2324. }
  2325. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2326. // stack region they still believe holds their gaicb.
  2327. std::this_thread::sleep_for(std::chrono::seconds(3));
  2328. }
  2329. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2330. if (!should_run_issue_2431_tests()) {
  2331. GTEST_SKIP()
  2332. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2333. }
  2334. std::atomic<bool> stop{false};
  2335. std::vector<std::thread> threads;
  2336. for (int t = 0; t < 8; ++t) {
  2337. threads.emplace_back([t, &stop] {
  2338. int i = 0;
  2339. while (!stop.load(std::memory_order_relaxed)) {
  2340. struct addrinfo hints;
  2341. memset(&hints, 0, sizeof(hints));
  2342. hints.ai_family = AF_UNSPEC;
  2343. hints.ai_socktype = SOCK_STREAM;
  2344. auto host = unique_unresolvable_host(t * 100000 + i++);
  2345. struct addrinfo *result = nullptr;
  2346. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2347. &result, /*timeout_sec=*/1);
  2348. if (rc == 0 && result) { freeaddrinfo(result); }
  2349. }
  2350. });
  2351. }
  2352. std::this_thread::sleep_for(std::chrono::seconds(8));
  2353. stop.store(true, std::memory_order_relaxed);
  2354. for (auto &th : threads) {
  2355. th.join();
  2356. }
  2357. std::this_thread::sleep_for(std::chrono::seconds(3));
  2358. }
  2359. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2360. if (!should_run_issue_2431_tests()) {
  2361. GTEST_SKIP()
  2362. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2363. }
  2364. std::atomic<bool> stop{false};
  2365. std::vector<std::thread> threads;
  2366. for (int t = 0; t < 8; ++t) {
  2367. threads.emplace_back([t, &stop] {
  2368. int i = 0;
  2369. while (!stop.load(std::memory_order_relaxed)) {
  2370. auto host = unique_unresolvable_host(t * 100000 + i++);
  2371. Client cli(host, 80);
  2372. cli.set_connection_timeout(1, 0);
  2373. cli.set_read_timeout(1, 0);
  2374. cli.set_write_timeout(1, 0);
  2375. (void)cli.Get("/");
  2376. }
  2377. });
  2378. }
  2379. std::this_thread::sleep_for(std::chrono::seconds(8));
  2380. stop.store(true, std::memory_order_relaxed);
  2381. for (auto &th : threads) {
  2382. th.join();
  2383. }
  2384. std::this_thread::sleep_for(std::chrono::seconds(3));
  2385. }
  2386. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2387. TEST(ConnectionErrorTest, InvalidHost) {
  2388. auto host = "-abcde.com";
  2389. #ifdef CPPHTTPLIB_SSL_ENABLED
  2390. auto port = 443;
  2391. SSLClient cli(host, port);
  2392. #else
  2393. auto port = 80;
  2394. Client cli(host, port);
  2395. #endif
  2396. cli.set_connection_timeout(std::chrono::seconds(2));
  2397. auto res = cli.Get("/");
  2398. ASSERT_TRUE(!res);
  2399. EXPECT_EQ(Error::Connection, res.error());
  2400. }
  2401. TEST(ConnectionErrorTest, InvalidHost2) {
  2402. auto host = "httpcan.org/";
  2403. #ifdef CPPHTTPLIB_SSL_ENABLED
  2404. SSLClient cli(host);
  2405. #else
  2406. Client cli(host);
  2407. #endif
  2408. cli.set_connection_timeout(std::chrono::seconds(2));
  2409. auto res = cli.Get("/");
  2410. ASSERT_TRUE(!res);
  2411. EXPECT_EQ(Error::Connection, res.error());
  2412. }
  2413. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2414. auto host = "httpcan.org/";
  2415. #ifdef CPPHTTPLIB_SSL_ENABLED
  2416. SSLClient cli(host);
  2417. #else
  2418. Client cli(host);
  2419. #endif
  2420. cli.set_connection_timeout(std::chrono::seconds(2));
  2421. auto res = cli.Get("/");
  2422. ASSERT_TRUE(!res);
  2423. stringstream s;
  2424. s << "error code: " << res.error();
  2425. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2426. }
  2427. TEST(ConnectionErrorTest, InvalidPort) {
  2428. auto host = "localhost";
  2429. auto port = 44380;
  2430. #ifdef CPPHTTPLIB_SSL_ENABLED
  2431. SSLClient cli(host, port);
  2432. #else
  2433. Client cli(host, port);
  2434. #endif
  2435. cli.set_connection_timeout(std::chrono::seconds(2));
  2436. auto res = cli.Get("/");
  2437. ASSERT_TRUE(!res);
  2438. EXPECT_TRUE(Error::Connection == res.error() ||
  2439. Error::ConnectionTimeout == res.error());
  2440. }
  2441. TEST(ConnectionErrorTest, Timeout_Online) {
  2442. auto host = "google.com";
  2443. #ifdef CPPHTTPLIB_SSL_ENABLED
  2444. auto port = 44380;
  2445. SSLClient cli(host, port);
  2446. #else
  2447. auto port = 8080;
  2448. Client cli(host, port);
  2449. #endif
  2450. cli.set_connection_timeout(std::chrono::seconds(2));
  2451. // only probe one address type so that the error reason
  2452. // correlates to the timed-out IPv4, not the unsupported
  2453. // IPv6 connection attempt
  2454. cli.set_address_family(AF_INET);
  2455. auto res = cli.Get("/");
  2456. ASSERT_TRUE(!res);
  2457. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2458. }
  2459. TEST(CancelTest, NoCancel_Online) {
  2460. auto host = "httpbingo.org";
  2461. auto path = std::string{"/range/32"};
  2462. #ifdef CPPHTTPLIB_SSL_ENABLED
  2463. auto port = 443;
  2464. SSLClient cli(host, port);
  2465. #else
  2466. auto port = 80;
  2467. Client cli(host, port);
  2468. #endif
  2469. cli.set_connection_timeout(std::chrono::seconds(5));
  2470. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2472. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2473. EXPECT_EQ(StatusCode::OK_200, res->status);
  2474. }
  2475. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2476. // Use /bytes with a large payload so that the DownloadProgress callback
  2477. // (which only fires for Content-Length responses) is invoked before the
  2478. // entire body is received, giving cancellation a chance to fire.
  2479. auto host = "httpbingo.org";
  2480. auto path = std::string{"/bytes/524288"};
  2481. #ifdef CPPHTTPLIB_SSL_ENABLED
  2482. auto port = 443;
  2483. SSLClient cli(host, port);
  2484. #else
  2485. auto port = 80;
  2486. Client cli(host, port);
  2487. #endif
  2488. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2489. cli.set_connection_timeout(std::chrono::seconds(5));
  2490. ASSERT_TRUE(!res);
  2491. EXPECT_EQ(Error::Canceled, res.error());
  2492. }
  2493. TEST(CancelTest, WithCancelLargePayload_Online) {
  2494. auto host = "httpbingo.org";
  2495. auto path = std::string{"/bytes/524288"};
  2496. #ifdef CPPHTTPLIB_SSL_ENABLED
  2497. auto port = 443;
  2498. SSLClient cli(host, port);
  2499. #else
  2500. auto port = 80;
  2501. Client cli(host, port);
  2502. #endif
  2503. cli.set_connection_timeout(std::chrono::seconds(5));
  2504. uint32_t count = 0;
  2505. auto res =
  2506. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2507. ASSERT_TRUE(!res);
  2508. EXPECT_EQ(Error::Canceled, res.error());
  2509. }
  2510. TEST(CancelTest, NoCancelPost) {
  2511. Server svr;
  2512. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2513. res.set_content("Hello World!", "text/plain");
  2514. });
  2515. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2516. auto se = detail::scope_exit([&] {
  2517. svr.stop();
  2518. thread.join();
  2519. ASSERT_FALSE(svr.is_running());
  2520. });
  2521. svr.wait_until_ready();
  2522. Client cli(HOST, PORT);
  2523. cli.set_connection_timeout(std::chrono::seconds(5));
  2524. auto res =
  2525. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2526. "application/json", [](uint64_t, uint64_t) { return true; });
  2527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2528. EXPECT_EQ("Hello World!", res->body);
  2529. EXPECT_EQ(StatusCode::OK_200, res->status);
  2530. }
  2531. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2532. Server svr;
  2533. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2534. res.set_content("Hello World!", "text/plain");
  2535. });
  2536. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2537. auto se = detail::scope_exit([&] {
  2538. svr.stop();
  2539. thread.join();
  2540. ASSERT_FALSE(svr.is_running());
  2541. });
  2542. svr.wait_until_ready();
  2543. Client cli(HOST, PORT);
  2544. cli.set_connection_timeout(std::chrono::seconds(5));
  2545. auto res =
  2546. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2547. "application/json", [](uint64_t, uint64_t) { return false; });
  2548. ASSERT_TRUE(!res);
  2549. EXPECT_EQ(Error::Canceled, res.error());
  2550. }
  2551. TEST(CancelTest, WithCancelLargePayloadPost) {
  2552. Server svr;
  2553. svr.set_payload_max_length(200 * 1024 * 1024);
  2554. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2555. res.set_content(LARGE_DATA, "text/plain");
  2556. });
  2557. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2558. auto se = detail::scope_exit([&] {
  2559. svr.stop();
  2560. thread.join();
  2561. ASSERT_FALSE(svr.is_running());
  2562. });
  2563. svr.wait_until_ready();
  2564. Client cli(HOST, PORT);
  2565. cli.set_payload_max_length(200 * 1024 * 1024);
  2566. cli.set_connection_timeout(std::chrono::seconds(5));
  2567. auto res =
  2568. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2569. "application/json", [](uint64_t, uint64_t) { return false; });
  2570. ASSERT_TRUE(!res);
  2571. EXPECT_EQ(Error::Canceled, res.error());
  2572. }
  2573. TEST(CancelTest, NoCancelPut) {
  2574. Server svr;
  2575. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2576. res.set_content("Hello World!", "text/plain");
  2577. });
  2578. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2579. auto se = detail::scope_exit([&] {
  2580. svr.stop();
  2581. thread.join();
  2582. ASSERT_FALSE(svr.is_running());
  2583. });
  2584. svr.wait_until_ready();
  2585. Client cli(HOST, PORT);
  2586. cli.set_connection_timeout(std::chrono::seconds(5));
  2587. auto res =
  2588. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2589. "application/json", [](uint64_t, uint64_t) { return true; });
  2590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2591. EXPECT_EQ("Hello World!", res->body);
  2592. EXPECT_EQ(StatusCode::OK_200, res->status);
  2593. }
  2594. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2595. Server svr;
  2596. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2597. res.set_content("Hello World!", "text/plain");
  2598. });
  2599. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2600. auto se = detail::scope_exit([&] {
  2601. svr.stop();
  2602. thread.join();
  2603. ASSERT_FALSE(svr.is_running());
  2604. });
  2605. svr.wait_until_ready();
  2606. Client cli(HOST, PORT);
  2607. cli.set_connection_timeout(std::chrono::seconds(5));
  2608. auto res =
  2609. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2610. "application/json", [](uint64_t, uint64_t) { return false; });
  2611. ASSERT_TRUE(!res);
  2612. EXPECT_EQ(Error::Canceled, res.error());
  2613. }
  2614. TEST(CancelTest, WithCancelLargePayloadPut) {
  2615. Server svr;
  2616. svr.set_payload_max_length(200 * 1024 * 1024);
  2617. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2618. res.set_content(LARGE_DATA, "text/plain");
  2619. });
  2620. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2621. auto se = detail::scope_exit([&] {
  2622. svr.stop();
  2623. thread.join();
  2624. ASSERT_FALSE(svr.is_running());
  2625. });
  2626. svr.wait_until_ready();
  2627. Client cli(HOST, PORT);
  2628. cli.set_payload_max_length(200 * 1024 * 1024);
  2629. cli.set_connection_timeout(std::chrono::seconds(5));
  2630. auto res =
  2631. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2632. "application/json", [](uint64_t, uint64_t) { return false; });
  2633. ASSERT_TRUE(!res);
  2634. EXPECT_EQ(Error::Canceled, res.error());
  2635. }
  2636. TEST(CancelTest, NoCancelPatch) {
  2637. Server svr;
  2638. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2639. res.set_content("Hello World!", "text/plain");
  2640. });
  2641. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2642. auto se = detail::scope_exit([&] {
  2643. svr.stop();
  2644. thread.join();
  2645. ASSERT_FALSE(svr.is_running());
  2646. });
  2647. svr.wait_until_ready();
  2648. Client cli(HOST, PORT);
  2649. cli.set_connection_timeout(std::chrono::seconds(5));
  2650. auto res =
  2651. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2652. "application/json", [](uint64_t, uint64_t) { return true; });
  2653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2654. EXPECT_EQ("Hello World!", res->body);
  2655. EXPECT_EQ(StatusCode::OK_200, res->status);
  2656. }
  2657. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2658. Server svr;
  2659. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2660. res.set_content("Hello World!", "text/plain");
  2661. });
  2662. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2663. auto se = detail::scope_exit([&] {
  2664. svr.stop();
  2665. thread.join();
  2666. ASSERT_FALSE(svr.is_running());
  2667. });
  2668. svr.wait_until_ready();
  2669. Client cli(HOST, PORT);
  2670. cli.set_connection_timeout(std::chrono::seconds(5));
  2671. auto res =
  2672. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2673. "application/json", [](uint64_t, uint64_t) { return false; });
  2674. ASSERT_TRUE(!res);
  2675. EXPECT_EQ(Error::Canceled, res.error());
  2676. }
  2677. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2678. Server svr;
  2679. svr.set_payload_max_length(200 * 1024 * 1024);
  2680. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2681. res.set_content(LARGE_DATA, "text/plain");
  2682. });
  2683. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2684. auto se = detail::scope_exit([&] {
  2685. svr.stop();
  2686. thread.join();
  2687. ASSERT_FALSE(svr.is_running());
  2688. });
  2689. svr.wait_until_ready();
  2690. Client cli(HOST, PORT);
  2691. cli.set_payload_max_length(200 * 1024 * 1024);
  2692. cli.set_connection_timeout(std::chrono::seconds(5));
  2693. auto res =
  2694. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2695. "application/json", [](uint64_t, uint64_t) { return false; });
  2696. ASSERT_TRUE(!res);
  2697. EXPECT_EQ(Error::Canceled, res.error());
  2698. }
  2699. TEST(CancelTest, NoCancelDelete) {
  2700. Server svr;
  2701. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2702. res.set_content("Hello World!", "text/plain");
  2703. });
  2704. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2705. auto se = detail::scope_exit([&] {
  2706. svr.stop();
  2707. thread.join();
  2708. ASSERT_FALSE(svr.is_running());
  2709. });
  2710. svr.wait_until_ready();
  2711. Client cli(HOST, PORT);
  2712. cli.set_connection_timeout(std::chrono::seconds(5));
  2713. auto res =
  2714. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2715. "application/json", [](uint64_t, uint64_t) { return true; });
  2716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2717. EXPECT_EQ("Hello World!", res->body);
  2718. EXPECT_EQ(StatusCode::OK_200, res->status);
  2719. }
  2720. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2721. Server svr;
  2722. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2723. res.set_content("Hello World!", "text/plain");
  2724. });
  2725. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2726. auto se = detail::scope_exit([&] {
  2727. svr.stop();
  2728. thread.join();
  2729. ASSERT_FALSE(svr.is_running());
  2730. });
  2731. svr.wait_until_ready();
  2732. Client cli(HOST, PORT);
  2733. cli.set_connection_timeout(std::chrono::seconds(5));
  2734. auto res =
  2735. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2736. "application/json", [](uint64_t, uint64_t) { return false; });
  2737. ASSERT_TRUE(!res);
  2738. EXPECT_EQ(Error::Canceled, res.error());
  2739. }
  2740. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2741. Server svr;
  2742. svr.set_payload_max_length(200 * 1024 * 1024);
  2743. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2744. res.set_content(LARGE_DATA, "text/plain");
  2745. });
  2746. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2747. auto se = detail::scope_exit([&] {
  2748. svr.stop();
  2749. thread.join();
  2750. ASSERT_FALSE(svr.is_running());
  2751. });
  2752. svr.wait_until_ready();
  2753. Client cli(HOST, PORT);
  2754. cli.set_payload_max_length(200 * 1024 * 1024);
  2755. cli.set_connection_timeout(std::chrono::seconds(5));
  2756. auto res =
  2757. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2758. "application/json", [](uint64_t, uint64_t) { return false; });
  2759. ASSERT_TRUE(!res);
  2760. EXPECT_EQ(Error::Canceled, res.error());
  2761. }
  2762. static std::string remove_whitespace(const std::string &input) {
  2763. std::string output;
  2764. output.reserve(input.size());
  2765. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2766. [](unsigned char c) { return !std::isspace(c); });
  2767. return output;
  2768. }
  2769. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2770. auto host = "httpbingo.org";
  2771. auto path = std::string{"/basic-auth/hello/world"};
  2772. #ifdef CPPHTTPLIB_SSL_ENABLED
  2773. auto port = 443;
  2774. SSLClient cli(host, port);
  2775. #else
  2776. auto port = 80;
  2777. Client cli(host, port);
  2778. #endif
  2779. {
  2780. auto res = cli.Get(path);
  2781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2782. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2783. }
  2784. {
  2785. auto res = cli.Get(
  2786. path, Headers{make_basic_authentication_header("hello", "world")});
  2787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2788. auto body = remove_whitespace(res->body);
  2789. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2790. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2791. EXPECT_EQ(StatusCode::OK_200, res->status);
  2792. }
  2793. {
  2794. cli.set_basic_auth("hello", "world");
  2795. auto res = cli.Get(path);
  2796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2797. auto body = remove_whitespace(res->body);
  2798. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2799. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2800. EXPECT_EQ(StatusCode::OK_200, res->status);
  2801. }
  2802. {
  2803. cli.set_basic_auth("hello", "bad");
  2804. auto res = cli.Get(path);
  2805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2806. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2807. }
  2808. {
  2809. cli.set_basic_auth("bad", "world");
  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. #ifdef CPPHTTPLIB_SSL_ENABLED
  2816. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2817. auto host = "httpbingo.org";
  2818. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2819. auto paths = std::vector<std::string>{
  2820. "/digest-auth/auth/hello/world/MD5",
  2821. "/digest-auth/auth/hello/world/SHA-256",
  2822. };
  2823. auto port = 443;
  2824. SSLClient cli(host, port);
  2825. {
  2826. auto res = cli.Get(unauth_path);
  2827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2828. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2829. }
  2830. {
  2831. cli.set_digest_auth("hello", "world");
  2832. for (const auto &path : paths) {
  2833. auto res = cli.Get(path.c_str());
  2834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2835. auto body = remove_whitespace(res->body);
  2836. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2837. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2838. EXPECT_EQ(StatusCode::OK_200, res->status);
  2839. }
  2840. cli.set_digest_auth("hello", "bad");
  2841. for (const auto &path : paths) {
  2842. auto res = cli.Get(path.c_str());
  2843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2844. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2845. }
  2846. }
  2847. }
  2848. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2849. // comma-separated list of challenges, and each challenge may itself carry a
  2850. // comma-separated auth-param list, so a server can legally offer Basic
  2851. // before Digest, either as two field lines or packed into one. Runs one 401
  2852. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2853. // value() joins them in receipt order) and checks that the retry carries a
  2854. // well-formed Digest Authorization header naming expected_realm.
  2855. static void
  2856. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2857. const std::string &expected_realm) {
  2858. std::atomic<int> hits{0};
  2859. Server svr;
  2860. svr.Get("/x", [&](const Request &req, Response &res) {
  2861. if (++hits == 1) {
  2862. res.status = StatusCode::Unauthorized_401;
  2863. for (const auto &challenge : challenges) {
  2864. res.set_header("WWW-Authenticate", challenge);
  2865. }
  2866. } else {
  2867. auto authorization = req.get_header_value("Authorization");
  2868. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2869. EXPECT_NE(std::string::npos,
  2870. authorization.find("realm=\"" + expected_realm + "\""));
  2871. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2872. res.set_content("ok", "text/plain");
  2873. }
  2874. });
  2875. auto port = svr.bind_to_any_port(HOST);
  2876. std::thread t([&]() { svr.listen_after_bind(); });
  2877. auto se = detail::scope_exit([&] {
  2878. svr.stop();
  2879. t.join();
  2880. });
  2881. svr.wait_until_ready();
  2882. Client cli(HOST, port);
  2883. cli.set_digest_auth("hello", "world");
  2884. auto res = cli.Get("/x");
  2885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2886. EXPECT_EQ(2, hits.load());
  2887. }
  2888. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2889. static const char *kDigestChallenge =
  2890. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2891. "algorithm=MD5";
  2892. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2893. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2894. "testrealm");
  2895. }
  2896. // Same challenge list with the schemes in the opposite order, to make sure
  2897. // the fix above didn't just special-case "Basic first".
  2898. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2899. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2900. "testrealm");
  2901. }
  2902. // A comma inside a quoted auth-param value must not be mistaken for the
  2903. // separator between two challenges (or two auth-params).
  2904. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2905. run_digest_challenge_list_test(
  2906. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2907. "algorithm=MD5"},
  2908. "test,realm");
  2909. }
  2910. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2911. // make_digest_authentication_header() dereferences both unconditionally, so
  2912. // a server sending a challenge missing either one must not be treated as
  2913. // usable -- doing so used to crash the client with std::out_of_range.
  2914. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2915. Server svr;
  2916. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2917. res.status = StatusCode::Unauthorized_401;
  2918. res.set_header("WWW-Authenticate", challenge);
  2919. });
  2920. auto port = svr.bind_to_any_port(HOST);
  2921. std::thread t([&]() { svr.listen_after_bind(); });
  2922. auto se = detail::scope_exit([&] {
  2923. svr.stop();
  2924. t.join();
  2925. });
  2926. svr.wait_until_ready();
  2927. Client cli(HOST, port);
  2928. cli.set_digest_auth("hello", "world");
  2929. auto res = cli.Get("/x");
  2930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2931. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2932. }
  2933. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2934. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2935. }
  2936. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2937. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2938. }
  2939. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2940. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2941. }
  2942. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  2943. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  2944. // when storing the values, so the header builder has to re-escape them (and
  2945. // keep algorithm a bare token); otherwise the value breaks out of its
  2946. // quoted-string and injects extra auth-params into the client's Authorization.
  2947. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  2948. std::atomic<int> hits{0};
  2949. std::string authorization;
  2950. Server svr;
  2951. svr.Get("/x", [&](const Request &req, Response &res) {
  2952. if (++hits == 1) {
  2953. res.status = StatusCode::Unauthorized_401;
  2954. // On the wire the quotes embedded in the values are backslash-escaped.
  2955. res.set_header("WWW-Authenticate",
  2956. "Digest realm=\"testrealm\", "
  2957. "nonce=\"n\\\"; injected=\\\"x\", "
  2958. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  2959. } else {
  2960. authorization = req.get_header_value("Authorization");
  2961. res.set_content("ok", "text/plain");
  2962. }
  2963. });
  2964. auto port = svr.bind_to_any_port(HOST);
  2965. std::thread t([&]() { svr.listen_after_bind(); });
  2966. auto se = detail::scope_exit([&] {
  2967. svr.stop();
  2968. t.join();
  2969. });
  2970. svr.wait_until_ready();
  2971. Client cli(HOST, port);
  2972. cli.set_digest_auth("hello", "world");
  2973. auto res = cli.Get("/x");
  2974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2975. EXPECT_EQ(2, hits.load());
  2976. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2977. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  2978. // inside its quoted-string rather than starting an "injected" auth-param.
  2979. EXPECT_NE(std::string::npos,
  2980. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  2981. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  2982. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  2983. }
  2984. #endif
  2985. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2986. auto host = "google.com";
  2987. auto another_host = "example.com";
  2988. auto wrong_ip = "0.0.0.0";
  2989. #ifdef CPPHTTPLIB_SSL_ENABLED
  2990. SSLClient cli(host);
  2991. #else
  2992. Client cli(host);
  2993. #endif
  2994. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2995. auto res = cli.Get("/");
  2996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2997. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2998. }
  2999. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3000. auto host = "google.com";
  3001. auto wrong_ip = "0.0.0.0";
  3002. #ifdef CPPHTTPLIB_SSL_ENABLED
  3003. SSLClient cli(host);
  3004. #else
  3005. Client cli(host);
  3006. #endif
  3007. cli.set_hostname_addr_map({{host, wrong_ip}});
  3008. auto res = cli.Get("/");
  3009. ASSERT_TRUE(!res);
  3010. EXPECT_EQ(Error::Connection, res.error());
  3011. }
  3012. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3013. // A mapped value that is not an IP literal must be resolved. "localhost"
  3014. // resolves from the hosts file, so this test needs no external DNS.
  3015. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3016. auto host = "target.invalid";
  3017. Server svr;
  3018. std::string received_host;
  3019. svr.Get("/hi", [&](const Request &req, Response &res) {
  3020. received_host = req.get_header_value("Host");
  3021. res.set_content("Hello World!", "text/plain");
  3022. });
  3023. auto port = svr.bind_to_any_port(HOST);
  3024. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3025. auto se = detail::scope_exit([&] {
  3026. svr.stop();
  3027. thread.join();
  3028. ASSERT_FALSE(svr.is_running());
  3029. });
  3030. svr.wait_until_ready();
  3031. Client cli(host, port);
  3032. cli.set_hostname_addr_map({{host, HOST}});
  3033. auto res = cli.Get("/hi");
  3034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3035. EXPECT_EQ(StatusCode::OK_200, res->status);
  3036. // The mapping only redirects the connection; the identity stays host_.
  3037. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3038. }
  3039. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3040. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3041. auto host = "target.invalid";
  3042. Server svr;
  3043. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3044. res.set_content("Hello World!", "text/plain");
  3045. });
  3046. auto port = svr.bind_to_any_port("127.0.0.1");
  3047. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3048. auto se = detail::scope_exit([&] {
  3049. svr.stop();
  3050. thread.join();
  3051. ASSERT_FALSE(svr.is_running());
  3052. });
  3053. svr.wait_until_ready();
  3054. Client cli(host, port);
  3055. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3056. auto res = cli.Get("/hi");
  3057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3058. EXPECT_EQ(StatusCode::OK_200, res->status);
  3059. }
  3060. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3061. // An empty mapped value must leave host_ as the connection target. Without
  3062. // that guard the empty value would become the host argument, getaddrinfo
  3063. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3064. // loopback - silently connecting somewhere the caller never asked for.
  3065. // The server listens on loopback, so such a fallback would succeed and is
  3066. // therefore observable as a failure of this test.
  3067. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3068. Server svr;
  3069. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3070. res.set_content("Hello World!", "text/plain");
  3071. });
  3072. auto port = svr.bind_to_any_port(HOST);
  3073. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3074. auto se = detail::scope_exit([&] {
  3075. svr.stop();
  3076. thread.join();
  3077. ASSERT_FALSE(svr.is_running());
  3078. });
  3079. svr.wait_until_ready();
  3080. Client cli(blackhole, port);
  3081. cli.set_hostname_addr_map({{blackhole, ""}});
  3082. cli.set_connection_timeout(1);
  3083. auto res = cli.Get("/hi");
  3084. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3085. }
  3086. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3087. auto host = "httpbingo.org";
  3088. auto path = std::string{"/absolute-redirect/3"};
  3089. #ifdef CPPHTTPLIB_SSL_ENABLED
  3090. SSLClient cli(host);
  3091. #else
  3092. Client cli(host);
  3093. #endif
  3094. cli.set_follow_location(true);
  3095. auto res = cli.Get(path);
  3096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3097. EXPECT_EQ(StatusCode::OK_200, res->status);
  3098. }
  3099. TEST(RedirectTest, Redirect_Online) {
  3100. auto host = "httpbingo.org";
  3101. auto path = std::string{"/redirect/3"};
  3102. #ifdef CPPHTTPLIB_SSL_ENABLED
  3103. SSLClient cli(host);
  3104. #else
  3105. Client cli(host);
  3106. #endif
  3107. cli.set_follow_location(true);
  3108. auto res = cli.Get(path);
  3109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3110. EXPECT_EQ(StatusCode::OK_200, res->status);
  3111. }
  3112. TEST(RelativeRedirectTest, Redirect_Online) {
  3113. auto host = "httpbingo.org";
  3114. auto path = std::string{"/relative-redirect/3"};
  3115. #ifdef CPPHTTPLIB_SSL_ENABLED
  3116. SSLClient cli(host);
  3117. #else
  3118. Client cli(host);
  3119. #endif
  3120. cli.set_follow_location(true);
  3121. auto res = cli.Get(path);
  3122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3123. EXPECT_EQ(StatusCode::OK_200, res->status);
  3124. }
  3125. TEST(TooManyRedirectTest, Redirect_Online) {
  3126. auto host = "httpbingo.org";
  3127. auto path = std::string{"/redirect/21"};
  3128. #ifdef CPPHTTPLIB_SSL_ENABLED
  3129. SSLClient cli(host);
  3130. #else
  3131. Client cli(host);
  3132. #endif
  3133. cli.set_follow_location(true);
  3134. auto res = cli.Get(path);
  3135. ASSERT_TRUE(!res);
  3136. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3137. }
  3138. #ifdef CPPHTTPLIB_SSL_ENABLED
  3139. TEST(YahooRedirectTest, Redirect_Online) {
  3140. Client cli("yahoo.com");
  3141. auto res = cli.Get("/");
  3142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3143. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3144. cli.set_follow_location(true);
  3145. res = cli.Get("/");
  3146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3147. EXPECT_EQ(StatusCode::OK_200, res->status);
  3148. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3149. }
  3150. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3151. #define REDIR_HOST "httpbingo.org"
  3152. #define REDIR_PATH "/redirect-to"
  3153. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3154. SSLClient cli(REDIR_HOST);
  3155. cli.set_follow_location(true);
  3156. auto res =
  3157. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3159. EXPECT_EQ(StatusCode::OK_200, res->status);
  3160. }
  3161. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3162. SSLClient cli(REDIR_HOST);
  3163. cli.set_follow_location(true);
  3164. Params params;
  3165. params.emplace("url", "http://example.com");
  3166. params.emplace("status_code", "302");
  3167. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3169. EXPECT_EQ(StatusCode::OK_200, res->status);
  3170. }
  3171. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3172. SSLClient cli(REDIR_HOST);
  3173. cli.set_follow_location(true);
  3174. Params params;
  3175. params.emplace("url", "http://example.com");
  3176. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3178. EXPECT_EQ(StatusCode::OK_200, res->status);
  3179. }
  3180. TEST(UrlWithSpace, Redirect_Online) {
  3181. SSLClient cli("edge.forgecdn.net");
  3182. cli.set_follow_location(true);
  3183. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3185. EXPECT_EQ(StatusCode::OK_200, res->status);
  3186. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3187. }
  3188. #endif
  3189. #if !defined(_WIN32) && !defined(_WIN64)
  3190. TEST(ReceiveSignals, Signal) {
  3191. auto setupSignalHandlers = []() {
  3192. struct sigaction act;
  3193. sigemptyset(&act.sa_mask);
  3194. act.sa_flags = SA_SIGINFO;
  3195. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3196. switch (sig) {
  3197. case SIGINT:
  3198. default: break;
  3199. }
  3200. };
  3201. ::sigaction(SIGINT, &act, nullptr);
  3202. };
  3203. Server svr;
  3204. int port = 0;
  3205. auto thread = std::thread([&]() {
  3206. setupSignalHandlers();
  3207. port = svr.bind_to_any_port(HOST);
  3208. svr.listen_after_bind();
  3209. });
  3210. auto se = detail::scope_exit([&] {
  3211. svr.stop();
  3212. thread.join();
  3213. ASSERT_FALSE(svr.is_running());
  3214. });
  3215. svr.wait_until_ready();
  3216. ASSERT_TRUE(svr.is_running());
  3217. pthread_kill(thread.native_handle(), SIGINT);
  3218. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3219. ASSERT_TRUE(svr.is_running());
  3220. }
  3221. #endif
  3222. TEST(RedirectToDifferentPort, Redirect) {
  3223. Server svr1;
  3224. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3225. res.set_content("Hello World!", "text/plain");
  3226. });
  3227. int svr1_port = 0;
  3228. auto thread1 = std::thread([&]() {
  3229. svr1_port = svr1.bind_to_any_port(HOST);
  3230. svr1.listen_after_bind();
  3231. });
  3232. Server svr2;
  3233. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3234. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3235. });
  3236. int svr2_port = 0;
  3237. auto thread2 = std::thread([&]() {
  3238. svr2_port = svr2.bind_to_any_port(HOST);
  3239. svr2.listen_after_bind();
  3240. });
  3241. auto se = detail::scope_exit([&] {
  3242. svr2.stop();
  3243. thread2.join();
  3244. svr1.stop();
  3245. thread1.join();
  3246. ASSERT_FALSE(svr2.is_running());
  3247. ASSERT_FALSE(svr1.is_running());
  3248. });
  3249. svr1.wait_until_ready();
  3250. svr2.wait_until_ready();
  3251. Client cli("localhost", svr2_port);
  3252. cli.set_follow_location(true);
  3253. auto res = cli.Get("/2");
  3254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3255. EXPECT_EQ(StatusCode::OK_200, res->status);
  3256. EXPECT_EQ("Hello World!", res->body);
  3257. }
  3258. // GET /redir on one server redirects to /target on another port, so the
  3259. // client follows it with a new client.
  3260. static Result
  3261. GetThroughRedirectToDifferentPort(Server::Handler target,
  3262. const std::function<void(Client &)> &setup,
  3263. const Headers &headers = Headers()) {
  3264. Server target_svr;
  3265. target_svr.Get("/target", target);
  3266. int target_port = 0;
  3267. auto target_thread = std::thread([&]() {
  3268. target_port = target_svr.bind_to_any_port(HOST);
  3269. target_svr.listen_after_bind();
  3270. });
  3271. Server origin_svr;
  3272. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3273. res.set_redirect(
  3274. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3275. });
  3276. int origin_port = 0;
  3277. auto origin_thread = std::thread([&]() {
  3278. origin_port = origin_svr.bind_to_any_port(HOST);
  3279. origin_svr.listen_after_bind();
  3280. });
  3281. auto se = detail::scope_exit([&] {
  3282. origin_svr.stop();
  3283. origin_thread.join();
  3284. target_svr.stop();
  3285. target_thread.join();
  3286. });
  3287. target_svr.wait_until_ready();
  3288. origin_svr.wait_until_ready();
  3289. Client cli("localhost", origin_port);
  3290. cli.set_follow_location(true);
  3291. setup(cli);
  3292. return cli.Get("/redir", headers);
  3293. }
  3294. static void
  3295. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3296. std::string captured_authorization;
  3297. auto result = GetThroughRedirectToDifferentPort(
  3298. [&](const Request &req, Response &res) {
  3299. captured_authorization = req.get_header_value("Authorization");
  3300. res.set_content("OK", "text/plain");
  3301. },
  3302. set_auth);
  3303. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3304. EXPECT_EQ(StatusCode::OK_200, result->status);
  3305. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3306. EXPECT_TRUE(captured_authorization.empty());
  3307. }
  3308. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3309. TestDoNotForwardCredentialsOnRedirect(
  3310. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3311. }
  3312. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3313. TestDoNotForwardCredentialsOnRedirect(
  3314. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3315. }
  3316. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3317. std::string captured_cookie;
  3318. auto result = GetThroughRedirectToDifferentPort(
  3319. [&](const Request &req, Response &res) {
  3320. captured_cookie = req.get_header_value("Cookie");
  3321. res.set_content("OK", "text/plain");
  3322. },
  3323. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3324. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3325. EXPECT_EQ(StatusCode::OK_200, result->status);
  3326. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3327. EXPECT_TRUE(captured_cookie.empty());
  3328. }
  3329. TEST(RedirectToSamePort, ForwardCookie) {
  3330. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3331. // header so that ordinary session flows keep working.
  3332. Server svr;
  3333. std::string captured_cookie;
  3334. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3335. res.set_redirect("/target", 302);
  3336. });
  3337. svr.Get("/target", [&](const Request &req, Response &res) {
  3338. captured_cookie = req.get_header_value("Cookie");
  3339. res.set_content("OK", "text/plain");
  3340. });
  3341. auto port = svr.bind_to_any_port(HOST);
  3342. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3343. auto se = detail::scope_exit([&] {
  3344. svr.stop();
  3345. thread.join();
  3346. ASSERT_FALSE(svr.is_running());
  3347. });
  3348. svr.wait_until_ready();
  3349. Client cli(HOST, port);
  3350. cli.set_follow_location(true);
  3351. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3352. auto res = cli.Get("/redir", headers);
  3353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3354. EXPECT_EQ(StatusCode::OK_200, res->status);
  3355. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3356. }
  3357. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3358. std::string authorization;
  3359. std::string trace_id;
  3360. auto result = GetThroughRedirectToDifferentPort(
  3361. [&](const Request &req, Response &res) {
  3362. authorization = req.get_header_value("Authorization");
  3363. trace_id = req.get_header_value("X-Trace-Id");
  3364. res.set_content("OK", "text/plain");
  3365. },
  3366. [](Client &cli) {
  3367. cli.set_default_headers(
  3368. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3369. });
  3370. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3371. EXPECT_EQ(StatusCode::OK_200, result->status);
  3372. // Like a header given with the request, a default one goes along unless it
  3373. // carries credentials (RFC 9110 15.4).
  3374. EXPECT_TRUE(authorization.empty());
  3375. EXPECT_EQ("42", trace_id);
  3376. }
  3377. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3378. auto result = GetThroughRedirectToDifferentPort(
  3379. [](const Request &, Response &res) {
  3380. res.set_content(std::string(2048, 'x'), "text/plain");
  3381. },
  3382. [](Client &cli) { cli.set_payload_max_length(1024); });
  3383. EXPECT_FALSE(result);
  3384. }
  3385. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3386. auto result = GetThroughRedirectToDifferentPort(
  3387. [](const Request &req, Response &res) {
  3388. // Answer after a second, or once the client gives up.
  3389. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3390. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3391. }
  3392. res.set_content("late", "text/plain");
  3393. },
  3394. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3395. ASSERT_FALSE(result);
  3396. EXPECT_EQ(Error::Read, result.error());
  3397. }
  3398. #ifdef CPPHTTPLIB_SSL_ENABLED
  3399. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3400. auto result = GetThroughRedirectToDifferentPort(
  3401. [](const Request &, Response &res) {
  3402. res.status = StatusCode::Unauthorized_401;
  3403. res.set_header("WWW-Authenticate",
  3404. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3405. },
  3406. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3407. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3408. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3409. }
  3410. #endif
  3411. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3412. Server svr;
  3413. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3414. // Port number that overflows int — should not crash
  3415. res.set_redirect("http://localhost:99999999999999999999/target");
  3416. });
  3417. auto port = svr.bind_to_any_port(HOST);
  3418. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3419. auto se = detail::scope_exit([&] {
  3420. svr.stop();
  3421. thread.join();
  3422. ASSERT_FALSE(svr.is_running());
  3423. });
  3424. svr.wait_until_ready();
  3425. Client cli(HOST, port);
  3426. cli.set_follow_location(true);
  3427. auto res = cli.Get("/redir");
  3428. // Should fail gracefully, not crash (no valid response due to bad port)
  3429. EXPECT_FALSE(res);
  3430. }
  3431. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3432. Server svr;
  3433. auto port = svr.bind_to_any_port(HOST);
  3434. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3435. // The server's own port followed by junk must not be followed
  3436. res.set_redirect("http://" + std::string(HOST) + ":" +
  3437. std::to_string(port) + "junk/target");
  3438. });
  3439. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3440. res.set_content("target", "text/plain");
  3441. });
  3442. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3443. auto se = detail::scope_exit([&] {
  3444. svr.stop();
  3445. thread.join();
  3446. ASSERT_FALSE(svr.is_running());
  3447. });
  3448. svr.wait_until_ready();
  3449. Client cli(HOST, port);
  3450. cli.set_follow_location(true);
  3451. auto res = cli.Get("/redir");
  3452. EXPECT_FALSE(res);
  3453. }
  3454. TEST(RedirectFromPageWithContent, Redirect) {
  3455. Server svr;
  3456. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3457. res.set_content("___", "text/plain");
  3458. res.set_redirect("/2");
  3459. });
  3460. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3461. res.set_content("Hello World!", "text/plain");
  3462. });
  3463. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3464. auto se = detail::scope_exit([&] {
  3465. svr.stop();
  3466. th.join();
  3467. ASSERT_FALSE(svr.is_running());
  3468. });
  3469. svr.wait_until_ready();
  3470. {
  3471. Client cli("localhost", PORT);
  3472. cli.set_follow_location(true);
  3473. std::string body;
  3474. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3475. body.append(data, data_length);
  3476. return true;
  3477. });
  3478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3479. EXPECT_EQ(StatusCode::OK_200, res->status);
  3480. EXPECT_EQ("Hello World!", body);
  3481. }
  3482. {
  3483. Client cli("localhost", PORT);
  3484. std::string body;
  3485. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3486. body.append(data, data_length);
  3487. return true;
  3488. });
  3489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3490. EXPECT_EQ(StatusCode::Found_302, res->status);
  3491. EXPECT_EQ("___", body);
  3492. }
  3493. }
  3494. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3495. Server svr;
  3496. auto port_str = std::to_string(PORT);
  3497. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3498. auto expected_host = "[::1]:" + port_str;
  3499. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3500. res.set_content("___", "text/plain");
  3501. // res.set_redirect("/2");
  3502. res.set_redirect(redirect_url);
  3503. });
  3504. svr.Get("/2", [&](const Request &req, Response &res) {
  3505. auto host_header = req.headers.find("Host");
  3506. ASSERT_TRUE(host_header != req.headers.end());
  3507. EXPECT_EQ(expected_host, host_header->second);
  3508. res.set_content("Hello World!", "text/plain");
  3509. });
  3510. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3511. auto se = detail::scope_exit([&] {
  3512. svr.stop();
  3513. th.join();
  3514. ASSERT_FALSE(svr.is_running());
  3515. });
  3516. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3517. // actually starts anything, so the condition !svr.is_running() will
  3518. // always remain true, and the loop never stops.
  3519. // This basically counts how many milliseconds have passed since the
  3520. // call to svr.listen(), and if after 5 seconds nothing started yet
  3521. // aborts the test.
  3522. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3523. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3524. ASSERT_LT(milliseconds, 5000U);
  3525. }
  3526. {
  3527. Client cli("::1", PORT);
  3528. cli.set_follow_location(true);
  3529. std::string body;
  3530. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3531. body.append(data, data_length);
  3532. return true;
  3533. });
  3534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3535. EXPECT_EQ(StatusCode::OK_200, res->status);
  3536. EXPECT_EQ("Hello World!", body);
  3537. }
  3538. {
  3539. Client cli("::1", PORT);
  3540. std::string body;
  3541. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3542. body.append(data, data_length);
  3543. return true;
  3544. });
  3545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3546. EXPECT_EQ(StatusCode::Found_302, res->status);
  3547. EXPECT_EQ("___", body);
  3548. }
  3549. }
  3550. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3551. Server svr;
  3552. svr.Get("/foo", [](const Request &req, Response &res) {
  3553. auto a = req.params.find("a");
  3554. if (a != req.params.end()) {
  3555. res.set_content((*a).second, "text/plain");
  3556. res.status = StatusCode::OK_200;
  3557. } else {
  3558. res.status = StatusCode::BadRequest_400;
  3559. }
  3560. });
  3561. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3562. auto se = detail::scope_exit([&] {
  3563. svr.stop();
  3564. thread.join();
  3565. ASSERT_FALSE(svr.is_running());
  3566. });
  3567. svr.wait_until_ready();
  3568. {
  3569. Client cli(HOST, PORT);
  3570. cli.set_path_encode(false);
  3571. auto res = cli.Get("/foo?a=explicitly+encoded");
  3572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3573. EXPECT_EQ(StatusCode::OK_200, res->status);
  3574. // This expects it back with a space, as the `+` won't have been
  3575. // url-encoded, and server-side the params get decoded turning `+`
  3576. // into spaces.
  3577. EXPECT_EQ("explicitly encoded", res->body);
  3578. }
  3579. }
  3580. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3581. // When path encoding is disabled the client must transmit the supplied
  3582. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3583. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3584. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3585. // than a space (0x20). Assert on the raw wire target to catch this.
  3586. Server svr;
  3587. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3588. svr.Get("/foo", [&](const Request &req, Response &res) {
  3589. EXPECT_EQ(expected_target, req.target);
  3590. res.status = StatusCode::OK_200;
  3591. });
  3592. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3593. auto se = detail::scope_exit([&] {
  3594. svr.stop();
  3595. thread.join();
  3596. ASSERT_FALSE(svr.is_running());
  3597. });
  3598. svr.wait_until_ready();
  3599. {
  3600. Client cli(HOST, PORT);
  3601. cli.set_path_encode(false);
  3602. auto res = cli.Get(expected_target.c_str());
  3603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3604. EXPECT_EQ(StatusCode::OK_200, res->status);
  3605. }
  3606. }
  3607. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3608. // `open_stream()` used to skip the path encoding that the buffered send
  3609. // path applies, so the same `path` produced different bytes in the request
  3610. // line depending on which API was used. Assert the two agree.
  3611. Server svr;
  3612. std::string target;
  3613. svr.Get(".*", [&](const Request &req, Response &res) {
  3614. target = req.target;
  3615. res.status = StatusCode::OK_200;
  3616. });
  3617. auto port = svr.bind_to_any_port(HOST);
  3618. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3619. auto se = detail::scope_exit([&] {
  3620. svr.stop();
  3621. thread.join();
  3622. ASSERT_FALSE(svr.is_running());
  3623. });
  3624. svr.wait_until_ready();
  3625. struct {
  3626. const char *path;
  3627. const char *expected;
  3628. } cases[] = {
  3629. {"/a b?x=1", "/a%20b?x=1"},
  3630. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3631. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3632. };
  3633. for (const auto &c : cases) {
  3634. Client cli(HOST, port);
  3635. target.clear();
  3636. auto res = cli.Get(c.path);
  3637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3638. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3639. auto buffered_target = target;
  3640. target.clear();
  3641. auto handle = cli.open_stream("GET", c.path);
  3642. EXPECT_TRUE(handle.is_valid())
  3643. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3644. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3645. }
  3646. }
  3647. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3648. // The `set_path_encode(false)` contract — transmit the supplied target
  3649. // verbatim — must hold for the streaming API too.
  3650. Server svr;
  3651. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3652. std::string target;
  3653. svr.Get("/foo", [&](const Request &req, Response &res) {
  3654. target = req.target;
  3655. res.status = StatusCode::OK_200;
  3656. });
  3657. auto port = svr.bind_to_any_port(HOST);
  3658. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3659. auto se = detail::scope_exit([&] {
  3660. svr.stop();
  3661. thread.join();
  3662. ASSERT_FALSE(svr.is_running());
  3663. });
  3664. svr.wait_until_ready();
  3665. {
  3666. Client cli(HOST, port);
  3667. cli.set_path_encode(false);
  3668. auto handle = cli.open_stream("GET", expected_target);
  3669. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3670. EXPECT_EQ(expected_target, target);
  3671. }
  3672. }
  3673. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3674. // With path encoding enabled a CR/LF in the target is percent-encoded
  3675. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3676. // write_request_line still backstops `set_path_encode(false)`, which is
  3677. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3678. Server svr;
  3679. // Captured before routing: the decoded path contains a newline, which a
  3680. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3681. std::string target;
  3682. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3683. target = req.target;
  3684. res.status = StatusCode::OK_200;
  3685. return Server::HandlerResponse::Handled;
  3686. });
  3687. auto port = svr.bind_to_any_port(HOST);
  3688. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3689. auto se = detail::scope_exit([&] {
  3690. svr.stop();
  3691. thread.join();
  3692. ASSERT_FALSE(svr.is_running());
  3693. });
  3694. svr.wait_until_ready();
  3695. {
  3696. Client cli(HOST, port);
  3697. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3698. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3699. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3700. }
  3701. }
  3702. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3703. // Every control character is percent-encoded, not just CR/LF, so the target
  3704. // passes the request-target check in write_request_line.
  3705. Server svr;
  3706. std::string target;
  3707. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3708. target = req.target;
  3709. res.status = StatusCode::OK_200;
  3710. return Server::HandlerResponse::Handled;
  3711. });
  3712. auto port = svr.bind_to_any_port(HOST);
  3713. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3714. auto se = detail::scope_exit([&] {
  3715. svr.stop();
  3716. thread.join();
  3717. ASSERT_FALSE(svr.is_running());
  3718. });
  3719. svr.wait_until_ready();
  3720. {
  3721. Client cli(HOST, port);
  3722. auto res = cli.Get("/a\tb\x1b\x7f");
  3723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3724. EXPECT_EQ("/a%09b%1B%7F", target);
  3725. }
  3726. }
  3727. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3728. // Nothing may reach the wire: a raw CR/LF target would split the request
  3729. // line and inject headers.
  3730. Server svr;
  3731. // Pre-routing so that "not called" means nothing reached the server at all,
  3732. // rather than merely failing to match a handler pattern.
  3733. auto handler_called = false;
  3734. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3735. handler_called = true;
  3736. res.status = StatusCode::OK_200;
  3737. return Server::HandlerResponse::Handled;
  3738. });
  3739. auto port = svr.bind_to_any_port(HOST);
  3740. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3741. auto se = detail::scope_exit([&] {
  3742. svr.stop();
  3743. thread.join();
  3744. ASSERT_FALSE(svr.is_running());
  3745. });
  3746. svr.wait_until_ready();
  3747. {
  3748. Client cli(HOST, port);
  3749. cli.set_path_encode(false);
  3750. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3751. EXPECT_FALSE(handle.is_valid());
  3752. EXPECT_EQ(Error::Write, handle.error);
  3753. EXPECT_FALSE(handler_called);
  3754. }
  3755. }
  3756. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3757. // Which of the two branches runs is decided by whether the query component
  3758. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3759. // an empty query and must still fall back to building one from
  3760. // `req.params`, while a non-empty query must win over `req.params`.
  3761. Server svr;
  3762. std::string target;
  3763. svr.Get("/foo", [&](const Request &req, Response &res) {
  3764. target = req.target;
  3765. res.status = StatusCode::OK_200;
  3766. });
  3767. auto port = svr.bind_to_any_port(HOST);
  3768. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3769. auto se = detail::scope_exit([&] {
  3770. svr.stop();
  3771. thread.join();
  3772. ASSERT_FALSE(svr.is_running());
  3773. });
  3774. svr.wait_until_ready();
  3775. {
  3776. // Trailing `?` -> empty query component -> `req.params` is used.
  3777. Client cli(HOST, port);
  3778. Request req;
  3779. req.method = "GET";
  3780. req.path = "/foo?";
  3781. req.params.emplace("a", "1");
  3782. target.clear();
  3783. auto res = cli.send(req);
  3784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3785. EXPECT_EQ("/foo?a=1", target);
  3786. }
  3787. {
  3788. // Non-empty query in `req.path` -> `req.params` is not appended.
  3789. Client cli(HOST, port);
  3790. Request req;
  3791. req.method = "GET";
  3792. req.path = "/foo?b=2";
  3793. req.params.emplace("a", "1");
  3794. target.clear();
  3795. auto res = cli.send(req);
  3796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3797. EXPECT_EQ("/foo?b=2", target);
  3798. }
  3799. }
  3800. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3801. Server svr;
  3802. svr.Get("/", [](const Request &req, Response &) {
  3803. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3804. });
  3805. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3806. auto se = detail::scope_exit([&] {
  3807. svr.stop();
  3808. thread.join();
  3809. ASSERT_FALSE(svr.is_running());
  3810. });
  3811. svr.wait_until_ready();
  3812. {
  3813. Client cli(HOST, PORT);
  3814. cli.set_path_encode(false);
  3815. auto res = cli.Get("/?something=%0A");
  3816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3817. EXPECT_EQ(StatusCode::OK_200, res->status);
  3818. }
  3819. }
  3820. TEST(BindServerTest, BindDualStack) {
  3821. Server svr;
  3822. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3823. res.set_content("Hello World!", "text/plain");
  3824. });
  3825. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3826. auto se = detail::scope_exit([&] {
  3827. svr.stop();
  3828. thread.join();
  3829. ASSERT_FALSE(svr.is_running());
  3830. });
  3831. svr.wait_until_ready();
  3832. {
  3833. Client cli("127.0.0.1", PORT);
  3834. auto res = cli.Get("/1");
  3835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3836. EXPECT_EQ(StatusCode::OK_200, res->status);
  3837. EXPECT_EQ("Hello World!", res->body);
  3838. }
  3839. {
  3840. Client cli("::1", PORT);
  3841. auto res = cli.Get("/1");
  3842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3843. EXPECT_EQ(StatusCode::OK_200, res->status);
  3844. EXPECT_EQ("Hello World!", res->body);
  3845. }
  3846. }
  3847. TEST(BindServerTest, BindAndListenSeparately) {
  3848. Server svr;
  3849. int port = svr.bind_to_any_port("0.0.0.0");
  3850. ASSERT_TRUE(svr.is_valid());
  3851. ASSERT_TRUE(port > 0);
  3852. svr.stop();
  3853. }
  3854. // Reports whether anything is still listening on a loopback port. A plain
  3855. // connect() is used instead of a Client request because a socket left bound by
  3856. // mistake accepts the connection into its backlog and never answers, which
  3857. // would hang the test instead of failing it.
  3858. static bool is_loopback_port_accepting(int port) {
  3859. sockaddr_in addr{};
  3860. addr.sin_family = AF_INET;
  3861. addr.sin_port = htons(static_cast<uint16_t>(port));
  3862. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3863. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3864. EXPECT_NE(sock, INVALID_SOCKET);
  3865. if (sock == INVALID_SOCKET) { return false; }
  3866. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3867. static_cast<socklen_t>(sizeof(addr)));
  3868. detail::close_socket(sock);
  3869. return ret == 0;
  3870. }
  3871. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3872. Server svr;
  3873. auto port = svr.bind_to_any_port("127.0.0.1");
  3874. ASSERT_TRUE(port > 0);
  3875. svr.stop();
  3876. // bind_to_any_port() already called listen(2), so until stop() closed the
  3877. // descriptor the port kept accepting connections into the backlog. ASSERT
  3878. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3879. // below blocks forever in the accept loop.
  3880. ASSERT_FALSE(is_loopback_port_accepting(port));
  3881. // Nothing is left to accept on, so listen_after_bind() must report failure
  3882. // instead of returning success without ever serving.
  3883. EXPECT_FALSE(svr.listen_after_bind());
  3884. // The failed listen marks the server decommissioned, so a waiter returns
  3885. // instead of spinning forever.
  3886. svr.wait_until_ready();
  3887. }
  3888. #ifdef CPPHTTPLIB_SSL_ENABLED
  3889. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3890. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3891. CLIENT_CA_CERT_DIR);
  3892. int port = svr.bind_to_any_port("0.0.0.0");
  3893. ASSERT_TRUE(svr.is_valid());
  3894. ASSERT_TRUE(port > 0);
  3895. svr.stop();
  3896. }
  3897. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3898. // or a rejected CustomRoute() registration would not stop the server binding.
  3899. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3900. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3901. CLIENT_CA_CERT_DIR);
  3902. ASSERT_TRUE(svr.is_valid());
  3903. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3904. EXPECT_FALSE(svr.is_valid());
  3905. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3906. }
  3907. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3908. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3909. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3910. int port = svr.bind_to_any_port("0.0.0.0");
  3911. ASSERT_TRUE(svr.is_valid());
  3912. ASSERT_TRUE(port > 0);
  3913. svr.stop();
  3914. }
  3915. TEST(BindServerTest, UpdateCertsPem) {
  3916. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3917. int port = svr.bind_to_any_port("0.0.0.0");
  3918. ASSERT_TRUE(svr.is_valid());
  3919. ASSERT_TRUE(port > 0);
  3920. // Read PEM files
  3921. std::string cert_pem, key_pem, ca_pem;
  3922. read_file(SERVER_CERT_FILE, cert_pem);
  3923. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3924. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3925. // Update server certificates using PEM API
  3926. ASSERT_TRUE(
  3927. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3928. ASSERT_TRUE(svr.is_valid());
  3929. svr.stop();
  3930. }
  3931. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3932. // Start server with client CA (enables client auth)
  3933. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3934. ASSERT_TRUE(svr.is_valid());
  3935. bool handler_called = false;
  3936. svr.Get("/test", [&](const Request &req, Response &res) {
  3937. handler_called = true;
  3938. // Verify client certificate is present
  3939. auto cert = req.peer_cert();
  3940. EXPECT_TRUE(static_cast<bool>(cert));
  3941. res.set_content("ok", "text/plain");
  3942. });
  3943. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3944. auto se = detail::scope_exit([&] {
  3945. svr.stop();
  3946. t.join();
  3947. ASSERT_FALSE(svr.is_running());
  3948. });
  3949. svr.wait_until_ready();
  3950. // Read PEM files
  3951. std::string cert_pem, key_pem, ca_pem;
  3952. read_file(SERVER_CERT_FILE, cert_pem);
  3953. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3954. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3955. // Update server certificates and client CA using PEM API while server running
  3956. ASSERT_TRUE(
  3957. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3958. // Connect with client certificate
  3959. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3960. cli.enable_server_certificate_verification(false);
  3961. cli.set_connection_timeout(30);
  3962. auto res = cli.Get("/test");
  3963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3964. ASSERT_EQ(StatusCode::OK_200, res->status);
  3965. ASSERT_TRUE(handler_called);
  3966. EXPECT_EQ("ok", res->body);
  3967. }
  3968. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  3969. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3970. ASSERT_TRUE(svr.is_valid());
  3971. svr.Get("/test", [](const Request &, Response &res) {
  3972. res.set_content("ok", "text/plain");
  3973. });
  3974. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3975. auto se = detail::scope_exit([&] {
  3976. svr.stop();
  3977. t.join();
  3978. ASSERT_FALSE(svr.is_running());
  3979. });
  3980. svr.wait_until_ready();
  3981. // A connection that sends no ClientHello keeps its handshake in progress,
  3982. // once the server has had a moment to start it.
  3983. auto error = Error::Success;
  3984. auto sock = detail::create_client_socket(
  3985. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  3986. /*connection_timeout_sec=*/5, 0,
  3987. /*read_timeout_sec=*/5, 0,
  3988. /*write_timeout_sec=*/5, 0, std::string(), error);
  3989. ASSERT_NE(INVALID_SOCKET, sock);
  3990. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  3991. std::string cert_pem, key_pem;
  3992. read_file(SERVER_CERT_FILE, cert_pem);
  3993. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3994. auto update = std::async(std::launch::async, [&]() {
  3995. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  3996. });
  3997. EXPECT_EQ(std::future_status::timeout,
  3998. update.wait_for(std::chrono::milliseconds(200)));
  3999. detail::close_socket(sock);
  4000. EXPECT_TRUE(update.get());
  4001. SSLClient cli(HOST, PORT);
  4002. cli.enable_server_certificate_verification(false);
  4003. auto res = cli.Get("/test");
  4004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4005. EXPECT_EQ(StatusCode::OK_200, res->status);
  4006. }
  4007. #endif
  4008. TEST(ErrorHandlerTest, ContentLength) {
  4009. Server svr;
  4010. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4011. res.status = StatusCode::OK_200;
  4012. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4013. "text/html"); // <= Content-Length still 13
  4014. });
  4015. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4016. res.set_content("Hello World!\n", "text/plain");
  4017. res.status = 524;
  4018. });
  4019. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4020. auto se = detail::scope_exit([&] {
  4021. svr.stop();
  4022. thread.join();
  4023. ASSERT_FALSE(svr.is_running());
  4024. });
  4025. svr.wait_until_ready();
  4026. {
  4027. Client cli(HOST, PORT);
  4028. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4030. EXPECT_EQ(StatusCode::OK_200, res->status);
  4031. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4032. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4033. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4034. }
  4035. }
  4036. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4037. TEST(ExceptionTest, WithoutExceptionHandler) {
  4038. Server svr;
  4039. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4040. throw std::runtime_error("exception...");
  4041. });
  4042. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4043. throw std::runtime_error("exception\r\n...");
  4044. });
  4045. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4046. auto se = detail::scope_exit([&] {
  4047. svr.stop();
  4048. listen_thread.join();
  4049. ASSERT_FALSE(svr.is_running());
  4050. });
  4051. svr.wait_until_ready();
  4052. Client cli("localhost", PORT);
  4053. {
  4054. auto res = cli.Get("/exception");
  4055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4056. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4057. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4058. }
  4059. {
  4060. auto res = cli.Get("/unknown");
  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. TEST(ExceptionTest, WithExceptionHandler) {
  4067. Server svr;
  4068. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4069. std::exception_ptr ep) {
  4070. EXPECT_FALSE(ep == nullptr);
  4071. try {
  4072. std::rethrow_exception(ep);
  4073. } catch (std::exception &e) {
  4074. EXPECT_EQ("abc", std::string(e.what()));
  4075. } catch (...) {}
  4076. res.status = StatusCode::InternalServerError_500;
  4077. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4078. "text/html"); // <= Content-Length still 13 at this point
  4079. });
  4080. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4081. res.set_content("Hello World!\n", "text/plain");
  4082. throw std::runtime_error("abc");
  4083. });
  4084. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4085. auto se = detail::scope_exit([&] {
  4086. svr.stop();
  4087. thread.join();
  4088. ASSERT_FALSE(svr.is_running());
  4089. });
  4090. svr.wait_until_ready();
  4091. for (size_t i = 0; i < 10; i++) {
  4092. Client cli(HOST, PORT);
  4093. for (size_t j = 0; j < 100; j++) {
  4094. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4096. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4097. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4098. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4099. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4100. }
  4101. cli.set_keep_alive(true);
  4102. for (size_t j = 0; j < 100; j++) {
  4103. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4105. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4106. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4107. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4108. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4109. }
  4110. }
  4111. }
  4112. TEST(ExceptionTest, AndErrorHandler) {
  4113. Server svr;
  4114. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4115. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4116. });
  4117. svr.set_exception_handler(
  4118. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4119. EXPECT_FALSE(ep == nullptr);
  4120. try {
  4121. std::rethrow_exception(ep);
  4122. } catch (std::exception &e) {
  4123. res.set_content(e.what(), "text/html");
  4124. } catch (...) {}
  4125. res.status = StatusCode::InternalServerError_500;
  4126. });
  4127. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4128. throw std::runtime_error("EXCEPTION");
  4129. });
  4130. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4131. res.set_content("ERROR", "text/html");
  4132. res.status = StatusCode::InternalServerError_500;
  4133. });
  4134. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4135. auto se = detail::scope_exit([&] {
  4136. svr.stop();
  4137. thread.join();
  4138. ASSERT_FALSE(svr.is_running());
  4139. });
  4140. svr.wait_until_ready();
  4141. Client cli(HOST, PORT);
  4142. {
  4143. auto res = cli.Get("/exception");
  4144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4145. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4146. EXPECT_EQ("EXCEPTION", res->body);
  4147. }
  4148. {
  4149. auto res = cli.Get("/error");
  4150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4151. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4152. EXPECT_EQ("ERROR", res->body);
  4153. }
  4154. {
  4155. auto res = cli.Get("/invalid");
  4156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4157. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4158. EXPECT_EQ("NOT_FOUND", res->body);
  4159. }
  4160. }
  4161. #endif
  4162. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4163. // process_request() wraps only routing() in a try/catch, so an exception from
  4164. // any other user callback used to unwind into the task queue - which does not
  4165. // catch - and terminate the process. Each test below runs the server on a
  4166. // single worker thread: a guard that catches the exception but still loses the
  4167. // thread would otherwise be hidden by a spare worker serving the follow-up
  4168. // request. Note that a regression here aborts the whole test binary rather
  4169. // than failing one test.
  4170. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4171. Server svr;
  4172. svr.new_task_queue = [] { return new ThreadPool(1); };
  4173. std::atomic<int> reported{0};
  4174. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4175. if (err == Error::UserCallbackException) { reported++; }
  4176. });
  4177. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4178. res.set_content_provider(
  4179. 1024, "text/plain",
  4180. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4181. sink.write("hello", 5);
  4182. throw std::runtime_error("from the content provider");
  4183. });
  4184. });
  4185. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4186. res.set_content("ok", "text/plain");
  4187. });
  4188. auto port = svr.bind_to_any_port(HOST);
  4189. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4190. auto se = detail::scope_exit([&] {
  4191. svr.stop();
  4192. listen_thread.join();
  4193. ASSERT_FALSE(svr.is_running());
  4194. });
  4195. svr.wait_until_ready();
  4196. {
  4197. Client cli(HOST, port);
  4198. cli.set_read_timeout(5, 0);
  4199. EXPECT_FALSE(cli.Get("/throw"));
  4200. }
  4201. EXPECT_TRUE(svr.is_running());
  4202. EXPECT_EQ(1, reported.load());
  4203. // A request on a fresh connection is still served.
  4204. {
  4205. Client cli(HOST, port);
  4206. auto res = cli.Get("/ok");
  4207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4208. EXPECT_EQ(StatusCode::OK_200, res->status);
  4209. EXPECT_EQ("ok", res->body);
  4210. }
  4211. }
  4212. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4213. Server svr;
  4214. svr.new_task_queue = [] { return new ThreadPool(1); };
  4215. std::atomic<bool> should_throw{true};
  4216. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4217. res.set_content("hi", "text/plain");
  4218. });
  4219. svr.set_post_routing_handler(
  4220. [&](const Request & /*req*/, Response & /*res*/) {
  4221. if (should_throw) {
  4222. throw std::runtime_error("from the post-routing handler");
  4223. }
  4224. });
  4225. auto port = svr.bind_to_any_port(HOST);
  4226. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4227. auto se = detail::scope_exit([&] {
  4228. svr.stop();
  4229. listen_thread.join();
  4230. ASSERT_FALSE(svr.is_running());
  4231. });
  4232. svr.wait_until_ready();
  4233. {
  4234. Client cli(HOST, port);
  4235. cli.set_read_timeout(5, 0);
  4236. EXPECT_FALSE(cli.Get("/hi"));
  4237. }
  4238. EXPECT_TRUE(svr.is_running());
  4239. should_throw = false;
  4240. {
  4241. Client cli(HOST, port);
  4242. auto res = cli.Get("/hi");
  4243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4244. EXPECT_EQ(StatusCode::OK_200, res->status);
  4245. EXPECT_EQ("hi", res->body);
  4246. }
  4247. }
  4248. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4249. // The guard reports the caught exception through the error logger, which is
  4250. // a user callback too. A logger that throws has to be contained as well, or
  4251. // the process would terminate from inside the catch.
  4252. Server svr;
  4253. svr.new_task_queue = [] { return new ThreadPool(1); };
  4254. std::atomic<int> reported{0};
  4255. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4256. if (err == Error::UserCallbackException) {
  4257. reported++;
  4258. throw std::runtime_error("from the error logger");
  4259. }
  4260. });
  4261. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4262. res.set_content_provider(
  4263. 1024, "text/plain",
  4264. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4265. sink.write("hello", 5);
  4266. throw std::runtime_error("from the content provider");
  4267. });
  4268. });
  4269. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4270. res.set_content("ok", "text/plain");
  4271. });
  4272. auto port = svr.bind_to_any_port(HOST);
  4273. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4274. auto se = detail::scope_exit([&] {
  4275. svr.stop();
  4276. listen_thread.join();
  4277. ASSERT_FALSE(svr.is_running());
  4278. });
  4279. svr.wait_until_ready();
  4280. {
  4281. Client cli(HOST, port);
  4282. cli.set_read_timeout(5, 0);
  4283. EXPECT_FALSE(cli.Get("/throw"));
  4284. }
  4285. EXPECT_TRUE(svr.is_running());
  4286. EXPECT_EQ(1, reported.load());
  4287. {
  4288. Client cli(HOST, port);
  4289. auto res = cli.Get("/ok");
  4290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4291. EXPECT_EQ(StatusCode::OK_200, res->status);
  4292. EXPECT_EQ("ok", res->body);
  4293. }
  4294. }
  4295. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4296. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4297. // so the exception unwinds through the ws::WebSocket object on its way to
  4298. // the guard. None of the HTTP cases above cross that.
  4299. Server svr;
  4300. svr.new_task_queue = [] { return new ThreadPool(1); };
  4301. std::atomic<int> reported{0};
  4302. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4303. if (err == Error::UserCallbackException) { reported++; }
  4304. });
  4305. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4306. throw std::runtime_error("from the WebSocket handler");
  4307. });
  4308. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4309. res.set_content("ok", "text/plain");
  4310. });
  4311. auto port = svr.bind_to_any_port(HOST);
  4312. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4313. auto se = detail::scope_exit([&] {
  4314. svr.stop();
  4315. listen_thread.join();
  4316. ASSERT_FALSE(svr.is_running());
  4317. });
  4318. svr.wait_until_ready();
  4319. {
  4320. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4321. "/ws");
  4322. auto res = client.connect();
  4323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4324. // The server dropped the connection instead of dying.
  4325. std::string msg;
  4326. EXPECT_FALSE(client.read(msg));
  4327. client.close();
  4328. }
  4329. EXPECT_TRUE(svr.is_running());
  4330. EXPECT_EQ(1, reported.load());
  4331. {
  4332. Client cli(HOST, port);
  4333. auto res = cli.Get("/ok");
  4334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4335. EXPECT_EQ(StatusCode::OK_200, res->status);
  4336. EXPECT_EQ("ok", res->body);
  4337. }
  4338. }
  4339. #ifdef CPPHTTPLIB_SSL_ENABLED
  4340. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4341. // SSLServer::process_and_close_socket() is a separate overload with its own
  4342. // guard, so it is exercised on its own.
  4343. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4344. ASSERT_TRUE(svr.is_valid());
  4345. svr.new_task_queue = [] { return new ThreadPool(1); };
  4346. std::atomic<int> reported{0};
  4347. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4348. if (err == Error::UserCallbackException) { reported++; }
  4349. });
  4350. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4351. res.set_content_provider(
  4352. 1024, "text/plain",
  4353. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4354. sink.write("hello", 5);
  4355. throw std::runtime_error("from the content provider");
  4356. });
  4357. });
  4358. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4359. res.set_content("ok", "text/plain");
  4360. });
  4361. auto port = svr.bind_to_any_port(HOST);
  4362. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4363. auto se = detail::scope_exit([&] {
  4364. svr.stop();
  4365. listen_thread.join();
  4366. ASSERT_FALSE(svr.is_running());
  4367. });
  4368. svr.wait_until_ready();
  4369. {
  4370. SSLClient cli(HOST, port);
  4371. cli.enable_server_certificate_verification(false);
  4372. cli.set_read_timeout(5, 0);
  4373. EXPECT_FALSE(cli.Get("/throw"));
  4374. }
  4375. EXPECT_TRUE(svr.is_running());
  4376. EXPECT_EQ(1, reported.load());
  4377. {
  4378. SSLClient cli(HOST, port);
  4379. cli.enable_server_certificate_verification(false);
  4380. auto res = cli.Get("/ok");
  4381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4382. EXPECT_EQ(StatusCode::OK_200, res->status);
  4383. EXPECT_EQ("ok", res->body);
  4384. }
  4385. }
  4386. #endif
  4387. #endif
  4388. TEST(NoContentTest, ContentLength) {
  4389. Server svr;
  4390. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4391. res.status = StatusCode::NoContent_204;
  4392. });
  4393. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4394. auto se = detail::scope_exit([&] {
  4395. svr.stop();
  4396. thread.join();
  4397. ASSERT_FALSE(svr.is_running());
  4398. });
  4399. svr.wait_until_ready();
  4400. {
  4401. Client cli(HOST, PORT);
  4402. auto res = cli.Get("/hi");
  4403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4404. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4405. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4406. }
  4407. }
  4408. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4409. #ifdef CPPHTTPLIB_SSL_ENABLED
  4410. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4411. ASSERT_TRUE(svr.is_valid());
  4412. #else
  4413. Server svr;
  4414. #endif
  4415. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4416. if (req.path == "/routing_handler") {
  4417. res.set_header("PRE_ROUTING", "on");
  4418. res.set_content("Routing Handler", "text/plain");
  4419. return httplib::Server::HandlerResponse::Handled;
  4420. }
  4421. return httplib::Server::HandlerResponse::Unhandled;
  4422. });
  4423. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4424. res.set_content("Error", "text/html");
  4425. });
  4426. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4427. if (req.path == "/routing_handler") {
  4428. res.set_header("POST_ROUTING", "on");
  4429. }
  4430. });
  4431. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4432. res.set_content("Hello World!\n", "text/plain");
  4433. });
  4434. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4435. auto se = detail::scope_exit([&] {
  4436. svr.stop();
  4437. thread.join();
  4438. ASSERT_FALSE(svr.is_running());
  4439. });
  4440. svr.wait_until_ready();
  4441. {
  4442. #ifdef CPPHTTPLIB_SSL_ENABLED
  4443. SSLClient cli(HOST, PORT);
  4444. cli.enable_server_certificate_verification(false);
  4445. #else
  4446. Client cli(HOST, PORT);
  4447. #endif
  4448. auto res = cli.Get("/routing_handler");
  4449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4450. EXPECT_EQ(StatusCode::OK_200, res->status);
  4451. EXPECT_EQ("Routing Handler", res->body);
  4452. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4453. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4454. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4455. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4456. }
  4457. {
  4458. #ifdef CPPHTTPLIB_SSL_ENABLED
  4459. SSLClient cli(HOST, PORT);
  4460. cli.enable_server_certificate_verification(false);
  4461. #else
  4462. Client cli(HOST, PORT);
  4463. #endif
  4464. auto res = cli.Get("/hi");
  4465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4466. EXPECT_EQ(StatusCode::OK_200, res->status);
  4467. EXPECT_EQ("Hello World!\n", res->body);
  4468. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4469. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4470. }
  4471. {
  4472. #ifdef CPPHTTPLIB_SSL_ENABLED
  4473. SSLClient cli(HOST, PORT);
  4474. cli.enable_server_certificate_verification(false);
  4475. #else
  4476. Client cli(HOST, PORT);
  4477. #endif
  4478. auto res = cli.Get("/aaa");
  4479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4480. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4481. EXPECT_EQ("Error", res->body);
  4482. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4483. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4484. }
  4485. }
  4486. TEST(RequestHandlerTest, PreRequestHandler) {
  4487. auto route_path = "/user/:user";
  4488. Server svr;
  4489. svr.Get("/hi", [](const Request &, Response &res) {
  4490. res.set_content("hi", "text/plain");
  4491. });
  4492. svr.Get(route_path, [](const Request &req, Response &res) {
  4493. res.set_content(req.path_params.at("user"), "text/plain");
  4494. });
  4495. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4496. if (req.matched_route == route_path) {
  4497. auto user = req.path_params.at("user");
  4498. if (user != "john") {
  4499. res.status = StatusCode::Forbidden_403;
  4500. res.set_content("error", "text/html");
  4501. return Server::HandlerResponse::Handled;
  4502. }
  4503. }
  4504. return Server::HandlerResponse::Unhandled;
  4505. });
  4506. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4507. auto se = detail::scope_exit([&] {
  4508. svr.stop();
  4509. thread.join();
  4510. ASSERT_FALSE(svr.is_running());
  4511. });
  4512. svr.wait_until_ready();
  4513. Client cli(HOST, PORT);
  4514. {
  4515. auto res = cli.Get("/hi");
  4516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4517. EXPECT_EQ(StatusCode::OK_200, res->status);
  4518. EXPECT_EQ("hi", res->body);
  4519. }
  4520. {
  4521. auto res = cli.Get("/user/john");
  4522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4523. EXPECT_EQ(StatusCode::OK_200, res->status);
  4524. EXPECT_EQ("john", res->body);
  4525. }
  4526. {
  4527. auto res = cli.Get("/user/invalid-user");
  4528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4529. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4530. EXPECT_EQ("error", res->body);
  4531. }
  4532. }
  4533. // The pre-request handler must run before the request body is read, so a
  4534. // rejected request never forces the server to buffer a (potentially large)
  4535. // body. Here the posted body is larger than the payload limit: if the body
  4536. // were read first the server would answer 413, but because the pre-request
  4537. // handler runs first it answers 403 and the body is never read.
  4538. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4539. Server svr;
  4540. svr.set_payload_max_length(8);
  4541. auto handler_ran = false;
  4542. svr.Post("/reject", [&](const Request &req, Response &res) {
  4543. handler_ran = true;
  4544. res.set_content(req.body, "text/plain");
  4545. });
  4546. svr.Post("/accept", [](const Request &req, Response &res) {
  4547. res.set_content(req.body, "text/plain");
  4548. });
  4549. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4550. if (req.matched_route == "/reject") {
  4551. res.status = StatusCode::Forbidden_403;
  4552. res.set_content("denied", "text/plain");
  4553. return Server::HandlerResponse::Handled;
  4554. }
  4555. return Server::HandlerResponse::Unhandled;
  4556. });
  4557. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4558. auto se = detail::scope_exit([&] {
  4559. svr.stop();
  4560. thread.join();
  4561. ASSERT_FALSE(svr.is_running());
  4562. });
  4563. svr.wait_until_ready();
  4564. Client cli(HOST, PORT);
  4565. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4566. // rejects with 403 before the body is read, so 413 is never reached.
  4567. {
  4568. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4570. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4571. EXPECT_EQ("denied", res->body);
  4572. EXPECT_FALSE(handler_ran);
  4573. }
  4574. // An approved route still reads the body and enforces the payload limit.
  4575. {
  4576. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4578. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4579. }
  4580. }
  4581. TEST(UserDataTest, BasicOperations) {
  4582. httplib::UserData ud;
  4583. // Initially empty
  4584. EXPECT_FALSE(ud.has("key"));
  4585. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4586. // set and get
  4587. ud.set("key", 42);
  4588. EXPECT_TRUE(ud.has("key"));
  4589. auto *p = ud.get<int>("key");
  4590. ASSERT_NE(nullptr, p);
  4591. EXPECT_EQ(42, *p);
  4592. // Type mismatch → nullptr
  4593. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4594. // Overwrite with different type
  4595. ud.set("key", std::string("hello"));
  4596. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4597. auto *s = ud.get<std::string>("key");
  4598. ASSERT_NE(nullptr, s);
  4599. EXPECT_EQ("hello", *s);
  4600. // erase
  4601. ud.erase("key");
  4602. EXPECT_FALSE(ud.has("key"));
  4603. // clear
  4604. ud.set("a", 1);
  4605. ud.set("b", 2);
  4606. ud.clear();
  4607. EXPECT_FALSE(ud.has("a"));
  4608. EXPECT_FALSE(ud.has("b"));
  4609. }
  4610. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4611. struct AuthCtx {
  4612. std::string user_id;
  4613. };
  4614. Server svr;
  4615. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4616. res.user_data.set("auth", AuthCtx{"alice"});
  4617. return Server::HandlerResponse::Unhandled;
  4618. });
  4619. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4620. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4621. ASSERT_NE(nullptr, ctx);
  4622. res.set_content("Hello " + ctx->user_id, "text/plain");
  4623. });
  4624. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4625. auto se = detail::scope_exit([&] {
  4626. svr.stop();
  4627. thread.join();
  4628. ASSERT_FALSE(svr.is_running());
  4629. });
  4630. svr.wait_until_ready();
  4631. Client cli(HOST, PORT);
  4632. auto res = cli.Get("/me");
  4633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4634. EXPECT_EQ(StatusCode::OK_200, res->status);
  4635. EXPECT_EQ("Hello alice", res->body);
  4636. }
  4637. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4638. struct RoleCtx {
  4639. std::string role;
  4640. };
  4641. Server svr;
  4642. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4643. res.user_data.set("role", RoleCtx{"admin"});
  4644. return Server::HandlerResponse::Unhandled;
  4645. });
  4646. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4647. auto *ctx = res.user_data.get<RoleCtx>("role");
  4648. ASSERT_NE(nullptr, ctx);
  4649. res.set_content(ctx->role, "text/plain");
  4650. });
  4651. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4652. auto se = detail::scope_exit([&] {
  4653. svr.stop();
  4654. thread.join();
  4655. ASSERT_FALSE(svr.is_running());
  4656. });
  4657. svr.wait_until_ready();
  4658. Client cli(HOST, PORT);
  4659. auto res = cli.Get("/role");
  4660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4661. EXPECT_EQ(StatusCode::OK_200, res->status);
  4662. EXPECT_EQ("admin", res->body);
  4663. }
  4664. TEST(InvalidFormatTest, StatusCode) {
  4665. Server svr;
  4666. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4667. res.set_content("Hello World!\n", "text/plain");
  4668. res.status = 9999; // Status should be a three-digit code...
  4669. });
  4670. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4671. auto se = detail::scope_exit([&] {
  4672. svr.stop();
  4673. thread.join();
  4674. ASSERT_FALSE(svr.is_running());
  4675. });
  4676. svr.wait_until_ready();
  4677. {
  4678. Client cli(HOST, PORT);
  4679. auto res = cli.Get("/hi");
  4680. ASSERT_FALSE(res);
  4681. }
  4682. }
  4683. TEST(URLFragmentTest, WithFragment) {
  4684. Server svr;
  4685. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4686. EXPECT_TRUE(req.target == "/hi");
  4687. });
  4688. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4689. auto se = detail::scope_exit([&] {
  4690. svr.stop();
  4691. thread.join();
  4692. ASSERT_FALSE(svr.is_running());
  4693. });
  4694. svr.wait_until_ready();
  4695. {
  4696. Client cli(HOST, PORT);
  4697. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4698. EXPECT_TRUE(res);
  4699. EXPECT_EQ(StatusCode::OK_200, res->status);
  4700. res = cli.Get("/hi%23key1=val1=key2=val2");
  4701. EXPECT_TRUE(res);
  4702. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4703. }
  4704. }
  4705. TEST(HeaderWriter, SetHeaderWriter) {
  4706. Server svr;
  4707. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4708. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4709. return detail::write_headers(strm, hdrs);
  4710. });
  4711. svr.Get("/hi", [](const Request &req, Response &res) {
  4712. auto it = req.headers.find("CustomClientHeader");
  4713. EXPECT_TRUE(it != req.headers.end());
  4714. EXPECT_EQ(it->second, "CustomClientValue");
  4715. res.set_content("Hello World!\n", "text/plain");
  4716. });
  4717. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4718. auto se = detail::scope_exit([&] {
  4719. svr.stop();
  4720. thread.join();
  4721. ASSERT_FALSE(svr.is_running());
  4722. });
  4723. svr.wait_until_ready();
  4724. {
  4725. Client cli(HOST, PORT);
  4726. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4727. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4728. return detail::write_headers(strm, hdrs);
  4729. });
  4730. auto res = cli.Get("/hi");
  4731. EXPECT_TRUE(res);
  4732. EXPECT_EQ(StatusCode::OK_200, res->status);
  4733. auto it = res->headers.find("CustomServerHeader");
  4734. EXPECT_TRUE(it != res->headers.end());
  4735. EXPECT_EQ(it->second, "CustomServerValue");
  4736. }
  4737. }
  4738. class ServerTest : public ::testing::Test {
  4739. protected:
  4740. ServerTest()
  4741. : cli_(HOST, PORT)
  4742. #ifdef CPPHTTPLIB_SSL_ENABLED
  4743. ,
  4744. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4745. #endif
  4746. {
  4747. #ifdef CPPHTTPLIB_SSL_ENABLED
  4748. cli_.enable_server_certificate_verification(false);
  4749. #endif
  4750. // Allow LARGE_DATA (100MB) responses
  4751. cli_.set_payload_max_length(200 * 1024 * 1024);
  4752. }
  4753. virtual void SetUp() {
  4754. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4755. svr_.set_payload_max_length(200 * 1024 * 1024);
  4756. svr_.set_mount_point("/", "./www");
  4757. svr_.set_mount_point("/mount", "./www2");
  4758. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4759. svr_.Get("/hi",
  4760. [&](const Request & /*req*/, Response &res) {
  4761. res.set_content("Hello World!", "text/plain");
  4762. })
  4763. .Get("/file_content",
  4764. [&](const Request & /*req*/, Response &res) {
  4765. res.set_file_content("./www/dir/test.html");
  4766. })
  4767. .Get("/file_content_with_content_type",
  4768. [&](const Request & /*req*/, Response &res) {
  4769. res.set_file_content("./www/file", "text/plain");
  4770. })
  4771. .Get("/invalid_file_content",
  4772. [&](const Request & /*req*/, Response &res) {
  4773. res.set_file_content("./www/dir/invalid_file_path");
  4774. })
  4775. .Get("/http_response_splitting",
  4776. [&](const Request & /*req*/, Response &res) {
  4777. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4778. EXPECT_EQ(0U, res.headers.size());
  4779. EXPECT_FALSE(res.has_header("a"));
  4780. res.set_header("a", "1\nSet-Cookie: a=1");
  4781. EXPECT_EQ(0U, res.headers.size());
  4782. EXPECT_FALSE(res.has_header("a"));
  4783. res.set_header("a", "1\rSet-Cookie: a=1");
  4784. EXPECT_EQ(0U, res.headers.size());
  4785. EXPECT_FALSE(res.has_header("a"));
  4786. res.set_header("a\r\nb", "0");
  4787. EXPECT_EQ(0U, res.headers.size());
  4788. EXPECT_FALSE(res.has_header("a"));
  4789. res.set_header("a\rb", "0");
  4790. EXPECT_EQ(0U, res.headers.size());
  4791. EXPECT_FALSE(res.has_header("a"));
  4792. res.set_header("a\nb", "0");
  4793. EXPECT_EQ(0U, res.headers.size());
  4794. EXPECT_FALSE(res.has_header("a"));
  4795. res.set_redirect("1\r\nSet-Cookie: a=1");
  4796. EXPECT_EQ(0U, res.headers.size());
  4797. EXPECT_FALSE(res.has_header("Location"));
  4798. })
  4799. .Get("/slow",
  4800. [&](const Request & /*req*/, Response &res) {
  4801. std::this_thread::sleep_for(std::chrono::seconds(4));
  4802. res.set_content("slow", "text/plain");
  4803. })
  4804. #if 0
  4805. .Post("/slowpost",
  4806. [&](const Request & /*req*/, Response &res) {
  4807. std::this_thread::sleep_for(std::chrono::seconds(2));
  4808. res.set_content("slow", "text/plain");
  4809. })
  4810. #endif
  4811. .Get("/remote_addr",
  4812. [&](const Request &req, Response &res) {
  4813. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4814. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4815. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4816. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4817. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4818. #endif
  4819. res.set_content(req.remote_addr, "text/plain");
  4820. })
  4821. .Get("/local_addr",
  4822. [&](const Request &req, Response &res) {
  4823. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4824. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4825. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4826. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4827. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4828. #endif
  4829. auto local_addr = req.local_addr;
  4830. auto local_port = std::to_string(req.local_port);
  4831. res.set_content(local_addr.append(":").append(local_port),
  4832. "text/plain");
  4833. })
  4834. .Get("/endwith%",
  4835. [&](const Request & /*req*/, Response &res) {
  4836. res.set_content("Hello World!", "text/plain");
  4837. })
  4838. .Get("/a\\+\\+b",
  4839. [&](const Request &req, Response &res) {
  4840. ASSERT_TRUE(req.has_param("a +b"));
  4841. auto val = req.get_param_value("a +b");
  4842. res.set_content(val, "text/plain");
  4843. })
  4844. .Get("/", [&](const Request & /*req*/,
  4845. Response &res) { res.set_redirect("/hi"); })
  4846. .Post("/1",
  4847. [](const Request & /*req*/, Response &res) {
  4848. res.set_redirect("/2", StatusCode::SeeOther_303);
  4849. })
  4850. .Get("/2",
  4851. [](const Request & /*req*/, Response &res) {
  4852. res.set_content("redirected.", "text/plain");
  4853. res.status = StatusCode::OK_200;
  4854. })
  4855. .Post("/person",
  4856. [&](const Request &req, Response &res) {
  4857. if (req.has_param("name") && req.has_param("note")) {
  4858. persons_[req.get_param_value("name")] =
  4859. req.get_param_value("note");
  4860. } else {
  4861. res.status = StatusCode::BadRequest_400;
  4862. }
  4863. })
  4864. .Put("/person",
  4865. [&](const Request &req, Response &res) {
  4866. if (req.has_param("name") && req.has_param("note")) {
  4867. persons_[req.get_param_value("name")] =
  4868. req.get_param_value("note");
  4869. } else {
  4870. res.status = StatusCode::BadRequest_400;
  4871. }
  4872. })
  4873. .Get("/person/(.*)",
  4874. [&](const Request &req, Response &res) {
  4875. string name = req.matches[1];
  4876. if (persons_.find(name) != persons_.end()) {
  4877. auto note = persons_[name];
  4878. res.set_content(note, "text/plain");
  4879. } else {
  4880. res.status = StatusCode::NotFound_404;
  4881. }
  4882. })
  4883. .Delete("/person",
  4884. [&](const Request &req, Response &res) {
  4885. if (req.has_param("name")) {
  4886. string name = req.get_param_value("name");
  4887. if (persons_.find(name) != persons_.end()) {
  4888. persons_.erase(name);
  4889. res.set_content("DELETED", "text/plain");
  4890. } else {
  4891. res.status = StatusCode::NotFound_404;
  4892. }
  4893. } else {
  4894. res.status = StatusCode::BadRequest_400;
  4895. }
  4896. })
  4897. .Post("/x-www-form-urlencoded-json",
  4898. [&](const Request &req, Response &res) {
  4899. auto json = req.get_param_value("json");
  4900. ASSERT_EQ(JSON_DATA, json);
  4901. res.set_content(json, "appliation/json");
  4902. res.status = StatusCode::OK_200;
  4903. })
  4904. .Get("/streamed-chunked",
  4905. [&](const Request & /*req*/, Response &res) {
  4906. res.set_chunked_content_provider(
  4907. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4908. sink.os << "123";
  4909. sink.os << "456";
  4910. sink.os << "789";
  4911. sink.done();
  4912. return true;
  4913. });
  4914. })
  4915. .Get("/streamed-chunked-with-prohibited-trailer",
  4916. [&](const Request & /*req*/, Response &res) {
  4917. auto i = new int(0);
  4918. // Declare both a prohibited trailer (Content-Length) and an
  4919. // allowed one
  4920. res.set_header("Trailer", "Content-Length, X-Allowed");
  4921. res.set_chunked_content_provider(
  4922. "text/plain",
  4923. [i](size_t /*offset*/, DataSink &sink) {
  4924. switch (*i) {
  4925. case 0: sink.os << "123"; break;
  4926. case 1: sink.os << "456"; break;
  4927. case 2: sink.os << "789"; break;
  4928. case 3: {
  4929. sink.done_with_trailer(
  4930. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4931. } break;
  4932. }
  4933. (*i)++;
  4934. return true;
  4935. },
  4936. [i](bool success) {
  4937. EXPECT_TRUE(success);
  4938. delete i;
  4939. });
  4940. })
  4941. .Get("/streamed-chunked2",
  4942. [&](const Request & /*req*/, Response &res) {
  4943. auto i = new int(0);
  4944. res.set_chunked_content_provider(
  4945. "text/plain",
  4946. [i](size_t /*offset*/, DataSink &sink) {
  4947. switch (*i) {
  4948. case 0: sink.os << "123"; break;
  4949. case 1: sink.os << "456"; break;
  4950. case 2: sink.os << "789"; break;
  4951. case 3: sink.done(); break;
  4952. }
  4953. (*i)++;
  4954. return true;
  4955. },
  4956. [i](bool success) {
  4957. EXPECT_TRUE(success);
  4958. delete i;
  4959. });
  4960. })
  4961. .Get("/streamed-chunked-with-trailer",
  4962. [&](const Request & /*req*/, Response &res) {
  4963. auto i = new int(0);
  4964. res.set_header("Trailer", "Dummy1, Dummy2");
  4965. res.set_chunked_content_provider(
  4966. "text/plain",
  4967. [i](size_t /*offset*/, DataSink &sink) {
  4968. switch (*i) {
  4969. case 0: sink.os << "123"; break;
  4970. case 1: sink.os << "456"; break;
  4971. case 2: sink.os << "789"; break;
  4972. case 3: {
  4973. sink.done_with_trailer(
  4974. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4975. } break;
  4976. }
  4977. (*i)++;
  4978. return true;
  4979. },
  4980. [i](bool success) {
  4981. EXPECT_TRUE(success);
  4982. delete i;
  4983. });
  4984. })
  4985. .Get("/streamed",
  4986. [&](const Request & /*req*/, Response &res) {
  4987. res.set_content_provider(
  4988. 6, "text/plain",
  4989. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4990. sink.os << (offset < 3 ? "a" : "b");
  4991. return true;
  4992. });
  4993. })
  4994. .Get("/streamed-without-length",
  4995. [&](const Request & /*req*/, Response &res) {
  4996. auto data = new std::string("abcdefg");
  4997. res.set_content_provider(
  4998. "text/plain",
  4999. [data](size_t offset, DataSink &sink) {
  5000. if (offset < data->size()) {
  5001. sink.os << data->substr(offset);
  5002. }
  5003. sink.done();
  5004. return true;
  5005. },
  5006. [data](bool success) {
  5007. EXPECT_TRUE(success);
  5008. delete data;
  5009. });
  5010. })
  5011. .Get("/streamed-with-range",
  5012. [&](const Request &req, Response &res) {
  5013. auto data = new std::string("abcdefg");
  5014. // An explicit status keeps the server from picking the 206 it
  5015. // would otherwise choose for a ranged request, so the response
  5016. // is not a partial representation.
  5017. auto status = req.get_param_value("status");
  5018. if (status == "200") {
  5019. res.status = StatusCode::OK_200;
  5020. } else if (status == "403") {
  5021. res.status = StatusCode::Forbidden_403;
  5022. }
  5023. res.set_content_provider(
  5024. data->size(), "text/plain",
  5025. [data](size_t offset, size_t length, DataSink &sink) {
  5026. size_t DATA_CHUNK_SIZE = 4;
  5027. const auto &d = *data;
  5028. auto out_len =
  5029. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5030. auto ret =
  5031. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5032. EXPECT_TRUE(ret);
  5033. return true;
  5034. },
  5035. [data, &req](bool success) {
  5036. EXPECT_EQ(success, !req.has_param("error"));
  5037. delete data;
  5038. });
  5039. })
  5040. .Get("/streamed-cancel",
  5041. [&](const Request & /*req*/, Response &res) {
  5042. res.set_content_provider(
  5043. size_t(-1), "text/plain",
  5044. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5045. sink.os << "data_chunk";
  5046. return true;
  5047. });
  5048. })
  5049. .Get("/regex-with-delimiter",
  5050. [&](const Request &req, Response & /*res*/) {
  5051. ASSERT_TRUE(req.has_param("key"));
  5052. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5053. })
  5054. .Get("/with-range",
  5055. [&](const Request & /*req*/, Response &res) {
  5056. res.set_content("abcdefg", "text/plain");
  5057. })
  5058. .Get("/test-start-time",
  5059. [&](const Request &req, Response & /*res*/) {
  5060. EXPECT_NE(req.start_time_,
  5061. std::chrono::steady_clock::time_point::min());
  5062. })
  5063. .Get("/with-range-customized-response",
  5064. [&](const Request & /*req*/, Response &res) {
  5065. res.status = StatusCode::BadRequest_400;
  5066. res.set_content(JSON_DATA, "application/json");
  5067. })
  5068. .Post("/chunked",
  5069. [&](const Request &req, Response & /*res*/) {
  5070. EXPECT_EQ(req.body, "dechunked post body");
  5071. })
  5072. .Post("/large-chunked",
  5073. [&](const Request &req, Response & /*res*/) {
  5074. std::string expected(6 * 30 * 1024u, 'a');
  5075. EXPECT_EQ(req.body, expected);
  5076. })
  5077. .Post("/multipart",
  5078. [&](const Request &req, Response & /*res*/) {
  5079. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5080. req.form.get_field_count("text2") +
  5081. req.form.get_field_count("file3") +
  5082. req.form.get_field_count("file4"));
  5083. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5084. req.form.get_file_count("file2"));
  5085. ASSERT_TRUE(!req.form.has_file("???"));
  5086. ASSERT_TRUE(!req.form.has_field("???"));
  5087. ASSERT_TRUE(req.body.empty());
  5088. {
  5089. const auto &text = req.form.get_field("text1");
  5090. EXPECT_EQ("text default", text);
  5091. }
  5092. {
  5093. const auto &text = req.form.get_field("text2");
  5094. EXPECT_EQ("aωb", text);
  5095. }
  5096. {
  5097. const auto &file = req.form.get_file("file1");
  5098. EXPECT_EQ("hello.txt", file.filename);
  5099. EXPECT_EQ("text/plain", file.content_type);
  5100. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5101. }
  5102. {
  5103. const auto &file = req.form.get_file("file2");
  5104. EXPECT_EQ("world.json", file.filename);
  5105. EXPECT_EQ("application/json", file.content_type);
  5106. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5107. }
  5108. {
  5109. const auto &text = req.form.get_field("file3");
  5110. EXPECT_EQ(0u, text.size());
  5111. }
  5112. {
  5113. const auto &text = req.form.get_field("file4");
  5114. EXPECT_EQ(0u, text.size());
  5115. }
  5116. })
  5117. .Post("/multipart/multi_file_values",
  5118. [&](const Request &req, Response & /*res*/) {
  5119. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5120. req.form.get_field_count("multi_text1"));
  5121. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5122. ASSERT_TRUE(!req.form.has_file("???"));
  5123. ASSERT_TRUE(!req.form.has_field("???"));
  5124. ASSERT_TRUE(req.body.empty());
  5125. {
  5126. const auto &text = req.form.get_field("text");
  5127. EXPECT_EQ("default text", text);
  5128. }
  5129. {
  5130. const auto &text1_values = req.form.get_fields("multi_text1");
  5131. EXPECT_EQ(2u, text1_values.size());
  5132. EXPECT_EQ("aaaaa", text1_values[0]);
  5133. EXPECT_EQ("bbbbb", text1_values[1]);
  5134. }
  5135. {
  5136. const auto &file1_values = req.form.get_files("multi_file1");
  5137. EXPECT_EQ(2u, file1_values.size());
  5138. auto file1 = file1_values[0];
  5139. EXPECT_EQ(file1.filename, "hello.txt");
  5140. EXPECT_EQ(file1.content_type, "text/plain");
  5141. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5142. auto file2 = file1_values[1];
  5143. EXPECT_EQ(file2.filename, "world.json");
  5144. EXPECT_EQ(file2.content_type, "application/json");
  5145. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5146. }
  5147. })
  5148. .Post("/empty",
  5149. [&](const Request &req, Response &res) {
  5150. EXPECT_EQ(req.body, "");
  5151. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5152. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5153. res.set_content("empty", "text/plain");
  5154. })
  5155. .Post("/empty-no-content-type",
  5156. [&](const Request &req, Response &res) {
  5157. EXPECT_EQ(req.body, "");
  5158. EXPECT_FALSE(req.has_header("Content-Type"));
  5159. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5160. res.set_content("empty-no-content-type", "text/plain");
  5161. })
  5162. .Post("/path-only",
  5163. [&](const Request &req, Response &res) {
  5164. EXPECT_EQ(req.body, "");
  5165. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5166. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5167. res.set_content("path-only", "text/plain");
  5168. })
  5169. .Post("/path-headers-only",
  5170. [&](const Request &req, Response &res) {
  5171. EXPECT_EQ(req.body, "");
  5172. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5173. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5174. EXPECT_EQ("world", req.get_header_value("hello"));
  5175. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5176. res.set_content("path-headers-only", "text/plain");
  5177. })
  5178. .Post("/post-large",
  5179. [&](const Request &req, Response &res) {
  5180. EXPECT_EQ(req.body, LARGE_DATA);
  5181. res.set_content(req.body, "text/plain");
  5182. })
  5183. .Post("/post-loopback",
  5184. [&](const Request &, Response &res,
  5185. ContentReader const &content_reader) {
  5186. std::string body;
  5187. content_reader([&](const char *data, size_t data_length) {
  5188. body.append(data, data_length);
  5189. return true;
  5190. });
  5191. res.set_content(body, "text/plain");
  5192. })
  5193. .Put("/put-loopback",
  5194. [&](const Request &, Response &res,
  5195. ContentReader const &content_reader) {
  5196. std::string body;
  5197. content_reader([&](const char *data, size_t data_length) {
  5198. body.append(data, data_length);
  5199. return true;
  5200. });
  5201. res.set_content(body, "text/plain");
  5202. })
  5203. .Patch("/patch-loopback",
  5204. [&](const Request &, Response &res,
  5205. ContentReader const &content_reader) {
  5206. std::string body;
  5207. content_reader([&](const char *data, size_t data_length) {
  5208. body.append(data, data_length);
  5209. return true;
  5210. });
  5211. res.set_content(body, "text/plain");
  5212. })
  5213. .Put("/empty-no-content-type",
  5214. [&](const Request &req, Response &res) {
  5215. EXPECT_EQ(req.body, "");
  5216. EXPECT_FALSE(req.has_header("Content-Type"));
  5217. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5218. res.set_content("empty-no-content-type", "text/plain");
  5219. })
  5220. .Put("/put",
  5221. [&](const Request &req, Response &res) {
  5222. EXPECT_EQ(req.body, "PUT");
  5223. res.set_content(req.body, "text/plain");
  5224. })
  5225. .Put("/put-large",
  5226. [&](const Request &req, Response &res) {
  5227. EXPECT_EQ(req.body, LARGE_DATA);
  5228. res.set_content(req.body, "text/plain");
  5229. })
  5230. .Patch("/patch",
  5231. [&](const Request &req, Response &res) {
  5232. EXPECT_EQ(req.body, "PATCH");
  5233. res.set_content(req.body, "text/plain");
  5234. })
  5235. .Delete("/delete",
  5236. [&](const Request & /*req*/, Response &res) {
  5237. res.set_content("DELETE", "text/plain");
  5238. })
  5239. .Delete("/delete-body",
  5240. [&](const Request &req, Response &res) {
  5241. EXPECT_EQ(req.body, "content");
  5242. res.set_content(req.body, "text/plain");
  5243. })
  5244. .Options(R"(\*)",
  5245. [&](const Request & /*req*/, Response &res) {
  5246. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5247. })
  5248. .CustomRoute("PROPFIND", "/dav/:id",
  5249. [&](const Request &req, Response &res) {
  5250. res.set_header("x-body-size",
  5251. std::to_string(req.body.size()));
  5252. res.set_header("x-matched-route", req.matched_route);
  5253. res.set_header("x-dav-id", req.path_params.at("id"));
  5254. res.status = StatusCode::MultiStatus_207;
  5255. res.set_content(req.body, "application/xml");
  5256. })
  5257. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5258. [&](const Request &req, Response &res) {
  5259. res.set_header("x-dav-match", req.matches[1]);
  5260. res.status = StatusCode::MultiStatus_207;
  5261. })
  5262. .CustomRoute("MKCOL", "/dav-mkcol",
  5263. [&](const Request &req, Response &res) {
  5264. EXPECT_TRUE(req.body.empty());
  5265. res.status = StatusCode::Created_201;
  5266. })
  5267. .CustomRoute(
  5268. "REPORT", "/dav-report",
  5269. [&](const Request & /*req*/, Response &res,
  5270. const ContentReader &content_reader) {
  5271. std::string body;
  5272. content_reader([&](const char *data, size_t data_length) {
  5273. body.append(data, data_length);
  5274. return true;
  5275. });
  5276. res.set_header("x-body-size", std::to_string(body.size()));
  5277. res.status = StatusCode::MultiStatus_207;
  5278. res.set_content(body, "application/xml");
  5279. })
  5280. .Get("/request-target",
  5281. [&](const Request &req, Response & /*res*/) {
  5282. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5283. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5284. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5285. })
  5286. .Get("/long-query-value",
  5287. [&](const Request &req, Response & /*res*/) {
  5288. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5289. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5290. })
  5291. .Get("/too-long-query-value",
  5292. [&](const Request &req, Response & /*res*/) {
  5293. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5294. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5295. })
  5296. .Get("/array-param",
  5297. [&](const Request &req, Response & /*res*/) {
  5298. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5299. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5300. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5301. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5302. })
  5303. .Get("/array-param-values",
  5304. [&](const Request &req, Response & /*res*/) {
  5305. auto values = req.get_param_values("array");
  5306. EXPECT_EQ(3u, values.size());
  5307. EXPECT_EQ("value1", values[0]);
  5308. EXPECT_EQ("value2", values[1]);
  5309. EXPECT_EQ("value3", values[2]);
  5310. auto empty = req.get_param_values("nonexistent");
  5311. EXPECT_TRUE(empty.empty());
  5312. })
  5313. .Post("/validate-no-multiple-headers",
  5314. [&](const Request &req, Response & /*res*/) {
  5315. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5316. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5317. })
  5318. .Post("/content_receiver",
  5319. [&](const Request &req, Response &res,
  5320. const ContentReader &content_reader) {
  5321. if (req.is_multipart_form_data()) {
  5322. std::vector<FormData> items;
  5323. content_reader(
  5324. [&](const FormData &file) {
  5325. items.push_back(file);
  5326. return true;
  5327. },
  5328. [&](const char *data, size_t data_length) {
  5329. items.back().content.append(data, data_length);
  5330. return true;
  5331. });
  5332. EXPECT_EQ(5u, items.size());
  5333. {
  5334. const auto &file = get_file_value(items, "text1");
  5335. EXPECT_TRUE(file.filename.empty());
  5336. EXPECT_EQ("text default", file.content);
  5337. }
  5338. {
  5339. const auto &file = get_file_value(items, "text2");
  5340. EXPECT_TRUE(file.filename.empty());
  5341. EXPECT_EQ("aωb", file.content);
  5342. }
  5343. {
  5344. const auto &file = get_file_value(items, "file1");
  5345. EXPECT_EQ("hello.txt", file.filename);
  5346. EXPECT_EQ("text/plain", file.content_type);
  5347. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5348. }
  5349. {
  5350. const auto &file = get_file_value(items, "file2");
  5351. EXPECT_EQ("world.json", file.filename);
  5352. EXPECT_EQ("application/json", file.content_type);
  5353. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5354. }
  5355. {
  5356. const auto &file = get_file_value(items, "file3");
  5357. EXPECT_TRUE(file.filename.empty());
  5358. EXPECT_EQ("application/octet-stream", file.content_type);
  5359. EXPECT_EQ(0u, file.content.size());
  5360. }
  5361. } else {
  5362. std::string body;
  5363. content_reader([&](const char *data, size_t data_length) {
  5364. EXPECT_EQ(7U, data_length);
  5365. body.append(data, data_length);
  5366. return true;
  5367. });
  5368. EXPECT_EQ(body, "content");
  5369. res.set_content(body, "text/plain");
  5370. }
  5371. })
  5372. .Put("/content_receiver",
  5373. [&](const Request & /*req*/, Response &res,
  5374. const ContentReader &content_reader) {
  5375. std::string body;
  5376. content_reader([&](const char *data, size_t data_length) {
  5377. body.append(data, data_length);
  5378. return true;
  5379. });
  5380. EXPECT_EQ(body, "content");
  5381. res.set_content(body, "text/plain");
  5382. })
  5383. .Patch("/content_receiver",
  5384. [&](const Request & /*req*/, Response &res,
  5385. const ContentReader &content_reader) {
  5386. std::string body;
  5387. content_reader([&](const char *data, size_t data_length) {
  5388. body.append(data, data_length);
  5389. return true;
  5390. });
  5391. EXPECT_EQ(body, "content");
  5392. res.set_content(body, "text/plain");
  5393. })
  5394. .Post("/query-string-and-body",
  5395. [&](const Request &req, Response & /*res*/) {
  5396. ASSERT_TRUE(req.has_param("key"));
  5397. EXPECT_EQ(req.get_param_value("key"), "value");
  5398. EXPECT_EQ(req.body, "content");
  5399. })
  5400. .Get("/last-request",
  5401. [&](const Request &req, Response & /*res*/) {
  5402. EXPECT_EQ("close", req.get_header_value("Connection"));
  5403. })
  5404. .Get(R"(/redirect/(\d+))",
  5405. [&](const Request &req, Response &res) {
  5406. auto num = std::stoi(req.matches[1]) + 1;
  5407. std::string url = "/redirect/" + std::to_string(num);
  5408. res.set_redirect(url);
  5409. })
  5410. .Post("/binary",
  5411. [&](const Request &req, Response &res) {
  5412. EXPECT_EQ(4U, req.body.size());
  5413. EXPECT_EQ("application/octet-stream",
  5414. req.get_header_value("Content-Type"));
  5415. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5416. res.set_content(req.body, "application/octet-stream");
  5417. })
  5418. .Put("/binary",
  5419. [&](const Request &req, Response &res) {
  5420. EXPECT_EQ(4U, req.body.size());
  5421. EXPECT_EQ("application/octet-stream",
  5422. req.get_header_value("Content-Type"));
  5423. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5424. res.set_content(req.body, "application/octet-stream");
  5425. })
  5426. .Patch("/binary",
  5427. [&](const Request &req, Response &res) {
  5428. EXPECT_EQ(4U, req.body.size());
  5429. EXPECT_EQ("application/octet-stream",
  5430. req.get_header_value("Content-Type"));
  5431. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5432. res.set_content(req.body, "application/octet-stream");
  5433. })
  5434. .Delete("/binary",
  5435. [&](const Request &req, Response &res) {
  5436. EXPECT_EQ(4U, req.body.size());
  5437. EXPECT_EQ("application/octet-stream",
  5438. req.get_header_value("Content-Type"));
  5439. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5440. res.set_content(req.body, "application/octet-stream");
  5441. })
  5442. .Get("/issue1772",
  5443. [&](const Request & /*req*/, Response &res) {
  5444. res.status = 401;
  5445. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5446. })
  5447. .Delete("/issue609",
  5448. [](const httplib::Request &, httplib::Response &res,
  5449. const httplib::ContentReader &) {
  5450. res.set_content("ok", "text/plain");
  5451. })
  5452. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5453. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5454. .Get("/compress",
  5455. [&](const Request & /*req*/, Response &res) {
  5456. res.set_content(
  5457. "12345678901234567890123456789012345678901234567890123456789"
  5458. "01234567890123456789012345678901234567890",
  5459. "text/plain");
  5460. })
  5461. .Get("/compress-with-charset",
  5462. [&](const Request & /*req*/, Response &res) {
  5463. res.set_content(
  5464. "12345678901234567890123456789012345678901234567890123456789"
  5465. "01234567890123456789012345678901234567890",
  5466. "application/json; charset=utf-8");
  5467. })
  5468. .Get("/nocompress",
  5469. [&](const Request & /*req*/, Response &res) {
  5470. res.set_content(
  5471. "12345678901234567890123456789012345678901234567890123456789"
  5472. "01234567890123456789012345678901234567890",
  5473. "application/octet-stream");
  5474. })
  5475. .Post("/compress-multipart",
  5476. [&](const Request &req, Response & /*res*/) {
  5477. EXPECT_EQ(2u, req.form.fields.size());
  5478. ASSERT_TRUE(!req.form.has_field("???"));
  5479. {
  5480. const auto &text = req.form.get_field("key1");
  5481. EXPECT_EQ("test", text);
  5482. }
  5483. {
  5484. const auto &text = req.form.get_field("key2");
  5485. EXPECT_EQ("--abcdefg123", text);
  5486. }
  5487. })
  5488. #endif
  5489. ;
  5490. persons_["john"] = "programmer";
  5491. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5492. svr_.wait_until_ready();
  5493. }
  5494. virtual void TearDown() {
  5495. svr_.stop();
  5496. if (!request_threads_.empty()) {
  5497. std::this_thread::sleep_for(std::chrono::seconds(1));
  5498. for (auto &t : request_threads_) {
  5499. t.join();
  5500. }
  5501. }
  5502. t_.join();
  5503. }
  5504. map<string, string> persons_;
  5505. #ifdef CPPHTTPLIB_SSL_ENABLED
  5506. SSLClient cli_;
  5507. SSLServer svr_;
  5508. #else
  5509. Client cli_;
  5510. Server svr_;
  5511. #endif
  5512. thread t_;
  5513. std::vector<thread> request_threads_;
  5514. };
  5515. TEST_F(ServerTest, GetMethod200) {
  5516. auto res = cli_.Get("/hi");
  5517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5518. EXPECT_EQ("HTTP/1.1", res->version);
  5519. EXPECT_EQ(StatusCode::OK_200, res->status);
  5520. EXPECT_EQ("OK", res->reason);
  5521. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5522. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5523. EXPECT_EQ("Hello World!", res->body);
  5524. }
  5525. TEST_F(ServerTest, GetEmptyFile) {
  5526. auto res = cli_.Get("/empty_file");
  5527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5528. EXPECT_EQ(StatusCode::OK_200, res->status);
  5529. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5530. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5531. EXPECT_EQ("", res->body);
  5532. }
  5533. TEST_F(ServerTest, GetFileContent) {
  5534. auto res = cli_.Get("/file_content");
  5535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5536. EXPECT_EQ(StatusCode::OK_200, res->status);
  5537. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5538. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5539. EXPECT_EQ("test.html", res->body);
  5540. }
  5541. TEST_F(ServerTest, GetFileContentWithRange) {
  5542. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5544. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5545. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5546. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5547. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5548. EXPECT_EQ("est", res->body);
  5549. }
  5550. TEST_F(ServerTest, GetFileContentWithContentType) {
  5551. auto res = cli_.Get("/file_content_with_content_type");
  5552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5553. EXPECT_EQ(StatusCode::OK_200, res->status);
  5554. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5555. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5556. EXPECT_EQ("file\n", res->body);
  5557. }
  5558. TEST_F(ServerTest, GetInvalidFileContent) {
  5559. auto res = cli_.Get("/invalid_file_content");
  5560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5561. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5562. }
  5563. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5564. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5566. EXPECT_EQ("HTTP/1.1", res->version);
  5567. EXPECT_EQ(StatusCode::OK_200, res->status);
  5568. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5569. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5570. EXPECT_EQ("Hello World!", res->body);
  5571. }
  5572. TEST_F(ServerTest, GetMethod302) {
  5573. auto res = cli_.Get("/");
  5574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5575. EXPECT_EQ(StatusCode::Found_302, res->status);
  5576. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5577. }
  5578. TEST_F(ServerTest, GetMethod302Redirect) {
  5579. cli_.set_follow_location(true);
  5580. auto res = cli_.Get("/");
  5581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5582. EXPECT_EQ(StatusCode::OK_200, res->status);
  5583. EXPECT_EQ("Hello World!", res->body);
  5584. EXPECT_EQ("/hi", res->location);
  5585. }
  5586. TEST_F(ServerTest, GetMethod404) {
  5587. auto res = cli_.Get("/invalid");
  5588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5589. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5590. }
  5591. TEST_F(ServerTest, HeadMethod200) {
  5592. auto res = cli_.Head("/hi");
  5593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5594. EXPECT_EQ(StatusCode::OK_200, res->status);
  5595. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5596. EXPECT_TRUE(res->body.empty());
  5597. }
  5598. TEST_F(ServerTest, HeadMethod200Static) {
  5599. auto res = cli_.Head("/mount/dir/index.html");
  5600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5601. EXPECT_EQ(StatusCode::OK_200, res->status);
  5602. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5603. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5604. EXPECT_TRUE(res->body.empty());
  5605. }
  5606. TEST_F(ServerTest, HeadMethod404) {
  5607. auto res = cli_.Head("/invalid");
  5608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5609. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5610. EXPECT_TRUE(res->body.empty());
  5611. }
  5612. TEST_F(ServerTest, GetMethodPersonJohn) {
  5613. auto res = cli_.Get("/person/john");
  5614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5615. EXPECT_EQ(StatusCode::OK_200, res->status);
  5616. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5617. EXPECT_EQ("programmer", res->body);
  5618. }
  5619. TEST_F(ServerTest, PostMethod1) {
  5620. auto res = cli_.Get("/person/john1");
  5621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5622. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5623. res = cli_.Post("/person", "name=john1&note=coder",
  5624. "application/x-www-form-urlencoded");
  5625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5626. ASSERT_EQ(StatusCode::OK_200, res->status);
  5627. res = cli_.Get("/person/john1");
  5628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5629. ASSERT_EQ(StatusCode::OK_200, res->status);
  5630. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5631. ASSERT_EQ("coder", res->body);
  5632. }
  5633. TEST_F(ServerTest, PostMethod2) {
  5634. auto res = cli_.Get("/person/john2");
  5635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5636. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5637. Params params;
  5638. params.emplace("name", "john2");
  5639. params.emplace("note", "coder");
  5640. res = cli_.Post("/person", params);
  5641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5642. ASSERT_EQ(StatusCode::OK_200, res->status);
  5643. res = cli_.Get("/person/john2");
  5644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5645. ASSERT_EQ(StatusCode::OK_200, res->status);
  5646. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5647. ASSERT_EQ("coder", res->body);
  5648. }
  5649. TEST_F(ServerTest, PutMethod3) {
  5650. auto res = cli_.Get("/person/john3");
  5651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5652. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5653. Params params;
  5654. params.emplace("name", "john3");
  5655. params.emplace("note", "coder");
  5656. res = cli_.Put("/person", params);
  5657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5658. ASSERT_EQ(StatusCode::OK_200, res->status);
  5659. res = cli_.Get("/person/john3");
  5660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5661. ASSERT_EQ(StatusCode::OK_200, res->status);
  5662. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5663. ASSERT_EQ("coder", res->body);
  5664. }
  5665. TEST_F(ServerTest, DeleteMethod1) {
  5666. auto res = cli_.Get("/person/john4");
  5667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5668. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5669. Params params;
  5670. params.emplace("name", "john4");
  5671. params.emplace("note", "coder");
  5672. res = cli_.Post("/person", params);
  5673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5674. ASSERT_EQ(StatusCode::OK_200, res->status);
  5675. res = cli_.Get("/person/john4");
  5676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5677. ASSERT_EQ(StatusCode::OK_200, res->status);
  5678. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5679. ASSERT_EQ("coder", res->body);
  5680. Params delete_params;
  5681. delete_params.emplace("name", "john4");
  5682. res = cli_.Delete("/person", delete_params);
  5683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5684. ASSERT_EQ(StatusCode::OK_200, res->status);
  5685. ASSERT_EQ("DELETED", res->body);
  5686. res = cli_.Get("/person/john4");
  5687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5688. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5689. }
  5690. TEST_F(ServerTest, DeleteMethod2) {
  5691. auto res = cli_.Get("/person/john5");
  5692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5693. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5694. Params params;
  5695. params.emplace("name", "john5");
  5696. params.emplace("note", "developer");
  5697. res = cli_.Post("/person", params);
  5698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5699. ASSERT_EQ(StatusCode::OK_200, res->status);
  5700. res = cli_.Get("/person/john5");
  5701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5702. ASSERT_EQ(StatusCode::OK_200, res->status);
  5703. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5704. ASSERT_EQ("developer", res->body);
  5705. Params delete_params;
  5706. delete_params.emplace("name", "john5");
  5707. Headers headers;
  5708. headers.emplace("Custom-Header", "test-value");
  5709. res = cli_.Delete("/person", headers, delete_params);
  5710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5711. ASSERT_EQ(StatusCode::OK_200, res->status);
  5712. ASSERT_EQ("DELETED", res->body);
  5713. res = cli_.Get("/person/john5");
  5714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5715. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5716. }
  5717. TEST_F(ServerTest, DeleteMethod3) {
  5718. auto res = cli_.Get("/person/john6");
  5719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5720. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5721. Params params;
  5722. params.emplace("name", "john6");
  5723. params.emplace("note", "tester");
  5724. res = cli_.Post("/person", params);
  5725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5726. ASSERT_EQ(StatusCode::OK_200, res->status);
  5727. res = cli_.Get("/person/john6");
  5728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5729. ASSERT_EQ(StatusCode::OK_200, res->status);
  5730. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5731. ASSERT_EQ("tester", res->body);
  5732. Params delete_params;
  5733. delete_params.emplace("name", "john6");
  5734. Headers headers;
  5735. headers.emplace("Custom-Header", "test-value");
  5736. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5738. ASSERT_EQ(StatusCode::OK_200, res->status);
  5739. ASSERT_EQ("DELETED", res->body);
  5740. res = cli_.Get("/person/john6");
  5741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5742. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5743. }
  5744. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5745. Params params;
  5746. params.emplace("json", JSON_DATA);
  5747. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5749. ASSERT_EQ(StatusCode::OK_200, res->status);
  5750. ASSERT_EQ(JSON_DATA, res->body);
  5751. }
  5752. TEST_F(ServerTest, PostEmptyContent) {
  5753. auto res = cli_.Post("/empty", "", "text/plain");
  5754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5755. ASSERT_EQ(StatusCode::OK_200, res->status);
  5756. ASSERT_EQ("empty", res->body);
  5757. }
  5758. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5759. auto res = cli_.Post("/empty-no-content-type");
  5760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5761. ASSERT_EQ(StatusCode::OK_200, res->status);
  5762. ASSERT_EQ("empty-no-content-type", res->body);
  5763. }
  5764. TEST_F(ServerTest, PostPathOnly) {
  5765. auto res = cli_.Post("/path-only");
  5766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5767. ASSERT_EQ(StatusCode::OK_200, res->status);
  5768. ASSERT_EQ("path-only", res->body);
  5769. }
  5770. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5771. auto res = cli_.Post("/path-headers-only",
  5772. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5774. ASSERT_EQ(StatusCode::OK_200, res->status);
  5775. ASSERT_EQ("path-headers-only", res->body);
  5776. }
  5777. TEST_F(ServerTest, PostLarge) {
  5778. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5780. ASSERT_EQ(StatusCode::OK_200, res->status);
  5781. EXPECT_EQ(LARGE_DATA, res->body);
  5782. }
  5783. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5784. auto res = cli_.Put("/empty-no-content-type");
  5785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5786. ASSERT_EQ(StatusCode::OK_200, res->status);
  5787. ASSERT_EQ("empty-no-content-type", res->body);
  5788. }
  5789. TEST_F(ServerTest, GetMethodDir) {
  5790. auto res = cli_.Get("/dir/");
  5791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5792. EXPECT_EQ(StatusCode::OK_200, res->status);
  5793. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5794. auto body = R"(<html>
  5795. <head>
  5796. </head>
  5797. <body>
  5798. <a href="/dir/test.html">Test</a>
  5799. <a href="/hi">hi</a>
  5800. </body>
  5801. </html>
  5802. )";
  5803. EXPECT_EQ(body, res->body);
  5804. }
  5805. TEST_F(ServerTest, GetMethodDirTest) {
  5806. auto res = cli_.Get("/dir/test.html");
  5807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5808. EXPECT_EQ(StatusCode::OK_200, res->status);
  5809. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5810. EXPECT_EQ("test.html", res->body);
  5811. }
  5812. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5813. auto res = cli_.Get("/dir/../dir/test.html");
  5814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5815. EXPECT_EQ(StatusCode::OK_200, res->status);
  5816. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5817. EXPECT_EQ("test.html", res->body);
  5818. }
  5819. TEST_F(ServerTest, GetMethodInvalidPath) {
  5820. auto res = cli_.Get("/dir/../test.html");
  5821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5822. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5823. }
  5824. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5825. auto res = cli_.Get("/../www/dir/test.html");
  5826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5827. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5828. }
  5829. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5830. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5832. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5833. }
  5834. TEST_F(ServerTest, GetMethodDirMountTest) {
  5835. auto res = cli_.Get("/mount/dir/test.html");
  5836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5837. EXPECT_EQ(StatusCode::OK_200, res->status);
  5838. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5839. EXPECT_EQ("test.html", res->body);
  5840. }
  5841. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5842. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5844. EXPECT_EQ(StatusCode::OK_200, res->status);
  5845. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5846. EXPECT_EQ("test.html", res->body);
  5847. }
  5848. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5849. auto res = cli_.Get("/mount/dir/../test.html");
  5850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5851. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5852. }
  5853. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5854. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5856. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5857. }
  5858. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5859. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5861. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5862. }
  5863. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5864. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5866. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5867. }
  5868. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5869. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5871. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5872. }
  5873. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  5874. auto res = cli_.Get("/mount/dir");
  5875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5876. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5877. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5878. }
  5879. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  5880. auto res = cli_.Get("//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, PostMethod303) {
  5886. auto res = cli_.Post("/1", "body", "text/plain");
  5887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5888. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5889. EXPECT_EQ("/2", res->get_header_value("Location"));
  5890. }
  5891. TEST_F(ServerTest, PostMethod303Redirect) {
  5892. cli_.set_follow_location(true);
  5893. auto res = cli_.Post("/1", "body", "text/plain");
  5894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5895. EXPECT_EQ(StatusCode::OK_200, res->status);
  5896. EXPECT_EQ("redirected.", res->body);
  5897. EXPECT_EQ("/2", res->location);
  5898. }
  5899. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5900. auto res = cli_.Get("/dir/test.abcde");
  5901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5902. EXPECT_EQ(StatusCode::OK_200, res->status);
  5903. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5904. EXPECT_EQ("abcde", res->body);
  5905. }
  5906. TEST_F(ServerTest, StaticFileRange) {
  5907. auto res =
  5908. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5910. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5911. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5912. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5913. EXPECT_EQ(true, res->has_header("Content-Range"));
  5914. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5915. EXPECT_EQ(std::string("cd"), res->body);
  5916. }
  5917. TEST_F(ServerTest, StaticFileRanges) {
  5918. auto res = cli_.Get("/dir/test.abcde",
  5919. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5921. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5922. EXPECT_TRUE(
  5923. res->get_header_value("Content-Type")
  5924. .find(
  5925. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5926. 0);
  5927. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5928. }
  5929. TEST_F(ServerTest, StaticFileRangeHead) {
  5930. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5932. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5933. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5934. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5935. EXPECT_EQ(true, res->has_header("Content-Range"));
  5936. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5937. }
  5938. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5939. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5941. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5942. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5943. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5944. EXPECT_EQ(true, res->has_header("Content-Range"));
  5945. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5946. res->get_header_value("Content-Range"));
  5947. EXPECT_EQ("LAST\n", res->body);
  5948. }
  5949. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5950. auto res =
  5951. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5953. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5954. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5955. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5956. EXPECT_EQ(true, res->has_header("Content-Range"));
  5957. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5958. }
  5959. TEST_F(ServerTest, StaticFileBigFile) {
  5960. auto res = cli_.Get("/dir/1MB.txt");
  5961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5962. EXPECT_EQ(StatusCode::OK_200, res->status);
  5963. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5964. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5965. }
  5966. TEST_F(ServerTest, InvalidBaseDirMount) {
  5967. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5968. }
  5969. TEST_F(ServerTest, Binary) {
  5970. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5971. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5972. "application/octet-stream");
  5973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5974. ASSERT_EQ(StatusCode::OK_200, res->status);
  5975. ASSERT_EQ(4U, res->body.size());
  5976. res = cli_.Put("/binary", binary.data(), binary.size(),
  5977. "application/octet-stream");
  5978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5979. ASSERT_EQ(StatusCode::OK_200, res->status);
  5980. ASSERT_EQ(4U, res->body.size());
  5981. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5982. "application/octet-stream");
  5983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5984. ASSERT_EQ(StatusCode::OK_200, res->status);
  5985. ASSERT_EQ(4U, res->body.size());
  5986. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5987. "application/octet-stream");
  5988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5989. ASSERT_EQ(StatusCode::OK_200, res->status);
  5990. ASSERT_EQ(4U, res->body.size());
  5991. }
  5992. TEST_F(ServerTest, BinaryString) {
  5993. auto binary = std::string("\x00\x01\x02\x03", 4);
  5994. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5996. ASSERT_EQ(StatusCode::OK_200, res->status);
  5997. ASSERT_EQ(4U, res->body.size());
  5998. res = cli_.Put("/binary", binary, "application/octet-stream");
  5999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6000. ASSERT_EQ(StatusCode::OK_200, res->status);
  6001. ASSERT_EQ(4U, res->body.size());
  6002. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6004. ASSERT_EQ(StatusCode::OK_200, res->status);
  6005. ASSERT_EQ(4U, res->body.size());
  6006. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6008. ASSERT_EQ(StatusCode::OK_200, res->status);
  6009. ASSERT_EQ(4U, res->body.size());
  6010. }
  6011. TEST_F(ServerTest, EmptyRequest) {
  6012. auto res = cli_.Get("");
  6013. ASSERT_TRUE(!res);
  6014. EXPECT_EQ(Error::Connection, res.error());
  6015. }
  6016. TEST_F(ServerTest, LongRequest) {
  6017. std::string request;
  6018. for (size_t i = 0; i < 545; i++) {
  6019. request += "/TooLongRequest";
  6020. }
  6021. request += "OK";
  6022. auto res = cli_.Get(request.c_str());
  6023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6024. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6025. }
  6026. TEST_F(ServerTest, TooLongRequest) {
  6027. std::string request;
  6028. for (size_t i = 0; i < 546; i++) {
  6029. request += "/TooLongRequest";
  6030. }
  6031. request += "_NG";
  6032. auto start = std::chrono::high_resolution_clock::now();
  6033. cli_.set_keep_alive(true);
  6034. auto res = cli_.Get(request.c_str());
  6035. auto end = std::chrono::high_resolution_clock::now();
  6036. auto elapsed =
  6037. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6038. .count();
  6039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6040. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6041. EXPECT_LE(elapsed, 1000);
  6042. EXPECT_EQ("close", res->get_header_value("Connection"));
  6043. EXPECT_FALSE(cli_.is_socket_open());
  6044. }
  6045. TEST_F(ServerTest, AlmostTooLongRequest) {
  6046. // test for #2046 - URI length check shouldn't include other content on req
  6047. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6048. // leading /, space, HTTP/1.1)
  6049. std::string request =
  6050. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6051. auto res = cli_.Get(request.c_str());
  6052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6053. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6054. }
  6055. TEST_F(ServerTest, LongHeader) {
  6056. Request req;
  6057. req.method = "GET";
  6058. req.path = "/hi";
  6059. std::string host_and_port;
  6060. host_and_port += HOST;
  6061. host_and_port += ":";
  6062. host_and_port += std::to_string(PORT);
  6063. req.headers.emplace("Host", host_and_port.c_str());
  6064. req.headers.emplace("Accept", "*/*");
  6065. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6066. req.headers.emplace(
  6067. "Header-Name",
  6068. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6069. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6070. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6071. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6072. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6073. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6074. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6075. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6076. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6077. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6078. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6079. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6080. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6081. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6082. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6083. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6084. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6085. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6086. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6087. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6088. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6089. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6090. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6091. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6092. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6093. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6094. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6095. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6096. "@@@@@@@@@@@@@@@@");
  6097. auto res = std::make_shared<Response>();
  6098. auto error = Error::Success;
  6099. auto ret = cli_.send(req, *res, error);
  6100. ASSERT_TRUE(ret);
  6101. EXPECT_EQ(StatusCode::OK_200, res->status);
  6102. }
  6103. TEST_F(ServerTest, LongQueryValue) {
  6104. auto start = std::chrono::high_resolution_clock::now();
  6105. cli_.set_keep_alive(true);
  6106. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6107. auto end = std::chrono::high_resolution_clock::now();
  6108. auto elapsed =
  6109. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6110. .count();
  6111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6112. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6113. EXPECT_LE(elapsed, 1000);
  6114. EXPECT_EQ("close", res->get_header_value("Connection"));
  6115. EXPECT_FALSE(cli_.is_socket_open());
  6116. }
  6117. TEST_F(ServerTest, TooLongQueryValue) {
  6118. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6119. ASSERT_FALSE(res);
  6120. EXPECT_EQ(Error::Read, res.error());
  6121. }
  6122. TEST_F(ServerTest, TooLongHeader) {
  6123. Request req;
  6124. req.method = "GET";
  6125. req.path = "/hi";
  6126. std::string host_and_port;
  6127. host_and_port += HOST;
  6128. host_and_port += ":";
  6129. host_and_port += std::to_string(PORT);
  6130. req.headers.emplace("Host", host_and_port.c_str());
  6131. req.headers.emplace("Accept", "*/*");
  6132. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6133. req.headers.emplace(
  6134. "Header-Name",
  6135. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6136. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6137. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6138. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6139. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6140. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6141. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6142. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6143. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6144. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6145. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6146. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6147. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6148. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6149. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6150. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6151. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6152. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6153. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6154. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6155. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6156. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6157. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6158. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6159. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6160. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6161. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6162. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6163. "@@@@@@@@@@@@@@@@@");
  6164. auto res = std::make_shared<Response>();
  6165. auto error = Error::Success;
  6166. auto ret = cli_.send(req, *res, error);
  6167. ASSERT_TRUE(ret);
  6168. EXPECT_EQ(StatusCode::OK_200, res->status);
  6169. }
  6170. TEST_F(ServerTest, HeaderCountAtLimit) {
  6171. // Test with headers just under the 100 limit
  6172. httplib::Headers headers;
  6173. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6174. // This should keep us just under the 100 header limit
  6175. for (int i = 0; i < 95; i++) {
  6176. std::string name = "X-Test-Header-" + std::to_string(i);
  6177. std::string value = "value" + std::to_string(i);
  6178. headers.emplace(name, value);
  6179. }
  6180. // This should work fine as we're under the limit
  6181. auto res = cli_.Get("/hi", headers);
  6182. EXPECT_TRUE(res);
  6183. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6184. }
  6185. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6186. // Test with many headers to exceed the 100 limit
  6187. httplib::Headers headers;
  6188. // Add 150 headers to definitely exceed the 100 limit
  6189. for (int i = 0; i < 150; i++) {
  6190. std::string name = "X-Test-Header-" + std::to_string(i);
  6191. std::string value = "value" + std::to_string(i);
  6192. headers.emplace(name, value);
  6193. }
  6194. // This should fail due to exceeding header count limit
  6195. cli_.set_keep_alive(true);
  6196. auto res = cli_.Get("/hi", headers);
  6197. // The server should respond with 400 Bad Request
  6198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6199. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6200. EXPECT_EQ("close", res->get_header_value("Connection"));
  6201. EXPECT_FALSE(cli_.is_socket_open());
  6202. }
  6203. TEST_F(ServerTest, PercentEncoding) {
  6204. auto res = cli_.Get("/e%6edwith%");
  6205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6206. EXPECT_EQ(StatusCode::OK_200, res->status);
  6207. }
  6208. TEST_F(ServerTest, PercentEncodingUnicode) {
  6209. auto res = cli_.Get("/e%u006edwith%");
  6210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6211. EXPECT_EQ(StatusCode::OK_200, res->status);
  6212. }
  6213. TEST_F(ServerTest, InvalidPercentEncoding) {
  6214. auto res = cli_.Get("/%endwith%");
  6215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6216. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6217. }
  6218. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6219. auto res = cli_.Get("/%uendwith%");
  6220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6221. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6222. }
  6223. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6224. auto res = cli_.Get("/hello?aaa=bbb%");
  6225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6226. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6227. }
  6228. TEST_F(ServerTest, PlusSignEncoding) {
  6229. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6231. EXPECT_EQ(StatusCode::OK_200, res->status);
  6232. EXPECT_EQ("a +b", res->body);
  6233. }
  6234. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6235. // This test simulates a potential DoS attack using many headers
  6236. // to verify our security fix prevents memory exhaustion
  6237. httplib::Headers attack_headers;
  6238. // Attempt to add many headers like an attacker would (200 headers to far
  6239. // exceed limit)
  6240. for (int i = 0; i < 200; i++) {
  6241. std::string name = "X-Attack-Header-" + std::to_string(i);
  6242. std::string value = "attack_payload_" + std::to_string(i);
  6243. attack_headers.emplace(name, value);
  6244. }
  6245. // Try to POST with excessive headers
  6246. cli_.set_keep_alive(true);
  6247. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6248. // Should either fail or return 400 Bad Request due to security limit
  6249. if (res) {
  6250. // If we get a response, it should be 400 Bad Request
  6251. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6252. EXPECT_EQ("close", res->get_header_value("Connection"));
  6253. }
  6254. EXPECT_FALSE(cli_.is_socket_open());
  6255. }
  6256. TEST_F(ServerTest, MultipartFormData) {
  6257. UploadFormDataItems items = {
  6258. {"text1", "text default", "", ""},
  6259. {"text2", "aωb", "", ""},
  6260. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6261. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6262. {"file3", "", "", "application/octet-stream"},
  6263. {"file4", "", "", " application/json tmp-string "}};
  6264. auto res = cli_.Post("/multipart", items);
  6265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6266. EXPECT_EQ(StatusCode::OK_200, res->status);
  6267. }
  6268. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6269. UploadFormDataItems items = {
  6270. {"text", "default text", "", ""},
  6271. {"multi_text1", "aaaaa", "", ""},
  6272. {"multi_text1", "bbbbb", "", ""},
  6273. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6274. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6275. "application/json"},
  6276. };
  6277. auto res = cli_.Post("/multipart/multi_file_values", items);
  6278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6279. EXPECT_EQ(StatusCode::OK_200, res->status);
  6280. }
  6281. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6282. auto res = cli_.Get("/hi");
  6283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6284. EXPECT_EQ(StatusCode::OK_200, res->status);
  6285. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6286. EXPECT_EQ("Hello World!", res->body);
  6287. }
  6288. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6289. Request req;
  6290. req.method = "POST";
  6291. req.path = "/chunked";
  6292. std::string host_and_port;
  6293. host_and_port += HOST;
  6294. host_and_port += ":";
  6295. host_and_port += std::to_string(PORT);
  6296. req.headers.emplace("Host", host_and_port.c_str());
  6297. req.headers.emplace("Accept", "*/*");
  6298. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6299. req.headers.emplace("Content-Type", "text/plain");
  6300. req.headers.emplace("Content-Length", "0");
  6301. req.headers.emplace(
  6302. "Transfer-Encoding",
  6303. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6304. // Client does not chunk, so make a chunked body manually.
  6305. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6306. auto res = std::make_shared<Response>();
  6307. auto error = Error::Success;
  6308. auto ret = cli_.send(req, *res, error);
  6309. ASSERT_TRUE(ret);
  6310. EXPECT_EQ(StatusCode::OK_200, res->status);
  6311. }
  6312. template <typename ClientT>
  6313. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6314. int expected_status) {
  6315. Request req;
  6316. req.method = "POST";
  6317. req.path = "/chunked";
  6318. std::string host_and_port;
  6319. host_and_port += HOST;
  6320. host_and_port += ":";
  6321. host_and_port += std::to_string(PORT);
  6322. req.headers.emplace("Host", host_and_port.c_str());
  6323. req.headers.emplace("Content-Length", "0");
  6324. req.headers.emplace("Transfer-Encoding", "chunked");
  6325. req.body = body;
  6326. auto res = std::make_shared<Response>();
  6327. auto error = Error::Success;
  6328. ASSERT_TRUE(cli.send(req, *res, error));
  6329. EXPECT_EQ(expected_status, res->status);
  6330. }
  6331. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6332. // rather than treat them as valid lengths.
  6333. template <typename ClientT>
  6334. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6335. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6336. }
  6337. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6338. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6339. }
  6340. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6341. expect_chunked_body_rejected(
  6342. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6343. }
  6344. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6345. // chunk-size line carries no CR, LF or other control character ahead of its
  6346. // terminator. Such a line must be refused rather than read as extension text.
  6347. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6348. expect_chunked_body_rejected(
  6349. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6350. }
  6351. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6352. expect_chunked_body_rejected(
  6353. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6354. }
  6355. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6356. expect_chunked_body_rejected(
  6357. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6358. }
  6359. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6360. // The literal stays split: a hex escape consumes every hex digit that
  6361. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6362. expect_chunked_body_rejected(
  6363. cli_, "4;a\x01"
  6364. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6365. }
  6366. TEST_F(ServerTest, AcceptsChunkExtension) {
  6367. expect_chunked_body_status(cli_,
  6368. "4;name=value\r\ndech\r\n"
  6369. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6370. "0;last\r\n\r\n",
  6371. StatusCode::OK_200);
  6372. }
  6373. TEST_F(ServerTest, GetStreamed2) {
  6374. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6376. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6377. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6378. EXPECT_EQ(true, res->has_header("Content-Range"));
  6379. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6380. EXPECT_EQ(std::string("ab"), res->body);
  6381. }
  6382. TEST_F(ServerTest, GetStreamed) {
  6383. auto res = cli_.Get("/streamed");
  6384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6385. EXPECT_EQ(StatusCode::OK_200, res->status);
  6386. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6387. EXPECT_EQ(std::string("aaabbb"), res->body);
  6388. }
  6389. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6390. auto res = cli_.Get("/streamed-without-length",
  6391. Headers{make_range_header({{0, -1}})});
  6392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6393. EXPECT_EQ(StatusCode::OK_200, res->status);
  6394. EXPECT_EQ(false, res->has_header("Content-Length"));
  6395. EXPECT_EQ(false, res->has_header("Content-Range"));
  6396. EXPECT_EQ(std::string("abcdefg"), res->body);
  6397. }
  6398. TEST_F(ServerTest, GetStreamedWithRange1) {
  6399. auto res =
  6400. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6402. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6403. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6404. EXPECT_EQ(true, res->has_header("Content-Range"));
  6405. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6406. EXPECT_EQ(std::string("def"), res->body);
  6407. }
  6408. TEST_F(ServerTest, GetStreamedWithRange2) {
  6409. auto res =
  6410. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6412. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6413. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6414. EXPECT_EQ(true, res->has_header("Content-Range"));
  6415. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6416. EXPECT_EQ(std::string("bcdefg"), res->body);
  6417. }
  6418. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6419. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6421. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6422. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6423. EXPECT_EQ(true, res->has_header("Content-Range"));
  6424. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6425. EXPECT_EQ(std::string("efg"), res->body);
  6426. }
  6427. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6428. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6429. // the entire representation.
  6430. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6431. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6433. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6434. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6435. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6436. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6437. }
  6438. }
  6439. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6440. auto res =
  6441. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6443. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6444. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6445. EXPECT_EQ(false, res->has_header("Content-Range"));
  6446. EXPECT_EQ(0U, res->body.size());
  6447. }
  6448. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6449. // Only a 206 is served as a partial representation. Under any other status
  6450. // `apply_ranges()` reported the full content length, so the body must match
  6451. // that header, and the content provider must never be asked for an offset
  6452. // outside the representation.
  6453. auto check = [&](int status, const char *range) {
  6454. auto path =
  6455. std::string("/streamed-with-range?status=") + std::to_string(status);
  6456. auto ctx = path + " Range: " + range;
  6457. auto res = cli_.Get(path, Headers{{"Range", range}});
  6458. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6459. EXPECT_EQ(status, res->status) << ctx;
  6460. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6461. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6462. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6463. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6464. };
  6465. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6466. check(403, "bytes=3-5");
  6467. // The offset is far past the representation.
  6468. check(403, "bytes=100000-100200");
  6469. // `first_pos` is still -1 here, and the bounds asserts in
  6470. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6471. check(403, "bytes=-3");
  6472. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6473. // multipart branch would have written one that is empty.
  6474. check(403, "bytes=1-2, 4-5");
  6475. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6476. // covers the whole representation.
  6477. check(200, "bytes=3-5");
  6478. check(200, "bytes=1-2, 4-5");
  6479. }
  6480. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6481. auto res =
  6482. cli_.Get("/streamed-with-range",
  6483. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6484. "92233720368547758079223372036854775807"}});
  6485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6486. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6487. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6488. EXPECT_EQ(false, res->has_header("Content-Range"));
  6489. EXPECT_EQ(0U, res->body.size());
  6490. }
  6491. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6492. auto res = cli_.Get(
  6493. "/with-range",
  6494. Headers{{"Range",
  6495. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6496. {"Accept-Encoding", ""}});
  6497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6498. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6499. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6500. EXPECT_EQ(true, res->has_header("Content-Range"));
  6501. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6502. EXPECT_EQ(std::string("abcdefg"), res->body);
  6503. }
  6504. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6505. auto res = cli_.Get("/with-range", Headers{
  6506. {"Range", "bytes=0-"},
  6507. {"Accept-Encoding", ""},
  6508. });
  6509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6510. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6511. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6512. EXPECT_EQ(true, res->has_header("Content-Range"));
  6513. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6514. EXPECT_EQ(std::string("abcdefg"), res->body);
  6515. }
  6516. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6517. auto res = cli_.Get("/streamed-with-range",
  6518. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6520. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6521. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6522. EXPECT_EQ(false, res->has_header("Content-Range"));
  6523. EXPECT_EQ(267U, res->body.size());
  6524. // Check that both range contents are present
  6525. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6526. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6527. // Check that Content-Range headers are present for both ranges
  6528. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6529. std::string::npos);
  6530. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6531. std::string::npos);
  6532. }
  6533. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6534. Ranges ranges;
  6535. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6536. ranges.emplace_back(0, -1);
  6537. }
  6538. auto res = cli_.Get("/streamed-with-range?error",
  6539. Headers{{make_range_header(ranges)}});
  6540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6541. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6542. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6543. EXPECT_EQ(false, res->has_header("Content-Range"));
  6544. EXPECT_EQ(0U, res->body.size());
  6545. }
  6546. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6547. auto res = cli_.Get("/streamed-with-range",
  6548. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6550. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6551. EXPECT_EQ(5U, res->body.size());
  6552. // Check that overlapping ranges are coalesced into a single range
  6553. EXPECT_EQ("bcdef", res->body);
  6554. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6555. // Should be single range, not multipart
  6556. EXPECT_TRUE(res->has_header("Content-Range"));
  6557. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6558. }
  6559. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6560. auto res = cli_.Get("/streamed-with-range",
  6561. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6563. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6564. EXPECT_EQ(268U, res->body.size());
  6565. // Check that both range contents are present
  6566. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6567. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6568. // Check that Content-Range headers are present for both ranges
  6569. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6570. std::string::npos);
  6571. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6572. std::string::npos);
  6573. }
  6574. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6575. auto res = cli_.Get("/streamed-with-range",
  6576. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6578. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6579. EXPECT_EQ(269U, res->body.size());
  6580. // Check that both duplicate range contents are present
  6581. size_t first_abc = res->body.find("abc\r\n");
  6582. EXPECT_TRUE(first_abc != std::string::npos);
  6583. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6584. EXPECT_TRUE(second_abc != std::string::npos);
  6585. // Check that Content-Range headers are present for both ranges
  6586. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6587. EXPECT_TRUE(first_range != std::string::npos);
  6588. size_t second_range =
  6589. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6590. EXPECT_TRUE(second_range != std::string::npos);
  6591. }
  6592. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6593. auto res =
  6594. cli_.Get("/streamed-with-range?error",
  6595. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6597. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6598. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6599. EXPECT_EQ(false, res->has_header("Content-Range"));
  6600. EXPECT_EQ(0U, res->body.size());
  6601. }
  6602. TEST_F(ServerTest, GetStreamedEndless) {
  6603. uint64_t offset = 0;
  6604. auto res = cli_.Get("/streamed-cancel",
  6605. [&](const char * /*data*/, uint64_t data_length) {
  6606. if (offset < 100) {
  6607. offset += data_length;
  6608. return true;
  6609. }
  6610. return false;
  6611. });
  6612. ASSERT_TRUE(!res);
  6613. EXPECT_EQ(Error::Canceled, res.error());
  6614. }
  6615. TEST_F(ServerTest, ClientStop) {
  6616. std::atomic_size_t count{4};
  6617. std::vector<std::thread> threads;
  6618. for (auto i = count.load(); i != 0; --i) {
  6619. threads.emplace_back([&]() {
  6620. auto res = cli_.Get("/streamed-cancel",
  6621. [&](const char *, uint64_t) { return true; });
  6622. --count;
  6623. ASSERT_TRUE(!res);
  6624. EXPECT_TRUE(res.error() == Error::Canceled ||
  6625. res.error() == Error::Read || res.error() == Error::Write);
  6626. });
  6627. }
  6628. std::this_thread::sleep_for(std::chrono::seconds(2));
  6629. while (count != 0) {
  6630. cli_.stop();
  6631. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6632. }
  6633. for (auto &t : threads) {
  6634. t.join();
  6635. }
  6636. }
  6637. TEST_F(ServerTest, GetWithRange1) {
  6638. auto res = cli_.Get("/with-range", Headers{
  6639. make_range_header({{3, 5}}),
  6640. {"Accept-Encoding", ""},
  6641. });
  6642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6643. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6644. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6645. EXPECT_EQ(true, res->has_header("Content-Range"));
  6646. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6647. EXPECT_EQ(std::string("def"), res->body);
  6648. }
  6649. TEST_F(ServerTest, GetWithRange2) {
  6650. auto res = cli_.Get("/with-range", Headers{
  6651. make_range_header({{1, -1}}),
  6652. {"Accept-Encoding", ""},
  6653. });
  6654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6655. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6656. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6657. EXPECT_EQ(true, res->has_header("Content-Range"));
  6658. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6659. EXPECT_EQ(std::string("bcdefg"), res->body);
  6660. }
  6661. TEST_F(ServerTest, GetWithRange3) {
  6662. auto res = cli_.Get("/with-range", Headers{
  6663. make_range_header({{0, 0}}),
  6664. {"Accept-Encoding", ""},
  6665. });
  6666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6667. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6668. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6669. EXPECT_EQ(true, res->has_header("Content-Range"));
  6670. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6671. EXPECT_EQ(std::string("a"), res->body);
  6672. }
  6673. TEST_F(ServerTest, GetWithRange4) {
  6674. auto res = cli_.Get("/with-range", Headers{
  6675. make_range_header({{-1, 2}}),
  6676. {"Accept-Encoding", ""},
  6677. });
  6678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6679. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6680. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6681. EXPECT_EQ(true, res->has_header("Content-Range"));
  6682. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6683. EXPECT_EQ(std::string("fg"), res->body);
  6684. }
  6685. TEST_F(ServerTest, GetWithRange5) {
  6686. auto res = cli_.Get("/with-range", Headers{
  6687. make_range_header({{0, 5}}),
  6688. {"Accept-Encoding", ""},
  6689. });
  6690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6691. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6692. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6693. EXPECT_EQ(true, res->has_header("Content-Range"));
  6694. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6695. EXPECT_EQ(std::string("abcdef"), res->body);
  6696. }
  6697. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6698. auto res =
  6699. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6701. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6702. }
  6703. TEST_F(ServerTest, GetWithRangeMultipart) {
  6704. auto res =
  6705. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6707. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6708. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6709. EXPECT_EQ(false, res->has_header("Content-Range"));
  6710. EXPECT_EQ(267U, res->body.size());
  6711. }
  6712. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6713. auto res = cli_.Get("/with-range",
  6714. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6716. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6717. }
  6718. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6719. auto res = cli_.Get("/with-range-customized-response",
  6720. Headers{{make_range_header({{1, 2}})}});
  6721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6722. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6723. EXPECT_EQ(true, res->has_header("Content-Length"));
  6724. EXPECT_EQ(false, res->has_header("Content-Range"));
  6725. EXPECT_EQ(JSON_DATA, res->body);
  6726. }
  6727. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6728. auto res = cli_.Get("/with-range-customized-response",
  6729. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6731. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6732. EXPECT_EQ(true, res->has_header("Content-Length"));
  6733. EXPECT_EQ(false, res->has_header("Content-Range"));
  6734. EXPECT_EQ(JSON_DATA, res->body);
  6735. }
  6736. TEST_F(ServerTest, Issue1772) {
  6737. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6739. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6740. }
  6741. TEST_F(ServerTest, Issue609) {
  6742. auto res = cli_.Delete("/issue609");
  6743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6744. EXPECT_EQ(StatusCode::OK_200, res->status);
  6745. EXPECT_EQ(std::string("ok"), res->body);
  6746. }
  6747. TEST_F(ServerTest, GetStreamedChunked) {
  6748. auto res = cli_.Get("/streamed-chunked");
  6749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6750. EXPECT_EQ(StatusCode::OK_200, res->status);
  6751. EXPECT_EQ(std::string("123456789"), res->body);
  6752. }
  6753. TEST_F(ServerTest, GetStreamedChunked2) {
  6754. auto res = cli_.Get("/streamed-chunked2");
  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, GetStreamedChunkedWithTrailer) {
  6760. auto res = cli_.Get("/streamed-chunked-with-trailer");
  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. EXPECT_TRUE(res->has_header("Trailer"));
  6765. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6766. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6767. // Trailers are now stored separately from headers (security fix)
  6768. EXPECT_EQ(2U, res->trailers.size());
  6769. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6770. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6771. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6772. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6773. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6774. // Verify trailers are NOT in headers (security verification)
  6775. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6776. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6777. }
  6778. TEST_F(ServerTest, LargeChunkedPost) {
  6779. Request req;
  6780. req.method = "POST";
  6781. req.path = "/large-chunked";
  6782. std::string host_and_port;
  6783. host_and_port += HOST;
  6784. host_and_port += ":";
  6785. host_and_port += std::to_string(PORT);
  6786. req.headers.emplace("Host", host_and_port.c_str());
  6787. req.headers.emplace("Accept", "*/*");
  6788. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6789. req.headers.emplace("Content-Type", "text/plain");
  6790. req.headers.emplace("Content-Length", "0");
  6791. req.headers.emplace("Transfer-Encoding", "chunked");
  6792. std::string long_string(30 * 1024u, 'a');
  6793. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6794. // Attempt to make a large enough post to exceed OS buffers, to test that
  6795. // the server handles short reads if the full chunk data isn't available.
  6796. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6797. auto res = std::make_shared<Response>();
  6798. auto error = Error::Success;
  6799. auto ret = cli_.send(req, *res, error);
  6800. ASSERT_TRUE(ret);
  6801. EXPECT_EQ(StatusCode::OK_200, res->status);
  6802. }
  6803. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6804. auto res = cli_.Get("/remote_addr");
  6805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6806. EXPECT_EQ(StatusCode::OK_200, res->status);
  6807. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6808. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6809. }
  6810. TEST_F(ServerTest, GetMethodLocalAddr) {
  6811. auto res = cli_.Get("/local_addr");
  6812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6813. EXPECT_EQ(StatusCode::OK_200, res->status);
  6814. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6815. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6816. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6817. }
  6818. TEST_F(ServerTest, HTTPResponseSplitting) {
  6819. auto res = cli_.Get("/http_response_splitting");
  6820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6821. EXPECT_EQ(StatusCode::OK_200, res->status);
  6822. }
  6823. TEST_F(ServerTest, SlowRequest) {
  6824. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6825. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6826. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6827. }
  6828. #if 0
  6829. TEST_F(ServerTest, SlowPost) {
  6830. char buffer[64 * 1024];
  6831. memset(buffer, 0x42, sizeof(buffer));
  6832. auto res = cli_.Post(
  6833. "/slowpost", 64 * 1024 * 1024,
  6834. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6835. auto ret = sink.write(buffer, sizeof(buffer));
  6836. EXPECT_TRUE(ret);
  6837. return true;
  6838. },
  6839. "text/plain");
  6840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6841. EXPECT_EQ(StatusCode::OK_200, res->status);
  6842. }
  6843. TEST_F(ServerTest, SlowPostFail) {
  6844. char buffer[64 * 1024];
  6845. memset(buffer, 0x42, sizeof(buffer));
  6846. cli_.set_write_timeout(std::chrono::seconds(0));
  6847. auto res = cli_.Post(
  6848. "/slowpost", 64 * 1024 * 1024,
  6849. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6850. sink.write(buffer, sizeof(buffer));
  6851. return true;
  6852. },
  6853. "text/plain");
  6854. ASSERT_TRUE(!res);
  6855. EXPECT_EQ(Error::Write, res.error());
  6856. }
  6857. #endif
  6858. TEST_F(ServerTest, Put) {
  6859. auto res = cli_.Put("/put", "PUT", "text/plain");
  6860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6861. EXPECT_EQ(StatusCode::OK_200, res->status);
  6862. EXPECT_EQ("PUT", res->body);
  6863. }
  6864. TEST_F(ServerTest, PutWithContentProvider) {
  6865. auto res = cli_.Put(
  6866. "/put", 3,
  6867. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6868. sink.os << "PUT";
  6869. return true;
  6870. },
  6871. "text/plain");
  6872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6873. EXPECT_EQ(StatusCode::OK_200, res->status);
  6874. EXPECT_EQ("PUT", res->body);
  6875. }
  6876. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6877. auto res = cli_.Post(
  6878. "/post", 42,
  6879. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6880. return false;
  6881. },
  6882. "text/plain");
  6883. ASSERT_TRUE(!res);
  6884. EXPECT_EQ(Error::Canceled, res.error());
  6885. }
  6886. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6887. auto res = cli_.Put(
  6888. "/put",
  6889. [](size_t /*offset*/, DataSink &sink) {
  6890. sink.os << "PUT";
  6891. sink.done();
  6892. return true;
  6893. },
  6894. "text/plain");
  6895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6896. EXPECT_EQ(StatusCode::OK_200, res->status);
  6897. EXPECT_EQ("PUT", res->body);
  6898. }
  6899. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6900. auto res = cli_.Post(
  6901. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6902. "text/plain");
  6903. ASSERT_TRUE(!res);
  6904. EXPECT_EQ(Error::Canceled, res.error());
  6905. }
  6906. TEST_F(ServerTest, PostLoopBack) {
  6907. std::string body;
  6908. auto res = cli_.Post(
  6909. "/post-loopback", 9,
  6910. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6911. EXPECT_EQ(9u, length);
  6912. sink.write("123", 3);
  6913. sink.write("456", 3);
  6914. sink.write("789", 3);
  6915. return true;
  6916. },
  6917. "text/plain",
  6918. [&body](const char *data, size_t data_length) {
  6919. body.append(data, data_length);
  6920. return true;
  6921. });
  6922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6923. EXPECT_EQ(StatusCode::OK_200, res->status);
  6924. EXPECT_EQ("123456789", body);
  6925. }
  6926. TEST_F(ServerTest, PutLoopBack) {
  6927. std::string body;
  6928. auto res = cli_.Put(
  6929. "/put-loopback", 9,
  6930. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6931. EXPECT_EQ(9u, length);
  6932. sink.write("123", 3);
  6933. sink.write("456", 3);
  6934. sink.write("789", 3);
  6935. return true;
  6936. },
  6937. "text/plain",
  6938. [&body](const char *data, size_t data_length) {
  6939. body.append(data, data_length);
  6940. return true;
  6941. });
  6942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6943. EXPECT_EQ(StatusCode::OK_200, res->status);
  6944. EXPECT_EQ("123456789", body);
  6945. }
  6946. TEST_F(ServerTest, PatchLoopBack) {
  6947. std::string body;
  6948. auto res = cli_.Patch(
  6949. "/patch-loopback", 9,
  6950. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6951. EXPECT_EQ(9u, length);
  6952. sink.write("123", 3);
  6953. sink.write("456", 3);
  6954. sink.write("789", 3);
  6955. return true;
  6956. },
  6957. "text/plain",
  6958. [&body](const char *data, size_t data_length) {
  6959. body.append(data, data_length);
  6960. return true;
  6961. });
  6962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6963. EXPECT_EQ(StatusCode::OK_200, res->status);
  6964. EXPECT_EQ("123456789", body);
  6965. }
  6966. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6967. std::string body;
  6968. auto res = cli_.Post(
  6969. "/post-loopback",
  6970. [](size_t /*offset*/, DataSink &sink) {
  6971. sink.write("123", 3);
  6972. sink.write("456", 3);
  6973. sink.write("789", 3);
  6974. sink.done();
  6975. return true;
  6976. },
  6977. "text/plain",
  6978. [&body](const char *data, size_t data_length) {
  6979. body.append(data, data_length);
  6980. return true;
  6981. });
  6982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6983. EXPECT_EQ(StatusCode::OK_200, res->status);
  6984. EXPECT_EQ("123456789", body);
  6985. }
  6986. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6987. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6988. cli_.set_compress(true);
  6989. auto res = cli_.Put(
  6990. "/put", 3,
  6991. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6992. sink.os << "PUT";
  6993. return true;
  6994. },
  6995. "text/plain");
  6996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6997. EXPECT_EQ(StatusCode::OK_200, res->status);
  6998. EXPECT_EQ("PUT", res->body);
  6999. }
  7000. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7001. cli_.set_compress(true);
  7002. auto res = cli_.Post(
  7003. "/post", 42,
  7004. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7005. return false;
  7006. },
  7007. "text/plain");
  7008. ASSERT_TRUE(!res);
  7009. EXPECT_EQ(Error::Canceled, res.error());
  7010. }
  7011. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7012. cli_.set_compress(true);
  7013. auto res = cli_.Put(
  7014. "/put",
  7015. [](size_t /*offset*/, DataSink &sink) {
  7016. sink.os << "PUT";
  7017. sink.done();
  7018. return true;
  7019. },
  7020. "text/plain");
  7021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7022. EXPECT_EQ(StatusCode::OK_200, res->status);
  7023. EXPECT_EQ("PUT", res->body);
  7024. }
  7025. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7026. cli_.set_compress(true);
  7027. auto res = cli_.Post(
  7028. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7029. "text/plain");
  7030. ASSERT_TRUE(!res);
  7031. EXPECT_EQ(Error::Canceled, res.error());
  7032. }
  7033. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7034. cli_.set_compress(true);
  7035. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7037. EXPECT_EQ(StatusCode::OK_200, res->status);
  7038. EXPECT_EQ(LARGE_DATA, res->body);
  7039. }
  7040. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7041. #ifdef CPPHTTPLIB_SSL_ENABLED
  7042. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7043. Client cli(s.c_str());
  7044. cli.enable_server_certificate_verification(false);
  7045. #else
  7046. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7047. Client cli(s.c_str());
  7048. #endif
  7049. cli.set_compress(true);
  7050. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7052. EXPECT_EQ(StatusCode::OK_200, res->status);
  7053. EXPECT_EQ(LARGE_DATA, res->body);
  7054. // The compressed size should be less than a 10th of the original. May vary
  7055. // depending on the zlib library.
  7056. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7057. static_cast<uint64_t>(10 * 1024 * 1024));
  7058. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7059. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7060. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7061. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7062. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7063. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7064. #endif
  7065. }
  7066. TEST_F(ServerTest, PutContentWithDeflate) {
  7067. cli_.set_compress(false);
  7068. Headers headers;
  7069. headers.emplace("Content-Encoding", "deflate");
  7070. // PUT in deflate format:
  7071. auto res = cli_.Put("/put", headers,
  7072. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7074. EXPECT_EQ(StatusCode::OK_200, res->status);
  7075. EXPECT_EQ("PUT", res->body);
  7076. }
  7077. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7078. Headers headers;
  7079. headers.emplace("Accept-Encoding", "gzip, deflate");
  7080. auto res = cli_.Get("/streamed-chunked", headers);
  7081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7082. EXPECT_EQ(StatusCode::OK_200, res->status);
  7083. EXPECT_EQ(std::string("123456789"), res->body);
  7084. }
  7085. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7086. Headers headers;
  7087. headers.emplace("Accept-Encoding", "gzip, deflate");
  7088. auto res = cli_.Get("/streamed-chunked2", headers);
  7089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7090. EXPECT_EQ(StatusCode::OK_200, res->status);
  7091. EXPECT_EQ(std::string("123456789"), res->body);
  7092. }
  7093. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7094. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7096. EXPECT_EQ(StatusCode::OK_200, res->status);
  7097. }
  7098. TEST(GzipDecompressor, ChunkedDecompression) {
  7099. std::string data;
  7100. for (size_t i = 0; i < 32 * 1024; ++i) {
  7101. data.push_back(static_cast<char>('a' + i % 26));
  7102. }
  7103. std::string compressed_data;
  7104. {
  7105. httplib::detail::gzip_compressor compressor;
  7106. bool result = compressor.compress(
  7107. data.data(), data.size(),
  7108. /*last=*/true,
  7109. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7110. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7111. compressed_data_size);
  7112. return true;
  7113. });
  7114. ASSERT_TRUE(result);
  7115. }
  7116. std::string decompressed_data;
  7117. {
  7118. httplib::detail::gzip_decompressor decompressor;
  7119. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7120. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7121. size_t chunk_size = 130;
  7122. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7123. chunk_begin += chunk_size) {
  7124. size_t current_chunk_size =
  7125. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7126. bool result = decompressor.decompress(
  7127. compressed_data.data() + chunk_begin, current_chunk_size,
  7128. [&](const char *decompressed_data_chunk,
  7129. size_t decompressed_data_chunk_size) {
  7130. decompressed_data.insert(decompressed_data.size(),
  7131. decompressed_data_chunk,
  7132. decompressed_data_chunk_size);
  7133. return true;
  7134. });
  7135. ASSERT_TRUE(result);
  7136. }
  7137. }
  7138. ASSERT_EQ(data, decompressed_data);
  7139. }
  7140. TEST(GzipDecompressor, DeflateDecompression) {
  7141. std::string original_text = "Raw deflate without gzip";
  7142. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7143. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7144. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7145. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7146. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7147. std::string decompressed_data;
  7148. {
  7149. httplib::detail::gzip_decompressor decompressor;
  7150. bool result = decompressor.decompress(
  7151. compressed_data.data(), compressed_data.size(),
  7152. [&](const char *decompressed_data_chunk,
  7153. size_t decompressed_data_chunk_size) {
  7154. decompressed_data.insert(decompressed_data.size(),
  7155. decompressed_data_chunk,
  7156. decompressed_data_chunk_size);
  7157. return true;
  7158. });
  7159. ASSERT_TRUE(result);
  7160. }
  7161. ASSERT_EQ(original_text, decompressed_data);
  7162. }
  7163. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7164. std::string original_text = "Raw deflate without gzip";
  7165. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7166. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7167. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7168. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7169. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7170. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7171. std::string decompressed_data;
  7172. {
  7173. httplib::detail::gzip_decompressor decompressor;
  7174. bool result = decompressor.decompress(
  7175. compressed_data.data(), compressed_data.size(),
  7176. [&](const char *decompressed_data_chunk,
  7177. size_t decompressed_data_chunk_size) {
  7178. decompressed_data.insert(decompressed_data.size(),
  7179. decompressed_data_chunk,
  7180. decompressed_data_chunk_size);
  7181. return true;
  7182. });
  7183. ASSERT_TRUE(result);
  7184. }
  7185. ASSERT_EQ(original_text, decompressed_data);
  7186. }
  7187. #endif
  7188. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7189. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7190. Headers headers;
  7191. headers.emplace("Accept-Encoding", "br");
  7192. auto res = cli_.Get("/streamed-chunked", headers);
  7193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7194. EXPECT_EQ(StatusCode::OK_200, res->status);
  7195. EXPECT_EQ(std::string("123456789"), res->body);
  7196. }
  7197. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7198. Headers headers;
  7199. headers.emplace("Accept-Encoding", "br");
  7200. auto res = cli_.Get("/streamed-chunked2", headers);
  7201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7202. EXPECT_EQ(StatusCode::OK_200, res->status);
  7203. EXPECT_EQ(std::string("123456789"), res->body);
  7204. }
  7205. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7206. cli_.set_compress(true);
  7207. auto res = cli_.Put(
  7208. "/put", 3,
  7209. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7210. sink.os << "PUT";
  7211. return true;
  7212. },
  7213. "text/plain");
  7214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7215. EXPECT_EQ(StatusCode::OK_200, res->status);
  7216. EXPECT_EQ("PUT", res->body);
  7217. }
  7218. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7219. cli_.set_compress(true);
  7220. auto res = cli_.Put(
  7221. "/put",
  7222. [](size_t /*offset*/, DataSink &sink) {
  7223. sink.os << "PUT";
  7224. sink.done();
  7225. return true;
  7226. },
  7227. "text/plain");
  7228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7229. EXPECT_EQ(StatusCode::OK_200, res->status);
  7230. EXPECT_EQ("PUT", res->body);
  7231. }
  7232. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7233. cli_.set_compress(true);
  7234. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7236. EXPECT_EQ(StatusCode::OK_200, res->status);
  7237. EXPECT_EQ(LARGE_DATA, res->body);
  7238. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7239. }
  7240. #endif
  7241. TEST_F(ServerTest, Patch) {
  7242. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7244. EXPECT_EQ(StatusCode::OK_200, res->status);
  7245. EXPECT_EQ("PATCH", res->body);
  7246. }
  7247. TEST_F(ServerTest, Delete) {
  7248. auto res = cli_.Delete("/delete");
  7249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7250. EXPECT_EQ(StatusCode::OK_200, res->status);
  7251. EXPECT_EQ("DELETE", res->body);
  7252. }
  7253. TEST_F(ServerTest, DeleteContentReceiver) {
  7254. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7256. EXPECT_EQ(StatusCode::OK_200, res->status);
  7257. EXPECT_EQ("content", res->body);
  7258. }
  7259. TEST_F(ServerTest, Options) {
  7260. auto res = cli_.Options("*");
  7261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7262. EXPECT_EQ(StatusCode::OK_200, res->status);
  7263. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7264. EXPECT_TRUE(res->body.empty());
  7265. }
  7266. TEST_F(ServerTest, URL) {
  7267. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7269. EXPECT_EQ(StatusCode::OK_200, res->status);
  7270. }
  7271. TEST_F(ServerTest, ArrayParam) {
  7272. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7274. EXPECT_EQ(StatusCode::OK_200, res->status);
  7275. }
  7276. TEST_F(ServerTest, ArrayParamValues) {
  7277. auto res =
  7278. cli_.Get("/array-param-values?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, NoMultipleHeaders) {
  7283. Headers headers = {{"Content-Length", "5"}};
  7284. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7285. "text/plain");
  7286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7287. EXPECT_EQ(StatusCode::OK_200, res->status);
  7288. }
  7289. TEST_F(ServerTest, PostContentReceiver) {
  7290. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7292. ASSERT_EQ(StatusCode::OK_200, res->status);
  7293. ASSERT_EQ("content", res->body);
  7294. }
  7295. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7296. UploadFormDataItems items = {
  7297. {"text1", "text default", "", ""},
  7298. {"text2", "aωb", "", ""},
  7299. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7300. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7301. {"file3", "", "", "application/octet-stream"},
  7302. };
  7303. auto res = cli_.Post("/content_receiver", items);
  7304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7305. EXPECT_EQ(StatusCode::OK_200, res->status);
  7306. }
  7307. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7308. UploadFormDataItems items = {
  7309. {"text1", "text default", "", ""},
  7310. {"text2", "aωb", "", ""},
  7311. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7312. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7313. {"file3", "", "", "application/octet-stream"},
  7314. };
  7315. auto boundary = std::string("+++++");
  7316. std::string body;
  7317. for (const auto &item : items) {
  7318. body += "--" + boundary + "\r\n";
  7319. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7320. if (!item.filename.empty()) {
  7321. body += "; filename=\"" + item.filename + "\"";
  7322. }
  7323. body += "\r\n";
  7324. if (!item.content_type.empty()) {
  7325. body += "Content-Type: " + item.content_type + "\r\n";
  7326. }
  7327. body += "\r\n";
  7328. body += item.content + "\r\n";
  7329. }
  7330. body += "--" + boundary + "--\r\n";
  7331. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7332. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7334. EXPECT_EQ(StatusCode::OK_200, res->status);
  7335. }
  7336. TEST(MultipartFormDataTest, FieldEscaping) {
  7337. Server svr;
  7338. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7339. const ContentReader &content_reader) {
  7340. ASSERT_TRUE(req.is_multipart_form_data());
  7341. std::vector<FormData> received;
  7342. content_reader(
  7343. [&](const FormData &file) {
  7344. received.push_back(file);
  7345. return true;
  7346. },
  7347. [&](const char *data, size_t data_length) {
  7348. received.back().content.append(data, data_length);
  7349. return true;
  7350. });
  7351. // '"', CR and LF in names and filenames are escaped following the
  7352. // WHATWG HTML standard, so each part still parses as a single part
  7353. // with no injected headers. Content types get CR/LF escaped too,
  7354. // while '"' (legal there, e.g. quoted charset) is preserved.
  7355. ASSERT_EQ(4U, received.size());
  7356. EXPECT_EQ("na%22me", received[0].name);
  7357. EXPECT_EQ("quoted name", received[0].content);
  7358. EXPECT_EQ("file", received[1].name);
  7359. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7360. received[1].filename);
  7361. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7362. EXPECT_EQ("injected", received[1].content);
  7363. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7364. EXPECT_EQ("my%22file.txt", received[2].filename);
  7365. EXPECT_EQ("cr lf name", received[2].content);
  7366. EXPECT_EQ("typed", received[3].name);
  7367. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7368. received[3].content_type);
  7369. EXPECT_EQ("typed content", received[3].content);
  7370. });
  7371. auto port = svr.bind_to_any_port("localhost");
  7372. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7373. auto se = detail::scope_exit([&] {
  7374. svr.stop();
  7375. t.join();
  7376. ASSERT_FALSE(svr.is_running());
  7377. });
  7378. svr.wait_until_ready();
  7379. Client cli("localhost", port);
  7380. UploadFormDataItems items = {
  7381. {"na\"me", "quoted name", "", ""},
  7382. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7383. "application/octet-stream"},
  7384. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7385. {"typed", "typed content", "",
  7386. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7387. };
  7388. auto res = cli.Post("/post", items);
  7389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7390. EXPECT_EQ(StatusCode::OK_200, res->status);
  7391. }
  7392. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7393. const UploadFormDataItems items = {
  7394. {"name1", "Content 1", "", ""},
  7395. {"name2", "Content 2", "file2.txt", "text/plain"},
  7396. };
  7397. Server svr;
  7398. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7399. const ContentReader &content_reader) {
  7400. ASSERT_TRUE(req.is_multipart_form_data());
  7401. std::vector<FormData> received;
  7402. content_reader(
  7403. [&](const FormData &file) {
  7404. received.push_back(file);
  7405. return true;
  7406. },
  7407. [&](const char *data, size_t data_length) {
  7408. received.back().content.append(data, data_length);
  7409. return true;
  7410. });
  7411. ASSERT_EQ(2U, received.size());
  7412. EXPECT_EQ("name1", received[0].name);
  7413. EXPECT_EQ("Content 1", received[0].content);
  7414. EXPECT_EQ("name2", received[1].name);
  7415. EXPECT_EQ("Content 2", received[1].content);
  7416. EXPECT_EQ("file2.txt", received[1].filename);
  7417. EXPECT_EQ("text/plain", received[1].content_type);
  7418. });
  7419. auto port = svr.bind_to_any_port("localhost");
  7420. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7421. auto se = detail::scope_exit([&] {
  7422. svr.stop();
  7423. t.join();
  7424. ASSERT_FALSE(svr.is_running());
  7425. });
  7426. svr.wait_until_ready();
  7427. Client cli("localhost", port);
  7428. // Whole-body serialization with a generated boundary
  7429. {
  7430. MultipartFormDataWriter writer;
  7431. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7432. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7433. writer.content_type());
  7434. auto body = writer.serialize(items);
  7435. EXPECT_EQ(body.size(), writer.content_length(items));
  7436. auto res = cli.Post("/post", body, writer.content_type());
  7437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7438. EXPECT_EQ(StatusCode::OK_200, res->status);
  7439. }
  7440. // Per-part framing with a custom boundary via a content provider
  7441. {
  7442. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7443. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7444. MultipartFormDataWriter writer("custom-boundary_123");
  7445. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7446. std::string body;
  7447. for (const auto &item : items) {
  7448. body += writer.item_begin(item);
  7449. body += item.content;
  7450. body += MultipartFormDataWriter::item_end();
  7451. }
  7452. body += writer.finish();
  7453. EXPECT_EQ(body.size(), writer.content_length(items));
  7454. auto res = cli.Post(
  7455. "/post", body.size(),
  7456. [&](size_t offset, size_t length, DataSink &sink) {
  7457. sink.write(body.data() + offset, length);
  7458. return true;
  7459. },
  7460. writer.content_type());
  7461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7462. EXPECT_EQ(StatusCode::OK_200, res->status);
  7463. }
  7464. }
  7465. TEST_F(ServerTest, PostContentReceiverGzip) {
  7466. cli_.set_compress(true);
  7467. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7469. ASSERT_EQ(StatusCode::OK_200, res->status);
  7470. ASSERT_EQ("content", res->body);
  7471. }
  7472. TEST_F(ServerTest, PutContentReceiver) {
  7473. auto res = cli_.Put("/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, PatchContentReceiver) {
  7479. auto res = cli_.Patch("/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. template <typename ClientType>
  7485. void TestWithHeadersAndContentReceiver(
  7486. ClientType &cli,
  7487. std::function<Result(ClientType &, const std::string &, const Headers &,
  7488. const std::string &, const std::string &,
  7489. ContentReceiver, DownloadProgress)>
  7490. request_func) {
  7491. Headers headers;
  7492. headers.emplace("X-Custom-Header", "test-value");
  7493. std::string received_body;
  7494. auto res = request_func(
  7495. cli, "/content_receiver", headers, "content", "application/json",
  7496. [&](const char *data, size_t data_length) {
  7497. received_body.append(data, data_length);
  7498. return true;
  7499. },
  7500. nullptr);
  7501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7502. EXPECT_EQ(StatusCode::OK_200, res->status);
  7503. EXPECT_EQ("content", received_body);
  7504. }
  7505. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7506. #ifdef CPPHTTPLIB_SSL_ENABLED
  7507. using ClientT = SSLClient;
  7508. #else
  7509. using ClientT = Client;
  7510. #endif
  7511. TestWithHeadersAndContentReceiver<ClientT>(
  7512. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7513. const std::string &body, const std::string &content_type,
  7514. ContentReceiver receiver, DownloadProgress progress) {
  7515. return cli.Post(path, headers, body, content_type, receiver, progress);
  7516. });
  7517. }
  7518. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7519. #ifdef CPPHTTPLIB_SSL_ENABLED
  7520. using ClientT = SSLClient;
  7521. #else
  7522. using ClientT = Client;
  7523. #endif
  7524. TestWithHeadersAndContentReceiver<ClientT>(
  7525. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7526. const std::string &body, const std::string &content_type,
  7527. ContentReceiver receiver, DownloadProgress progress) {
  7528. return cli.Put(path, headers, body, content_type, receiver, progress);
  7529. });
  7530. }
  7531. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7532. #ifdef CPPHTTPLIB_SSL_ENABLED
  7533. using ClientT = SSLClient;
  7534. #else
  7535. using ClientT = Client;
  7536. #endif
  7537. TestWithHeadersAndContentReceiver<ClientT>(
  7538. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7539. const std::string &body, const std::string &content_type,
  7540. ContentReceiver receiver, DownloadProgress progress) {
  7541. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7542. });
  7543. }
  7544. template <typename ClientType>
  7545. void TestWithHeadersAndContentReceiverWithProgress(
  7546. ClientType &cli,
  7547. std::function<Result(ClientType &, const std::string &, const Headers &,
  7548. const std::string &, const std::string &,
  7549. ContentReceiver, DownloadProgress)>
  7550. request_func) {
  7551. Headers headers;
  7552. headers.emplace("X-Test-Header", "progress-test");
  7553. std::string received_body;
  7554. auto progress_called = false;
  7555. auto res = request_func(
  7556. cli, "/content_receiver", headers, "content", "text/plain",
  7557. [&](const char *data, size_t data_length) {
  7558. received_body.append(data, data_length);
  7559. return true;
  7560. },
  7561. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7562. progress_called = true;
  7563. return true;
  7564. });
  7565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7566. EXPECT_EQ(StatusCode::OK_200, res->status);
  7567. EXPECT_EQ("content", received_body);
  7568. EXPECT_TRUE(progress_called);
  7569. }
  7570. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7571. #ifdef CPPHTTPLIB_SSL_ENABLED
  7572. using ClientT = SSLClient;
  7573. #else
  7574. using ClientT = Client;
  7575. #endif
  7576. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7577. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7578. const std::string &body, const std::string &content_type,
  7579. ContentReceiver receiver, DownloadProgress progress) {
  7580. return cli.Post(path, headers, body, content_type, receiver, progress);
  7581. });
  7582. }
  7583. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7584. #ifdef CPPHTTPLIB_SSL_ENABLED
  7585. using ClientT = SSLClient;
  7586. #else
  7587. using ClientT = Client;
  7588. #endif
  7589. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7590. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7591. const std::string &body, const std::string &content_type,
  7592. ContentReceiver receiver, DownloadProgress progress) {
  7593. return cli.Put(path, headers, body, content_type, receiver, progress);
  7594. });
  7595. }
  7596. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7597. #ifdef CPPHTTPLIB_SSL_ENABLED
  7598. using ClientT = SSLClient;
  7599. #else
  7600. using ClientT = Client;
  7601. #endif
  7602. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7603. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7604. const std::string &body, const std::string &content_type,
  7605. ContentReceiver receiver, DownloadProgress progress) {
  7606. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7607. });
  7608. }
  7609. template <typename ClientType>
  7610. void TestWithHeadersAndContentReceiverError(
  7611. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7612. const Headers &, const std::string &,
  7613. const std::string &, ContentReceiver)>
  7614. request_func) {
  7615. Headers headers;
  7616. headers.emplace("X-Error-Test", "true");
  7617. std::string received_body;
  7618. auto receiver_failed = false;
  7619. auto res =
  7620. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7621. [&](const char *data, size_t data_length) {
  7622. received_body.append(data, data_length);
  7623. receiver_failed = true;
  7624. return false;
  7625. });
  7626. ASSERT_FALSE(res);
  7627. EXPECT_TRUE(receiver_failed);
  7628. }
  7629. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7630. #ifdef CPPHTTPLIB_SSL_ENABLED
  7631. using ClientT = SSLClient;
  7632. #else
  7633. using ClientT = Client;
  7634. #endif
  7635. TestWithHeadersAndContentReceiverError<ClientT>(
  7636. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7637. const std::string &body, const std::string &content_type,
  7638. ContentReceiver receiver) {
  7639. return cli.Post(path, headers, body, content_type, receiver);
  7640. });
  7641. }
  7642. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7643. #ifdef CPPHTTPLIB_SSL_ENABLED
  7644. using ClientT = SSLClient;
  7645. #else
  7646. using ClientT = Client;
  7647. #endif
  7648. TestWithHeadersAndContentReceiverError<ClientT>(
  7649. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7650. const std::string &body, const std::string &content_type,
  7651. ContentReceiver receiver) {
  7652. return cli.Put(path, headers, body, content_type, receiver);
  7653. });
  7654. }
  7655. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7656. #ifdef CPPHTTPLIB_SSL_ENABLED
  7657. using ClientT = SSLClient;
  7658. #else
  7659. using ClientT = Client;
  7660. #endif
  7661. TestWithHeadersAndContentReceiverError<ClientT>(
  7662. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7663. const std::string &body, const std::string &content_type,
  7664. ContentReceiver receiver) {
  7665. return cli.Patch(path, headers, body, content_type, receiver);
  7666. });
  7667. }
  7668. TEST_F(ServerTest, PostQueryStringAndBody) {
  7669. auto res =
  7670. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7672. ASSERT_EQ(StatusCode::OK_200, res->status);
  7673. }
  7674. TEST_F(ServerTest, HTTP2Magic) {
  7675. Request req;
  7676. req.method = "PRI";
  7677. req.path = "*";
  7678. req.body = "SM";
  7679. auto res = std::make_shared<Response>();
  7680. auto error = Error::Success;
  7681. auto ret = cli_.send(req, *res, error);
  7682. ASSERT_TRUE(ret);
  7683. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7684. }
  7685. TEST_F(ServerTest, KeepAlive) {
  7686. auto res = cli_.Get("/hi");
  7687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7688. EXPECT_EQ(StatusCode::OK_200, res->status);
  7689. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7690. EXPECT_EQ("Hello World!", res->body);
  7691. res = cli_.Get("/hi");
  7692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7693. EXPECT_EQ(StatusCode::OK_200, res->status);
  7694. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7695. EXPECT_EQ("Hello World!", res->body);
  7696. res = cli_.Get("/hi");
  7697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7698. EXPECT_EQ(StatusCode::OK_200, res->status);
  7699. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7700. EXPECT_EQ("Hello World!", res->body);
  7701. res = cli_.Get("/not-exist");
  7702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7703. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7704. res = cli_.Post("/empty", "", "text/plain");
  7705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7706. EXPECT_EQ(StatusCode::OK_200, res->status);
  7707. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7708. EXPECT_EQ("empty", res->body);
  7709. EXPECT_EQ("close", res->get_header_value("Connection"));
  7710. res = cli_.Post(
  7711. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7712. "text/plain");
  7713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7714. EXPECT_EQ(StatusCode::OK_200, res->status);
  7715. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7716. EXPECT_EQ("empty", res->body);
  7717. cli_.set_keep_alive(false);
  7718. res = cli_.Get("/last-request");
  7719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7720. EXPECT_EQ(StatusCode::OK_200, res->status);
  7721. EXPECT_EQ("close", res->get_header_value("Connection"));
  7722. }
  7723. TEST_F(ServerTest, TooManyRedirect) {
  7724. cli_.set_follow_location(true);
  7725. auto res = cli_.Get("/redirect/0");
  7726. ASSERT_TRUE(!res);
  7727. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7728. }
  7729. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7730. Request req;
  7731. req.method = "FOOBAR";
  7732. req.path = "/hi";
  7733. cli_.set_keep_alive(true);
  7734. auto res = cli_.send(req);
  7735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7736. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7737. EXPECT_EQ("close", res->get_header_value("Connection"));
  7738. EXPECT_FALSE(cli_.is_socket_open());
  7739. }
  7740. TEST_F(ServerTest, CustomRouteReadsBody) {
  7741. const std::string xml =
  7742. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7743. Request req;
  7744. req.method = "PROPFIND";
  7745. req.path = "/dav/dir";
  7746. req.set_header("Depth", "1");
  7747. req.body = xml;
  7748. auto res = cli_.send(req);
  7749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7750. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7751. EXPECT_EQ(xml, res->body);
  7752. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7753. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7754. }
  7755. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7756. Request req;
  7757. req.method = "PROPFIND";
  7758. req.path = "/dav/42";
  7759. auto res = cli_.send(req);
  7760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7761. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7762. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7763. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7764. }
  7765. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7766. Request req;
  7767. req.method = "PROPFIND";
  7768. req.path = "/dav-re/123";
  7769. auto res = cli_.send(req);
  7770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7771. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7772. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7773. }
  7774. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7775. Request req;
  7776. req.method = "MKCOL";
  7777. req.path = "/dav-mkcol";
  7778. auto res = cli_.send(req);
  7779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7780. EXPECT_EQ(StatusCode::Created_201, res->status);
  7781. }
  7782. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7783. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7784. Request req;
  7785. req.method = "REPORT";
  7786. req.path = "/dav-report";
  7787. req.body = xml;
  7788. auto res = cli_.send(req);
  7789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7790. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7791. EXPECT_EQ(xml, res->body);
  7792. }
  7793. // A content reader route must fire even when the request carries no body,
  7794. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7795. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7796. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7797. Request req;
  7798. req.method = "REPORT";
  7799. req.path = "/dav-report";
  7800. auto res = cli_.send(req);
  7801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7802. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7803. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7804. }
  7805. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7806. Request req;
  7807. req.method = "PROPFIND";
  7808. req.path = "/not-dav";
  7809. auto res = cli_.send(req);
  7810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7811. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7812. }
  7813. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7814. Request req;
  7815. req.method = "UNLOCK";
  7816. req.path = "/dav/dir";
  7817. cli_.set_keep_alive(true);
  7818. auto res = cli_.send(req);
  7819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7820. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7821. EXPECT_EQ("close", res->get_header_value("Connection"));
  7822. EXPECT_FALSE(cli_.is_socket_open());
  7823. }
  7824. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7825. // The mount point serves this path, but only for GET and HEAD.
  7826. auto get_res = cli_.Get("/dir/index.html");
  7827. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7828. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7829. Request req;
  7830. req.method = "PROPFIND";
  7831. req.path = "/dir/index.html";
  7832. auto res = cli_.send(req);
  7833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7834. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7835. }
  7836. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7837. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7838. cli_.set_keep_alive(true);
  7839. for (auto i = 0; i < 2; i++) {
  7840. Request req;
  7841. req.method = "PROPFIND";
  7842. req.path = "/dav/dir";
  7843. req.body = xml;
  7844. auto res = cli_.send(req);
  7845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7846. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7847. EXPECT_EQ(xml, res->body);
  7848. EXPECT_TRUE(cli_.is_socket_open());
  7849. }
  7850. // A built-in method must still be served on the same connection.
  7851. cli_.set_keep_alive(false);
  7852. auto res = cli_.Get("/hi");
  7853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7854. EXPECT_EQ(StatusCode::OK_200, res->status);
  7855. EXPECT_EQ("close", res->get_header_value("Connection"));
  7856. }
  7857. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7858. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7859. Request req;
  7860. req.method = "PROPFIND";
  7861. req.path = "/dav/dir";
  7862. req.set_header("Expect", "100-continue");
  7863. req.body = xml;
  7864. auto res = cli_.send(req);
  7865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7866. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7867. EXPECT_EQ(xml, res->body);
  7868. }
  7869. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7870. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7871. TEST_F(ServerTest, Gzip) {
  7872. Headers headers;
  7873. headers.emplace("Accept-Encoding", "gzip, deflate");
  7874. auto res = cli_.Get("/compress", headers);
  7875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7876. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7877. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7878. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7879. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7880. "7890123456789012345678901234567890",
  7881. res->body);
  7882. EXPECT_EQ(StatusCode::OK_200, res->status);
  7883. }
  7884. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7885. Headers headers;
  7886. headers.emplace("Accept-Encoding", "gzip, deflate");
  7887. auto res = cli_.Get("/compress-with-charset", headers);
  7888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7889. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7890. EXPECT_EQ("application/json; charset=utf-8",
  7891. res->get_header_value("Content-Type"));
  7892. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7893. "7890123456789012345678901234567890",
  7894. res->body);
  7895. EXPECT_EQ(StatusCode::OK_200, res->status);
  7896. }
  7897. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7898. Headers headers;
  7899. headers.emplace("Accept-Encoding", "");
  7900. auto res = cli_.Get("/compress", headers);
  7901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7902. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7903. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7904. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7905. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7906. "7890123456789012345678901234567890",
  7907. res->body);
  7908. EXPECT_EQ(StatusCode::OK_200, res->status);
  7909. }
  7910. TEST_F(ServerTest, GzipWithContentReceiver) {
  7911. Headers headers;
  7912. headers.emplace("Accept-Encoding", "gzip, deflate");
  7913. std::string body;
  7914. auto res = cli_.Get("/compress", headers,
  7915. [&](const char *data, uint64_t data_length) {
  7916. EXPECT_EQ(100U, data_length);
  7917. body.append(data, data_length);
  7918. return true;
  7919. });
  7920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7921. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7922. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7923. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7924. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7925. "7890123456789012345678901234567890",
  7926. body);
  7927. EXPECT_EQ(StatusCode::OK_200, res->status);
  7928. }
  7929. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7930. Headers headers;
  7931. headers.emplace("Accept-Encoding", "gzip, deflate");
  7932. cli_.set_decompress(false);
  7933. auto res = cli_.Get("/compress", headers);
  7934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7935. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7936. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7937. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7938. EXPECT_EQ(33U, res->body.size());
  7939. EXPECT_EQ(StatusCode::OK_200, res->status);
  7940. }
  7941. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7942. Headers headers;
  7943. headers.emplace("Accept-Encoding", "");
  7944. std::string body;
  7945. auto res = cli_.Get("/compress", headers,
  7946. [&](const char *data, uint64_t data_length) {
  7947. EXPECT_EQ(100U, data_length);
  7948. body.append(data, data_length);
  7949. return true;
  7950. });
  7951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7952. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7953. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7954. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7955. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7956. "7890123456789012345678901234567890",
  7957. body);
  7958. EXPECT_EQ(StatusCode::OK_200, res->status);
  7959. }
  7960. TEST_F(ServerTest, NoGzip) {
  7961. Headers headers;
  7962. headers.emplace("Accept-Encoding", "gzip, deflate");
  7963. auto res = cli_.Get("/nocompress", headers);
  7964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7965. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7966. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7967. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7968. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7969. "7890123456789012345678901234567890",
  7970. res->body);
  7971. EXPECT_EQ(StatusCode::OK_200, res->status);
  7972. }
  7973. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7974. Headers headers;
  7975. headers.emplace("Accept-Encoding", "gzip, deflate");
  7976. std::string body;
  7977. auto res = cli_.Get("/nocompress", headers,
  7978. [&](const char *data, uint64_t data_length) {
  7979. EXPECT_EQ(100U, data_length);
  7980. body.append(data, data_length);
  7981. return true;
  7982. });
  7983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7984. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7985. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7986. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7987. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7988. "7890123456789012345678901234567890",
  7989. body);
  7990. EXPECT_EQ(StatusCode::OK_200, res->status);
  7991. }
  7992. TEST_F(ServerTest, MultipartFormDataGzip) {
  7993. UploadFormDataItems items = {
  7994. {"key1", "test", "", ""},
  7995. {"key2", "--abcdefg123", "", ""},
  7996. };
  7997. cli_.set_compress(true);
  7998. auto res = cli_.Post("/compress-multipart", items);
  7999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8000. EXPECT_EQ(StatusCode::OK_200, res->status);
  8001. }
  8002. #endif
  8003. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8004. // Static file compression is opt-in, so these run their own server rather than
  8005. // flipping it on for the shared ServerTest fixture, which would silently
  8006. // rewrite what every other static file test is asserting.
  8007. class StaticFileCompressionTest : public ::testing::Test {
  8008. protected:
  8009. void TearDown() override {
  8010. if (t_.joinable()) {
  8011. svr_.stop();
  8012. t_.join();
  8013. }
  8014. }
  8015. int start(const std::function<void(Server &)> &configure = nullptr) {
  8016. // Serves the same tree as a directory of build-time compressed assets
  8017. // would be served: the mount point names the coding the files are already
  8018. // stored in. Registered before "/" so it is the one that matches.
  8019. svr_.set_mount_point("/pre-encoded", "./www",
  8020. {{"Content-Encoding", "gzip"}});
  8021. svr_.set_mount_point("/", "./www");
  8022. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8023. res.set_file_content("./www/dir/index.html", "text/html");
  8024. });
  8025. svr_.Get("/pre-encoded-file-content",
  8026. [](const Request & /*req*/, Response &res) {
  8027. res.set_header("Content-Encoding", "gzip");
  8028. res.set_file_content("./www/dir/index.html", "text/html");
  8029. });
  8030. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8031. res.set_content_provider(
  8032. 6, "text/plain",
  8033. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8034. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8035. return true;
  8036. });
  8037. });
  8038. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8039. res.set_content_provider(
  8040. 1000, "text/plain",
  8041. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8042. if (offset < 100) {
  8043. std::string data(100, 'A');
  8044. sink.write(data.data(), data.size());
  8045. return true;
  8046. }
  8047. std::this_thread::sleep_for(std::chrono::seconds(2));
  8048. std::string data(900, 'B');
  8049. sink.write(data.data(), data.size());
  8050. return true;
  8051. });
  8052. });
  8053. if (configure) { configure(svr_); }
  8054. auto port = svr_.bind_to_any_port(HOST);
  8055. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8056. svr_.wait_until_ready();
  8057. return port;
  8058. }
  8059. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8060. // Every file under ./www except 1MB.txt is smaller than the default
  8061. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8062. // it out of the way.
  8063. static void enable_without_floor(Server &svr) {
  8064. svr.set_static_file_compression(true);
  8065. svr.set_static_file_compression_min_length(0);
  8066. }
  8067. Server svr_;
  8068. std::thread t_;
  8069. };
  8070. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8071. auto port = start();
  8072. Client cli(HOST, port);
  8073. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8075. EXPECT_EQ(StatusCode::OK_200, res->status);
  8076. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8077. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8078. EXPECT_EQ(1048576U, res->body.size());
  8079. }
  8080. TEST_F(StaticFileCompressionTest, MountPoint) {
  8081. auto port = start(enable);
  8082. Client cli(HOST, port);
  8083. cli.set_decompress(false);
  8084. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8086. EXPECT_EQ(StatusCode::OK_200, res->status);
  8087. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8088. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8089. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8090. // The response stays self-delimiting: a length, not a chunked body.
  8091. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8092. EXPECT_EQ(std::to_string(res->body.size()),
  8093. res->get_header_value("Content-Length"));
  8094. EXPECT_LT(res->body.size(), 1048576U);
  8095. EXPECT_FALSE(res->body.empty());
  8096. }
  8097. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8098. auto port = start(enable);
  8099. Client cli(HOST, port);
  8100. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8102. EXPECT_EQ(StatusCode::OK_200, res->status);
  8103. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8104. EXPECT_EQ(1048576U, res->body.size());
  8105. }
  8106. TEST_F(StaticFileCompressionTest, FileContent) {
  8107. auto port = start(enable_without_floor);
  8108. Client cli(HOST, port);
  8109. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8111. EXPECT_EQ(StatusCode::OK_200, res->status);
  8112. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8113. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8114. EXPECT_EQ(104U, res->body.size());
  8115. }
  8116. // A handler that serves an already-encoded file names the coding itself. The
  8117. // file-backed path decided its coding from Accept-Encoding and the content
  8118. // type alone, so it compressed the stored bytes a second time and appended a
  8119. // second Content-Encoding field line.
  8120. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8121. auto port = start(enable_without_floor);
  8122. Client cli(HOST, port);
  8123. cli.set_decompress(false);
  8124. auto res = cli.Get("/pre-encoded-file-content",
  8125. Headers{{"Accept-Encoding", "gzip"}});
  8126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8127. EXPECT_EQ(StatusCode::OK_200, res->status);
  8128. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8129. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8130. // Vary belongs to a coding the server chose, and it chose none here.
  8131. EXPECT_FALSE(res->has_header("Vary"));
  8132. // The file travels exactly as it is stored on disk.
  8133. EXPECT_EQ(104U, res->body.size());
  8134. }
  8135. // The 1MB file clears the default floor, so this one runs the configuration a
  8136. // deployment would actually have.
  8137. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8138. auto port = start(enable);
  8139. Client cli(HOST, port);
  8140. cli.set_decompress(false);
  8141. auto res =
  8142. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8144. EXPECT_EQ(StatusCode::OK_200, res->status);
  8145. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8146. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8147. EXPECT_FALSE(res->has_header("Vary"));
  8148. EXPECT_EQ(1048576U, res->body.size());
  8149. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8150. }
  8151. TEST_F(StaticFileCompressionTest, Head) {
  8152. auto port = start(enable);
  8153. Client cli(HOST, port);
  8154. cli.set_decompress(false);
  8155. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8156. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8157. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8159. EXPECT_EQ(StatusCode::OK_200, res->status);
  8160. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8161. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8162. // HEAD still reports the size a GET would return.
  8163. EXPECT_EQ(get->get_header_value("Content-Length"),
  8164. res->get_header_value("Content-Length"));
  8165. EXPECT_TRUE(res->body.empty());
  8166. }
  8167. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8168. auto port = start(enable);
  8169. Client cli(HOST, port);
  8170. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8171. {"Accept-Encoding", "gzip"}});
  8172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8173. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8174. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8175. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8176. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8177. EXPECT_EQ("cd", res->body);
  8178. }
  8179. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8180. auto port = start(enable);
  8181. Client cli(HOST, port);
  8182. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8184. EXPECT_EQ(StatusCode::OK_200, res->status);
  8185. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8186. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8187. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8188. }
  8189. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8190. auto port = start(enable);
  8191. Client cli(HOST, port);
  8192. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8194. EXPECT_EQ(StatusCode::OK_200, res->status);
  8195. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8196. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8197. EXPECT_TRUE(res->body.empty());
  8198. }
  8199. TEST_F(StaticFileCompressionTest, MinLength) {
  8200. auto port = start(enable);
  8201. Client cli(HOST, port);
  8202. // 104 bytes, well under the default floor. Compressing it would add the
  8203. // gzip header and trailer to a body that already fits in one packet.
  8204. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8206. EXPECT_EQ(StatusCode::OK_200, res->status);
  8207. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8208. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8209. }
  8210. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8211. auto port = start([](Server &svr) {
  8212. svr.set_static_file_compression(true);
  8213. svr.set_static_file_compression_min_length(1);
  8214. });
  8215. Client cli(HOST, port);
  8216. cli.set_decompress(false);
  8217. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8219. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8220. // A 9-byte file comes back larger than it went in, because gzip's header and
  8221. // trailer outweigh anything deflate can save. That is the end of the range
  8222. // the floor exists to keep out.
  8223. EXPECT_GT(res->body.size(), 9U);
  8224. }
  8225. TEST_F(StaticFileCompressionTest, MaxLength) {
  8226. auto port = start([](Server &svr) {
  8227. svr.set_static_file_compression(true);
  8228. svr.set_static_file_compression_min_length(0);
  8229. svr.set_static_file_compression_max_length(1024);
  8230. });
  8231. Client cli(HOST, port);
  8232. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8233. // defines `small` as a macro on Windows.
  8234. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8235. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8236. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8237. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8238. // Under it: compressed.
  8239. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8240. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8241. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8242. }
  8243. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8244. auto port = start(enable_without_floor);
  8245. Client cli(HOST, port);
  8246. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8247. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8248. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8249. auto identity_etag = identity->get_header_value("ETag");
  8250. ASSERT_FALSE(identity_etag.empty());
  8251. auto gzipped =
  8252. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8253. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8254. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8255. auto gzip_etag = gzipped->get_header_value("ETag");
  8256. ASSERT_FALSE(gzip_etag.empty());
  8257. // Two representations, two validators.
  8258. EXPECT_NE(identity_etag, gzip_etag);
  8259. // Each one revalidates against the request that would produce it...
  8260. auto fresh =
  8261. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8262. {"If-None-Match", gzip_etag}});
  8263. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8264. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8265. auto fresh_identity =
  8266. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8267. {"If-None-Match", identity_etag}});
  8268. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8269. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8270. // ...and not against the other representation.
  8271. auto crossed =
  8272. cli.Get("/dir/index.html",
  8273. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8274. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8275. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8276. }
  8277. // The opt-in covers responses the server reads off disk itself. A caller's own
  8278. // known-length provider keeps its Content-Length and, more importantly, keeps
  8279. // delivering incrementally: routing it through a compressor would hold every
  8280. // write back until zlib's window filled.
  8281. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8282. auto port = start(enable);
  8283. Client cli(HOST, port);
  8284. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8286. EXPECT_EQ(StatusCode::OK_200, res->status);
  8287. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8288. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8289. EXPECT_EQ("aaabbb", res->body);
  8290. }
  8291. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8292. auto port = start(enable);
  8293. Client cli(HOST, port);
  8294. cli.set_read_timeout(1, 0);
  8295. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8296. Headers{{"Accept-Encoding", "gzip"}});
  8297. ASSERT_TRUE(handle.is_valid());
  8298. // The provider writes 100 bytes and then stalls for longer than the read
  8299. // timeout. Those first bytes have to arrive anyway: run the response through
  8300. // a compressor and zlib holds them until its window fills, so the read would
  8301. // come back empty instead.
  8302. char buf[256];
  8303. auto n = handle.read(buf, sizeof(buf));
  8304. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8305. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8306. }
  8307. #endif
  8308. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8309. TEST_F(ServerTest, Brotli) {
  8310. Headers headers;
  8311. headers.emplace("Accept-Encoding", "br");
  8312. auto res = cli_.Get("/compress", headers);
  8313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8314. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8315. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8316. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8317. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8318. "7890123456789012345678901234567890",
  8319. res->body);
  8320. EXPECT_EQ(StatusCode::OK_200, res->status);
  8321. }
  8322. #endif
  8323. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8324. TEST_F(ServerTest, Zstd) {
  8325. Headers headers;
  8326. headers.emplace("Accept-Encoding", "zstd");
  8327. auto res = cli_.Get("/compress", headers);
  8328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8329. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8330. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8331. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8332. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8333. "7890123456789012345678901234567890",
  8334. res->body);
  8335. EXPECT_EQ(StatusCode::OK_200, res->status);
  8336. }
  8337. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8338. Headers headers;
  8339. headers.emplace("Accept-Encoding", "");
  8340. auto res = cli_.Get("/compress", headers);
  8341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8342. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8343. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8344. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8345. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8346. "7890123456789012345678901234567890",
  8347. res->body);
  8348. EXPECT_EQ(StatusCode::OK_200, res->status);
  8349. }
  8350. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8351. Headers headers;
  8352. headers.emplace("Accept-Encoding", "zstd");
  8353. std::string body;
  8354. auto res = cli_.Get("/compress", headers,
  8355. [&](const char *data, uint64_t data_length) {
  8356. EXPECT_EQ(100U, data_length);
  8357. body.append(data, data_length);
  8358. return true;
  8359. });
  8360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8361. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8362. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8363. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8364. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8365. "7890123456789012345678901234567890",
  8366. body);
  8367. EXPECT_EQ(StatusCode::OK_200, res->status);
  8368. }
  8369. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8370. Headers headers;
  8371. headers.emplace("Accept-Encoding", "zstd");
  8372. cli_.set_decompress(false);
  8373. auto res = cli_.Get("/compress", headers);
  8374. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8375. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8376. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8377. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8379. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8380. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8381. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8382. EXPECT_EQ(StatusCode::OK_200, res->status);
  8383. ASSERT_EQ(26U, res->body.size());
  8384. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8385. 0);
  8386. }
  8387. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8388. Headers headers;
  8389. headers.emplace("Accept-Encoding", "");
  8390. std::string body;
  8391. auto res = cli_.Get("/compress", headers,
  8392. [&](const char *data, uint64_t data_length) {
  8393. EXPECT_EQ(100U, data_length);
  8394. body.append(data, data_length);
  8395. return true;
  8396. });
  8397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8398. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8399. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8400. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8401. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8402. "7890123456789012345678901234567890",
  8403. body);
  8404. EXPECT_EQ(StatusCode::OK_200, res->status);
  8405. }
  8406. TEST_F(ServerTest, NoZstd) {
  8407. Headers headers;
  8408. headers.emplace("Accept-Encoding", "zstd");
  8409. auto res = cli_.Get("/nocompress", headers);
  8410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8411. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8412. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8413. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8414. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8415. "7890123456789012345678901234567890",
  8416. res->body);
  8417. EXPECT_EQ(StatusCode::OK_200, res->status);
  8418. }
  8419. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8420. Headers headers;
  8421. headers.emplace("Accept-Encoding", "zstd");
  8422. std::string body;
  8423. auto res = cli_.Get("/nocompress", headers,
  8424. [&](const char *data, uint64_t data_length) {
  8425. EXPECT_EQ(100U, data_length);
  8426. body.append(data, data_length);
  8427. return true;
  8428. });
  8429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8430. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8431. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8432. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8433. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8434. "7890123456789012345678901234567890",
  8435. body);
  8436. EXPECT_EQ(StatusCode::OK_200, res->status);
  8437. }
  8438. // TODO: How to enable zstd ??
  8439. TEST_F(ServerTest, MultipartFormDataZstd) {
  8440. UploadFormDataItems items = {
  8441. {"key1", "test", "", ""},
  8442. {"key2", "--abcdefg123", "", ""},
  8443. };
  8444. Headers headers;
  8445. headers.emplace("Accept-Encoding", "zstd");
  8446. cli_.set_compress(true);
  8447. auto res = cli_.Post("/compress-multipart", headers, items);
  8448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8449. EXPECT_EQ(StatusCode::OK_200, res->status);
  8450. }
  8451. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8452. Headers headers;
  8453. headers.emplace("Accept-Encoding", "zstd");
  8454. cli_.set_compress(true);
  8455. auto res = cli_.Put(
  8456. "/put", headers, 3,
  8457. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8458. sink.os << "PUT";
  8459. return true;
  8460. },
  8461. "text/plain");
  8462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8463. EXPECT_EQ(StatusCode::OK_200, res->status);
  8464. EXPECT_EQ("PUT", res->body);
  8465. }
  8466. // Pre-compression logging tests
  8467. TEST_F(ServerTest, PreCompressionLogging) {
  8468. // Test data for compression (matches the actual /compress endpoint content)
  8469. const std::string test_content =
  8470. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8471. "3456789012345678901234567890";
  8472. // Variables to capture logging data
  8473. std::string pre_compression_body;
  8474. std::string pre_compression_content_type;
  8475. std::string pre_compression_content_encoding;
  8476. std::string post_compression_body;
  8477. std::string post_compression_content_type;
  8478. std::string post_compression_content_encoding;
  8479. // Set up pre-compression logger
  8480. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8481. const Response &res) {
  8482. pre_compression_body = res.body;
  8483. pre_compression_content_type = res.get_header_value("Content-Type");
  8484. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8485. });
  8486. // Set up post-compression logger
  8487. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8488. post_compression_body = res.body;
  8489. post_compression_content_type = res.get_header_value("Content-Type");
  8490. post_compression_content_encoding =
  8491. res.get_header_value("Content-Encoding");
  8492. });
  8493. // Test with gzip compression
  8494. Headers headers;
  8495. headers.emplace("Accept-Encoding", "gzip");
  8496. auto res = cli_.Get("/compress", headers);
  8497. // Verify response was compressed
  8498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8499. EXPECT_EQ(StatusCode::OK_200, res->status);
  8500. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8501. // Verify pre-compression logger captured uncompressed content
  8502. EXPECT_EQ(test_content, pre_compression_body);
  8503. EXPECT_EQ("text/plain", pre_compression_content_type);
  8504. EXPECT_TRUE(pre_compression_content_encoding
  8505. .empty()); // No encoding header before compression
  8506. // Verify post-compression logger captured compressed content
  8507. EXPECT_NE(test_content,
  8508. post_compression_body); // Should be different after compression
  8509. EXPECT_EQ("text/plain", post_compression_content_type);
  8510. EXPECT_EQ("gzip", post_compression_content_encoding);
  8511. // Verify compressed content is smaller
  8512. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8513. }
  8514. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8515. const std::string test_content =
  8516. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8517. "3456789012345678901234567890";
  8518. std::string pre_compression_body;
  8519. std::string post_compression_body;
  8520. svr_.set_pre_compression_logger(
  8521. [&](const Request & /*req*/, const Response &res) {
  8522. pre_compression_body = res.body;
  8523. });
  8524. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8525. post_compression_body = res.body;
  8526. });
  8527. Headers headers;
  8528. headers.emplace("Accept-Encoding", "br");
  8529. auto res = cli_.Get("/compress", headers);
  8530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8531. EXPECT_EQ(StatusCode::OK_200, res->status);
  8532. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8533. // Verify pre-compression content is uncompressed
  8534. EXPECT_EQ(test_content, pre_compression_body);
  8535. // Verify post-compression content is compressed
  8536. EXPECT_NE(test_content, post_compression_body);
  8537. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8538. }
  8539. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8540. const std::string test_content =
  8541. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8542. "3456789012345678901234567890";
  8543. std::string pre_compression_body;
  8544. std::string post_compression_body;
  8545. svr_.set_pre_compression_logger(
  8546. [&](const Request & /*req*/, const Response &res) {
  8547. pre_compression_body = res.body;
  8548. });
  8549. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8550. post_compression_body = res.body;
  8551. });
  8552. // Request without compression (use /nocompress endpoint)
  8553. Headers headers;
  8554. auto res = cli_.Get("/nocompress", headers);
  8555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8556. EXPECT_EQ(StatusCode::OK_200, res->status);
  8557. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8558. // Pre-compression logger should not be called when no compression is applied
  8559. EXPECT_TRUE(
  8560. pre_compression_body.empty()); // Pre-compression logger not called
  8561. EXPECT_EQ(
  8562. test_content,
  8563. post_compression_body); // Post-compression logger captures final content
  8564. }
  8565. TEST_F(ServerTest, LoggerSeesContentLength) {
  8566. size_t logged_content_length = 0;
  8567. std::string logged_content_length_header;
  8568. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8569. logged_content_length = res.content_length_;
  8570. logged_content_length_header = res.get_header_value("Content-Length");
  8571. });
  8572. auto res = cli_.Get("/nocompress");
  8573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8574. EXPECT_EQ(StatusCode::OK_200, res->status);
  8575. EXPECT_EQ(res->body.size(), logged_content_length);
  8576. EXPECT_EQ(std::to_string(logged_content_length),
  8577. logged_content_length_header);
  8578. }
  8579. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8580. const std::string test_content =
  8581. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8582. "3456789012345678901234567890";
  8583. std::string pre_compression_body;
  8584. bool pre_logger_called = false;
  8585. // Set only pre-compression logger
  8586. svr_.set_pre_compression_logger(
  8587. [&](const Request & /*req*/, const Response &res) {
  8588. pre_compression_body = res.body;
  8589. pre_logger_called = true;
  8590. });
  8591. Headers headers;
  8592. headers.emplace("Accept-Encoding", "gzip");
  8593. auto res = cli_.Get("/compress", headers);
  8594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8595. EXPECT_EQ(StatusCode::OK_200, res->status);
  8596. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8597. // Verify pre-compression logger was called
  8598. EXPECT_TRUE(pre_logger_called);
  8599. EXPECT_EQ(test_content, pre_compression_body);
  8600. }
  8601. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8602. {
  8603. // Test with Expect: 100-continue header - success case
  8604. // Server returns 100 Continue, client sends body, server returns 200 OK
  8605. Request req;
  8606. req.method = "POST";
  8607. req.path = "/post-large";
  8608. req.set_header("Expect", "100-continue");
  8609. req.body = LARGE_DATA;
  8610. Response res;
  8611. auto error = Error::Success;
  8612. cli_.set_keep_alive(true);
  8613. auto ret = cli_.send(req, res, error);
  8614. EXPECT_TRUE(ret);
  8615. EXPECT_EQ(StatusCode::OK_200, res.status);
  8616. EXPECT_EQ(LARGE_DATA, res.body);
  8617. }
  8618. {
  8619. // Test with Expect: 100-continue header - error case
  8620. // Client should not send the body when server returns an error
  8621. Request req;
  8622. req.method = "POST";
  8623. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8624. req.set_header("Expect", "100-continue");
  8625. req.body = LARGE_DATA;
  8626. Response res;
  8627. auto error = Error::Success;
  8628. auto start = std::chrono::high_resolution_clock::now();
  8629. cli_.set_keep_alive(true);
  8630. auto ret = cli_.send(req, res, error);
  8631. auto end = std::chrono::high_resolution_clock::now();
  8632. auto elapsed =
  8633. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8634. .count();
  8635. // With Expect: 100-continue, request completes successfully but with error
  8636. EXPECT_TRUE(ret);
  8637. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8638. EXPECT_EQ("close", res.get_header_value("Connection"));
  8639. EXPECT_FALSE(cli_.is_socket_open());
  8640. EXPECT_LE(elapsed, 2000);
  8641. }
  8642. {
  8643. // Send an extra GET request to ensure error recovery without hanging
  8644. Request req;
  8645. req.method = "GET";
  8646. req.path = "/hi";
  8647. auto start = std::chrono::high_resolution_clock::now();
  8648. auto res = cli_.send(req);
  8649. auto end = std::chrono::high_resolution_clock::now();
  8650. auto elapsed =
  8651. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8652. .count();
  8653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8654. EXPECT_EQ(StatusCode::OK_200, res->status);
  8655. EXPECT_EQ("Hello World!", res->body);
  8656. EXPECT_LE(elapsed, 500);
  8657. }
  8658. }
  8659. TEST(ZstdDecompressor, ChunkedDecompression) {
  8660. std::string data;
  8661. for (size_t i = 0; i < 32 * 1024; ++i) {
  8662. data.push_back(static_cast<char>('a' + i % 26));
  8663. }
  8664. std::string compressed_data;
  8665. {
  8666. httplib::detail::zstd_compressor compressor;
  8667. bool result = compressor.compress(
  8668. data.data(), data.size(),
  8669. /*last=*/true,
  8670. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8671. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8672. compressed_data_size);
  8673. return true;
  8674. });
  8675. ASSERT_TRUE(result);
  8676. }
  8677. std::string decompressed_data;
  8678. {
  8679. httplib::detail::zstd_decompressor decompressor;
  8680. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8681. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8682. size_t chunk_size = 130;
  8683. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8684. chunk_begin += chunk_size) {
  8685. size_t current_chunk_size =
  8686. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8687. bool result = decompressor.decompress(
  8688. compressed_data.data() + chunk_begin, current_chunk_size,
  8689. [&](const char *decompressed_data_chunk,
  8690. size_t decompressed_data_chunk_size) {
  8691. decompressed_data.insert(decompressed_data.size(),
  8692. decompressed_data_chunk,
  8693. decompressed_data_chunk_size);
  8694. return true;
  8695. });
  8696. ASSERT_TRUE(result);
  8697. }
  8698. }
  8699. ASSERT_EQ(data, decompressed_data);
  8700. }
  8701. TEST(ZstdDecompressor, Decompress) {
  8702. std::string original_text = "Compressed with ZSTD";
  8703. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8704. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8705. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8706. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8707. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8708. std::string decompressed_data;
  8709. {
  8710. httplib::detail::zstd_decompressor decompressor;
  8711. bool result = decompressor.decompress(
  8712. compressed_data.data(), compressed_data.size(),
  8713. [&](const char *decompressed_data_chunk,
  8714. size_t decompressed_data_chunk_size) {
  8715. decompressed_data.insert(decompressed_data.size(),
  8716. decompressed_data_chunk,
  8717. decompressed_data_chunk_size);
  8718. return true;
  8719. });
  8720. ASSERT_TRUE(result);
  8721. }
  8722. ASSERT_EQ(original_text, decompressed_data);
  8723. }
  8724. #endif
  8725. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8726. // separate chunks so that the server sees each part in its own read(). Used to
  8727. // place a read boundary at a specific offset of a request body.
  8728. static bool send_request_in_parts(time_t read_timeout_sec,
  8729. const std::vector<std::string> &parts,
  8730. std::string *resp = nullptr,
  8731. int port = PORT) {
  8732. auto error = Error::Success;
  8733. auto client_sock = detail::create_client_socket(
  8734. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8735. /*connection_timeout_sec=*/5, 0,
  8736. /*read_timeout_sec=*/5, 0,
  8737. /*write_timeout_sec=*/5, 0, std::string(), error);
  8738. if (client_sock == INVALID_SOCKET) { return false; }
  8739. auto ret = detail::process_client_socket(
  8740. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8741. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8742. for (size_t i = 0; i < parts.size(); i++) {
  8743. const auto &part = parts[i];
  8744. if (part.size() !=
  8745. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8746. return false;
  8747. }
  8748. if (i + 1 < parts.size()) {
  8749. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8750. }
  8751. }
  8752. char buf[512];
  8753. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8754. while (line_reader.getline()) {
  8755. if (resp) { *resp += line_reader.ptr(); }
  8756. }
  8757. return true;
  8758. });
  8759. detail::close_socket(client_sock);
  8760. return ret;
  8761. }
  8762. // Sends a raw request to a server listening at HOST:PORT.
  8763. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8764. std::string *resp = nullptr, int port = PORT) {
  8765. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8766. }
  8767. #ifdef CPPHTTPLIB_SSL_ENABLED
  8768. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  8769. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8770. ASSERT_TRUE(svr.is_valid());
  8771. svr.set_read_timeout(1, 0);
  8772. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8773. auto se = detail::scope_exit([&] {
  8774. svr.stop();
  8775. t.join();
  8776. ASSERT_FALSE(svr.is_running());
  8777. });
  8778. svr.wait_until_ready();
  8779. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  8780. // keeps each wait well within the read timeout. The server gives up a
  8781. // second in, so the bytes sent after that fail.
  8782. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  8783. parts.resize(26, std::string(1, '\0'));
  8784. EXPECT_FALSE(send_request_in_parts(5, parts));
  8785. }
  8786. #endif
  8787. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8788. Server svr;
  8789. std::string header_value;
  8790. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8791. header_value = req.get_header_value("foo");
  8792. res.set_content("ok", "text/plain");
  8793. });
  8794. thread t = thread([&] { svr.listen(HOST, PORT); });
  8795. auto se = detail::scope_exit([&] {
  8796. svr.stop();
  8797. t.join();
  8798. ASSERT_FALSE(svr.is_running());
  8799. });
  8800. svr.wait_until_ready();
  8801. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8802. // like characters are not treated the same - use vertical tab and escape.
  8803. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8804. "foo: \t \v bar \x1B\t \r\n"
  8805. "Connection: close\r\n"
  8806. "\r\n";
  8807. std::string res;
  8808. ASSERT_TRUE(send_request(5, req, &res));
  8809. EXPECT_EQ(header_value, "");
  8810. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8811. }
  8812. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8813. Server svr;
  8814. std::string received;
  8815. svr.Get("/order", [&](const Request &req, Response &res) {
  8816. received = entries_to_string(req.headers);
  8817. res.set_content("ok", "text/plain");
  8818. });
  8819. auto port = svr.bind_to_any_port(HOST);
  8820. thread t = thread([&] { svr.listen_after_bind(); });
  8821. auto se = detail::scope_exit([&] {
  8822. svr.stop();
  8823. t.join();
  8824. ASSERT_FALSE(svr.is_running());
  8825. });
  8826. svr.wait_until_ready();
  8827. const std::string req = "GET /order HTTP/1.1\r\n"
  8828. "X-First: 1\r\n"
  8829. "X-Dup: a\r\n"
  8830. "X-Second: 2\r\n"
  8831. "X-Dup: b\r\n"
  8832. "Connection: close\r\n"
  8833. "\r\n";
  8834. std::string res;
  8835. ASSERT_TRUE(send_request(5, req, &res, port));
  8836. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8837. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  8838. }
  8839. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8840. Server svr;
  8841. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8842. res.set_header("Set-Cookie", "first=1");
  8843. res.set_header("X-Between", "y");
  8844. res.set_header("Set-Cookie", "second=2");
  8845. res.set_content("ok", "text/plain");
  8846. });
  8847. auto port = svr.bind_to_any_port(HOST);
  8848. thread t = thread([&] { svr.listen_after_bind(); });
  8849. auto se = detail::scope_exit([&] {
  8850. svr.stop();
  8851. t.join();
  8852. ASSERT_FALSE(svr.is_running());
  8853. });
  8854. svr.wait_until_ready();
  8855. Client cli(HOST, port);
  8856. auto res = cli.Get("/cookies");
  8857. ASSERT_TRUE(res);
  8858. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8859. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8860. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8861. }
  8862. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8863. Server svr;
  8864. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8865. auto i = new int(0);
  8866. res.set_header("Trailer", "X-Safe, X-Reflected");
  8867. res.set_chunked_content_provider(
  8868. "text/plain",
  8869. [i](size_t /*offset*/, DataSink &sink) {
  8870. if (*i == 0) {
  8871. sink.os << "body";
  8872. } else {
  8873. Headers trailer;
  8874. // A valid trailer that must survive.
  8875. trailer.emplace("X-Safe", "safe");
  8876. // Attacker-controlled value carrying CR/LF (response splitting).
  8877. trailer.emplace("X-Reflected",
  8878. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8879. // Attacker-controlled name carrying CR/LF.
  8880. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8881. sink.done_with_trailer(trailer);
  8882. }
  8883. (*i)++;
  8884. return true;
  8885. },
  8886. [i](bool /*success*/) { delete i; });
  8887. });
  8888. thread t = thread([&] { svr.listen(HOST, PORT); });
  8889. auto se = detail::scope_exit([&] {
  8890. svr.stop();
  8891. t.join();
  8892. ASSERT_FALSE(svr.is_running());
  8893. });
  8894. svr.wait_until_ready();
  8895. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8896. "Host: " + HOST +
  8897. "\r\n"
  8898. "Connection: close\r\n"
  8899. "\r\n";
  8900. std::string res;
  8901. ASSERT_TRUE(send_request(5, req, &res));
  8902. // The injected fields must not appear anywhere in the raw response.
  8903. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8904. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8905. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8906. // Invalid trailers are dropped entirely, matching set_header().
  8907. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8908. // The valid trailer still passes through.
  8909. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8910. }
  8911. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8912. Server svr;
  8913. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8914. // res.headers is a public field an application can populate directly,
  8915. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8916. // A valid header that must survive.
  8917. res.headers.emplace("X-Safe", "safe");
  8918. // Attacker-controlled value carrying CR/LF (response splitting).
  8919. res.headers.emplace("X-Reflected",
  8920. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8921. // Attacker-controlled name carrying CR/LF.
  8922. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8923. res.set_content("body", "text/plain");
  8924. });
  8925. thread t = thread([&] { svr.listen(HOST, PORT); });
  8926. auto se = detail::scope_exit([&] {
  8927. svr.stop();
  8928. t.join();
  8929. ASSERT_FALSE(svr.is_running());
  8930. });
  8931. svr.wait_until_ready();
  8932. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8933. "Host: " + HOST +
  8934. "\r\n"
  8935. "Connection: close\r\n"
  8936. "\r\n";
  8937. std::string res;
  8938. ASSERT_TRUE(send_request(5, req, &res));
  8939. // The injected fields must not appear anywhere in the raw response.
  8940. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8941. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8942. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8943. // Invalid headers are dropped entirely, matching set_header().
  8944. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8945. // The valid header still passes through.
  8946. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8947. }
  8948. // Forward declaration: in split builds split.py strips `inline` and moves the
  8949. // definition into httplib.cc, so detail::write_request_line is not visible from
  8950. // the public httplib.h. Re-declaring it here lets the tests link against the
  8951. // symbol in both header-only and split builds.
  8952. namespace httplib {
  8953. namespace detail {
  8954. ssize_t write_request_line(Stream &strm, const std::string &method,
  8955. const std::string &path);
  8956. } // namespace detail
  8957. } // namespace httplib
  8958. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  8959. // A well-formed target is written verbatim.
  8960. {
  8961. detail::BufferStream strm;
  8962. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8963. EXPECT_GT(n, 0);
  8964. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8965. }
  8966. // A target carrying CR/LF, SP or other control octets must be rejected
  8967. // before anything reaches the wire, otherwise it splits the request line and
  8968. // injects a header or a whole request.
  8969. const std::string evil_targets[] = {
  8970. "/a\r\nInjected: pwned",
  8971. "/a\rInjected",
  8972. "/a\nInjected",
  8973. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8974. "/a b",
  8975. "/a\tb",
  8976. "/a\x7f",
  8977. };
  8978. for (const auto &evil : evil_targets) {
  8979. detail::BufferStream strm;
  8980. auto n = detail::write_request_line(strm, "GET", evil);
  8981. EXPECT_LT(n, 0);
  8982. EXPECT_TRUE(strm.get_buffer().empty());
  8983. }
  8984. }
  8985. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8986. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  8987. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  8988. // target reaches write_request. The client must fail cleanly with
  8989. // Error::Write instead of putting a request-line-less, header-injecting
  8990. // request on the wire.
  8991. Server svr;
  8992. svr.Get("/a", [](const Request &, Response &res) {
  8993. res.set_content("ok", "text/plain");
  8994. });
  8995. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8996. auto se = detail::scope_exit([&] {
  8997. svr.stop();
  8998. thread.join();
  8999. ASSERT_FALSE(svr.is_running());
  9000. });
  9001. svr.wait_until_ready();
  9002. {
  9003. Client cli(HOST, PORT);
  9004. cli.set_path_encode(false);
  9005. // The request is rejected before anything is written, so the connection
  9006. // stays silent and the subsequent response read would otherwise block for
  9007. // the full default read timeout. Shorten it -- the assertion is on the
  9008. // error, not the timeout.
  9009. cli.set_read_timeout(1, 0);
  9010. auto res = cli.Get("/a\r\nInjected: pwned");
  9011. EXPECT_FALSE(res);
  9012. EXPECT_EQ(Error::Write, res.error());
  9013. }
  9014. }
  9015. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9016. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9017. // including extension methods.
  9018. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9019. for (const auto &method : good_methods) {
  9020. detail::BufferStream strm;
  9021. auto n = detail::write_request_line(strm, method, "/");
  9022. EXPECT_GT(n, 0);
  9023. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9024. }
  9025. // A method carrying CR/LF would split the request line and smuggle a whole
  9026. // request ahead of the real one. A space or an empty method corrupts the
  9027. // request line. All must be rejected before anything reaches the wire.
  9028. const std::string evil_methods[] = {
  9029. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9030. "GET\r\nInjected: pwned",
  9031. "GET\r",
  9032. "GET\n",
  9033. "GE T",
  9034. "",
  9035. };
  9036. for (const auto &evil : evil_methods) {
  9037. detail::BufferStream strm;
  9038. auto n = detail::write_request_line(strm, evil, "/");
  9039. EXPECT_LT(n, 0);
  9040. EXPECT_TRUE(strm.get_buffer().empty());
  9041. }
  9042. }
  9043. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9044. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9045. // through Client::send must fail with Error::Write and no request, neither
  9046. // the smuggled one nor the real one, may reach the server.
  9047. Server svr;
  9048. std::atomic<int> request_count(0);
  9049. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9050. request_count++;
  9051. res.status = StatusCode::OK_200;
  9052. return Server::HandlerResponse::Handled;
  9053. });
  9054. auto port = svr.bind_to_any_port(HOST);
  9055. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9056. auto se = detail::scope_exit([&] {
  9057. svr.stop();
  9058. thread.join();
  9059. ASSERT_FALSE(svr.is_running());
  9060. });
  9061. svr.wait_until_ready();
  9062. {
  9063. Client cli(HOST, port);
  9064. const std::string evil_methods[] = {
  9065. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9066. "GE T",
  9067. "",
  9068. };
  9069. for (const auto &evil : evil_methods) {
  9070. Request req;
  9071. req.method = evil;
  9072. req.path = "/";
  9073. auto res = cli.send(req);
  9074. EXPECT_FALSE(res);
  9075. EXPECT_EQ(Error::Write, res.error());
  9076. }
  9077. auto handle =
  9078. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9079. EXPECT_FALSE(handle.is_valid());
  9080. EXPECT_EQ(Error::Write, handle.error);
  9081. // A valid request on the same client still goes through.
  9082. auto res = cli.Get("/");
  9083. ASSERT_TRUE(res);
  9084. EXPECT_EQ(StatusCode::OK_200, res->status);
  9085. }
  9086. EXPECT_EQ(1, request_count.load());
  9087. }
  9088. // Sends a raw request and verifies that there isn't a crash or exception.
  9089. static void test_raw_request(const std::string &req,
  9090. std::string *out = nullptr) {
  9091. Server svr;
  9092. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9093. res.set_content("ok", "text/plain");
  9094. });
  9095. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9096. res.set_content("ok", "text/plain");
  9097. });
  9098. svr.Get("/header_field_value_check",
  9099. [&](const Request & /*req*/, Response &res) {
  9100. res.set_content("ok", "text/plain");
  9101. });
  9102. svr.CustomRoute("PROPFIND", "/dav",
  9103. [&](const Request & /*req*/, Response &res) {
  9104. res.status = StatusCode::MultiStatus_207;
  9105. });
  9106. // Server read timeout must be longer than the client read timeout for the
  9107. // bug to reproduce, probably to force the server to process a request
  9108. // without a trailing blank line.
  9109. const time_t client_read_timeout_sec = 1;
  9110. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9111. bool listen_thread_ok = false;
  9112. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9113. auto se = detail::scope_exit([&] {
  9114. svr.stop();
  9115. t.join();
  9116. ASSERT_FALSE(svr.is_running());
  9117. EXPECT_TRUE(listen_thread_ok);
  9118. });
  9119. svr.wait_until_ready();
  9120. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9121. }
  9122. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9123. // A certain header line causes an exception if the header property is parsed
  9124. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9125. test_raw_request(
  9126. "GET /hi HTTP/1.1\r\n"
  9127. " : "
  9128. " "
  9129. " ");
  9130. }
  9131. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9132. // A certain header line causes an exception if the header property *name* is
  9133. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9134. // greedy matcher and requires backtracking when there are a lot of ":"
  9135. // characters.
  9136. // This occurs with libc++ but not libstdc++.
  9137. test_raw_request(
  9138. "GET /hi HTTP/1.1\r\n"
  9139. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9140. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9141. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9142. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9143. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9144. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9145. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9146. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9147. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9148. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9149. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9150. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9151. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9152. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9153. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9154. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9155. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9156. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9157. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9158. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9159. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9160. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9161. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9162. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9163. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9164. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9165. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9166. "&&&%%%");
  9167. }
  9168. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9169. // Make sure this doesn't crash the server.
  9170. // In a previous version of the header line regex, the "\r" rendered the line
  9171. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9172. // a new position where the leading white space ended and the field value
  9173. // began.
  9174. // The crash occurs with libc++ but not libstdc++.
  9175. test_raw_request("GET /hi HTTP/1.1\r\n"
  9176. "a:" +
  9177. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9178. "\r\n"
  9179. "\r\n");
  9180. }
  9181. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9182. std::string out;
  9183. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9184. "Content-Type: text/plain\r\n"
  9185. "Transfer-Encoding: chunked\r\n"
  9186. "\r\n"
  9187. "nothex\r\n",
  9188. &out);
  9189. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9190. }
  9191. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9192. std::string out;
  9193. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9194. "Content-Type: text/plain\r\n"
  9195. "Transfer-Encoding: chunked\r\n"
  9196. "\r\n"
  9197. "3\r\n"
  9198. "xyz\r\n"
  9199. "NaN\r\n",
  9200. &out);
  9201. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9202. }
  9203. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9204. std::string out;
  9205. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9206. "Content-Type: text/plain\r\n"
  9207. "Transfer-Encoding: chunked\r\n"
  9208. "\r\n"
  9209. // Length is too large for 64 bits.
  9210. "1ffffffffffffffff\r\n"
  9211. "xyz\r\n",
  9212. &out);
  9213. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9214. }
  9215. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9216. test_raw_request("GET /hi HTTP/1.1\r\n"
  9217. "Content-Type: text/plain\r\n\r");
  9218. }
  9219. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9220. std::string out;
  9221. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9222. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9223. }
  9224. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9225. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9226. std::string out;
  9227. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9228. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9229. }
  9230. }
  9231. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9232. std::string out;
  9233. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9234. "Connection: close\r\n\r\n",
  9235. &out);
  9236. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9237. }
  9238. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9239. Server svr;
  9240. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9241. EXPECT_TRUE(!req.remote_addr.empty());
  9242. });
  9243. thread t = thread([&] { svr.listen(HOST, PORT); });
  9244. auto se = detail::scope_exit([&] {
  9245. svr.stop();
  9246. t.join();
  9247. ASSERT_FALSE(svr.is_running());
  9248. });
  9249. svr.wait_until_ready();
  9250. // Send an invalid request line to trigger Bad Request
  9251. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9252. std::string out;
  9253. ASSERT_TRUE(send_request(5, bad_req, &out));
  9254. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9255. }
  9256. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9257. // answered right away rather than blocking on a read that waits for EOF.
  9258. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9259. std::string out;
  9260. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9261. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9262. }
  9263. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9264. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9265. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9266. for (const auto *method : methods) {
  9267. Server svr;
  9268. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9269. EXPECT_FALSE(svr.is_valid()) << method;
  9270. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9271. }
  9272. }
  9273. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9274. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9275. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9276. for (const auto *method : methods) {
  9277. Server svr;
  9278. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9279. EXPECT_FALSE(svr.is_valid()) << method;
  9280. }
  9281. }
  9282. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9283. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9284. "COPY", "MOVE", "LOCK",
  9285. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9286. Server svr;
  9287. for (const auto *method : methods) {
  9288. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9289. }
  9290. EXPECT_TRUE(svr.is_valid());
  9291. }
  9292. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9293. Server svr;
  9294. svr.CustomRoute("POST", "/x",
  9295. [](const Request &, Response &, const ContentReader &) {});
  9296. EXPECT_FALSE(svr.is_valid());
  9297. }
  9298. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9299. Server svr;
  9300. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9301. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9302. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9303. EXPECT_FALSE(svr.is_valid());
  9304. }
  9305. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9306. Server svr;
  9307. auto captured = Error::Success;
  9308. svr.set_error_logger(
  9309. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9310. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9311. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9312. }
  9313. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9314. std::string out;
  9315. std::string request(
  9316. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9317. test_raw_request(request, &out);
  9318. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9319. }
  9320. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9321. std::string out;
  9322. std::string request(
  9323. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9324. test_raw_request(request, &out);
  9325. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9326. }
  9327. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9328. std::string out;
  9329. std::string request(
  9330. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9331. test_raw_request(request, &out);
  9332. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9333. }
  9334. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9335. std::string out;
  9336. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9337. "Test: \r\n\r\n",
  9338. &out);
  9339. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9340. }
  9341. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9342. Server svr;
  9343. std::string x_custom;
  9344. std::string cookie;
  9345. std::string xff;
  9346. std::string x_unicode;
  9347. std::string x_iis;
  9348. svr.Get("/check", [&](const Request &req, Response &res) {
  9349. x_custom = req.get_header_value("X-Custom");
  9350. cookie = req.get_header_value("Cookie");
  9351. xff = req.get_header_value("X-Forwarded-For");
  9352. x_unicode = req.get_header_value("X-Unicode");
  9353. x_iis = req.get_header_value("X-IIS");
  9354. res.set_content("ok", "text/plain");
  9355. });
  9356. thread t = thread([&] { svr.listen(HOST, PORT); });
  9357. auto se = detail::scope_exit([&] {
  9358. svr.stop();
  9359. t.join();
  9360. ASSERT_FALSE(svr.is_running());
  9361. });
  9362. svr.wait_until_ready();
  9363. const std::string req = "GET /check HTTP/1.1\r\n"
  9364. "Host: localhost\r\n"
  9365. "X-Custom: a%0D%0AInjected: b\r\n"
  9366. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9367. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9368. "X-Unicode: %E3%81%82\r\n"
  9369. "X-IIS: %u00E9\r\n"
  9370. "Connection: close\r\n"
  9371. "\r\n";
  9372. std::string res;
  9373. ASSERT_TRUE(send_request(5, req, &res));
  9374. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9375. // Every value must be returned verbatim (wire form), with no decoding.
  9376. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9377. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9378. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9379. EXPECT_EQ("%E3%81%82", x_unicode);
  9380. EXPECT_EQ("%u00E9", x_iis);
  9381. }
  9382. // Applications that previously relied on automatic percent-decoding can
  9383. // reproduce the old behavior by explicitly calling decode_path_component()
  9384. // or, for RFC 3986 conformance, decode_uri_component().
  9385. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9386. Server svr;
  9387. std::string decoded;
  9388. svr.Get("/check", [&](const Request &req, Response &res) {
  9389. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9390. res.set_content("ok", "text/plain");
  9391. });
  9392. thread t = thread([&] { svr.listen(HOST, PORT); });
  9393. auto se = detail::scope_exit([&] {
  9394. svr.stop();
  9395. t.join();
  9396. ASSERT_FALSE(svr.is_running());
  9397. });
  9398. svr.wait_until_ready();
  9399. const std::string req = "GET /check HTTP/1.1\r\n"
  9400. "Host: localhost\r\n"
  9401. "X-Custom: hello%20world\r\n"
  9402. "Connection: close\r\n"
  9403. "\r\n";
  9404. std::string res;
  9405. ASSERT_TRUE(send_request(5, req, &res));
  9406. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9407. EXPECT_EQ("hello world", decoded);
  9408. }
  9409. // Regression test for #2033. Browsers send Referer values that include
  9410. // percent-encoded characters such as %0A inside the URL. Decoding the
  9411. // header value would either trip the post-decode CR/LF/NUL guard (the
  9412. // original bug, returning 400) or, after that guard was relaxed, silently
  9413. // store a literal LF — both unacceptable. The wire form must round-trip.
  9414. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9415. Server svr;
  9416. std::string referer;
  9417. svr.Get("/check", [&](const Request &req, Response &res) {
  9418. referer = req.get_header_value("Referer");
  9419. res.set_content("ok", "text/plain");
  9420. });
  9421. thread t = thread([&] { svr.listen(HOST, PORT); });
  9422. auto se = detail::scope_exit([&] {
  9423. svr.stop();
  9424. t.join();
  9425. ASSERT_FALSE(svr.is_running());
  9426. });
  9427. svr.wait_until_ready();
  9428. const std::string req = "GET /check HTTP/1.1\r\n"
  9429. "Host: localhost\r\n"
  9430. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9431. "Connection: close\r\n"
  9432. "\r\n";
  9433. std::string res;
  9434. ASSERT_TRUE(send_request(5, req, &res));
  9435. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9436. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9437. }
  9438. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9439. Server svr;
  9440. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9441. res.set_header("Cache-Control", "no-cache");
  9442. res.set_chunked_content_provider(
  9443. "text/event-stream", [](size_t offset, DataSink &sink) {
  9444. std::string s = "data:";
  9445. s += std::to_string(offset);
  9446. s += "\n\n";
  9447. auto ret = sink.write(s.data(), s.size());
  9448. EXPECT_TRUE(ret);
  9449. std::this_thread::sleep_for(std::chrono::seconds(1));
  9450. return true;
  9451. });
  9452. });
  9453. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9454. svr.wait_until_ready();
  9455. Client client(HOST, PORT);
  9456. const Headers headers = {{"Accept", "text/event-stream"}};
  9457. auto get_thread = std::thread([&client, &headers]() {
  9458. auto res = client.Get(
  9459. "/events", headers,
  9460. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9461. });
  9462. auto se = detail::scope_exit([&] {
  9463. svr.stop();
  9464. get_thread.join();
  9465. listen_thread.join();
  9466. ASSERT_FALSE(svr.is_running());
  9467. });
  9468. // Give GET time to get a few messages.
  9469. std::this_thread::sleep_for(std::chrono::seconds(2));
  9470. }
  9471. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9472. httplib::Server svr;
  9473. svr.Post("/hi",
  9474. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9475. res.status = StatusCode::OK_200;
  9476. });
  9477. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9478. svr.wait_until_ready();
  9479. Client cli(HOST, PORT);
  9480. auto res = cli.Post("/hi", "data", "text/plain");
  9481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9482. EXPECT_EQ(StatusCode::OK_200, res->status);
  9483. svr.stop();
  9484. thread.join();
  9485. ASSERT_FALSE(svr.is_running());
  9486. res = cli.Post("/hi", "data", "text/plain");
  9487. ASSERT_FALSE(res);
  9488. }
  9489. TEST(ServerStopTest, ListenFailure) {
  9490. Server svr;
  9491. auto t = thread([&]() {
  9492. auto ret = svr.listen("????", PORT);
  9493. EXPECT_FALSE(ret);
  9494. });
  9495. svr.wait_until_ready();
  9496. svr.stop();
  9497. t.join();
  9498. }
  9499. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9500. TEST(ServerStopTest, Decommision) {
  9501. Server svr;
  9502. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9503. for (int i = 0; i < 4; i++) {
  9504. auto is_even = !(i % 2);
  9505. std::thread t{[&] {
  9506. try {
  9507. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9508. if (is_even) {
  9509. throw std::runtime_error("Some thing that happens to go wrong.");
  9510. }
  9511. svr.listen(HOST, PORT);
  9512. } catch (...) { svr.decommission(); }
  9513. }};
  9514. svr.wait_until_ready();
  9515. // Server is up
  9516. {
  9517. Client cli(HOST, PORT);
  9518. auto res = cli.Get("/hi");
  9519. if (is_even) {
  9520. EXPECT_FALSE(res);
  9521. } else {
  9522. EXPECT_TRUE(res);
  9523. EXPECT_EQ("hi...", res->body);
  9524. }
  9525. }
  9526. svr.stop();
  9527. t.join();
  9528. // Server is down...
  9529. {
  9530. Client cli(HOST, PORT);
  9531. auto res = cli.Get("/hi");
  9532. EXPECT_FALSE(res);
  9533. }
  9534. }
  9535. }
  9536. #endif
  9537. // Helper function for string body upload progress tests
  9538. template <typename SetupHandler, typename ClientCall>
  9539. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9540. ClientCall &&client_call,
  9541. const string &body) {
  9542. Server svr;
  9543. setup_handler(svr);
  9544. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9545. auto se = detail::scope_exit([&] {
  9546. svr.stop();
  9547. t.join();
  9548. });
  9549. svr.wait_until_ready();
  9550. Client cli(HOST, PORT);
  9551. vector<uint64_t> progress_values;
  9552. bool progress_called = false;
  9553. auto res =
  9554. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9555. progress_values.push_back(current);
  9556. progress_called = true;
  9557. return true;
  9558. });
  9559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9560. EXPECT_EQ(200, res->status);
  9561. EXPECT_TRUE(progress_called);
  9562. }
  9563. TEST(UploadProgressTest, PostStringBodyBasic) {
  9564. TestStringBodyUploadProgress(
  9565. [](Server &svr) {
  9566. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9567. res.set_content("received", "text/plain");
  9568. });
  9569. },
  9570. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9571. return cli.Post("/test", body, "text/plain", progress_callback);
  9572. },
  9573. "test data for upload progress");
  9574. }
  9575. TEST(UploadProgressTest, PutStringBodyBasic) {
  9576. TestStringBodyUploadProgress(
  9577. [](Server &svr) {
  9578. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9579. res.set_content("put received", "text/plain");
  9580. });
  9581. },
  9582. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9583. return cli.Put("/test", body, "text/plain", progress_callback);
  9584. },
  9585. "put test data for upload progress");
  9586. }
  9587. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9588. TestStringBodyUploadProgress(
  9589. [](Server &svr) {
  9590. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9591. res.set_content("patch received", "text/plain");
  9592. });
  9593. },
  9594. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9595. return cli.Patch("/test", body, "text/plain", progress_callback);
  9596. },
  9597. "patch test data for upload progress");
  9598. }
  9599. // Helper function for content provider upload progress tests
  9600. template <typename SetupHandler, typename ClientCall>
  9601. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9602. ClientCall &&client_call) {
  9603. Server svr;
  9604. setup_handler(svr);
  9605. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9606. auto se = detail::scope_exit([&] {
  9607. svr.stop();
  9608. t.join();
  9609. });
  9610. svr.wait_until_ready();
  9611. Client cli(HOST, PORT);
  9612. vector<uint64_t> progress_values;
  9613. auto res =
  9614. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9615. progress_values.push_back(current);
  9616. return true;
  9617. });
  9618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9619. EXPECT_EQ(200, res->status);
  9620. EXPECT_FALSE(progress_values.empty());
  9621. }
  9622. TEST(UploadProgressTest, PostContentProviderProgress) {
  9623. TestContentProviderUploadProgress(
  9624. [](Server &svr) {
  9625. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9626. res.set_content("provider received", "text/plain");
  9627. });
  9628. },
  9629. [](Client &cli, UploadProgress progress_callback) {
  9630. return cli.Post(
  9631. "/test", 10,
  9632. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9633. sink.os << "test data";
  9634. return true;
  9635. },
  9636. "text/plain", progress_callback);
  9637. });
  9638. }
  9639. // Helper function for multipart upload progress tests
  9640. template <typename SetupHandler, typename ClientCall>
  9641. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9642. ClientCall &&client_call,
  9643. const string &endpoint) {
  9644. Server svr;
  9645. setup_handler(svr);
  9646. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9647. auto se = detail::scope_exit([&] {
  9648. svr.stop();
  9649. t.join();
  9650. });
  9651. svr.wait_until_ready();
  9652. Client cli(HOST, PORT);
  9653. vector<uint64_t> progress_values;
  9654. UploadFormDataItems items = {
  9655. {"field1", "value1", "", ""},
  9656. {"field2", "longer value for progress tracking test", "", ""},
  9657. {"file1", "file content data for upload progress", "test.txt",
  9658. "text/plain"}};
  9659. auto res = client_call(cli, endpoint, items,
  9660. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9661. progress_values.push_back(current);
  9662. return true;
  9663. });
  9664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9665. EXPECT_EQ(200, res->status);
  9666. EXPECT_FALSE(progress_values.empty());
  9667. }
  9668. TEST(UploadProgressTest, PostMultipartProgress) {
  9669. TestMultipartUploadProgress(
  9670. [](Server &svr) {
  9671. svr.Post("/multipart", [](const Request &req, Response &res) {
  9672. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9673. res.set_content("multipart received", "text/plain");
  9674. });
  9675. },
  9676. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9677. UploadProgress progress_callback) {
  9678. return cli.Post(endpoint, items, progress_callback);
  9679. },
  9680. "/multipart");
  9681. }
  9682. // Helper function for basic download progress tests
  9683. template <typename SetupHandler, typename ClientCall>
  9684. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9685. ClientCall &&client_call, const string &endpoint,
  9686. size_t expected_content_size) {
  9687. Server svr;
  9688. setup_handler(svr);
  9689. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9690. auto se = detail::scope_exit([&] {
  9691. svr.stop();
  9692. t.join();
  9693. });
  9694. svr.wait_until_ready();
  9695. Client cli(HOST, PORT);
  9696. vector<uint64_t> progress_values;
  9697. auto res = client_call(cli, endpoint,
  9698. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9699. progress_values.push_back(current);
  9700. return true;
  9701. });
  9702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9703. EXPECT_EQ(200, res->status);
  9704. EXPECT_FALSE(progress_values.empty());
  9705. EXPECT_EQ(expected_content_size, res->body.size());
  9706. }
  9707. TEST(DownloadProgressTest, GetBasic) {
  9708. TestBasicDownloadProgress(
  9709. [](Server &svr) {
  9710. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9711. string content(1000, 'D');
  9712. res.set_content(content, "text/plain");
  9713. });
  9714. },
  9715. [](Client &cli, const string &endpoint,
  9716. DownloadProgress progress_callback) {
  9717. return cli.Get(endpoint, progress_callback);
  9718. },
  9719. "/download", 1000u);
  9720. }
  9721. // Helper function for content receiver download progress tests
  9722. template <typename SetupHandler, typename ClientCall>
  9723. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9724. ClientCall &&client_call,
  9725. const string &endpoint,
  9726. size_t expected_content_size) {
  9727. Server svr;
  9728. setup_handler(svr);
  9729. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9730. auto se = detail::scope_exit([&] {
  9731. svr.stop();
  9732. t.join();
  9733. });
  9734. svr.wait_until_ready();
  9735. Client cli(HOST, PORT);
  9736. vector<uint64_t> progress_values;
  9737. string received_body;
  9738. auto res = client_call(
  9739. cli, endpoint,
  9740. [&](const char *data, size_t data_length) -> bool {
  9741. received_body.append(data, data_length);
  9742. return true;
  9743. },
  9744. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9745. progress_values.push_back(current);
  9746. return true;
  9747. });
  9748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9749. EXPECT_EQ(200, res->status);
  9750. EXPECT_FALSE(progress_values.empty());
  9751. EXPECT_EQ(expected_content_size, received_body.size());
  9752. EXPECT_TRUE(res->body.empty());
  9753. }
  9754. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9755. TestContentReceiverDownloadProgress(
  9756. [](Server &svr) {
  9757. svr.Get("/download-receiver",
  9758. [](const Request & /*req*/, Response &res) {
  9759. string content(2000, 'R');
  9760. res.set_content(content, "text/plain");
  9761. });
  9762. },
  9763. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9764. DownloadProgress progress_callback) {
  9765. return cli.Get(endpoint, content_receiver, progress_callback);
  9766. },
  9767. "/download-receiver", 2000u);
  9768. }
  9769. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9770. // A provider reaching a pass with nothing to hand over - an empty buffer
  9771. // popped off a queue, say - must not be taken to mean the body is finished.
  9772. // It used to end the loop with the terminating chunk unwritten while the
  9773. // server still considered the response complete, so the peer waited for an
  9774. // end that never arrived.
  9775. Server svr;
  9776. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9777. auto step = std::make_shared<int>(0);
  9778. res.set_chunked_content_provider("text/plain",
  9779. [step](size_t /*offset*/, DataSink &sink) {
  9780. switch ((*step)++) {
  9781. case 0: sink.write("", 0); break;
  9782. case 1: sink.write("hello", 5); break;
  9783. default: sink.done(); break;
  9784. }
  9785. return true;
  9786. });
  9787. });
  9788. auto port = svr.bind_to_any_port(HOST);
  9789. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9790. auto listen_se = detail::scope_exit([&] {
  9791. svr.stop();
  9792. listen_thread.join();
  9793. ASSERT_FALSE(svr.is_running());
  9794. });
  9795. svr.wait_until_ready();
  9796. Client cli(HOST, port);
  9797. // Without the fix the body is never terminated, so bound the wait rather
  9798. // than letting the test hang on the default read timeout.
  9799. cli.set_read_timeout(5, 0);
  9800. auto res = cli.Get("/stream");
  9801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9802. EXPECT_EQ(StatusCode::OK_200, res->status);
  9803. EXPECT_EQ("hello", res->body);
  9804. }
  9805. TEST(StreamingTest, NoContentLengthStreaming) {
  9806. Server svr;
  9807. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9808. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9809. if (offset < 6) {
  9810. sink.os << (offset < 3 ? "a" : "b");
  9811. } else {
  9812. sink.done();
  9813. }
  9814. return true;
  9815. });
  9816. });
  9817. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9818. auto listen_se = detail::scope_exit([&] {
  9819. svr.stop();
  9820. listen_thread.join();
  9821. ASSERT_FALSE(svr.is_running());
  9822. });
  9823. svr.wait_until_ready();
  9824. Client client(HOST, PORT);
  9825. auto get_thread = std::thread([&client]() {
  9826. std::string s;
  9827. auto res =
  9828. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9829. s += std::string(data, len);
  9830. return true;
  9831. });
  9832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9833. EXPECT_EQ(StatusCode::OK_200, res->status);
  9834. EXPECT_EQ("aaabbb", s);
  9835. });
  9836. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9837. // Give GET time to get a few messages.
  9838. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9839. }
  9840. TEST(MountTest, Unmount) {
  9841. Server svr;
  9842. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9843. auto se = detail::scope_exit([&] {
  9844. svr.stop();
  9845. listen_thread.join();
  9846. ASSERT_FALSE(svr.is_running());
  9847. });
  9848. svr.wait_until_ready();
  9849. Client cli("localhost", PORT);
  9850. svr.set_mount_point("/mount2", "./www2");
  9851. auto res = cli.Get("/");
  9852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9853. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9854. res = cli.Get("/mount2/dir/test.html");
  9855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9856. EXPECT_EQ(StatusCode::OK_200, res->status);
  9857. svr.set_mount_point("/", "./www");
  9858. res = cli.Get("/dir/");
  9859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9860. EXPECT_EQ(StatusCode::OK_200, res->status);
  9861. svr.remove_mount_point("/");
  9862. res = cli.Get("/dir/");
  9863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9864. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9865. svr.remove_mount_point("/mount2");
  9866. res = cli.Get("/mount2/dir/test.html");
  9867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9868. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9869. }
  9870. TEST(MountTest, PathSegmentBoundary) {
  9871. Server svr;
  9872. svr.set_mount_point("/mount2", "./www2");
  9873. svr.set_mount_point("/", "./www");
  9874. auto port = svr.bind_to_any_port(HOST);
  9875. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9876. auto se = detail::scope_exit([&] {
  9877. svr.stop();
  9878. listen_thread.join();
  9879. ASSERT_FALSE(svr.is_running());
  9880. });
  9881. svr.wait_until_ready();
  9882. Client cli(HOST, port);
  9883. auto res = cli.Get("/mount2/dir/test.html");
  9884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9885. EXPECT_EQ(StatusCode::OK_200, res->status);
  9886. // "/mount2" must not match part-way through a path segment.
  9887. res = cli.Get("/mount2dir/test.html");
  9888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9889. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9890. // A mount point ending in '/' keeps matching every path below it.
  9891. res = cli.Get("/dir/test.html");
  9892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9893. EXPECT_EQ(StatusCode::OK_200, res->status);
  9894. }
  9895. TEST(MountTest, Redicect) {
  9896. Server svr;
  9897. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9898. auto se = detail::scope_exit([&] {
  9899. svr.stop();
  9900. listen_thread.join();
  9901. ASSERT_FALSE(svr.is_running());
  9902. });
  9903. svr.set_mount_point("/", "./www");
  9904. svr.wait_until_ready();
  9905. Client cli("localhost", PORT);
  9906. auto res = cli.Get("/dir/");
  9907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9908. EXPECT_EQ(StatusCode::OK_200, res->status);
  9909. res = cli.Get("/dir");
  9910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9911. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9912. res = cli.Get("/file");
  9913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9914. EXPECT_EQ(StatusCode::OK_200, res->status);
  9915. res = cli.Get("/file/");
  9916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9917. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9918. cli.set_follow_location(true);
  9919. res = cli.Get("/dir");
  9920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9921. EXPECT_EQ(StatusCode::OK_200, res->status);
  9922. }
  9923. TEST(MountTest, MultibytesPathName) {
  9924. Server svr;
  9925. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9926. auto se = detail::scope_exit([&] {
  9927. svr.stop();
  9928. listen_thread.join();
  9929. ASSERT_FALSE(svr.is_running());
  9930. });
  9931. svr.set_mount_point("/", "./www");
  9932. svr.wait_until_ready();
  9933. Client cli("localhost", PORT);
  9934. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  9935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9936. EXPECT_EQ(StatusCode::OK_200, res->status);
  9937. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  9938. }
  9939. #ifdef _WIN32
  9940. // Issue #2435: mmap::open() must succeed even when another handle holds
  9941. // the file open for writing (e.g. an active log file).
  9942. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  9943. const char *path = "mmap_concurrent_writer_test.txt";
  9944. const char *content = "hello";
  9945. {
  9946. std::ofstream f(path, std::ios::binary);
  9947. f.write(content, static_cast<std::streamsize>(strlen(content)));
  9948. }
  9949. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  9950. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  9951. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  9952. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  9953. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  9954. detail::mmap m(path);
  9955. ASSERT_TRUE(m.is_open());
  9956. EXPECT_EQ(strlen(content), m.size());
  9957. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  9958. }
  9959. #endif
  9960. #ifndef _WIN32
  9961. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  9962. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  9963. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  9964. TEST(MmapTest, FailedMappingIsNotOpen) {
  9965. const char *path = "./mmap_failed_mapping_test_dir";
  9966. ASSERT_EQ(0, ::mkdir(path, 0755));
  9967. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  9968. detail::mmap m(path);
  9969. EXPECT_FALSE(m.is_open());
  9970. EXPECT_EQ(0U, m.size());
  9971. EXPECT_NE(static_cast<const void *>(m.data()),
  9972. static_cast<const void *>(MAP_FAILED));
  9973. }
  9974. #endif
  9975. TEST(KeepAliveTest, ReadTimeout) {
  9976. Server svr;
  9977. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9978. std::this_thread::sleep_for(std::chrono::seconds(2));
  9979. res.set_content("a", "text/plain");
  9980. });
  9981. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9982. res.set_content("b", "text/plain");
  9983. });
  9984. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9985. auto se = detail::scope_exit([&] {
  9986. svr.stop();
  9987. listen_thread.join();
  9988. ASSERT_FALSE(svr.is_running());
  9989. });
  9990. svr.wait_until_ready();
  9991. Client cli("localhost", PORT);
  9992. cli.set_keep_alive(true);
  9993. cli.set_read_timeout(std::chrono::seconds(1));
  9994. auto resa = cli.Get("/a");
  9995. ASSERT_FALSE(resa);
  9996. EXPECT_EQ(Error::Read, resa.error());
  9997. auto resb = cli.Get("/b");
  9998. ASSERT_TRUE(resb);
  9999. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10000. EXPECT_EQ("b", resb->body);
  10001. }
  10002. TEST(KeepAliveTest, MaxCount) {
  10003. size_t keep_alive_max_count = 3;
  10004. Server svr;
  10005. svr.set_keep_alive_max_count(keep_alive_max_count);
  10006. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10007. res.set_content("Hello World!", "text/plain");
  10008. });
  10009. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10010. auto se = detail::scope_exit([&] {
  10011. svr.stop();
  10012. listen_thread.join();
  10013. ASSERT_FALSE(svr.is_running());
  10014. });
  10015. svr.wait_until_ready();
  10016. Client cli(HOST, PORT);
  10017. cli.set_keep_alive(true);
  10018. for (size_t i = 0; i < 5; i++) {
  10019. auto result = cli.Get("/hi");
  10020. ASSERT_TRUE(result);
  10021. EXPECT_EQ(StatusCode::OK_200, result->status);
  10022. if (i == keep_alive_max_count - 1) {
  10023. EXPECT_EQ("close", result->get_header_value("Connection"));
  10024. } else {
  10025. EXPECT_FALSE(result->has_header("Connection"));
  10026. }
  10027. }
  10028. }
  10029. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10030. // can pull the next one into the server's buffer. The server must serve it
  10031. // without waiting for the socket to become readable again. The keep-alive
  10032. // timeout outlasts the client's read timeout, so a request left waiting for it
  10033. // shows up as a missing response.
  10034. static void serve_pipelining_routes(Server &svr,
  10035. const std::function<void(int)> &client) {
  10036. svr.set_keep_alive_timeout(5);
  10037. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10038. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10039. });
  10040. svr.Post("/echo", [](const Request &req, Response &res) {
  10041. res.set_content("echo " + req.body, "text/plain");
  10042. });
  10043. auto port = svr.bind_to_any_port(HOST);
  10044. thread t = thread([&] { svr.listen_after_bind(); });
  10045. auto se = detail::scope_exit([&] {
  10046. svr.stop();
  10047. t.join();
  10048. });
  10049. svr.wait_until_ready();
  10050. client(port);
  10051. }
  10052. static std::string
  10053. send_pipelined_requests(const std::vector<std::string> &parts) {
  10054. Server svr;
  10055. std::string res;
  10056. serve_pipelining_routes(svr, [&](int port) {
  10057. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10058. });
  10059. return res;
  10060. }
  10061. static void expect_in_order(const std::string &res,
  10062. const std::vector<std::string> &bodies) {
  10063. size_t pos = 0;
  10064. for (const auto &body : bodies) {
  10065. pos = res.find(body, pos);
  10066. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10067. pos += body.size();
  10068. }
  10069. }
  10070. TEST(KeepAliveTest, PipelinedRequests) {
  10071. auto res = send_pipelined_requests(
  10072. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10073. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10074. "Content-Length: 4\r\n\r\nbody"
  10075. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10076. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10077. }
  10078. // The second request starts in the server's buffer and ends on the socket.
  10079. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10080. auto res =
  10081. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10082. "GET /hi/2 HTTP/1.1\r\nHo",
  10083. "st: localhost\r\nConnection: close\r\n\r\n"});
  10084. expect_in_order(res, {"hi 1", "hi 2"});
  10085. }
  10086. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10087. // CRLF after a body does not turn into a 400 for the next request.
  10088. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10089. auto res = send_pipelined_requests(
  10090. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10091. "Content-Length: 4\r\n\r\nbody\r\n"
  10092. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10093. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10094. expect_in_order(res, {"echo body", "hi 2"});
  10095. }
  10096. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10097. // must not be served as the next request.
  10098. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10099. auto res = send_pipelined_requests(
  10100. {"INVALID REQUEST LINE\r\n\r\n"
  10101. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10102. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10103. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10104. }
  10105. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10106. // Over TLS, the next request is held by the TLS library as already decrypted
  10107. // data rather than on the socket.
  10108. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10109. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10110. std::string res;
  10111. serve_pipelining_routes(svr, [&](int port) {
  10112. auto error = Error::Success;
  10113. auto sock = detail::create_client_socket(
  10114. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  10115. /*connection_timeout_sec=*/5, 0,
  10116. /*read_timeout_sec=*/2, 0,
  10117. /*write_timeout_sec=*/5, 0, std::string(), error);
  10118. ASSERT_NE(INVALID_SOCKET, sock);
  10119. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  10120. auto ctx = SSL_CTX_new(TLS_client_method());
  10121. auto ssl = SSL_new(ctx);
  10122. auto ssl_se = detail::scope_exit([&] {
  10123. SSL_free(ssl);
  10124. SSL_CTX_free(ctx);
  10125. });
  10126. SSL_set_fd(ssl, static_cast<int>(sock));
  10127. ASSERT_EQ(1, SSL_connect(ssl));
  10128. // One write, so all three requests arrive in one TLS record
  10129. const std::string req =
  10130. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10131. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10132. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
  10133. ASSERT_EQ(static_cast<int>(req.size()),
  10134. SSL_write(ssl, req.data(), static_cast<int>(req.size())));
  10135. char buf[512];
  10136. int n;
  10137. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  10138. res.append(buf, static_cast<size_t>(n));
  10139. }
  10140. });
  10141. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10142. }
  10143. #endif
  10144. TEST(KeepAliveTest, Issue1041) {
  10145. Server svr;
  10146. svr.set_keep_alive_timeout(3);
  10147. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10148. res.set_content("Hello World!", "text/plain");
  10149. });
  10150. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10151. auto se = detail::scope_exit([&] {
  10152. svr.stop();
  10153. listen_thread.join();
  10154. ASSERT_FALSE(svr.is_running());
  10155. });
  10156. svr.wait_until_ready();
  10157. Client cli(HOST, PORT);
  10158. cli.set_keep_alive(true);
  10159. auto result = cli.Get("/hi");
  10160. ASSERT_TRUE(result);
  10161. EXPECT_EQ(StatusCode::OK_200, result->status);
  10162. std::this_thread::sleep_for(std::chrono::seconds(5));
  10163. result = cli.Get("/hi");
  10164. ASSERT_TRUE(result);
  10165. EXPECT_EQ(StatusCode::OK_200, result->status);
  10166. }
  10167. TEST(KeepAliveTest, Issue1959) {
  10168. Server svr;
  10169. svr.set_keep_alive_timeout(5);
  10170. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10171. res.set_content("a", "text/plain");
  10172. });
  10173. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10174. auto se = detail::scope_exit([&] {
  10175. if (!svr.is_running()) return;
  10176. svr.stop();
  10177. listen_thread.join();
  10178. ASSERT_FALSE(svr.is_running());
  10179. });
  10180. svr.wait_until_ready();
  10181. Client cli("localhost", PORT);
  10182. cli.set_keep_alive(true);
  10183. using namespace std::chrono;
  10184. auto start = steady_clock::now();
  10185. cli.Get("/a");
  10186. svr.stop();
  10187. listen_thread.join();
  10188. auto end = steady_clock::now();
  10189. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10190. EXPECT_LT(elapsed, 5000);
  10191. }
  10192. #ifdef CPPHTTPLIB_SSL_ENABLED
  10193. TEST(KeepAliveTest, SSLClientReconnection) {
  10194. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10195. ASSERT_TRUE(svr.is_valid());
  10196. svr.set_keep_alive_timeout(1);
  10197. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10198. res.set_content("Hello World!", "text/plain");
  10199. });
  10200. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10201. auto se = detail::scope_exit([&] {
  10202. svr.stop();
  10203. listen_thread.join();
  10204. ASSERT_FALSE(svr.is_running());
  10205. });
  10206. svr.wait_until_ready();
  10207. SSLClient cli(HOST, PORT);
  10208. cli.enable_server_certificate_verification(false);
  10209. cli.set_keep_alive(true);
  10210. auto result = cli.Get("/hi");
  10211. ASSERT_TRUE(result);
  10212. EXPECT_EQ(StatusCode::OK_200, result->status);
  10213. result = cli.Get("/hi");
  10214. ASSERT_TRUE(result);
  10215. EXPECT_EQ(StatusCode::OK_200, result->status);
  10216. std::this_thread::sleep_for(std::chrono::seconds(2));
  10217. // Recoonect
  10218. result = cli.Get("/hi");
  10219. ASSERT_TRUE(result);
  10220. EXPECT_EQ(StatusCode::OK_200, result->status);
  10221. result = cli.Get("/hi");
  10222. ASSERT_TRUE(result);
  10223. EXPECT_EQ(StatusCode::OK_200, result->status);
  10224. }
  10225. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10226. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10227. ASSERT_TRUE(svr.is_valid());
  10228. svr.set_keep_alive_timeout(1);
  10229. std::string content = "reconnect";
  10230. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10231. res.set_content("Hello World!", "text/plain");
  10232. });
  10233. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10234. auto se = detail::scope_exit([&] {
  10235. svr.stop();
  10236. listen_thread.join();
  10237. ASSERT_FALSE(svr.is_running());
  10238. });
  10239. svr.wait_until_ready();
  10240. SSLClient cli(HOST, PORT);
  10241. cli.enable_server_certificate_verification(false);
  10242. cli.set_keep_alive(true);
  10243. auto result = cli.Post(
  10244. "/hi", content.size(),
  10245. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10246. sink.write(content.c_str(), content.size());
  10247. return true;
  10248. },
  10249. "text/plain");
  10250. ASSERT_TRUE(result);
  10251. EXPECT_EQ(200, result->status);
  10252. std::this_thread::sleep_for(std::chrono::seconds(2));
  10253. // Recoonect
  10254. result = cli.Post(
  10255. "/hi", content.size(),
  10256. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10257. sink.write(content.c_str(), content.size());
  10258. return true;
  10259. },
  10260. "text/plain");
  10261. ASSERT_TRUE(result);
  10262. EXPECT_EQ(200, result->status);
  10263. result = cli.Post(
  10264. "/hi", content.size(),
  10265. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10266. sink.write(content.c_str(), content.size());
  10267. return true;
  10268. },
  10269. "text/plain");
  10270. ASSERT_TRUE(result);
  10271. EXPECT_EQ(200, result->status);
  10272. }
  10273. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10274. using namespace httplib::tls;
  10275. {
  10276. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10277. ASSERT_TRUE(svr.is_valid());
  10278. svr.Get("/sni", [&](const Request &req, Response &res) {
  10279. std::string expected = req.sni();
  10280. EXPECT_EQ(expected, req.get_param_value("expected"));
  10281. res.set_content("ok", "text/plain");
  10282. });
  10283. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10284. auto se = detail::scope_exit([&] {
  10285. svr.stop();
  10286. listen_thread.join();
  10287. ASSERT_FALSE(svr.is_running());
  10288. });
  10289. svr.wait_until_ready();
  10290. {
  10291. SSLClient cli("localhost", PORT);
  10292. cli.enable_server_certificate_verification(false);
  10293. auto res = cli.Get("/sni?expected=localhost");
  10294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10295. }
  10296. {
  10297. SSLClient cli("::1", PORT);
  10298. cli.enable_server_certificate_verification(false);
  10299. auto res = cli.Get("/sni?expected=");
  10300. // NOTE: This may fail if the server is listening on IPv4 only
  10301. // (e.g., when localhost resolves to 127.0.0.1 only)
  10302. if (res) {
  10303. EXPECT_EQ(StatusCode::OK_200, res->status);
  10304. } else {
  10305. EXPECT_EQ(Error::Connection, res.error());
  10306. }
  10307. }
  10308. }
  10309. }
  10310. #endif
  10311. TEST(ClientProblemDetectionTest, ContentProvider) {
  10312. Server svr;
  10313. size_t content_length = 1024 * 1024;
  10314. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10315. res.set_content_provider(
  10316. content_length, "text/plain",
  10317. [&](size_t offset, size_t length, DataSink &sink) {
  10318. auto out_len = std::min(length, static_cast<size_t>(1024));
  10319. std::string out(out_len, '@');
  10320. sink.write(out.data(), out_len);
  10321. return offset < 4096;
  10322. },
  10323. [](bool success) { ASSERT_FALSE(success); });
  10324. });
  10325. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10326. res.set_content_provider(
  10327. 0, "text/plain",
  10328. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10329. EXPECT_TRUE(false);
  10330. return true;
  10331. },
  10332. [](bool success) { ASSERT_FALSE(success); });
  10333. });
  10334. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10335. auto se = detail::scope_exit([&] {
  10336. svr.stop();
  10337. listen_thread.join();
  10338. ASSERT_FALSE(svr.is_running());
  10339. });
  10340. svr.wait_until_ready();
  10341. Client cli("localhost", PORT);
  10342. {
  10343. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10344. size_t /*data_length*/) { return false; });
  10345. ASSERT_FALSE(res);
  10346. }
  10347. {
  10348. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10349. size_t /*data_length*/) { return false; });
  10350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10351. }
  10352. }
  10353. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10354. // A provider that reports success without writing anything and without
  10355. // calling done() used to be handed the same offset and length again on every
  10356. // pass, so it spun for as long as the peer stayed connected.
  10357. Server svr;
  10358. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10359. res.set_content("ok", "text/plain");
  10360. });
  10361. auto port = svr.bind_to_any_port(HOST);
  10362. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10363. auto se = detail::scope_exit([&] {
  10364. svr.stop();
  10365. listen_thread.join();
  10366. ASSERT_FALSE(svr.is_running());
  10367. });
  10368. svr.wait_until_ready();
  10369. std::atomic<int> call_count{0};
  10370. Client cli(HOST, port);
  10371. auto res = cli.Post(
  10372. "/", 1024,
  10373. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10374. // Give up after enough passes to show the spin, so that losing the
  10375. // check below fails this test instead of hanging it.
  10376. return ++call_count < 100;
  10377. },
  10378. "text/plain");
  10379. ASSERT_FALSE(res);
  10380. EXPECT_EQ(Error::Write, res.error());
  10381. EXPECT_EQ(1, call_count.load());
  10382. }
  10383. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10384. // A writer only has to assign `write`. The other three used to be left as
  10385. // empty std::functions, so a provider calling one threw
  10386. // std::bad_function_call out of the thread running it and took the whole
  10387. // process down.
  10388. DataSink sink;
  10389. std::string written;
  10390. sink.write = [&](const char *data, size_t data_len) {
  10391. written.append(data, data_len);
  10392. return true;
  10393. };
  10394. EXPECT_TRUE(sink.is_writable());
  10395. sink.done();
  10396. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10397. EXPECT_TRUE(written.empty());
  10398. }
  10399. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10400. // A sink that cannot carry trailers still has to finish.
  10401. DataSink sink;
  10402. auto done_count = 0;
  10403. sink.done = [&]() { done_count++; };
  10404. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10405. EXPECT_EQ(1, done_count);
  10406. }
  10407. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10408. Server svr;
  10409. const std::string body(4096, 'x');
  10410. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10411. res.set_content_provider(body.size(), "text/plain",
  10412. [&](size_t offset, size_t length, DataSink &sink) {
  10413. sink.write(body.data() + offset, length);
  10414. sink.done();
  10415. return true;
  10416. });
  10417. });
  10418. auto port = svr.bind_to_any_port(HOST);
  10419. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10420. auto se = detail::scope_exit([&] {
  10421. svr.stop();
  10422. listen_thread.join();
  10423. ASSERT_FALSE(svr.is_running());
  10424. });
  10425. svr.wait_until_ready();
  10426. Client cli(HOST, port);
  10427. auto res = cli.Get("/");
  10428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10429. EXPECT_EQ(StatusCode::OK_200, res->status);
  10430. EXPECT_EQ(body, res->body);
  10431. }
  10432. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10433. Server svr;
  10434. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10435. res.set_content_provider(
  10436. 1024, "text/plain",
  10437. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10438. sink.write("hello", 5);
  10439. sink.done(); // short of the 1024 bytes the response promised
  10440. return true;
  10441. });
  10442. });
  10443. auto port = svr.bind_to_any_port(HOST);
  10444. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10445. auto se = detail::scope_exit([&] {
  10446. svr.stop();
  10447. listen_thread.join();
  10448. ASSERT_FALSE(svr.is_running());
  10449. });
  10450. svr.wait_until_ready();
  10451. Client cli(HOST, port);
  10452. cli.set_read_timeout(5, 0);
  10453. // The response is short of its Content-Length, so the client cannot read a
  10454. // complete body. What matters is that this returns at all: a no-op done()
  10455. // would leave the writer looping over a provider that never makes progress.
  10456. auto res = cli.Get("/");
  10457. EXPECT_FALSE(res);
  10458. }
  10459. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10460. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10461. // The compressed path builds the whole body before connecting, so this
  10462. // fails client-side and never reaches a server.
  10463. Client cli(HOST, PORT);
  10464. cli.set_compress(true);
  10465. auto res = cli.Post(
  10466. "/", 1024,
  10467. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10468. sink.write("hello", 5);
  10469. sink.done(); // short of the 1024 bytes the request announced
  10470. return true;
  10471. },
  10472. "text/plain");
  10473. ASSERT_FALSE(res);
  10474. EXPECT_EQ(Error::Write, res.error());
  10475. }
  10476. #endif
  10477. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  10478. Server svr;
  10479. svr.set_error_handler([](Request const &, Response &res) -> void {
  10480. res.set_chunked_content_provider(
  10481. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10482. sink.os << "hello";
  10483. sink.os << "world";
  10484. sink.done();
  10485. return true;
  10486. });
  10487. });
  10488. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10489. auto se = detail::scope_exit([&] {
  10490. svr.stop();
  10491. listen_thread.join();
  10492. ASSERT_FALSE(svr.is_running());
  10493. });
  10494. svr.wait_until_ready();
  10495. Client cli("localhost", PORT);
  10496. auto res = cli.Get("/");
  10497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10498. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10499. EXPECT_EQ("helloworld", res->body);
  10500. }
  10501. // A body set after a content provider must replace it, not be sent through it.
  10502. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  10503. Server svr;
  10504. svr.set_mount_point("/", "./www");
  10505. svr.set_file_request_handler([](const Request &req, Response &res) {
  10506. if (req.path == "/dir/test.html") {
  10507. res.status = StatusCode::Forbidden_403;
  10508. res.set_content(std::string(5000, 'D'), "text/plain");
  10509. } else if (req.path == "/file") {
  10510. res.status = StatusCode::Forbidden_403;
  10511. res.body = "Denied";
  10512. }
  10513. });
  10514. auto port = svr.bind_to_any_port(HOST);
  10515. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10516. auto se = detail::scope_exit([&] {
  10517. svr.stop();
  10518. t.join();
  10519. ASSERT_FALSE(svr.is_running());
  10520. });
  10521. svr.wait_until_ready();
  10522. Client cli(HOST, port);
  10523. {
  10524. auto res = cli.Get("/dir/test.html");
  10525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10526. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10527. EXPECT_EQ(std::string(5000, 'D'), res->body);
  10528. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  10529. }
  10530. {
  10531. auto res = cli.Get("/file");
  10532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10533. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10534. EXPECT_EQ("Denied", res->body);
  10535. }
  10536. {
  10537. auto res = cli.Get("/dir/index.html");
  10538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10539. EXPECT_EQ(StatusCode::OK_200, res->status);
  10540. EXPECT_EQ(0U, res->body.find("<html>"));
  10541. }
  10542. }
  10543. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  10544. Server svr;
  10545. std::vector<bool> released;
  10546. std::mutex released_mutex;
  10547. auto releaser = [&](bool success) {
  10548. std::lock_guard<std::mutex> guard(released_mutex);
  10549. released.push_back(success);
  10550. };
  10551. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  10552. return sink.write(&"hello"[offset], length);
  10553. };
  10554. svr.Get("/sized", [&](const Request &, Response &res) {
  10555. res.status = StatusCode::NotFound_404;
  10556. res.set_content_provider(5, "text/plain", provider, releaser);
  10557. });
  10558. svr.Get("/chunked", [&](const Request &, Response &res) {
  10559. res.status = StatusCode::ServiceUnavailable_503;
  10560. res.set_chunked_content_provider(
  10561. "text/plain",
  10562. [](size_t, DataSink &sink) {
  10563. sink.os << "chunk";
  10564. sink.done();
  10565. return true;
  10566. },
  10567. releaser);
  10568. });
  10569. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  10570. res.set_content_provider(5, "text/plain", provider, releaser);
  10571. throw std::runtime_error("after the provider");
  10572. });
  10573. svr.set_error_handler([](const Request &req, Response &res) {
  10574. // Leave the exception handler's content to it.
  10575. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  10576. res.set_content(std::string(1000, 'E'), "text/html");
  10577. return Server::HandlerResponse::Handled;
  10578. });
  10579. svr.set_exception_handler(
  10580. [](const Request &, Response &res, std::exception_ptr) {
  10581. res.status = StatusCode::InternalServerError_500;
  10582. res.set_content(std::string(1000, 'X'), "text/html");
  10583. });
  10584. auto port = svr.bind_to_any_port(HOST);
  10585. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10586. auto se = detail::scope_exit([&] {
  10587. svr.stop();
  10588. t.join();
  10589. ASSERT_FALSE(svr.is_running());
  10590. });
  10591. svr.wait_until_ready();
  10592. Client cli(HOST, port);
  10593. {
  10594. auto res = cli.Get("/sized");
  10595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10596. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10597. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10598. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  10599. }
  10600. {
  10601. auto res = cli.Get("/chunked");
  10602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10603. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  10604. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10605. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  10606. }
  10607. {
  10608. auto res = cli.Get("/throw");
  10609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10610. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  10611. EXPECT_EQ(std::string(1000, 'X'), res->body);
  10612. }
  10613. std::lock_guard<std::mutex> guard(released_mutex);
  10614. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  10615. }
  10616. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  10617. Server svr;
  10618. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  10619. return sink.write(&"abc"[offset], length);
  10620. };
  10621. svr.Get("/file-then-body", [](const Request &, Response &res) {
  10622. res.set_file_content("./www/dir/test.html");
  10623. res.set_content("body", "text/plain");
  10624. });
  10625. svr.Get("/body-then-file", [](const Request &, Response &res) {
  10626. res.set_content(std::string(100, 'B'), "text/plain");
  10627. res.set_file_content("./www/dir/test.html");
  10628. });
  10629. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  10630. res.set_content(std::string(100, 'B'), "text/plain");
  10631. res.set_content_provider(3, "text/plain", abc);
  10632. });
  10633. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  10634. res.set_content_provider(3, "text/plain", abc);
  10635. res.set_content(std::string(100, 'B'), "text/plain");
  10636. });
  10637. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  10638. res.set_content_provider(3, "text/plain", abc);
  10639. res.body = "direct";
  10640. });
  10641. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  10642. res.set_file_content("./www/dir/test.html");
  10643. res.body = "direct";
  10644. });
  10645. auto port = svr.bind_to_any_port(HOST);
  10646. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10647. auto se = detail::scope_exit([&] {
  10648. svr.stop();
  10649. t.join();
  10650. ASSERT_FALSE(svr.is_running());
  10651. });
  10652. svr.wait_until_ready();
  10653. Client cli(HOST, port);
  10654. auto expect_body = [&](const char *path, const std::string &body) {
  10655. // Uncompressed, so Content-Length can be compared with the body.
  10656. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  10657. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  10658. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10659. EXPECT_EQ(body, res->body) << path;
  10660. EXPECT_EQ(std::to_string(body.size()),
  10661. res->get_header_value("Content-Length"))
  10662. << path;
  10663. };
  10664. expect_body("/file-then-body", "body");
  10665. expect_body("/body-then-file", "test.html");
  10666. expect_body("/body-then-provider", "abc");
  10667. expect_body("/provider-then-body", std::string(100, 'B'));
  10668. expect_body("/provider-then-direct-body", "direct");
  10669. expect_body("/file-then-direct-body", "direct");
  10670. // Ranges are checked against the body, not the dropped provider.
  10671. {
  10672. auto res = cli.Get("/provider-then-direct-body",
  10673. Headers{{make_range_header({{1, 2}})}});
  10674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10675. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10676. EXPECT_EQ("ir", res->body);
  10677. }
  10678. {
  10679. auto res = cli.Get("/file-then-direct-body",
  10680. Headers{{make_range_header({{7, 8}})}});
  10681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10682. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  10683. }
  10684. }
  10685. // Forward declaration (see the base64_encode note).
  10686. namespace httplib {
  10687. namespace detail {
  10688. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  10689. const std::string &content_type,
  10690. EncodingType encoding);
  10691. } // namespace detail
  10692. } // namespace httplib
  10693. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  10694. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  10695. ASSERT_TRUE(mm->is_open());
  10696. Response res;
  10697. detail::set_file_content_provider(res, mm, "text/html",
  10698. detail::EncodingType::None);
  10699. std::string out;
  10700. DataSink sink;
  10701. sink.write = [&](const char *d, size_t l) {
  10702. out.append(d, l);
  10703. return true;
  10704. };
  10705. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  10706. EXPECT_EQ("test.html", out);
  10707. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  10708. EXPECT_EQ("test.html", out);
  10709. }
  10710. TEST(LongPollingTest, ClientCloseDetection) {
  10711. Server svr;
  10712. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10713. res.set_chunked_content_provider(
  10714. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10715. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10716. sink.os << "hello";
  10717. auto count = 10;
  10718. while (count > 0 && sink.is_writable()) {
  10719. this_thread::sleep_for(chrono::milliseconds(10));
  10720. count--;
  10721. }
  10722. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  10723. return true;
  10724. });
  10725. });
  10726. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10727. auto se = detail::scope_exit([&] {
  10728. svr.stop();
  10729. listen_thread.join();
  10730. ASSERT_FALSE(svr.is_running());
  10731. });
  10732. svr.wait_until_ready();
  10733. Client cli("localhost", PORT);
  10734. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10735. EXPECT_EQ("hello", string(data, data_length));
  10736. return false; // close the socket immediately.
  10737. });
  10738. ASSERT_FALSE(res);
  10739. }
  10740. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  10741. Server svr;
  10742. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10743. res.set_chunked_content_provider(
  10744. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10745. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10746. sink.os << "hello";
  10747. EXPECT_TRUE(sink.os.good());
  10748. // Wait for the client to close the connection
  10749. auto count = 10;
  10750. while (count > 0 && sink.is_writable()) {
  10751. this_thread::sleep_for(chrono::milliseconds(10));
  10752. count--;
  10753. }
  10754. // After client disconnect, write repeatedly until the socket
  10755. // write actually fails (small writes may be absorbed by the
  10756. // kernel buffer)
  10757. std::string chunk(1024, 'x');
  10758. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  10759. sink.os << chunk;
  10760. }
  10761. EXPECT_TRUE(sink.os.fail());
  10762. return true;
  10763. });
  10764. });
  10765. auto port = svr.bind_to_any_port("localhost");
  10766. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10767. auto se = detail::scope_exit([&] {
  10768. svr.stop();
  10769. listen_thread.join();
  10770. ASSERT_FALSE(svr.is_running());
  10771. });
  10772. svr.wait_until_ready();
  10773. Client cli("localhost", port);
  10774. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10775. EXPECT_EQ("hello", string(data, data_length));
  10776. return false; // close the socket immediately.
  10777. });
  10778. ASSERT_FALSE(res);
  10779. }
  10780. TEST(GetWithParametersTest, GetWithParameters) {
  10781. Server svr;
  10782. svr.Get("/", [&](const Request &req, Response &) {
  10783. EXPECT_EQ("world", req.get_param_value("hello"));
  10784. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10785. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10786. });
  10787. svr.Get("/params", [&](const Request &req, Response &) {
  10788. EXPECT_EQ("world", req.get_param_value("hello"));
  10789. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10790. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10791. });
  10792. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10793. EXPECT_EQ("resource-id", req.matches[1]);
  10794. EXPECT_EQ("foo", req.get_param_value("param1"));
  10795. EXPECT_EQ("bar", req.get_param_value("param2"));
  10796. });
  10797. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10798. EXPECT_EQ("user-id", req.path_params.at("id"));
  10799. EXPECT_EQ("foo", req.get_param_value("param1"));
  10800. EXPECT_EQ("bar", req.get_param_value("param2"));
  10801. });
  10802. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10803. auto se = detail::scope_exit([&] {
  10804. svr.stop();
  10805. listen_thread.join();
  10806. ASSERT_FALSE(svr.is_running());
  10807. });
  10808. svr.wait_until_ready();
  10809. {
  10810. Client cli(HOST, PORT);
  10811. Params params;
  10812. params.emplace("hello", "world");
  10813. params.emplace("hello2", "world2");
  10814. params.emplace("hello3", "world3");
  10815. auto res = cli.Get("/", params, Headers{});
  10816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10817. EXPECT_EQ(StatusCode::OK_200, res->status);
  10818. }
  10819. {
  10820. Client cli(HOST, PORT);
  10821. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  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("/resources/resource-id?param1=foo&param2=bar");
  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("/users/user-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. TEST(GetWithParametersTest, GetWithParameters2) {
  10839. Server svr;
  10840. svr.Get("/", [&](const Request &req, Response &res) {
  10841. auto text = req.get_param_value("hello");
  10842. res.set_content(text, "text/plain");
  10843. });
  10844. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10845. auto se = detail::scope_exit([&] {
  10846. svr.stop();
  10847. listen_thread.join();
  10848. ASSERT_FALSE(svr.is_running());
  10849. });
  10850. svr.wait_until_ready();
  10851. Client cli("localhost", PORT);
  10852. Params params;
  10853. params.emplace("hello", "world");
  10854. std::string body;
  10855. auto res = cli.Get("/", params, Headers{},
  10856. [&](const char *data, size_t data_length) {
  10857. body.append(data, data_length);
  10858. return true;
  10859. });
  10860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10861. EXPECT_EQ(StatusCode::OK_200, res->status);
  10862. EXPECT_EQ("world", body);
  10863. }
  10864. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  10865. Server svr;
  10866. svr.Get("/search", [&](const Request &req, Response &res) {
  10867. auto q = req.get_param_value("q");
  10868. res.set_content(q, "text/plain");
  10869. });
  10870. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10871. auto se = detail::scope_exit([&] {
  10872. svr.stop();
  10873. listen_thread.join();
  10874. ASSERT_FALSE(svr.is_running());
  10875. });
  10876. svr.wait_until_ready();
  10877. Client cli("localhost", PORT);
  10878. // Verify that Get(path, params) works without requiring Headers argument
  10879. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  10880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10881. EXPECT_EQ(StatusCode::OK_200, res->status);
  10882. EXPECT_EQ("cpp-httplib", res->body);
  10883. }
  10884. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  10885. auto host = "httpbingo.org";
  10886. auto path = std::string{"/range/32"};
  10887. #ifdef CPPHTTPLIB_SSL_ENABLED
  10888. SSLClient cli(host);
  10889. #else
  10890. Client cli(host);
  10891. #endif
  10892. cli.set_default_headers({make_range_header({{1, 10}})});
  10893. cli.set_connection_timeout(5);
  10894. {
  10895. auto res = cli.Get(path);
  10896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10897. EXPECT_EQ("bcdefghijk", res->body);
  10898. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10899. }
  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. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  10908. Server svr;
  10909. svr.set_default_headers({{"Hello", "World"}});
  10910. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10911. res.set_content("ok", "text/plain");
  10912. });
  10913. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10914. auto se = detail::scope_exit([&] {
  10915. svr.stop();
  10916. listen_thread.join();
  10917. ASSERT_FALSE(svr.is_running());
  10918. });
  10919. svr.wait_until_ready();
  10920. Client cli("localhost", PORT);
  10921. auto res = cli.Get("/");
  10922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10923. EXPECT_EQ(StatusCode::OK_200, res->status);
  10924. EXPECT_EQ("ok", res->body);
  10925. EXPECT_EQ("World", res->get_header_value("Hello"));
  10926. }
  10927. #ifdef CPPHTTPLIB_SSL_ENABLED
  10928. TEST(KeepAliveTest, ReadTimeoutSSL) {
  10929. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10930. ASSERT_TRUE(svr.is_valid());
  10931. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10932. std::this_thread::sleep_for(std::chrono::seconds(2));
  10933. res.set_content("a", "text/plain");
  10934. });
  10935. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10936. res.set_content("b", "text/plain");
  10937. });
  10938. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10939. auto se = detail::scope_exit([&] {
  10940. svr.stop();
  10941. listen_thread.join();
  10942. ASSERT_FALSE(svr.is_running());
  10943. });
  10944. svr.wait_until_ready();
  10945. SSLClient cli("localhost", PORT);
  10946. cli.enable_server_certificate_verification(false);
  10947. cli.set_keep_alive(true);
  10948. cli.set_read_timeout(std::chrono::seconds(1));
  10949. auto resa = cli.Get("/a");
  10950. ASSERT_TRUE(!resa);
  10951. EXPECT_EQ(Error::Read, resa.error());
  10952. auto resb = cli.Get("/b");
  10953. ASSERT_TRUE(resb);
  10954. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10955. EXPECT_EQ("b", resb->body);
  10956. }
  10957. // Closing an idle keep-alive connection sends close_notify and returns. The
  10958. // server must not wait for the client's close_notify: an idle client never
  10959. // sends one, so the worker would be held until the read timeout expires, and
  10960. // stop() would wait for it.
  10961. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  10962. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10963. ASSERT_TRUE(svr.is_valid());
  10964. svr.set_keep_alive_timeout(1);
  10965. svr.set_read_timeout(10, 0);
  10966. svr.Get("/", [](const Request &, Response &res) {
  10967. res.set_content("ok", "text/plain");
  10968. });
  10969. auto port = svr.bind_to_any_port(HOST);
  10970. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10971. auto se = detail::scope_exit([&] {
  10972. if (listen_thread.joinable()) {
  10973. svr.stop();
  10974. listen_thread.join();
  10975. }
  10976. });
  10977. svr.wait_until_ready();
  10978. SSLClient cli(HOST, port);
  10979. cli.enable_server_certificate_verification(false);
  10980. cli.set_keep_alive(true);
  10981. auto res = cli.Get("/");
  10982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10983. EXPECT_EQ(StatusCode::OK_200, res->status);
  10984. // Stay idle past the keep-alive timeout so the server closes the connection.
  10985. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  10986. auto start = std::chrono::steady_clock::now();
  10987. svr.stop();
  10988. listen_thread.join();
  10989. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10990. std::chrono::steady_clock::now() - start)
  10991. .count();
  10992. EXPECT_LT(elapsed, 3000);
  10993. }
  10994. #endif
  10995. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  10996. protected:
  10997. ServerTestWithAI_PASSIVE()
  10998. : cli_(HOST, PORT)
  10999. #ifdef CPPHTTPLIB_SSL_ENABLED
  11000. ,
  11001. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11002. #endif
  11003. {
  11004. #ifdef CPPHTTPLIB_SSL_ENABLED
  11005. cli_.enable_server_certificate_verification(false);
  11006. #endif
  11007. }
  11008. virtual void SetUp() {
  11009. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11010. res.set_content("Hello World!", "text/plain");
  11011. });
  11012. t_ = thread(
  11013. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11014. svr_.wait_until_ready();
  11015. }
  11016. virtual void TearDown() {
  11017. svr_.stop();
  11018. t_.join();
  11019. }
  11020. #ifdef CPPHTTPLIB_SSL_ENABLED
  11021. SSLClient cli_;
  11022. SSLServer svr_;
  11023. #else
  11024. Client cli_;
  11025. Server svr_;
  11026. #endif
  11027. thread t_;
  11028. };
  11029. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11030. auto res = cli_.Get("/hi");
  11031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11032. EXPECT_EQ(StatusCode::OK_200, res->status);
  11033. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11034. EXPECT_EQ("Hello World!", res->body);
  11035. }
  11036. class ServerUpDownTest : public ::testing::Test {
  11037. protected:
  11038. ServerUpDownTest() : cli_(HOST, PORT) {}
  11039. virtual void SetUp() {
  11040. t_ = thread([&]() {
  11041. svr_.bind_to_any_port(HOST);
  11042. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11043. ASSERT_TRUE(svr_.listen_after_bind());
  11044. });
  11045. svr_.wait_until_ready();
  11046. }
  11047. virtual void TearDown() {
  11048. svr_.stop();
  11049. t_.join();
  11050. }
  11051. Client cli_;
  11052. Server svr_;
  11053. thread t_;
  11054. };
  11055. TEST_F(ServerUpDownTest, QuickStartStop) {
  11056. // Should not crash, especially when run with
  11057. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11058. }
  11059. class PayloadMaxLengthTest : public ::testing::Test {
  11060. protected:
  11061. PayloadMaxLengthTest()
  11062. : cli_(HOST, PORT)
  11063. #ifdef CPPHTTPLIB_SSL_ENABLED
  11064. ,
  11065. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11066. #endif
  11067. {
  11068. #ifdef CPPHTTPLIB_SSL_ENABLED
  11069. cli_.enable_server_certificate_verification(false);
  11070. #endif
  11071. }
  11072. virtual void SetUp() {
  11073. svr_.set_payload_max_length(8);
  11074. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11075. res.set_content("test", "text/plain");
  11076. });
  11077. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11078. svr_.wait_until_ready();
  11079. }
  11080. virtual void TearDown() {
  11081. svr_.stop();
  11082. t_.join();
  11083. }
  11084. #ifdef CPPHTTPLIB_SSL_ENABLED
  11085. SSLClient cli_;
  11086. SSLServer svr_;
  11087. #else
  11088. Client cli_;
  11089. Server svr_;
  11090. #endif
  11091. thread t_;
  11092. };
  11093. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11094. auto res = cli_.Post("/test", "123456789", "text/plain");
  11095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11096. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11097. res = cli_.Post("/test", "12345678", "text/plain");
  11098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11099. EXPECT_EQ(StatusCode::OK_200, res->status);
  11100. }
  11101. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11102. // Test chunked encoding with payload exceeding the 8-byte limit
  11103. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11104. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11106. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11107. }
  11108. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11109. // Test chunked encoding with payload within the 8-byte limit
  11110. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11111. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11113. EXPECT_EQ(StatusCode::OK_200, res->status);
  11114. }
  11115. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11116. // Test using send_request to send chunked data exceeding payload limit
  11117. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11118. "Host: " +
  11119. std::string(HOST) + ":" + std::to_string(PORT) +
  11120. "\r\n"
  11121. "Transfer-Encoding: chunked\r\n"
  11122. "Connection: close\r\n"
  11123. "\r\n"
  11124. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  11125. "0123456789\r\n"
  11126. "0\r\n" // End chunk
  11127. "\r\n";
  11128. std::string response;
  11129. bool result = send_request(1, chunked_request, &response);
  11130. if (!result) {
  11131. // If send_request fails, it might be because the server closed the
  11132. // connection due to payload limit enforcement, which is acceptable
  11133. SUCCEED()
  11134. << "Server rejected oversized chunked request (connection closed)";
  11135. } else {
  11136. // If we got a response, check if it's an error response or connection was
  11137. // closed early Short response length indicates connection was closed due to
  11138. // payload limit
  11139. if (response.length() <= 10) {
  11140. SUCCEED() << "Server closed connection for oversized chunked request";
  11141. } else {
  11142. // Check for error status codes
  11143. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11144. response.find("Payload Too Large") != std::string::npos ||
  11145. response.find("400") != std::string::npos);
  11146. }
  11147. }
  11148. }
  11149. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  11150. // Test request without Content-Length header exceeding payload limit
  11151. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11152. "Host: " +
  11153. std::string(HOST) + ":" +
  11154. std::to_string(PORT) +
  11155. "\r\n"
  11156. "Connection: close\r\n"
  11157. "\r\n";
  11158. // Add payload exceeding the 8-byte limit
  11159. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  11160. request_without_content_length += large_payload;
  11161. std::string response;
  11162. bool result = send_request(1, request_without_content_length, &response);
  11163. if (!result) {
  11164. // If send_request fails, server likely closed connection due to payload
  11165. // limit
  11166. SUCCEED() << "Server rejected oversized request without Content-Length "
  11167. "(connection closed)";
  11168. } else {
  11169. // Check if server responded with error or closed connection early
  11170. if (response.length() <= 10) {
  11171. SUCCEED() << "Server closed connection for oversized request without "
  11172. "Content-Length";
  11173. } else {
  11174. // Check for error status codes
  11175. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11176. response.find("Payload Too Large") != std::string::npos ||
  11177. response.find("400") != std::string::npos);
  11178. }
  11179. }
  11180. }
  11181. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  11182. // Test request without Content-Length header within payload limit
  11183. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11184. "Host: " +
  11185. std::string(HOST) + ":" +
  11186. std::to_string(PORT) +
  11187. "\r\n"
  11188. "Connection: close\r\n"
  11189. "\r\n";
  11190. // Add payload within the 8-byte limit
  11191. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  11192. request_without_content_length += small_payload;
  11193. std::string response;
  11194. bool result = send_request(1, request_without_content_length, &response);
  11195. // For requests without Content-Length, the server may have different behavior
  11196. // The key is that it should not reject due to payload limit for small
  11197. // payloads
  11198. if (result) {
  11199. // Check for any HTTP response (success or error, but not connection closed)
  11200. if (response.length() > 10) {
  11201. SUCCEED()
  11202. << "Server processed request without Content-Length within limit";
  11203. } else {
  11204. // Short response might indicate connection closed, which is acceptable
  11205. SUCCEED() << "Server closed connection for request without "
  11206. "Content-Length (acceptable behavior)";
  11207. }
  11208. } else {
  11209. // Connection failure might be due to protocol requirements
  11210. SUCCEED() << "Connection issue with request without Content-Length "
  11211. "(environment-specific)";
  11212. }
  11213. }
  11214. class LargePayloadMaxLengthTest : public ::testing::Test {
  11215. protected:
  11216. LargePayloadMaxLengthTest()
  11217. : cli_(HOST, PORT)
  11218. #ifdef CPPHTTPLIB_SSL_ENABLED
  11219. ,
  11220. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11221. #endif
  11222. {
  11223. #ifdef CPPHTTPLIB_SSL_ENABLED
  11224. cli_.enable_server_certificate_verification(false);
  11225. #endif
  11226. }
  11227. virtual void SetUp() {
  11228. // Set 10MB payload limit
  11229. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  11230. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  11231. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11232. res.set_content("Large payload test", "text/plain");
  11233. });
  11234. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11235. svr_.wait_until_ready();
  11236. }
  11237. virtual void TearDown() {
  11238. svr_.stop();
  11239. t_.join();
  11240. }
  11241. #ifdef CPPHTTPLIB_SSL_ENABLED
  11242. SSLClient cli_;
  11243. SSLServer svr_;
  11244. #else
  11245. Client cli_;
  11246. Server svr_;
  11247. #endif
  11248. thread t_;
  11249. };
  11250. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  11251. // Test chunked encoding with payload within 10MB limit
  11252. std::string medium_payload(5 * 1024 * 1024,
  11253. 'A'); // 5MB payload, within 10MB limit
  11254. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  11255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11256. EXPECT_EQ(StatusCode::OK_200, res->status);
  11257. }
  11258. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  11259. // Test chunked encoding with payload exceeding 10MB limit
  11260. std::string large_payload(12 * 1024 * 1024,
  11261. 'B'); // 12MB payload, exceeds 10MB limit
  11262. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  11263. // Server may either return 413 or close the connection
  11264. if (res) {
  11265. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11266. } else {
  11267. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  11268. }
  11269. }
  11270. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  11271. // Test request without Content-Length header within 10MB limit
  11272. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11273. "Host: " +
  11274. std::string(HOST) + ":" +
  11275. std::to_string(PORT) +
  11276. "\r\n"
  11277. "Connection: close\r\n"
  11278. "\r\n";
  11279. // Add 1MB payload (within 10MB limit)
  11280. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  11281. request_without_content_length += medium_payload;
  11282. std::string response;
  11283. bool result = send_request(5, request_without_content_length, &response);
  11284. if (result) {
  11285. // Should get a proper HTTP response for payloads within limit
  11286. if (response.length() > 10) {
  11287. SUCCEED() << "Server processed 1MB request without Content-Length within "
  11288. "10MB limit";
  11289. } else {
  11290. SUCCEED() << "Server closed connection (acceptable behavior for no "
  11291. "Content-Length)";
  11292. }
  11293. } else {
  11294. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  11295. }
  11296. }
  11297. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  11298. // Test request without Content-Length header exceeding 10MB limit
  11299. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11300. "Host: " +
  11301. std::string(HOST) + ":" +
  11302. std::to_string(PORT) +
  11303. "\r\n"
  11304. "Connection: close\r\n"
  11305. "\r\n";
  11306. // Add 12MB payload (exceeds 10MB limit)
  11307. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  11308. request_without_content_length += large_payload;
  11309. std::string response;
  11310. bool result = send_request(10, request_without_content_length, &response);
  11311. if (!result) {
  11312. // Server should close connection due to payload limit
  11313. SUCCEED() << "Server rejected 12MB request without Content-Length "
  11314. "(connection closed)";
  11315. } else {
  11316. // Check for error response
  11317. if (response.length() <= 10) {
  11318. SUCCEED()
  11319. << "Server closed connection for 12MB request exceeding 10MB limit";
  11320. } else {
  11321. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11322. response.find("Payload Too Large") != std::string::npos ||
  11323. response.find("400") != std::string::npos);
  11324. }
  11325. }
  11326. }
  11327. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  11328. Server svr;
  11329. svr.Get("/", [](const Request &, Response &res) {
  11330. // Claims far more than it sends, then drops the connection.
  11331. res.set_content_provider(size_t(1) << 41, "text/plain",
  11332. [](size_t, size_t, DataSink &sink) {
  11333. sink.write("abc", 3);
  11334. return false;
  11335. });
  11336. });
  11337. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11338. auto se = detail::scope_exit([&] {
  11339. svr.stop();
  11340. thread.join();
  11341. ASSERT_FALSE(svr.is_running());
  11342. });
  11343. svr.wait_until_ready();
  11344. Client cli(HOST, PORT);
  11345. cli.set_payload_max_length(0);
  11346. EXPECT_FALSE(cli.Get("/"));
  11347. }
  11348. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11349. // `payload_max_length` is not enforced on decompressed body in ContentReader
  11350. // path.
  11351. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  11352. Server svr;
  11353. const size_t LIMIT = 64 * 1024; // 64KB
  11354. svr.set_payload_max_length(LIMIT);
  11355. size_t total = 0;
  11356. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11357. const ContentReader &content_reader) {
  11358. content_reader([&](const char * /*data*/, size_t len) {
  11359. total += len;
  11360. return true;
  11361. });
  11362. res.status = 200;
  11363. res.set_content("stream_ok", "text/plain");
  11364. });
  11365. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11366. auto se = detail::scope_exit([&] {
  11367. svr.stop();
  11368. thread.join();
  11369. ASSERT_FALSE(svr.is_running());
  11370. });
  11371. svr.wait_until_ready();
  11372. // Prepare 256KB raw data and gzip-compress it
  11373. std::string raw(256 * 1024, 'A');
  11374. std::string gz;
  11375. {
  11376. z_stream zs{};
  11377. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  11378. Z_DEFAULT_STRATEGY);
  11379. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  11380. zs.avail_in = static_cast<uInt>(raw.size());
  11381. char outbuf[4096];
  11382. int ret;
  11383. do {
  11384. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  11385. zs.avail_out = sizeof(outbuf);
  11386. ret = deflate(&zs, Z_FINISH);
  11387. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  11388. } while (ret != Z_STREAM_END);
  11389. deflateEnd(&zs);
  11390. }
  11391. Client cli(HOST, PORT);
  11392. cli.set_connection_timeout(std::chrono::seconds(5));
  11393. Headers headers = {{"Content-Encoding", "gzip"}};
  11394. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  11395. "application/octet-stream");
  11396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11397. // Server must reject oversized decompressed payloads with 413.
  11398. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11399. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11400. EXPECT_LE(total, LIMIT);
  11401. }
  11402. #ifndef CPPHTTPLIB_SSL_ENABLED
  11403. // For a request with neither Content-Length nor Transfer-Encoding, the
  11404. // non-SSL raw-socket fallback in read_content_core() used to hand the
  11405. // compressed wire bytes straight to the ContentReader without ever routing
  11406. // them through the decompressor, so payload_max_length_ only bounded the
  11407. // compressed size on the wire, not the decompressed size.
  11408. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  11409. Server svr;
  11410. const size_t LIMIT = 64 * 1024; // 64KB
  11411. svr.set_payload_max_length(LIMIT);
  11412. size_t total = 0;
  11413. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11414. const ContentReader &content_reader) {
  11415. content_reader([&](const char * /*data*/, size_t len) {
  11416. total += len;
  11417. return true;
  11418. });
  11419. res.status = 200;
  11420. res.set_content("stream_ok", "text/plain");
  11421. });
  11422. auto port = svr.bind_to_any_port(HOST);
  11423. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11424. auto se = detail::scope_exit([&] {
  11425. svr.stop();
  11426. thread.join();
  11427. ASSERT_FALSE(svr.is_running());
  11428. });
  11429. svr.wait_until_ready();
  11430. // Prepare 256KB raw data and gzip-compress it, same payload as the
  11431. // StreamingGzipDecompression test above.
  11432. std::string raw(256 * 1024, 'A');
  11433. std::string gz;
  11434. {
  11435. httplib::detail::gzip_compressor compressor;
  11436. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  11437. [&](const char *chunk, size_t len) {
  11438. gz.append(chunk, len);
  11439. return true;
  11440. });
  11441. ASSERT_TRUE(result);
  11442. }
  11443. // Send the gzip body over raw TCP with neither Content-Length nor
  11444. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  11445. // kicks in.
  11446. std::string req = "POST /stream HTTP/1.1\r\n"
  11447. "Host: " +
  11448. std::string(HOST) + ":" + std::to_string(port) +
  11449. "\r\n"
  11450. "Content-Encoding: gzip\r\n"
  11451. "Connection: close\r\n"
  11452. "\r\n" +
  11453. gz;
  11454. std::string response;
  11455. ASSERT_TRUE(send_request(5, req, &response, port));
  11456. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11457. EXPECT_LE(total, LIMIT);
  11458. }
  11459. #endif
  11460. #endif
  11461. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  11462. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  11463. // the payload must be passed through untouched instead of being rejected.
  11464. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  11465. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11466. Server svr;
  11467. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  11468. res.set_content(body, "image/jpeg");
  11469. res.set_header("Content-Encoding", "UTF-8");
  11470. });
  11471. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  11472. res.set_content(body, "image/jpeg");
  11473. res.set_header("Content-Encoding", "identity");
  11474. });
  11475. svr.Post("/echo", [](const Request &req, Response &res) {
  11476. res.set_content(req.body, "image/jpeg");
  11477. });
  11478. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11479. auto se = detail::scope_exit([&] {
  11480. svr.stop();
  11481. t.join();
  11482. ASSERT_FALSE(svr.is_running());
  11483. });
  11484. svr.wait_until_ready();
  11485. Client cli(HOST, PORT);
  11486. {
  11487. auto res = cli.Get("/image");
  11488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11489. EXPECT_EQ(StatusCode::OK_200, res->status);
  11490. EXPECT_EQ(body, res->body);
  11491. }
  11492. {
  11493. auto res = cli.Get("/identity");
  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. // The same applies to a request body reaching the server.
  11500. Headers headers = {{"Content-Encoding", "UTF-8"}};
  11501. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  11502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11503. EXPECT_EQ(StatusCode::OK_200, res->status);
  11504. EXPECT_EQ(body, res->body);
  11505. }
  11506. }
  11507. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  11508. // gzip-encoded response even when the build has no zlib support.
  11509. static const char GZIPPED_HELLO_WORLD[] = {
  11510. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  11511. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  11512. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  11513. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  11514. // A content coding is a whole token, not something the field value merely
  11515. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  11516. // as "fibre" look like Brotli, and turned a multi-coding value like
  11517. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  11518. // it was never meant to see.
  11519. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  11520. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11521. Server svr;
  11522. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  11523. res.set_content(body, "image/jpeg");
  11524. res.set_header("Content-Encoding", "fibre");
  11525. });
  11526. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  11527. res.set_content(body, "image/jpeg");
  11528. res.set_header("Content-Encoding", "gzip, br");
  11529. });
  11530. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  11531. res.set_content(body, "image/jpeg");
  11532. res.set_header("Content-Encoding", "x-zstd-ish");
  11533. });
  11534. auto port = svr.bind_to_any_port(HOST);
  11535. thread t = thread([&]() { svr.listen_after_bind(); });
  11536. auto se = detail::scope_exit([&] {
  11537. svr.stop();
  11538. t.join();
  11539. ASSERT_FALSE(svr.is_running());
  11540. });
  11541. svr.wait_until_ready();
  11542. Client cli(HOST, port);
  11543. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  11544. auto res = cli.Get(path);
  11545. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11546. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11547. // Not a coding we recognize, so the payload comes back untouched
  11548. EXPECT_EQ(body, res->body) << path;
  11549. }
  11550. }
  11551. // A content coding cpp-httplib recognizes but was not built with must be
  11552. // reported as such. Handing the still-compressed payload back to the caller
  11553. // would silently corrupt it.
  11554. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  11555. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11556. Server svr;
  11557. // "image/jpeg" keeps the server from applying a content coding of its own,
  11558. // so the hand-crafted Content-Encoding below survives.
  11559. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  11560. res.set_content(gzipped, "image/jpeg");
  11561. res.set_header("Content-Encoding", "gzip");
  11562. });
  11563. // Content codings are case-insensitive (RFC 9110 8.4.1).
  11564. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  11565. res.set_content(gzipped, "image/jpeg");
  11566. res.set_header("Content-Encoding", "GZIP");
  11567. });
  11568. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11569. auto se = detail::scope_exit([&] {
  11570. svr.stop();
  11571. t.join();
  11572. ASSERT_FALSE(svr.is_running());
  11573. });
  11574. svr.wait_until_ready();
  11575. Client cli(HOST, PORT);
  11576. {
  11577. auto res = cli.Get("/gzipped");
  11578. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11580. EXPECT_EQ("Hello World!", res->body);
  11581. #else
  11582. ASSERT_FALSE(res);
  11583. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11584. #endif
  11585. }
  11586. {
  11587. // open_stream() must behave the same way.
  11588. auto handle = cli.open_stream("GET", "/gzipped");
  11589. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11590. ASSERT_TRUE(handle.is_valid());
  11591. std::string received;
  11592. char buf[256];
  11593. ssize_t n;
  11594. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11595. received.append(buf, static_cast<size_t>(n));
  11596. }
  11597. EXPECT_EQ("Hello World!", received);
  11598. #else
  11599. EXPECT_FALSE(handle.is_valid());
  11600. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  11601. #endif
  11602. }
  11603. {
  11604. // A differently-cased coding must not be mistaken for an unknown one, or
  11605. // the body would be handed back still compressed.
  11606. auto res = cli.Get("/gzipped-uppercase");
  11607. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11609. EXPECT_EQ("Hello World!", res->body);
  11610. #else
  11611. ASSERT_FALSE(res);
  11612. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11613. #endif
  11614. }
  11615. }
  11616. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11617. // A handler serving pre-compressed content (e.g. build-time gzipped static
  11618. // assets) sets Content-Encoding itself. The server used to pick a coding from
  11619. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  11620. // body a second time and appending a second Content-Encoding field line, so
  11621. // clients that decode one coding per listed value handed back raw gzip bytes.
  11622. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  11623. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11624. Server svr;
  11625. // text/plain is a compressible type, so only the pre-set Content-Encoding
  11626. // keeps the server from applying a coding of its own.
  11627. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11628. res.set_content(gzipped, "text/plain");
  11629. res.set_header("Content-Encoding", "gzip");
  11630. });
  11631. auto port = svr.bind_to_any_port(HOST);
  11632. thread t = thread([&]() { svr.listen_after_bind(); });
  11633. auto se = detail::scope_exit([&] {
  11634. svr.stop();
  11635. t.join();
  11636. ASSERT_FALSE(svr.is_running());
  11637. });
  11638. svr.wait_until_ready();
  11639. Client cli(HOST, port);
  11640. Headers headers = {{"Accept-Encoding", "gzip"}};
  11641. auto res = cli.Get("/pre-gzipped", headers);
  11642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11643. EXPECT_EQ(StatusCode::OK_200, res->status);
  11644. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11645. EXPECT_EQ("Hello World!", res->body);
  11646. }
  11647. // A chunked provider settles its coding where the headers are written and
  11648. // reuses it at write time. Both ends of that have to hold: a handler's own
  11649. // Content-Encoding suppresses the coding, and a response without one is still
  11650. // compressed as it always was.
  11651. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  11652. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11653. const std::string plain = "Hello World! Hello World! Hello World!";
  11654. Server svr;
  11655. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11656. res.set_header("Content-Encoding", "gzip");
  11657. res.set_chunked_content_provider(
  11658. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  11659. sink.write(gzipped.data(), gzipped.size());
  11660. sink.done();
  11661. return true;
  11662. });
  11663. });
  11664. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  11665. res.set_chunked_content_provider(
  11666. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  11667. sink.write(plain.data(), plain.size());
  11668. sink.done();
  11669. return true;
  11670. });
  11671. });
  11672. auto port = svr.bind_to_any_port(HOST);
  11673. thread t = thread([&]() { svr.listen_after_bind(); });
  11674. auto se = detail::scope_exit([&] {
  11675. svr.stop();
  11676. t.join();
  11677. ASSERT_FALSE(svr.is_running());
  11678. });
  11679. svr.wait_until_ready();
  11680. Client cli(HOST, port);
  11681. Headers headers = {{"Accept-Encoding", "gzip"}};
  11682. {
  11683. auto res = cli.Get("/pre-gzipped", headers);
  11684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11685. EXPECT_EQ(StatusCode::OK_200, res->status);
  11686. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11687. EXPECT_EQ("Hello World!", res->body);
  11688. }
  11689. {
  11690. auto res = cli.Get("/negotiated", headers);
  11691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11692. EXPECT_EQ(StatusCode::OK_200, res->status);
  11693. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  11694. EXPECT_EQ(plain, res->body);
  11695. }
  11696. }
  11697. #endif
  11698. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  11699. // the same message as the comma-joined one, so both have to be read the same
  11700. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  11701. // single gzip coding, and a body the sender says was encoded twice was handed
  11702. // back after one pass, still compressed but presented as decoded.
  11703. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  11704. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11705. Server svr;
  11706. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  11707. res.set_content(body, "image/jpeg");
  11708. res.headers.emplace("Content-Encoding", "gzip");
  11709. res.headers.emplace("Content-Encoding", "gzip");
  11710. });
  11711. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  11712. res.set_content(body, "image/jpeg");
  11713. res.set_header("Content-Encoding", "gzip, gzip");
  11714. });
  11715. auto port = svr.bind_to_any_port(HOST);
  11716. thread t = thread([&]() { svr.listen_after_bind(); });
  11717. auto se = detail::scope_exit([&] {
  11718. svr.stop();
  11719. t.join();
  11720. ASSERT_FALSE(svr.is_running());
  11721. });
  11722. svr.wait_until_ready();
  11723. Client cli(HOST, port);
  11724. // Two codings is not something cpp-httplib decodes, so both representations
  11725. // take the pass-through path rather than one of them being gunzipped once.
  11726. for (const char *path : {"/split", "/joined"}) {
  11727. auto res = cli.Get(path);
  11728. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11729. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11730. EXPECT_EQ(body, res->body) << path;
  11731. }
  11732. }
  11733. // Regression test for DoS vulnerability: a malicious server sending a response
  11734. // without Content-Length header must not cause unbounded memory consumption on
  11735. // the client side. The client should stop reading after a reasonable limit,
  11736. // similar to the server-side set_payload_max_length protection.
  11737. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  11738. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11739. #ifndef _WIN32
  11740. signal(SIGPIPE, SIG_IGN);
  11741. #endif
  11742. auto server_thread = std::thread([] {
  11743. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  11744. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11745. default_socket_options(srv);
  11746. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11747. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11748. sockaddr_in addr{};
  11749. addr.sin_family = AF_INET;
  11750. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11751. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11752. int opt = 1;
  11753. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11754. #ifdef _WIN32
  11755. reinterpret_cast<const char *>(&opt),
  11756. #else
  11757. &opt,
  11758. #endif
  11759. sizeof(opt));
  11760. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11761. ::listen(srv, 1);
  11762. sockaddr_in cli_addr{};
  11763. socklen_t cli_len = sizeof(cli_addr);
  11764. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11765. if (cli != INVALID_SOCKET) {
  11766. char buf[4096];
  11767. ::recv(cli, buf, sizeof(buf), 0);
  11768. // Malicious response: no Content-Length, no chunked encoding
  11769. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11770. "Connection: close\r\n"
  11771. "\r\n";
  11772. ::send(cli,
  11773. #ifdef _WIN32
  11774. static_cast<const char *>(response_header.c_str()),
  11775. static_cast<int>(response_header.size()),
  11776. #else
  11777. response_header.c_str(), response_header.size(),
  11778. #endif
  11779. 0);
  11780. // Send 10MB of data
  11781. std::string chunk(64 * 1024, 'A');
  11782. size_t total_sent = 0;
  11783. while (total_sent < MALICIOUS_DATA_SIZE) {
  11784. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  11785. auto sent = ::send(cli,
  11786. #ifdef _WIN32
  11787. static_cast<const char *>(chunk.c_str()),
  11788. static_cast<int>(to_send),
  11789. #else
  11790. chunk.c_str(), to_send,
  11791. #endif
  11792. 0);
  11793. if (sent <= 0) break;
  11794. total_sent += static_cast<size_t>(sent);
  11795. }
  11796. detail::close_socket(cli);
  11797. }
  11798. detail::close_socket(srv);
  11799. });
  11800. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11801. size_t total_read = 0;
  11802. {
  11803. Client cli("127.0.0.1", PORT + 2);
  11804. cli.set_read_timeout(5, 0);
  11805. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11806. auto stream = cli.open_stream("GET", "/malicious");
  11807. ASSERT_TRUE(stream.is_valid());
  11808. char buffer[64 * 1024];
  11809. ssize_t n;
  11810. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11811. total_read += static_cast<size_t>(n);
  11812. }
  11813. } // StreamHandle and Client destroyed here, closing the socket
  11814. server_thread.join();
  11815. // With set_payload_max_length, the client must stop reading before consuming
  11816. // all 10MB. The read loop should be cut off at or near the configured limit.
  11817. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  11818. << "Client read " << total_read << " bytes, exceeding the configured "
  11819. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  11820. }
  11821. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  11822. // the entire response body without truncation.
  11823. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  11824. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  11825. #ifndef _WIN32
  11826. signal(SIGPIPE, SIG_IGN);
  11827. #endif
  11828. auto server_thread = std::thread([] {
  11829. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11830. default_socket_options(srv);
  11831. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11832. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11833. sockaddr_in addr{};
  11834. addr.sin_family = AF_INET;
  11835. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11836. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11837. int opt = 1;
  11838. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11839. #ifdef _WIN32
  11840. reinterpret_cast<const char *>(&opt),
  11841. #else
  11842. &opt,
  11843. #endif
  11844. sizeof(opt));
  11845. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11846. ::listen(srv, 1);
  11847. sockaddr_in cli_addr{};
  11848. socklen_t cli_len = sizeof(cli_addr);
  11849. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11850. if (cli != INVALID_SOCKET) {
  11851. char buf[4096];
  11852. ::recv(cli, buf, sizeof(buf), 0);
  11853. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11854. "Connection: close\r\n"
  11855. "\r\n";
  11856. ::send(cli,
  11857. #ifdef _WIN32
  11858. static_cast<const char *>(response_header.c_str()),
  11859. static_cast<int>(response_header.size()),
  11860. #else
  11861. response_header.c_str(), response_header.size(),
  11862. #endif
  11863. 0);
  11864. std::string chunk(64 * 1024, 'A');
  11865. size_t total_sent = 0;
  11866. while (total_sent < DATA_SIZE) {
  11867. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11868. auto sent = ::send(cli,
  11869. #ifdef _WIN32
  11870. static_cast<const char *>(chunk.c_str()),
  11871. static_cast<int>(to_send),
  11872. #else
  11873. chunk.c_str(), to_send,
  11874. #endif
  11875. 0);
  11876. if (sent <= 0) break;
  11877. total_sent += static_cast<size_t>(sent);
  11878. }
  11879. #ifdef _WIN32
  11880. ::shutdown(cli, SD_SEND);
  11881. #else
  11882. ::shutdown(cli, SHUT_WR);
  11883. #endif
  11884. // Drain until the client closes its end, ensuring all data is delivered
  11885. char drain[1024];
  11886. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11887. detail::close_socket(cli);
  11888. }
  11889. detail::close_socket(srv);
  11890. });
  11891. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11892. size_t total_read = 0;
  11893. {
  11894. Client cli("127.0.0.1", PORT + 2);
  11895. cli.set_read_timeout(5, 0);
  11896. cli.set_payload_max_length(0); // 0 means no limit
  11897. auto stream = cli.open_stream("GET", "/data");
  11898. ASSERT_TRUE(stream.is_valid());
  11899. char buffer[64 * 1024];
  11900. ssize_t n;
  11901. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11902. total_read += static_cast<size_t>(n);
  11903. }
  11904. }
  11905. server_thread.join();
  11906. EXPECT_EQ(total_read, DATA_SIZE)
  11907. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  11908. << " bytes without truncation, but only read " << total_read << " bytes.";
  11909. }
  11910. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  11911. // enormous Content-Length must not cause the client to pre-allocate a huge
  11912. // response body buffer. The reservation is capped at payload_max_length_, and
  11913. // the read itself fails when the body exceeds the limit.
  11914. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  11915. #ifndef _WIN32
  11916. signal(SIGPIPE, SIG_IGN);
  11917. #endif
  11918. auto server_thread = std::thread([] {
  11919. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11920. default_socket_options(srv);
  11921. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11922. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11923. sockaddr_in addr{};
  11924. addr.sin_family = AF_INET;
  11925. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11926. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11927. int opt = 1;
  11928. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11929. #ifdef _WIN32
  11930. reinterpret_cast<const char *>(&opt),
  11931. #else
  11932. &opt,
  11933. #endif
  11934. sizeof(opt));
  11935. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11936. ::listen(srv, 1);
  11937. sockaddr_in cli_addr{};
  11938. socklen_t cli_len = sizeof(cli_addr);
  11939. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11940. if (cli != INVALID_SOCKET) {
  11941. char buf[4096];
  11942. ::recv(cli, buf, sizeof(buf), 0);
  11943. // Malicious response: claim a 20GB body but send only a tiny payload.
  11944. std::string response = "HTTP/1.1 200 OK\r\n"
  11945. "Content-Length: 20000000000\r\n"
  11946. "\r\n"
  11947. "abc";
  11948. ::send(cli,
  11949. #ifdef _WIN32
  11950. static_cast<const char *>(response.c_str()),
  11951. static_cast<int>(response.size()),
  11952. #else
  11953. response.c_str(), response.size(),
  11954. #endif
  11955. 0);
  11956. detail::close_socket(cli);
  11957. }
  11958. detail::close_socket(srv);
  11959. });
  11960. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11961. {
  11962. Client cli("127.0.0.1", PORT + 2);
  11963. cli.set_read_timeout(5, 0);
  11964. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  11965. // result in a 20GB pre-allocation. The Get() call is expected to fail
  11966. // (server claims more bytes than payload_max_length permits), but it must
  11967. // not exhaust memory before getting there.
  11968. auto res = cli.Get("/malicious");
  11969. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  11970. }
  11971. server_thread.join();
  11972. }
  11973. // Verify that content_receiver bypasses the default payload_max_length,
  11974. // allowing streaming downloads larger than 100MB without requiring an explicit
  11975. // set_payload_max_length call.
  11976. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  11977. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11978. #ifndef _WIN32
  11979. signal(SIGPIPE, SIG_IGN);
  11980. #endif
  11981. auto server_thread = std::thread([] {
  11982. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11983. default_socket_options(srv);
  11984. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11985. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11986. sockaddr_in addr{};
  11987. addr.sin_family = AF_INET;
  11988. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11989. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11990. int opt = 1;
  11991. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11992. #ifdef _WIN32
  11993. reinterpret_cast<const char *>(&opt),
  11994. #else
  11995. &opt,
  11996. #endif
  11997. sizeof(opt));
  11998. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11999. ::listen(srv, 1);
  12000. sockaddr_in cli_addr{};
  12001. socklen_t cli_len = sizeof(cli_addr);
  12002. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12003. if (cli != INVALID_SOCKET) {
  12004. char buf[4096];
  12005. ::recv(cli, buf, sizeof(buf), 0);
  12006. // Response with Content-Length larger than default 100MB limit
  12007. auto content_length = std::to_string(DATA_SIZE);
  12008. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12009. "Content-Length: " +
  12010. content_length +
  12011. "\r\n"
  12012. "Connection: close\r\n"
  12013. "\r\n";
  12014. ::send(cli,
  12015. #ifdef _WIN32
  12016. static_cast<const char *>(response_header.c_str()),
  12017. static_cast<int>(response_header.size()),
  12018. #else
  12019. response_header.c_str(), response_header.size(),
  12020. #endif
  12021. 0);
  12022. std::string chunk(64 * 1024, 'A');
  12023. size_t total_sent = 0;
  12024. while (total_sent < DATA_SIZE) {
  12025. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12026. auto sent = ::send(cli,
  12027. #ifdef _WIN32
  12028. static_cast<const char *>(chunk.c_str()),
  12029. static_cast<int>(to_send),
  12030. #else
  12031. chunk.c_str(), to_send,
  12032. #endif
  12033. 0);
  12034. if (sent <= 0) break;
  12035. total_sent += static_cast<size_t>(sent);
  12036. }
  12037. detail::close_socket(cli);
  12038. }
  12039. detail::close_socket(srv);
  12040. });
  12041. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12042. size_t total_received = 0;
  12043. {
  12044. Client cli("127.0.0.1", PORT + 2);
  12045. cli.set_read_timeout(10, 0);
  12046. // Do NOT call set_payload_max_length — use the default 100MB limit
  12047. auto res =
  12048. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12049. total_received += data_length;
  12050. return true;
  12051. });
  12052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12053. EXPECT_EQ(StatusCode::OK_200, res->status);
  12054. }
  12055. server_thread.join();
  12056. EXPECT_EQ(total_received, DATA_SIZE)
  12057. << "With content_receiver, the client should read all " << DATA_SIZE
  12058. << " bytes despite the default 100MB payload_max_length, but only read "
  12059. << total_received << " bytes.";
  12060. }
  12061. // Verify that an explicit set_payload_max_length smaller than the response is
  12062. // enforced even when a content_receiver is used.
  12063. TEST(ClientVulnerabilityTest,
  12064. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12065. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12066. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12067. #ifndef _WIN32
  12068. signal(SIGPIPE, SIG_IGN);
  12069. #endif
  12070. auto server_thread = std::thread([] {
  12071. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12072. default_socket_options(srv);
  12073. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12074. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12075. sockaddr_in addr{};
  12076. addr.sin_family = AF_INET;
  12077. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12078. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12079. int opt = 1;
  12080. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12081. #ifdef _WIN32
  12082. reinterpret_cast<const char *>(&opt),
  12083. #else
  12084. &opt,
  12085. #endif
  12086. sizeof(opt));
  12087. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12088. ::listen(srv, 1);
  12089. sockaddr_in cli_addr{};
  12090. socklen_t cli_len = sizeof(cli_addr);
  12091. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12092. if (cli != INVALID_SOCKET) {
  12093. char buf[4096];
  12094. ::recv(cli, buf, sizeof(buf), 0);
  12095. auto content_length = std::to_string(DATA_SIZE);
  12096. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12097. "Content-Length: " +
  12098. content_length +
  12099. "\r\n"
  12100. "Connection: close\r\n"
  12101. "\r\n";
  12102. ::send(cli,
  12103. #ifdef _WIN32
  12104. static_cast<const char *>(response_header.c_str()),
  12105. static_cast<int>(response_header.size()),
  12106. #else
  12107. response_header.c_str(), response_header.size(),
  12108. #endif
  12109. 0);
  12110. std::string chunk(64 * 1024, 'A');
  12111. size_t total_sent = 0;
  12112. while (total_sent < DATA_SIZE) {
  12113. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12114. auto sent = ::send(cli,
  12115. #ifdef _WIN32
  12116. static_cast<const char *>(chunk.c_str()),
  12117. static_cast<int>(to_send),
  12118. #else
  12119. chunk.c_str(), to_send,
  12120. #endif
  12121. 0);
  12122. if (sent <= 0) break;
  12123. total_sent += static_cast<size_t>(sent);
  12124. }
  12125. detail::close_socket(cli);
  12126. }
  12127. detail::close_socket(srv);
  12128. });
  12129. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12130. size_t total_received = 0;
  12131. {
  12132. Client cli("127.0.0.1", PORT + 2);
  12133. cli.set_read_timeout(10, 0);
  12134. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  12135. auto res =
  12136. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12137. total_received += data_length;
  12138. return true;
  12139. });
  12140. // Should fail because 200MB exceeds the explicit 150MB limit
  12141. EXPECT_FALSE(res);
  12142. }
  12143. server_thread.join();
  12144. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12145. << "Client with content_receiver should respect the explicit "
  12146. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12147. << total_received << " bytes.";
  12148. }
  12149. // Verify that an explicit set_payload_max_length larger than the response
  12150. // allows the content_receiver to read all data successfully.
  12151. TEST(ClientVulnerabilityTest,
  12152. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  12153. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12154. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  12155. #ifndef _WIN32
  12156. signal(SIGPIPE, SIG_IGN);
  12157. #endif
  12158. auto server_thread = std::thread([] {
  12159. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12160. default_socket_options(srv);
  12161. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12162. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12163. sockaddr_in addr{};
  12164. addr.sin_family = AF_INET;
  12165. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12166. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12167. int opt = 1;
  12168. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12169. #ifdef _WIN32
  12170. reinterpret_cast<const char *>(&opt),
  12171. #else
  12172. &opt,
  12173. #endif
  12174. sizeof(opt));
  12175. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12176. ::listen(srv, 1);
  12177. sockaddr_in cli_addr{};
  12178. socklen_t cli_len = sizeof(cli_addr);
  12179. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12180. if (cli != INVALID_SOCKET) {
  12181. char buf[4096];
  12182. ::recv(cli, buf, sizeof(buf), 0);
  12183. auto content_length = std::to_string(DATA_SIZE);
  12184. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12185. "Content-Length: " +
  12186. content_length +
  12187. "\r\n"
  12188. "Connection: close\r\n"
  12189. "\r\n";
  12190. ::send(cli,
  12191. #ifdef _WIN32
  12192. static_cast<const char *>(response_header.c_str()),
  12193. static_cast<int>(response_header.size()),
  12194. #else
  12195. response_header.c_str(), response_header.size(),
  12196. #endif
  12197. 0);
  12198. std::string chunk(64 * 1024, 'A');
  12199. size_t total_sent = 0;
  12200. while (total_sent < DATA_SIZE) {
  12201. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12202. auto sent = ::send(cli,
  12203. #ifdef _WIN32
  12204. static_cast<const char *>(chunk.c_str()),
  12205. static_cast<int>(to_send),
  12206. #else
  12207. chunk.c_str(), to_send,
  12208. #endif
  12209. 0);
  12210. if (sent <= 0) break;
  12211. total_sent += static_cast<size_t>(sent);
  12212. }
  12213. #ifdef _WIN32
  12214. ::shutdown(cli, SD_SEND);
  12215. #else
  12216. ::shutdown(cli, SHUT_WR);
  12217. #endif
  12218. char drain[1024];
  12219. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12220. detail::close_socket(cli);
  12221. }
  12222. detail::close_socket(srv);
  12223. });
  12224. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12225. size_t total_received = 0;
  12226. {
  12227. Client cli("127.0.0.1", PORT + 2);
  12228. cli.set_read_timeout(10, 0);
  12229. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  12230. auto res =
  12231. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12232. total_received += data_length;
  12233. return true;
  12234. });
  12235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12236. EXPECT_EQ(StatusCode::OK_200, res->status);
  12237. }
  12238. server_thread.join();
  12239. EXPECT_EQ(total_received, DATA_SIZE)
  12240. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  12241. << " bytes (larger than " << DATA_SIZE
  12242. << " bytes response), content_receiver should read all data, but only "
  12243. "read "
  12244. << total_received << " bytes.";
  12245. }
  12246. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  12247. // Regression test for "zip bomb" attack on the client side: a malicious server
  12248. // sends a small gzip-compressed response that decompresses to a huge payload.
  12249. // The client must enforce payload_max_length on the decompressed size.
  12250. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  12251. constexpr size_t DECOMPRESSED_SIZE =
  12252. 10 * 1024 * 1024; // 10MB after decompression
  12253. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12254. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  12255. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  12256. std::string compressed;
  12257. {
  12258. httplib::detail::gzip_compressor compressor;
  12259. bool ok =
  12260. compressor.compress(uncompressed.data(), uncompressed.size(),
  12261. /*last=*/true, [&](const char *buf, size_t len) {
  12262. compressed.append(buf, len);
  12263. return true;
  12264. });
  12265. ASSERT_TRUE(ok);
  12266. }
  12267. // Sanity: compressed data should be much smaller than the decompressed size
  12268. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  12269. #ifndef _WIN32
  12270. signal(SIGPIPE, SIG_IGN);
  12271. #endif
  12272. // Set up the listening socket in the main thread so the server is guaranteed
  12273. // to be ready before the client connects (eliminates race condition).
  12274. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12275. default_socket_options(srv);
  12276. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12277. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12278. sockaddr_in addr{};
  12279. addr.sin_family = AF_INET;
  12280. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  12281. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12282. int opt = 1;
  12283. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12284. #ifdef _WIN32
  12285. reinterpret_cast<const char *>(&opt),
  12286. #else
  12287. &opt,
  12288. #endif
  12289. sizeof(opt));
  12290. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12291. ASSERT_EQ(0, ::listen(srv, 1));
  12292. auto server_thread = std::thread([&compressed, srv] {
  12293. sockaddr_in cli_addr{};
  12294. socklen_t cli_len = sizeof(cli_addr);
  12295. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12296. if (cli != INVALID_SOCKET) {
  12297. // Read the full HTTP request (until \r\n\r\n)
  12298. char buf[4096];
  12299. size_t total = 0;
  12300. while (total < sizeof(buf)) {
  12301. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  12302. if (n <= 0) break;
  12303. total += static_cast<size_t>(n);
  12304. // Check for end of headers
  12305. if (total >= 4) {
  12306. std::string req(buf, total);
  12307. if (req.find("\r\n\r\n") != std::string::npos) break;
  12308. }
  12309. }
  12310. // Malicious response: gzip-compressed body, no Content-Length
  12311. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12312. "Content-Encoding: gzip\r\n"
  12313. "Connection: close\r\n"
  12314. "\r\n";
  12315. ::send(cli,
  12316. #ifdef _WIN32
  12317. static_cast<const char *>(response_header.c_str()),
  12318. static_cast<int>(response_header.size()),
  12319. #else
  12320. response_header.c_str(), response_header.size(),
  12321. #endif
  12322. 0);
  12323. // Send the compressed payload (small on the wire, huge when decompressed)
  12324. size_t total_sent = 0;
  12325. while (total_sent < compressed.size()) {
  12326. auto to_send = std::min(compressed.size() - total_sent,
  12327. static_cast<size_t>(64 * 1024));
  12328. auto sent =
  12329. ::send(cli,
  12330. #ifdef _WIN32
  12331. static_cast<const char *>(compressed.c_str() + total_sent),
  12332. static_cast<int>(to_send),
  12333. #else
  12334. compressed.c_str() + total_sent, to_send,
  12335. #endif
  12336. 0);
  12337. if (sent <= 0) break;
  12338. total_sent += static_cast<size_t>(sent);
  12339. }
  12340. detail::close_socket(cli);
  12341. }
  12342. });
  12343. auto se = detail::scope_exit([&] {
  12344. detail::close_socket(srv);
  12345. server_thread.join();
  12346. });
  12347. size_t total_decompressed = 0;
  12348. {
  12349. Client cli("127.0.0.1", PORT + 3);
  12350. cli.set_read_timeout(5, 0);
  12351. cli.set_decompress(true);
  12352. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12353. auto stream = cli.open_stream("GET", "/zipbomb");
  12354. ASSERT_TRUE(stream.is_valid());
  12355. char buffer[64 * 1024];
  12356. ssize_t n;
  12357. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12358. total_decompressed += static_cast<size_t>(n);
  12359. }
  12360. }
  12361. // The decompressed size must be capped by payload_max_length. Without
  12362. // protection, the client would decompress the full 10MB from a tiny
  12363. // compressed payload, enabling a zip bomb DoS attack.
  12364. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  12365. << "Client decompressed " << total_decompressed
  12366. << " bytes from a gzip response. The decompressed size should be "
  12367. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  12368. }
  12369. #endif
  12370. TEST(HostAndPortPropertiesTest, NoSSL) {
  12371. httplib::Client cli("www.google.com", 1234);
  12372. ASSERT_EQ("www.google.com", cli.host());
  12373. ASSERT_EQ(1234, cli.port());
  12374. }
  12375. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  12376. httplib::Client cli("www.google.com:1234");
  12377. ASSERT_EQ("www.google.com", cli.host());
  12378. ASSERT_EQ(1234, cli.port());
  12379. }
  12380. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  12381. // Port number that overflows int — should not crash, client becomes invalid
  12382. httplib::Client cli("http://www.google.com:99999999999999999999");
  12383. ASSERT_FALSE(cli.is_valid());
  12384. }
  12385. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  12386. // Port 99999 exceeds valid range (1-65535) — should not crash
  12387. httplib::Client cli("http://www.google.com:99999");
  12388. ASSERT_FALSE(cli.is_valid());
  12389. auto res = cli.Get("/");
  12390. EXPECT_FALSE(res);
  12391. EXPECT_EQ(Error::Connection, res.error());
  12392. }
  12393. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  12394. httplib::Client cli("http://www.google.com:80abc");
  12395. ASSERT_FALSE(cli.is_valid());
  12396. }
  12397. #ifdef CPPHTTPLIB_SSL_ENABLED
  12398. TEST(HostAndPortPropertiesTest, SSL) {
  12399. httplib::SSLClient cli("www.google.com");
  12400. ASSERT_EQ("www.google.com", cli.host());
  12401. ASSERT_EQ(443, cli.port());
  12402. }
  12403. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  12404. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  12405. std::string cert;
  12406. read_file(CA_CERT_FILE, cert);
  12407. httplib::SSLClient httplib_client("www.google.com");
  12408. // Load CA store first time
  12409. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12410. // Load CA store second time (update)
  12411. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12412. // Verify client is still valid and can make connections
  12413. httplib_client.enable_server_certificate_verification(true);
  12414. auto res = httplib_client.Get("/");
  12415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12416. // Google may return 200 or 301 depending on various factors
  12417. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  12418. res->status == StatusCode::MovedPermanently_301);
  12419. }
  12420. TEST(SSLClientTest, ServerNameIndication_Online) {
  12421. auto host = "httpbingo.org";
  12422. auto path = std::string{"/get"};
  12423. SSLClient cli(host, 443);
  12424. auto res = cli.Get(path);
  12425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12426. ASSERT_EQ(StatusCode::OK_200, res->status);
  12427. }
  12428. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  12429. // Use a site that will cause SSL verification failure due to self-signed cert
  12430. SSLClient cli("self-signed.badssl.com", 443);
  12431. cli.enable_server_certificate_verification(true);
  12432. auto res = cli.Get("/");
  12433. ASSERT_TRUE(!res);
  12434. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12435. // Verify backend error is captured for SSLServerVerification
  12436. // This occurs when certificate verification fails
  12437. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  12438. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  12439. EXPECT_NE(0UL, res.ssl_backend_error());
  12440. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12441. // For OpenSSL, ssl_error is 0 for verification errors
  12442. EXPECT_EQ(0, res.ssl_error());
  12443. #if !defined(_WIN32) || \
  12444. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12445. // On non-Windows or when Windows Schannel is disabled, the error comes
  12446. // from OpenSSL's verification
  12447. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  12448. res.ssl_backend_error());
  12449. #endif
  12450. #endif
  12451. }
  12452. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  12453. // Use a site where hostname doesn't match the certificate
  12454. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  12455. SSLClient cli("wrong.host.badssl.com", 443);
  12456. cli.enable_server_certificate_verification(true);
  12457. cli.enable_server_hostname_verification(true);
  12458. auto res = cli.Get("/");
  12459. ASSERT_TRUE(!res);
  12460. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  12461. // Verify backend error is captured for hostname verification failure
  12462. EXPECT_NE(0UL, res.ssl_backend_error());
  12463. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12464. // For OpenSSL, ssl_error is 0 for verification errors
  12465. EXPECT_EQ(0, res.ssl_error());
  12466. #if !defined(_WIN32) || \
  12467. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12468. // On non-Windows or when Windows Schannel is disabled, the error comes
  12469. // from OpenSSL's hostname verification
  12470. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  12471. res.ssl_backend_error());
  12472. #endif
  12473. #endif
  12474. }
  12475. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  12476. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12477. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  12478. SSLClient cli("www.google.com", 443);
  12479. cli.enable_server_certificate_verification(true);
  12480. auto res = cli.Get("/");
  12481. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12482. }
  12483. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  12484. SSLClient cli("www.google.com", 443);
  12485. cli.enable_server_certificate_verification(true);
  12486. cli.enable_windows_certificate_verification(false);
  12487. auto res = cli.Get("/");
  12488. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12489. }
  12490. // The server sends an intermediate cross-signed by a root Windows trusts,
  12491. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  12492. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  12493. SSLClient cli("accounts.spotify.com", 443);
  12494. auto res = cli.Get("/");
  12495. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  12496. << " ssl_backend_error=" << res.ssl_backend_error();
  12497. }
  12498. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  12499. // policy status, which no backend reports for a self-signed certificate.
  12500. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  12501. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12502. ASSERT_TRUE(svr.is_valid());
  12503. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12504. auto se = detail::scope_exit([&] {
  12505. svr.stop();
  12506. t.join();
  12507. ASSERT_FALSE(svr.is_running());
  12508. });
  12509. svr.wait_until_ready();
  12510. SSLClient cli("127.0.0.1", PORT);
  12511. cli.set_connection_timeout(30);
  12512. auto res = cli.Get("/");
  12513. ASSERT_FALSE(res);
  12514. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12515. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  12516. }
  12517. #endif
  12518. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  12519. Client cli("https://google.com");
  12520. auto res = cli.Get("/");
  12521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12522. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12523. }
  12524. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  12525. SSLClient cli("google.com");
  12526. cli.set_ca_cert_path(CA_CERT_FILE);
  12527. auto res = cli.Get("/");
  12528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12529. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12530. }
  12531. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  12532. SSLClient cli("google.com");
  12533. cli.enable_server_certificate_verification(true);
  12534. cli.set_ca_cert_path("hello");
  12535. auto res = cli.Get("/");
  12536. ASSERT_TRUE(!res);
  12537. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  12538. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  12539. // should be set
  12540. EXPECT_EQ(0, res.ssl_error());
  12541. // Verify backend error is captured for SSLLoadingCerts
  12542. // This error occurs when loading CA certificates fails
  12543. EXPECT_NE(0UL, res.ssl_backend_error());
  12544. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12545. // OpenSSL specific error codes:
  12546. // > openssl errstr 0x80000002
  12547. // error:80000002:system library::No such file or directory
  12548. // > openssl errstr 0xA000126
  12549. // error:0A000126:SSL routines::unexpected eof while reading
  12550. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  12551. res.ssl_backend_error() == 0xA000126);
  12552. #endif
  12553. }
  12554. TEST(SSLClientTest, ServerCertificateVerification4) {
  12555. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12556. ASSERT_TRUE(svr.is_valid());
  12557. svr.Get("/test", [&](const Request &, Response &res) {
  12558. res.set_content("test", "text/plain");
  12559. svr.stop();
  12560. ASSERT_TRUE(true);
  12561. });
  12562. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12563. auto se = detail::scope_exit([&] {
  12564. t.join();
  12565. ASSERT_FALSE(svr.is_running());
  12566. });
  12567. svr.wait_until_ready();
  12568. SSLClient cli("127.0.0.1", PORT);
  12569. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12570. cli.enable_server_certificate_verification(true);
  12571. cli.set_connection_timeout(30);
  12572. auto res = cli.Get("/test");
  12573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12574. ASSERT_EQ(StatusCode::OK_200, res->status);
  12575. }
  12576. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  12577. std::string cert;
  12578. read_file(CA_CERT_FILE, cert);
  12579. SSLClient cli("google.com");
  12580. cli.load_ca_cert_store(cert.data(), cert.size());
  12581. const auto res = cli.Get("/");
  12582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12583. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12584. }
  12585. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  12586. // clang-format off
  12587. static constexpr char cert[] =
  12588. "GlobalSign Root CA\n"
  12589. "==================\n"
  12590. "-----BEGIN CERTIFICATE-----\n"
  12591. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  12592. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  12593. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  12594. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  12595. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  12596. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  12597. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  12598. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  12599. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  12600. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  12601. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  12602. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  12603. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  12604. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  12605. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  12606. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  12607. "-----END CERTIFICATE-----\n";
  12608. // clang-format on
  12609. SSLClient cli("google.com");
  12610. cli.load_ca_cert_store(cert, sizeof(cert));
  12611. const auto res = cli.Get("/");
  12612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12613. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12614. }
  12615. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  12616. SSLClient cli("www.youtube.com");
  12617. cli.set_ca_cert_path(CA_CERT_FILE);
  12618. cli.enable_server_certificate_verification(true);
  12619. cli.set_follow_location(true);
  12620. auto res = cli.Get("/");
  12621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12622. ASSERT_EQ(StatusCode::OK_200, res->status);
  12623. }
  12624. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  12625. SSLClient cli("wWw.YouTube.Com");
  12626. cli.set_ca_cert_path(CA_CERT_FILE);
  12627. cli.enable_server_certificate_verification(true);
  12628. cli.enable_server_hostname_verification(true);
  12629. cli.set_follow_location(true);
  12630. auto res = cli.Get("/");
  12631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12632. ASSERT_EQ(StatusCode::OK_200, res->status);
  12633. }
  12634. TEST(SSLClientTest, HostNameMatchCase_Online) {
  12635. SSLClient cli("gOoGlE.COm");
  12636. cli.enable_server_certificate_verification(true);
  12637. cli.enable_server_hostname_verification(true);
  12638. cli.set_follow_location(true);
  12639. auto res = cli.Get("/");
  12640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12641. ASSERT_EQ(StatusCode::OK_200, res->status);
  12642. }
  12643. TEST(SSLClientTest, Issue2004_Online) {
  12644. Client client("https://google.com");
  12645. client.set_follow_location(true);
  12646. auto res = client.Get("/");
  12647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12648. ASSERT_EQ(StatusCode::OK_200, res->status);
  12649. auto body = res->body;
  12650. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  12651. }
  12652. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  12653. // Create SSLClient with invalid cert/key to make is_valid() return false
  12654. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  12655. "nonexistent_key.pem");
  12656. // is_valid() should be false due to cert loading failure
  12657. ASSERT_FALSE(cli.is_valid());
  12658. auto res = cli.Get("/");
  12659. ASSERT_FALSE(res);
  12660. EXPECT_EQ(Error::SSLConnection, res.error());
  12661. }
  12662. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  12663. // Test for Issue #2251: SSL error not properly reported when client cert
  12664. // and key paths are swapped or mismatched
  12665. // This simulates the scenario where user accidentally swaps the cert and key
  12666. // files
  12667. // Using client cert file as private key and vice versa (completely wrong)
  12668. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  12669. // Should fail validation due to cert/key mismatch
  12670. ASSERT_FALSE(cli.is_valid());
  12671. // Attempt to make a request should fail with proper error
  12672. auto res = cli.Get("/");
  12673. ASSERT_FALSE(res);
  12674. EXPECT_EQ(Error::SSLConnection, res.error());
  12675. // SSL error should be recorded in the Result object (this is the key fix for
  12676. // Issue #2251)
  12677. auto backend_error = res.ssl_backend_error();
  12678. EXPECT_NE(0u, backend_error);
  12679. }
  12680. // Tests cert/key mismatch detection at the TLS context level
  12681. TEST(TlsApiTest, ClientCertKeyMismatch) {
  12682. // Test that using mismatched cert/key causes connection failure.
  12683. // We verify this at the SSLClient level rather than through internal
  12684. // TLS API functions.
  12685. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  12686. cli.enable_server_certificate_verification(false);
  12687. cli.set_connection_timeout(2);
  12688. // The mismatch should cause a connection or handshake error
  12689. auto res = cli.Get("/test");
  12690. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  12691. // Either way, the request should fail
  12692. EXPECT_FALSE(res);
  12693. }
  12694. #endif
  12695. #if 0
  12696. TEST(SSLClientTest, SetInterfaceWithINET6) {
  12697. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  12698. ASSERT_TRUE(cli != nullptr);
  12699. cli->set_address_family(AF_INET6);
  12700. cli->set_interface("en0");
  12701. auto res = cli->Get("/get");
  12702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12703. ASSERT_EQ(StatusCode::OK_200, res->status);
  12704. }
  12705. #endif
  12706. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  12707. #ifdef CPPHTTPLIB_SSL_ENABLED
  12708. void ClientCertPresent(
  12709. const std::string &client_cert_file,
  12710. const std::string &client_private_key_file,
  12711. const std::string &client_encrypted_private_key_pass = std::string()) {
  12712. using namespace httplib::tls;
  12713. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12714. CLIENT_CA_CERT_DIR);
  12715. ASSERT_TRUE(svr.is_valid());
  12716. svr.Get("/test", [&](const Request &req, Response &res) {
  12717. res.set_content("test", "text/plain");
  12718. auto cert = req.peer_cert();
  12719. ASSERT_TRUE(static_cast<bool>(cert));
  12720. std::string common_name = cert.subject_cn();
  12721. EXPECT_EQ("Common Name", common_name);
  12722. });
  12723. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12724. auto se = detail::scope_exit([&] {
  12725. svr.stop();
  12726. t.join();
  12727. ASSERT_FALSE(svr.is_running());
  12728. });
  12729. svr.wait_until_ready();
  12730. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  12731. client_encrypted_private_key_pass);
  12732. cli.enable_server_certificate_verification(false);
  12733. cli.set_connection_timeout(30);
  12734. auto res = cli.Get("/test");
  12735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12736. ASSERT_EQ(StatusCode::OK_200, res->status);
  12737. }
  12738. TEST(SSLClientServerTest, ClientCertPresent) {
  12739. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12740. }
  12741. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  12742. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12743. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12744. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12745. }
  12746. // PEM memory-based constructor tests (works with all TLS backends)
  12747. void PemMemoryClientCertPresent(
  12748. const std::string &client_cert_file,
  12749. const std::string &client_private_key_file,
  12750. const std::string &client_encrypted_private_key_pass = std::string()) {
  12751. // Read PEM files into memory
  12752. std::string server_cert_pem, server_key_pem;
  12753. std::string client_ca_pem;
  12754. std::string client_cert_pem, client_key_pem;
  12755. read_file(SERVER_CERT_FILE, server_cert_pem);
  12756. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12757. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12758. read_file(client_cert_file, client_cert_pem);
  12759. read_file(client_private_key_file, client_key_pem);
  12760. // Create server with PEM memory
  12761. SSLServer::PemMemory server_pem = {
  12762. server_cert_pem.c_str(),
  12763. server_cert_pem.size(),
  12764. server_key_pem.c_str(),
  12765. server_key_pem.size(),
  12766. client_ca_pem.c_str(),
  12767. client_ca_pem.size(),
  12768. nullptr // no password for server key
  12769. };
  12770. SSLServer svr(server_pem);
  12771. ASSERT_TRUE(svr.is_valid());
  12772. svr.Get("/test", [&](const Request &, Response &res) {
  12773. res.set_content("test", "text/plain");
  12774. });
  12775. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12776. auto se = detail::scope_exit([&] {
  12777. svr.stop();
  12778. t.join();
  12779. ASSERT_FALSE(svr.is_running());
  12780. });
  12781. svr.wait_until_ready();
  12782. // Create client with PEM memory
  12783. const char *password = client_encrypted_private_key_pass.empty()
  12784. ? nullptr
  12785. : client_encrypted_private_key_pass.c_str();
  12786. SSLClient::PemMemory client_pem = {
  12787. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  12788. client_key_pem.size(), password};
  12789. SSLClient cli(HOST, PORT, client_pem);
  12790. cli.enable_server_certificate_verification(false);
  12791. cli.set_connection_timeout(30);
  12792. auto res = cli.Get("/test");
  12793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12794. ASSERT_EQ(StatusCode::OK_200, res->status);
  12795. }
  12796. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  12797. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12798. }
  12799. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  12800. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12801. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12802. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12803. }
  12804. TEST(SSLClientServerTest, ClientCertMissing) {
  12805. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12806. CLIENT_CA_CERT_DIR);
  12807. ASSERT_TRUE(svr.is_valid());
  12808. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  12809. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12810. auto se = detail::scope_exit([&] {
  12811. svr.stop();
  12812. t.join();
  12813. ASSERT_FALSE(svr.is_running());
  12814. });
  12815. svr.wait_until_ready();
  12816. SSLClient cli(HOST, PORT);
  12817. cli.set_connection_timeout(30);
  12818. // cert.pem does not match HOST. Skip the hostname check, which runs before
  12819. // the chain check on Windows, so the result does not depend on the order.
  12820. cli.enable_server_hostname_verification(false);
  12821. auto res = cli.Get("/test");
  12822. ASSERT_TRUE(!res);
  12823. // When client cert is missing and server requires it, connection fails
  12824. // Error type depends on backend implementation
  12825. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12826. res.error() == Error::SSLConnection);
  12827. // Verify backend error is captured
  12828. // Note: This test may have different error codes depending on the exact
  12829. // verification failure
  12830. EXPECT_NE(0UL, res.ssl_backend_error());
  12831. }
  12832. TEST(SSLClientServerTest, TrustDirOptional) {
  12833. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12834. ASSERT_TRUE(svr.is_valid());
  12835. svr.Get("/test", [&](const Request &, Response &res) {
  12836. res.set_content("test", "text/plain");
  12837. });
  12838. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12839. auto se = detail::scope_exit([&] {
  12840. svr.stop();
  12841. t.join();
  12842. ASSERT_FALSE(svr.is_running());
  12843. });
  12844. svr.wait_until_ready();
  12845. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12846. cli.enable_server_certificate_verification(false);
  12847. cli.set_connection_timeout(30);
  12848. auto res = cli.Get("/test");
  12849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12850. ASSERT_EQ(StatusCode::OK_200, res->status);
  12851. }
  12852. TEST(SSLClientServerTest, SSLConnectTimeout) {
  12853. class NoListenSSLServer : public SSLServer {
  12854. public:
  12855. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  12856. const char *client_ca_cert_file_path,
  12857. const char *client_ca_cert_dir_path = nullptr)
  12858. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  12859. client_ca_cert_dir_path),
  12860. stop_(false) {}
  12861. std::atomic_bool stop_;
  12862. private:
  12863. bool process_and_close_socket(socket_t /*sock*/) override {
  12864. // Don't create SSL context
  12865. while (!stop_.load()) {
  12866. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  12867. }
  12868. return true;
  12869. }
  12870. };
  12871. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12872. CLIENT_CA_CERT_FILE);
  12873. ASSERT_TRUE(svr.is_valid());
  12874. svr.Get("/test", [&](const Request &, Response &res) {
  12875. res.set_content("test", "text/plain");
  12876. });
  12877. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12878. auto se = detail::scope_exit([&] {
  12879. svr.stop_ = true;
  12880. svr.stop();
  12881. t.join();
  12882. ASSERT_FALSE(svr.is_running());
  12883. });
  12884. svr.wait_until_ready();
  12885. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12886. cli.enable_server_certificate_verification(false);
  12887. cli.set_connection_timeout(1);
  12888. auto res = cli.Get("/test");
  12889. ASSERT_TRUE(!res);
  12890. EXPECT_EQ(Error::SSLConnection, res.error());
  12891. // Timeout results in WantRead error code (maps to backend-specific value)
  12892. EXPECT_NE(0, res.ssl_error());
  12893. }
  12894. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  12895. // Test SSLServer with client certificate verification using the standard
  12896. // constructor (ContextSetupCallback is tested by backend-specific tests)
  12897. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12898. CLIENT_CA_CERT_DIR);
  12899. ASSERT_TRUE(svr.is_valid());
  12900. svr.Get("/test", [&](const Request &req, Response &res) {
  12901. res.set_content("test", "text/plain");
  12902. auto cert = req.peer_cert();
  12903. ASSERT_TRUE(static_cast<bool>(cert));
  12904. auto common_name = cert.subject_cn();
  12905. EXPECT_EQ("Common Name", common_name);
  12906. });
  12907. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12908. auto se = detail::scope_exit([&] {
  12909. svr.stop();
  12910. t.join();
  12911. ASSERT_FALSE(svr.is_running());
  12912. });
  12913. svr.wait_until_ready();
  12914. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12915. cli.enable_server_certificate_verification(false);
  12916. cli.set_connection_timeout(30);
  12917. auto res = cli.Get("/test");
  12918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12919. ASSERT_EQ(StatusCode::OK_200, res->status);
  12920. }
  12921. // Test verify_hostname for both OpenSSL and MbedTLS backends
  12922. // Verifies that wildcard matching and exact matching work consistently
  12923. TEST(SSLClientServerTest, TlsVerifyHostname) {
  12924. using namespace httplib::tls;
  12925. // We need a running server to test against
  12926. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12927. ASSERT_TRUE(svr.is_valid());
  12928. svr.Get("/test", [](const Request &, Response &res) {
  12929. res.set_content("ok", "text/plain");
  12930. });
  12931. thread t([&]() { svr.listen(HOST, PORT); });
  12932. auto se = detail::scope_exit([&] {
  12933. svr.stop();
  12934. t.join();
  12935. });
  12936. svr.wait_until_ready();
  12937. bool verify_callback_called = false;
  12938. bool verify_result_wrong = false;
  12939. SSLClient cli(HOST, PORT);
  12940. cli.enable_server_certificate_verification(true);
  12941. cli.set_ca_cert_path(CA_CERT_FILE);
  12942. cli.set_connection_timeout(5);
  12943. // Note: Test certificate has CN="Common Name", not "localhost"
  12944. bool verify_result_cn = false;
  12945. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12946. verify_callback_called = true;
  12947. if (!ctx.cert) return false;
  12948. // Test 1: "Common Name" should match (our test server cert CN)
  12949. verify_result_cn = ctx.check_hostname("Common Name");
  12950. // Test 2: wrong hostname should not match
  12951. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  12952. return true; // Accept for the purpose of this test
  12953. });
  12954. auto res = cli.Get("/test");
  12955. // The request may succeed or fail depending on cert configuration
  12956. // but the callback should have been called
  12957. ASSERT_TRUE(verify_callback_called)
  12958. << "Verify callback should have been called";
  12959. // CN="Common Name" should match our test certificate
  12960. //
  12961. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  12962. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  12963. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  12964. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  12965. // <openssl/base.h>, which is included transitively when
  12966. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  12967. #if defined(OPENSSL_IS_BORINGSSL)
  12968. EXPECT_FALSE(verify_result_cn)
  12969. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  12970. #else
  12971. EXPECT_TRUE(verify_result_cn)
  12972. << "verify_hostname should match 'Common Name' (certificate CN)";
  12973. #endif
  12974. // Wrong hostname should not match
  12975. EXPECT_FALSE(verify_result_wrong)
  12976. << "verify_hostname should not match 'wronghost.example.com'";
  12977. }
  12978. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  12979. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  12980. // X509_check_ip behavior and must hold for every backend.
  12981. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  12982. using namespace httplib::tls;
  12983. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  12984. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  12985. ASSERT_TRUE(svr.is_valid());
  12986. svr.Get("/test", [](const Request &, Response &res) {
  12987. res.set_content("ok", "text/plain");
  12988. });
  12989. thread t([&]() { svr.listen(HOST, PORT); });
  12990. auto se = detail::scope_exit([&] {
  12991. svr.stop();
  12992. t.join();
  12993. });
  12994. svr.wait_until_ready();
  12995. bool verify_callback_called = false;
  12996. bool ip_matched_via_cn = true;
  12997. SSLClient cli(HOST, PORT);
  12998. cli.enable_server_certificate_verification(true);
  12999. cli.set_ca_cert_path(CA_CERT_FILE);
  13000. cli.set_connection_timeout(5);
  13001. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13002. verify_callback_called = true;
  13003. if (!ctx.cert) return false;
  13004. // The IP appears only in the CN, so it must NOT be accepted.
  13005. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  13006. return true; // Accept for the purpose of this test
  13007. });
  13008. cli.Get("/test");
  13009. ASSERT_TRUE(verify_callback_called)
  13010. << "Verify callback should have been called";
  13011. EXPECT_FALSE(ip_matched_via_cn)
  13012. << "An IP host must not be authenticated via the certificate CN";
  13013. }
  13014. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  13015. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  13016. using namespace httplib::tls;
  13017. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  13018. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  13019. ASSERT_TRUE(svr.is_valid());
  13020. svr.Get("/test", [](const Request &, Response &res) {
  13021. res.set_content("ok", "text/plain");
  13022. });
  13023. thread t([&]() { svr.listen(HOST, PORT); });
  13024. auto se = detail::scope_exit([&] {
  13025. svr.stop();
  13026. t.join();
  13027. });
  13028. svr.wait_until_ready();
  13029. bool verify_callback_called = false;
  13030. bool san_matched = false;
  13031. bool wrong_ipv6_matched = true;
  13032. bool cn_ipv6_matched = true;
  13033. SSLClient cli(HOST, PORT);
  13034. cli.enable_server_certificate_verification(true);
  13035. cli.set_ca_cert_path(CA_CERT_FILE);
  13036. cli.set_connection_timeout(5);
  13037. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13038. verify_callback_called = true;
  13039. if (!ctx.cert) return false;
  13040. // Matches the IPv6 iPAddress SAN.
  13041. san_matched = ctx.check_hostname("2001:db8::1");
  13042. // A different IPv6 address must not match.
  13043. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  13044. // "::1" lives only in the CN, so it must not be accepted.
  13045. cn_ipv6_matched = ctx.check_hostname("::1");
  13046. return true; // Accept for the purpose of this test
  13047. });
  13048. cli.Get("/test");
  13049. ASSERT_TRUE(verify_callback_called)
  13050. << "Verify callback should have been called";
  13051. EXPECT_TRUE(san_matched)
  13052. << "verify_hostname should match an IPv6 iPAddress SAN";
  13053. EXPECT_FALSE(wrong_ipv6_matched)
  13054. << "verify_hostname should not match a non-matching IPv6 address";
  13055. EXPECT_FALSE(cn_ipv6_matched)
  13056. << "An IPv6 host must not be authenticated via the certificate CN";
  13057. }
  13058. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  13059. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  13060. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  13061. using namespace httplib::tls;
  13062. // SANs: DNS:a.zz, IP:42.46.122.122
  13063. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13064. ASSERT_TRUE(svr.is_valid());
  13065. svr.Get("/test", [](const Request &, Response &res) {
  13066. res.set_content("ok", "text/plain");
  13067. });
  13068. auto port = svr.bind_to_any_port(HOST);
  13069. thread t([&]() { svr.listen_after_bind(); });
  13070. auto se = detail::scope_exit([&] {
  13071. svr.stop();
  13072. t.join();
  13073. });
  13074. svr.wait_until_ready();
  13075. bool verify_callback_called = false;
  13076. bool dns_san_matched = false;
  13077. bool ip_san_matched = false;
  13078. bool ip_matched_via_dns_san = true;
  13079. bool dns_matched_via_ip_san = true;
  13080. SSLClient cli(HOST, port);
  13081. cli.enable_server_certificate_verification(true);
  13082. cli.set_ca_cert_path(CA_CERT_FILE);
  13083. cli.set_connection_timeout(5);
  13084. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13085. verify_callback_called = true;
  13086. if (!ctx.cert) return false;
  13087. dns_san_matched = ctx.check_hostname("a.zz");
  13088. ip_san_matched = ctx.check_hostname("42.46.122.122");
  13089. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  13090. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  13091. return true; // Accept for the purpose of this test
  13092. });
  13093. cli.Get("/test");
  13094. ASSERT_TRUE(verify_callback_called)
  13095. << "Verify callback should have been called";
  13096. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  13097. EXPECT_TRUE(ip_san_matched)
  13098. << "verify_hostname should match an iPAddress SAN";
  13099. EXPECT_FALSE(ip_matched_via_dns_san)
  13100. << "An IP host must not be authenticated via a dNSName SAN";
  13101. EXPECT_FALSE(dns_matched_via_ip_san)
  13102. << "A DNS host must not be authenticated via an iPAddress SAN";
  13103. }
  13104. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  13105. // "www.*.example.test" names one host and not every host under example.test.
  13106. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  13107. using namespace httplib::tls;
  13108. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  13109. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  13110. ASSERT_TRUE(svr.is_valid());
  13111. svr.Get("/test", [](const Request &, Response &res) {
  13112. res.set_content("ok", "text/plain");
  13113. });
  13114. auto port = svr.bind_to_any_port(HOST);
  13115. thread t([&]() { svr.listen_after_bind(); });
  13116. auto se = detail::scope_exit([&] {
  13117. svr.stop();
  13118. t.join();
  13119. });
  13120. svr.wait_until_ready();
  13121. bool verify_callback_called = false;
  13122. bool leftmost_wildcard_matched = false;
  13123. bool wildcard_spanned_labels = true;
  13124. bool inner_wildcard_matched = true;
  13125. SSLClient cli(HOST, port);
  13126. cli.enable_server_certificate_verification(true);
  13127. cli.set_ca_cert_path(CA_CERT_FILE);
  13128. cli.set_connection_timeout(5);
  13129. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13130. verify_callback_called = true;
  13131. if (!ctx.cert) return false;
  13132. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  13133. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  13134. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  13135. return true; // Accept for the purpose of this test
  13136. });
  13137. cli.Get("/test");
  13138. ASSERT_TRUE(verify_callback_called)
  13139. << "Verify callback should have been called";
  13140. EXPECT_TRUE(leftmost_wildcard_matched)
  13141. << "A leftmost wildcard should match a single label";
  13142. EXPECT_FALSE(wildcard_spanned_labels)
  13143. << "A wildcard label must not match more than one label";
  13144. EXPECT_FALSE(inner_wildcard_matched)
  13145. << "A wildcard outside the leftmost label must not be honoured";
  13146. }
  13147. // sans() must report each SAN entry under its own type.
  13148. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  13149. using namespace httplib::tls;
  13150. // SANs: DNS:a.zz, IP:42.46.122.122
  13151. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13152. ASSERT_TRUE(svr.is_valid());
  13153. svr.Get("/test", [](const Request &, Response &res) {
  13154. res.set_content("ok", "text/plain");
  13155. });
  13156. auto port = svr.bind_to_any_port(HOST);
  13157. thread t([&]() { svr.listen_after_bind(); });
  13158. auto se = detail::scope_exit([&] {
  13159. svr.stop();
  13160. t.join();
  13161. });
  13162. svr.wait_until_ready();
  13163. bool verify_callback_called = false;
  13164. std::vector<SanEntry> sans;
  13165. SSLClient cli(HOST, port);
  13166. cli.enable_server_certificate_verification(true);
  13167. cli.set_ca_cert_path(CA_CERT_FILE);
  13168. cli.set_connection_timeout(5);
  13169. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13170. verify_callback_called = true;
  13171. if (!ctx.cert) return false;
  13172. sans = ctx.sans();
  13173. return true; // Accept for the purpose of this test
  13174. });
  13175. cli.Get("/test");
  13176. ASSERT_TRUE(verify_callback_called)
  13177. << "Verify callback should have been called";
  13178. auto has_san = [&](SanType type, const std::string &value) {
  13179. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  13180. return san.type == type && san.value == value;
  13181. });
  13182. };
  13183. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  13184. << "sans() should report the dNSName SAN";
  13185. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  13186. << "sans() should report the iPAddress SAN";
  13187. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  13188. << "sans() must not report the dNSName SAN as an address";
  13189. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  13190. << "sans() must not report the iPAddress SAN as a DNS name";
  13191. }
  13192. #endif
  13193. // mbedTLS-specific callback constructor test
  13194. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  13195. #ifdef CPPHTTPLIB_SSL_ENABLED
  13196. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  13197. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13198. ASSERT_TRUE(svr.is_valid());
  13199. // Set up a handler to verify client certificate is present
  13200. bool client_cert_verified = false;
  13201. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13202. // Verify that client certificate was provided
  13203. client_cert_verified = true;
  13204. res.set_content("success", "text/plain");
  13205. });
  13206. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13207. auto se = detail::scope_exit([&] {
  13208. svr.stop();
  13209. t.join();
  13210. ASSERT_FALSE(svr.is_running());
  13211. });
  13212. svr.wait_until_ready();
  13213. // Client with certificate
  13214. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13215. cli.enable_server_certificate_verification(false);
  13216. cli.set_connection_timeout(30);
  13217. auto res = cli.Get("/test");
  13218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13219. ASSERT_EQ(StatusCode::OK_200, res->status);
  13220. ASSERT_TRUE(client_cert_verified);
  13221. EXPECT_EQ("success", res->body);
  13222. }
  13223. #endif
  13224. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  13225. // backends
  13226. #ifdef CPPHTTPLIB_SSL_ENABLED
  13227. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  13228. using namespace httplib::tls;
  13229. // Test that when client CA cert file is provided,
  13230. // the server properly requests and validates client certificates
  13231. // Create a server with client authentication
  13232. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13233. ASSERT_TRUE(svr.is_valid());
  13234. bool handler_called = false;
  13235. svr.Get("/test", [&](const Request &req, Response &res) {
  13236. handler_called = true;
  13237. // Verify that a client certificate was provided
  13238. auto cert = req.peer_cert();
  13239. ASSERT_TRUE(static_cast<bool>(cert));
  13240. // Get the issuer name
  13241. std::string issuer_str = cert.issuer_name();
  13242. ASSERT_FALSE(issuer_str.empty());
  13243. // The client certificate should be issued by our test CA
  13244. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  13245. res.set_content("authenticated", "text/plain");
  13246. });
  13247. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13248. auto se = detail::scope_exit([&] {
  13249. svr.stop();
  13250. t.join();
  13251. ASSERT_FALSE(svr.is_running());
  13252. });
  13253. svr.wait_until_ready();
  13254. // Connect with a client certificate issued by the CA
  13255. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13256. cli.enable_server_certificate_verification(false);
  13257. cli.set_connection_timeout(30);
  13258. auto res = cli.Get("/test");
  13259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13260. ASSERT_EQ(StatusCode::OK_200, res->status);
  13261. ASSERT_TRUE(handler_called);
  13262. EXPECT_EQ("authenticated", res->body);
  13263. }
  13264. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  13265. using namespace httplib::tls;
  13266. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13267. ASSERT_TRUE(svr.is_valid());
  13268. svr.Get("/test", [](const Request &, Response &res) {
  13269. res.set_content("ok", "text/plain");
  13270. });
  13271. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13272. auto se = detail::scope_exit([&] {
  13273. svr.stop();
  13274. t.join();
  13275. });
  13276. svr.wait_until_ready();
  13277. SSLClient cli(HOST, PORT);
  13278. cli.enable_server_certificate_verification(false);
  13279. cli.set_connection_timeout(30);
  13280. bool cert_checked = false;
  13281. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13282. if (ctx.cert) {
  13283. auto sans = ctx.sans();
  13284. // Test certificate may or may not have SANs - just verify the API
  13285. // works If SANs exist, verify the types are valid
  13286. for (const auto &san : sans) {
  13287. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  13288. san.type == SanType::EMAIL || san.type == SanType::URI ||
  13289. san.type == SanType::OTHER);
  13290. EXPECT_FALSE(san.value.empty());
  13291. }
  13292. cert_checked = true;
  13293. }
  13294. return true;
  13295. });
  13296. auto res = cli.Get("/test");
  13297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13298. EXPECT_TRUE(cert_checked);
  13299. }
  13300. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  13301. using namespace httplib::tls;
  13302. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13303. ASSERT_TRUE(svr.is_valid());
  13304. svr.Get("/test", [](const Request &, Response &res) {
  13305. res.set_content("ok", "text/plain");
  13306. });
  13307. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13308. auto se = detail::scope_exit([&] {
  13309. svr.stop();
  13310. t.join();
  13311. });
  13312. svr.wait_until_ready();
  13313. SSLClient cli(HOST, PORT);
  13314. cli.enable_server_certificate_verification(false);
  13315. cli.set_connection_timeout(30);
  13316. bool validity_checked = false;
  13317. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13318. if (ctx.cert) {
  13319. time_t not_before = 0, not_after = 0;
  13320. bool result = ctx.validity(not_before, not_after);
  13321. EXPECT_TRUE(result);
  13322. // Verify that not_before < now < not_after for a valid cert
  13323. time_t now = time(nullptr);
  13324. EXPECT_LT(not_before, now);
  13325. EXPECT_GT(not_after, now);
  13326. validity_checked = true;
  13327. }
  13328. return true;
  13329. });
  13330. auto res = cli.Get("/test");
  13331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13332. EXPECT_TRUE(validity_checked);
  13333. }
  13334. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  13335. using namespace httplib::tls;
  13336. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13337. ASSERT_TRUE(svr.is_valid());
  13338. svr.Get("/test", [](const Request &, Response &res) {
  13339. res.set_content("ok", "text/plain");
  13340. });
  13341. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13342. auto se = detail::scope_exit([&] {
  13343. svr.stop();
  13344. t.join();
  13345. });
  13346. svr.wait_until_ready();
  13347. SSLClient cli(HOST, PORT);
  13348. cli.enable_server_certificate_verification(false);
  13349. cli.set_connection_timeout(30);
  13350. bool serial_checked = false;
  13351. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13352. if (ctx.cert) {
  13353. std::string serial = ctx.serial();
  13354. EXPECT_FALSE(serial.empty());
  13355. // Serial should be a hex string
  13356. for (char c : serial) {
  13357. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  13358. (c >= 'a' && c <= 'f'));
  13359. }
  13360. serial_checked = true;
  13361. }
  13362. return true;
  13363. });
  13364. auto res = cli.Get("/test");
  13365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13366. EXPECT_TRUE(serial_checked);
  13367. }
  13368. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  13369. // Test 1: Valid CA file - no error should be recorded
  13370. {
  13371. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13372. CLIENT_CA_CERT_FILE);
  13373. ASSERT_TRUE(svr.is_valid());
  13374. // With valid setup, last_ssl_error should be 0
  13375. EXPECT_EQ(0, svr.ssl_last_error());
  13376. }
  13377. // Test 2: Invalid CA file content
  13378. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  13379. {
  13380. // Create a temporary file with completely invalid content
  13381. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  13382. {
  13383. std::ofstream ofs(temp_invalid_ca);
  13384. ofs << "This is not a certificate file at all\n";
  13385. ofs << "Just plain text content\n";
  13386. }
  13387. // Create server with invalid CA file
  13388. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  13389. // Clean up temporary file
  13390. std::remove(temp_invalid_ca);
  13391. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  13392. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  13393. // Note: SSL_CTX_load_verify_locations typically fails first,
  13394. // but our error handling code path is still exercised
  13395. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  13396. }
  13397. }
  13398. TEST(VerifyCallbackTest, VerifyContextFields) {
  13399. using namespace httplib::tls;
  13400. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13401. ASSERT_TRUE(svr.is_valid());
  13402. svr.Get("/test", [](const Request &, Response &res) {
  13403. res.set_content("ok", "text/plain");
  13404. });
  13405. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13406. auto se = detail::scope_exit([&] {
  13407. svr.stop();
  13408. t.join();
  13409. });
  13410. svr.wait_until_ready();
  13411. SSLClient cli(HOST, PORT);
  13412. cli.enable_server_certificate_verification(false);
  13413. cli.set_connection_timeout(30);
  13414. int callback_count = 0;
  13415. bool saw_leaf_cert = false;
  13416. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13417. if (ctx.cert) {
  13418. callback_count++;
  13419. // We should see at least one certificate (the leaf)
  13420. std::string cn = ctx.subject_cn();
  13421. if (!cn.empty()) { saw_leaf_cert = true; }
  13422. // Verify context fields are populated
  13423. EXPECT_NE(ctx.session, nullptr);
  13424. EXPECT_GE(ctx.depth, 0);
  13425. }
  13426. return true;
  13427. });
  13428. auto res = cli.Get("/test");
  13429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13430. EXPECT_GT(callback_count, 0);
  13431. EXPECT_TRUE(saw_leaf_cert);
  13432. }
  13433. // A verifier belongs to the client that set it, not to the thread that set it.
  13434. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  13435. using namespace httplib::tls;
  13436. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13437. ASSERT_TRUE(svr.is_valid());
  13438. svr.Get("/test", [](const Request &, Response &res) {
  13439. res.set_content("ok", "text/plain");
  13440. });
  13441. auto port = svr.bind_to_any_port(HOST);
  13442. thread t([&]() { svr.listen_after_bind(); });
  13443. auto se = detail::scope_exit([&] {
  13444. svr.stop();
  13445. t.join();
  13446. });
  13447. svr.wait_until_ready();
  13448. auto rejecting_calls = 0;
  13449. SSLClient rejecting(HOST, port);
  13450. rejecting.enable_server_certificate_verification(false);
  13451. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  13452. rejecting_calls++;
  13453. return false;
  13454. });
  13455. auto accepting_calls = 0;
  13456. SSLClient accepting(HOST, port);
  13457. accepting.enable_server_certificate_verification(false);
  13458. // Set on another thread than the requests below.
  13459. thread([&]() {
  13460. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  13461. accepting_calls++;
  13462. return true;
  13463. });
  13464. }).join();
  13465. // Requested on another thread than the verifier was set on.
  13466. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  13467. EXPECT_GT(rejecting_calls, 0);
  13468. auto res = accepting.Get("/test");
  13469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13470. EXPECT_GT(accepting_calls, 0);
  13471. }
  13472. // VerifyContext::session is the same handle the other tls:: functions take.
  13473. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  13474. using namespace httplib::tls;
  13475. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13476. ASSERT_TRUE(svr.is_valid());
  13477. svr.Get("/test", [](const Request &, Response &res) {
  13478. res.set_content("ok", "text/plain");
  13479. });
  13480. auto port = svr.bind_to_any_port(HOST);
  13481. thread t([&]() { svr.listen_after_bind(); });
  13482. auto se = detail::scope_exit([&] {
  13483. svr.stop();
  13484. t.join();
  13485. });
  13486. svr.wait_until_ready();
  13487. SSLClient cli(HOST, port);
  13488. cli.enable_server_certificate_verification(false);
  13489. session_t verifier_session = nullptr;
  13490. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  13491. verifier_session = ctx.session;
  13492. return true;
  13493. });
  13494. session_t session_verifier_session = nullptr;
  13495. cli.set_session_verifier([&](session_t session) {
  13496. session_verifier_session = session;
  13497. return SSLVerifierResponse::NoDecisionMade;
  13498. });
  13499. auto res = cli.Get("/test");
  13500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13501. EXPECT_NE(nullptr, verifier_session);
  13502. EXPECT_EQ(session_verifier_session, verifier_session);
  13503. }
  13504. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  13505. using httplib::tls::TlsError;
  13506. // Test that verify_error_to_string returns empty for success
  13507. std::string success_str = TlsError::verify_error_to_string(0);
  13508. EXPECT_TRUE(success_str.empty());
  13509. // Test that verify_error_to_string returns non-empty for error codes
  13510. // Using a common error code (certificate expired)
  13511. std::string error_str =
  13512. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  13513. EXPECT_FALSE(error_str.empty());
  13514. }
  13515. TEST(SessionVerifierTest, CertificateAccepted) {
  13516. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13517. ASSERT_TRUE(svr.is_valid());
  13518. svr.Get("/test", [](const Request &, Response &res) {
  13519. res.set_content("ok", "text/plain");
  13520. });
  13521. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13522. auto se = detail::scope_exit([&] {
  13523. svr.stop();
  13524. t.join();
  13525. });
  13526. svr.wait_until_ready();
  13527. SSLClient cli(HOST, PORT);
  13528. cli.enable_server_certificate_verification(false);
  13529. cli.set_connection_timeout(30);
  13530. bool callback_called = false;
  13531. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13532. EXPECT_NE(session, nullptr);
  13533. callback_called = true;
  13534. return SSLVerifierResponse::CertificateAccepted;
  13535. });
  13536. auto res = cli.Get("/test");
  13537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13538. EXPECT_EQ(200, res->status);
  13539. EXPECT_TRUE(callback_called);
  13540. }
  13541. TEST(SessionVerifierTest, CertificateRejected) {
  13542. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13543. ASSERT_TRUE(svr.is_valid());
  13544. svr.Get("/test", [](const Request &, Response &res) {
  13545. res.set_content("ok", "text/plain");
  13546. });
  13547. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13548. auto se = detail::scope_exit([&] {
  13549. svr.stop();
  13550. t.join();
  13551. });
  13552. svr.wait_until_ready();
  13553. SSLClient cli(HOST, PORT);
  13554. cli.enable_server_certificate_verification(false);
  13555. cli.set_connection_timeout(30);
  13556. bool callback_called = false;
  13557. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13558. EXPECT_NE(session, nullptr);
  13559. callback_called = true;
  13560. return SSLVerifierResponse::CertificateRejected;
  13561. });
  13562. auto res = cli.Get("/test");
  13563. EXPECT_FALSE(res);
  13564. EXPECT_TRUE(callback_called);
  13565. }
  13566. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  13567. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13568. ASSERT_TRUE(svr.is_valid());
  13569. svr.Get("/test", [](const Request &, Response &res) {
  13570. res.set_content("ok", "text/plain");
  13571. });
  13572. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13573. auto se = detail::scope_exit([&] {
  13574. svr.stop();
  13575. t.join();
  13576. });
  13577. svr.wait_until_ready();
  13578. // NoDecisionMade with verification disabled should succeed (no default check)
  13579. SSLClient cli(HOST, PORT);
  13580. cli.enable_server_certificate_verification(false);
  13581. cli.set_connection_timeout(30);
  13582. bool callback_called = false;
  13583. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13584. EXPECT_NE(session, nullptr);
  13585. callback_called = true;
  13586. return SSLVerifierResponse::NoDecisionMade;
  13587. });
  13588. auto res = cli.Get("/test");
  13589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13590. EXPECT_EQ(200, res->status);
  13591. EXPECT_TRUE(callback_called);
  13592. }
  13593. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  13594. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13595. ASSERT_TRUE(svr.is_valid());
  13596. svr.Get("/test", [](const Request &, Response &res) {
  13597. res.set_content("ok", "text/plain");
  13598. });
  13599. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13600. auto se = detail::scope_exit([&] {
  13601. svr.stop();
  13602. t.join();
  13603. });
  13604. svr.wait_until_ready();
  13605. // NoDecisionMade with verification enabled should fail (self-signed cert).
  13606. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  13607. // so we only check that the request fails, not whether the callback was
  13608. // called.
  13609. SSLClient cli(HOST, PORT);
  13610. cli.enable_server_certificate_verification(true);
  13611. cli.set_connection_timeout(30);
  13612. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13613. EXPECT_NE(session, nullptr);
  13614. return SSLVerifierResponse::NoDecisionMade;
  13615. });
  13616. auto res = cli.Get("/test");
  13617. EXPECT_FALSE(res);
  13618. }
  13619. TEST(SSLClientServerTest, ClientCAListFromPem) {
  13620. // Test SSL server using PemMemory constructor with client CA certificates
  13621. // Read PEM files
  13622. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13623. read_file(SERVER_CERT_FILE, server_cert_pem);
  13624. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13625. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13626. // Create SSLServer with PemMemory constructor including client CA
  13627. SSLServer::PemMemory server_pem = {
  13628. server_cert_pem.c_str(),
  13629. server_cert_pem.size(),
  13630. server_key_pem.c_str(),
  13631. server_key_pem.size(),
  13632. client_ca_pem.c_str(),
  13633. client_ca_pem.size(),
  13634. nullptr // no password for server key
  13635. };
  13636. SSLServer svr(server_pem);
  13637. ASSERT_TRUE(svr.is_valid());
  13638. // No SSL error should be recorded for valid setup
  13639. EXPECT_EQ(0, svr.ssl_last_error());
  13640. // Set up server endpoints
  13641. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  13642. res.set_content("ok", "text/plain");
  13643. });
  13644. // Start server in a thread
  13645. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  13646. svr.wait_until_ready();
  13647. // Connect with client certificate (using constructor with paths)
  13648. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13649. cli.enable_server_certificate_verification(false);
  13650. auto res = cli.Get("/test-pem-ca");
  13651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13652. EXPECT_EQ(200, res->status);
  13653. EXPECT_EQ("ok", res->body);
  13654. svr.stop();
  13655. server_thread.join();
  13656. }
  13657. #endif
  13658. #ifdef _WIN32
  13659. TEST(CleanupTest, WSACleanup) {
  13660. int ret = WSACleanup();
  13661. ASSERT_EQ(0, ret);
  13662. }
  13663. #endif
  13664. #ifndef CPPHTTPLIB_SSL_ENABLED
  13665. TEST(NoSSLSupport, SimpleInterface) {
  13666. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  13667. }
  13668. #endif
  13669. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  13670. TEST(InvalidScheme, SimpleInterface) {
  13671. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  13672. }
  13673. #endif
  13674. TEST(NoScheme, SimpleInterface) {
  13675. Client cli("yahoo.com:80");
  13676. ASSERT_TRUE(cli.is_valid());
  13677. }
  13678. TEST(SendAPI, SimpleInterface_Online) {
  13679. Client cli("http://yahoo.com");
  13680. Request req;
  13681. req.method = "GET";
  13682. req.path = "/";
  13683. auto res = cli.send(req);
  13684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13685. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13686. }
  13687. TEST(SendAPI, WithParamsInRequest) {
  13688. Server svr;
  13689. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  13690. EXPECT_TRUE(req.has_param("test"));
  13691. EXPECT_EQ("test_value", req.get_param_value("test"));
  13692. });
  13693. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13694. auto se = detail::scope_exit([&] {
  13695. svr.stop();
  13696. t.join();
  13697. ASSERT_FALSE(svr.is_running());
  13698. });
  13699. svr.wait_until_ready();
  13700. Client cli(HOST, PORT);
  13701. {
  13702. Request req;
  13703. req.method = "GET";
  13704. req.path = "/";
  13705. req.params.emplace("test", "test_value");
  13706. auto res = cli.send(req);
  13707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13708. }
  13709. {
  13710. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  13711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13712. }
  13713. }
  13714. TEST(ClientImplMethods, GetSocketTest) {
  13715. httplib::Server svr;
  13716. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  13717. res.status = StatusCode::OK_200;
  13718. });
  13719. auto port = svr.bind_to_any_port("127.0.0.1");
  13720. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13721. auto se = detail::scope_exit([&] {
  13722. svr.stop();
  13723. thread.join();
  13724. ASSERT_FALSE(svr.is_running());
  13725. });
  13726. svr.wait_until_ready();
  13727. {
  13728. httplib::Client cli("127.0.0.1", port);
  13729. cli.set_keep_alive(true);
  13730. // Use the behavior of cpp-httplib of opening the connection
  13731. // only when the first request happens. If that changes,
  13732. // this test would be obsolete.
  13733. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  13734. // This also implicitly tests the server. But other tests would fail much
  13735. // earlier than this one to be considered.
  13736. auto res = cli.Get("/");
  13737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13738. EXPECT_EQ(StatusCode::OK_200, res->status);
  13739. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  13740. }
  13741. }
  13742. #ifdef CPPHTTPLIB_SSL_ENABLED
  13743. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  13744. Client cli("http://yahoo.com");
  13745. auto res = cli.Get("/");
  13746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13747. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13748. cli.set_follow_location(true);
  13749. res = cli.Get("/");
  13750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13751. EXPECT_EQ(StatusCode::OK_200, res->status);
  13752. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13753. }
  13754. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  13755. Client cli("https://yahoo.com");
  13756. auto res = cli.Get("/");
  13757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13758. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13759. cli.set_follow_location(true);
  13760. res = cli.Get("/");
  13761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13762. EXPECT_EQ(StatusCode::OK_200, res->status);
  13763. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13764. }
  13765. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  13766. Client cli("https://yahoo.com");
  13767. auto res = cli.Get("/");
  13768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13769. ASSERT_FALSE(!res);
  13770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13771. ASSERT_FALSE(res == nullptr);
  13772. ASSERT_TRUE(res != nullptr);
  13773. EXPECT_EQ(Error::Success, res.error());
  13774. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  13775. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  13776. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13777. cli.set_follow_location(true);
  13778. res = cli.Get("/");
  13779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13780. EXPECT_EQ(Error::Success, res.error());
  13781. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  13782. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  13783. EXPECT_EQ(StatusCode::OK_200, res->status);
  13784. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13785. }
  13786. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13787. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  13788. Client cli("https://cdnjs.cloudflare.com");
  13789. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  13790. Headers{{"Accept-Encoding", "br"}});
  13791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13792. EXPECT_EQ(StatusCode::OK_200, res->status);
  13793. EXPECT_EQ(287630U, res->body.size());
  13794. EXPECT_EQ("application/javascript; charset=utf-8",
  13795. res->get_header_value("Content-Type"));
  13796. }
  13797. #endif
  13798. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  13799. #undef REDIR_HOST // Silence compiler warning
  13800. #define REDIR_HOST "https://httpbingo.org"
  13801. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  13802. Client cli(REDIR_HOST);
  13803. cli.set_follow_location(true);
  13804. auto res =
  13805. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  13806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13807. EXPECT_EQ(StatusCode::OK_200, res->status);
  13808. }
  13809. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  13810. Client cli(REDIR_HOST);
  13811. cli.set_follow_location(true);
  13812. Params params;
  13813. params.emplace("url", "http://example.com");
  13814. params.emplace("status_code", "302");
  13815. auto res = cli.Get(REDIR_PATH, params, Headers{});
  13816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13817. EXPECT_EQ(StatusCode::OK_200, res->status);
  13818. }
  13819. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  13820. Client cli(REDIR_HOST);
  13821. cli.set_follow_location(true);
  13822. Params params;
  13823. params.emplace("url", "http://example.com");
  13824. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  13825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13826. EXPECT_EQ(StatusCode::OK_200, res->status);
  13827. }
  13828. TEST(HttpToHttpsRedirectTest, CertFile) {
  13829. auto ssl_port = PORT + 1;
  13830. Server svr;
  13831. ASSERT_TRUE(svr.is_valid());
  13832. svr.Get("/index", [&](const Request &, Response &res) {
  13833. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13834. "/index");
  13835. svr.stop();
  13836. });
  13837. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13838. ASSERT_TRUE(ssl_svr.is_valid());
  13839. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  13840. res.set_content("test", "text/plain");
  13841. ssl_svr.stop();
  13842. });
  13843. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13844. thread t2 =
  13845. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  13846. auto se = detail::scope_exit([&] {
  13847. t2.join();
  13848. t.join();
  13849. ASSERT_FALSE(svr.is_running());
  13850. });
  13851. svr.wait_until_ready();
  13852. ssl_svr.wait_until_ready();
  13853. Client cli("127.0.0.1", PORT);
  13854. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13855. cli.enable_server_certificate_verification(true);
  13856. cli.set_follow_location(true);
  13857. cli.set_connection_timeout(30);
  13858. auto res = cli.Get("/index");
  13859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13860. ASSERT_EQ(StatusCode::OK_200, res->status);
  13861. }
  13862. TEST(SSLClientRedirectTest, CertFile) {
  13863. auto ssl_port = PORT + 1;
  13864. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13865. ASSERT_TRUE(ssl_svr1.is_valid());
  13866. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13867. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13868. "/index");
  13869. ssl_svr1.stop();
  13870. });
  13871. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13872. ASSERT_TRUE(ssl_svr2.is_valid());
  13873. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13874. res.set_content("test", "text/plain");
  13875. ssl_svr2.stop();
  13876. });
  13877. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13878. thread t2 =
  13879. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13880. auto se = detail::scope_exit([&] {
  13881. t2.join();
  13882. t.join();
  13883. ASSERT_FALSE(ssl_svr1.is_running());
  13884. });
  13885. ssl_svr1.wait_until_ready();
  13886. ssl_svr2.wait_until_ready();
  13887. SSLClient cli("127.0.0.1", PORT);
  13888. std::string cert;
  13889. read_file(SERVER_CERT2_FILE, cert);
  13890. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13891. cli.enable_server_certificate_verification(true);
  13892. cli.set_follow_location(true);
  13893. cli.set_connection_timeout(30);
  13894. auto res = cli.Get("/index");
  13895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13896. ASSERT_EQ(StatusCode::OK_200, res->status);
  13897. }
  13898. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  13899. // another port, so the client follows it with a new client.
  13900. static Result GetThroughTlsRedirectToDifferentPort(
  13901. const std::function<void(SSLClient &)> &setup,
  13902. const char *target_cert = SERVER_CERT2_FILE) {
  13903. auto ssl_port = PORT + 1;
  13904. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13905. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13906. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13907. "/index");
  13908. });
  13909. SSLServer ssl_svr2(target_cert, SERVER_PRIVATE_KEY_FILE);
  13910. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13911. res.set_content("test", "text/plain");
  13912. });
  13913. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  13914. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  13915. auto se = detail::scope_exit([&] {
  13916. ssl_svr2.stop();
  13917. ssl_svr1.stop();
  13918. t2.join();
  13919. t.join();
  13920. });
  13921. ssl_svr1.wait_until_ready();
  13922. ssl_svr2.wait_until_ready();
  13923. SSLClient cli("127.0.0.1", PORT);
  13924. cli.set_follow_location(true);
  13925. cli.set_connection_timeout(30);
  13926. setup(cli);
  13927. return cli.Get("/index");
  13928. }
  13929. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  13930. auto calls = 0;
  13931. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  13932. cli.enable_server_certificate_verification(false);
  13933. // Accept the first server only.
  13934. cli.set_session_verifier([&](tls::session_t) {
  13935. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  13936. : SSLVerifierResponse::CertificateRejected;
  13937. });
  13938. });
  13939. EXPECT_FALSE(res);
  13940. EXPECT_EQ(2, calls);
  13941. }
  13942. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  13943. std::string pinned;
  13944. auto res = GetThroughTlsRedirectToDifferentPort(
  13945. [&](SSLClient &cli) {
  13946. cli.enable_server_certificate_verification(false);
  13947. // Pin the first certificate seen.
  13948. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  13949. if (pinned.empty()) { pinned = ctx.serial(); }
  13950. return ctx.serial() == pinned;
  13951. });
  13952. },
  13953. // A certificate other than the first server's.
  13954. SERVER_CERT_FILE);
  13955. EXPECT_FALSE(res);
  13956. EXPECT_FALSE(pinned.empty());
  13957. }
  13958. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  13959. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  13960. std::string cert;
  13961. read_file(SERVER_CERT2_FILE, cert);
  13962. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13963. });
  13964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13965. EXPECT_EQ(StatusCode::OK_200, res->status);
  13966. }
  13967. #endif
  13968. #ifdef CPPHTTPLIB_SSL_ENABLED
  13969. // Test that set_ca_cert_store() skips system certs (consistent with
  13970. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  13971. // should be trusted - system certs should NOT be loaded.
  13972. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  13973. // Load a specific cert that is NOT a system CA cert
  13974. std::string cert;
  13975. read_file(SERVER_CERT2_FILE, cert);
  13976. SSLClient cli("google.com");
  13977. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13978. cli.enable_server_certificate_verification(true);
  13979. // This should FAIL because:
  13980. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  13981. // 2. System certs should NOT be loaded when custom store is set
  13982. // If system certs WERE loaded, this would succeed
  13983. auto res = cli.Get("/");
  13984. ASSERT_FALSE(res);
  13985. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13986. }
  13987. // Same as above, but through the native store handle path. Regression test:
  13988. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  13989. // merged system certs into the user-provided store.
  13990. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  13991. std::string cert;
  13992. read_file(SERVER_CERT2_FILE, cert);
  13993. SSLClient cli("google.com");
  13994. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13995. cli.enable_server_certificate_verification(true);
  13996. auto res = cli.Get("/");
  13997. ASSERT_FALSE(res);
  13998. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13999. }
  14000. // A custom store set via the native handle must still verify a server whose
  14001. // cert it does contain.
  14002. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  14003. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14004. ASSERT_TRUE(svr.is_valid());
  14005. svr.Get("/test", [&](const Request &, Response &res) {
  14006. res.set_content("test", "text/plain");
  14007. });
  14008. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14009. auto se = detail::scope_exit([&] {
  14010. svr.stop();
  14011. t.join();
  14012. ASSERT_FALSE(svr.is_running());
  14013. });
  14014. svr.wait_until_ready();
  14015. SSLClient cli("127.0.0.1", PORT);
  14016. std::string cert;
  14017. read_file(SERVER_CERT2_FILE, cert);
  14018. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14019. cli.enable_server_certificate_verification(true);
  14020. cli.set_connection_timeout(30);
  14021. auto res = cli.Get("/test");
  14022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14023. ASSERT_EQ(StatusCode::OK_200, res->status);
  14024. }
  14025. // CA certs loaded through the universal Client must be transferred to the
  14026. // client created internally for following an HTTPS redirect. Regression test:
  14027. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  14028. // the CA data for redirect transfer.
  14029. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  14030. auto ssl_port = PORT + 1;
  14031. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14032. ASSERT_TRUE(ssl_svr1.is_valid());
  14033. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14034. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14035. "/index");
  14036. });
  14037. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14038. ASSERT_TRUE(ssl_svr2.is_valid());
  14039. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14040. res.set_content("test", "text/plain");
  14041. });
  14042. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14043. thread t2 =
  14044. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14045. auto se = detail::scope_exit([&] {
  14046. ssl_svr2.stop();
  14047. ssl_svr1.stop();
  14048. t2.join();
  14049. t.join();
  14050. ASSERT_FALSE(ssl_svr1.is_running());
  14051. });
  14052. ssl_svr1.wait_until_ready();
  14053. ssl_svr2.wait_until_ready();
  14054. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14055. std::string cert;
  14056. read_file(SERVER_CERT2_FILE, cert);
  14057. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14058. cli.enable_server_certificate_verification(true);
  14059. cli.set_follow_location(true);
  14060. cli.set_connection_timeout(30);
  14061. auto res = cli.Get("/index");
  14062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14063. ASSERT_EQ(StatusCode::OK_200, res->status);
  14064. }
  14065. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  14066. // so a host signed by a system CA verifies even though a custom CA is set
  14067. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  14068. std::string cert;
  14069. read_file(SERVER_CERT2_FILE, cert);
  14070. SSLClient cli("google.com");
  14071. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14072. cli.enable_system_ca(true);
  14073. cli.enable_server_certificate_verification(true);
  14074. auto res = cli.Get("/");
  14075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14076. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14077. }
  14078. // The custom CA remains effective when combined with the system CA
  14079. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  14080. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14081. ASSERT_TRUE(svr.is_valid());
  14082. svr.Get("/test", [&](const Request &, Response &res) {
  14083. res.set_content("test", "text/plain");
  14084. });
  14085. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14086. auto se = detail::scope_exit([&] {
  14087. svr.stop();
  14088. t.join();
  14089. ASSERT_FALSE(svr.is_running());
  14090. });
  14091. svr.wait_until_ready();
  14092. SSLClient cli("127.0.0.1", PORT);
  14093. std::string cert;
  14094. read_file(SERVER_CERT2_FILE, cert);
  14095. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14096. cli.enable_system_ca(true);
  14097. cli.enable_server_certificate_verification(true);
  14098. cli.set_connection_timeout(30);
  14099. auto res = cli.Get("/test");
  14100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14101. ASSERT_EQ(StatusCode::OK_200, res->status);
  14102. }
  14103. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  14104. // skip chain verification entirely (only the certificate identity was
  14105. // checked), so a server presenting an untrusted certificate with a matching
  14106. // IP SAN was accepted. The chain must be validated for IP hosts too.
  14107. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  14108. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14109. ASSERT_TRUE(svr.is_valid());
  14110. svr.Get("/test", [&](const Request &, Response &res) {
  14111. res.set_content("test", "text/plain");
  14112. });
  14113. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14114. auto se = detail::scope_exit([&] {
  14115. svr.stop();
  14116. t.join();
  14117. ASSERT_FALSE(svr.is_running());
  14118. });
  14119. svr.wait_until_ready();
  14120. SSLClient cli("127.0.0.1", PORT);
  14121. std::string cert;
  14122. // A trusted CA that did not sign the server certificate. The server cert
  14123. // (cert2) carries the matching IP SAN, so only chain validation can reject
  14124. // this connection.
  14125. read_file(CLIENT_CA_CERT_FILE, cert);
  14126. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14127. cli.enable_server_certificate_verification(true);
  14128. cli.set_connection_timeout(30);
  14129. auto res = cli.Get("/test");
  14130. ASSERT_FALSE(res);
  14131. }
  14132. // enable_system_ca(false) prevents system CA loading entirely
  14133. TEST(SSLClientTest, DisableSystemCa_Online) {
  14134. SSLClient cli("google.com");
  14135. cli.enable_system_ca(false);
  14136. cli.enable_server_certificate_verification(true);
  14137. auto res = cli.Get("/");
  14138. ASSERT_FALSE(res);
  14139. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  14140. // itself when the CA chain is empty
  14141. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  14142. res.error() == Error::SSLConnection);
  14143. }
  14144. // The universal Client forwards enable_system_ca()
  14145. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  14146. std::string cert;
  14147. read_file(SERVER_CERT2_FILE, cert);
  14148. Client cli("https://google.com");
  14149. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14150. cli.enable_system_ca(true);
  14151. cli.enable_server_certificate_verification(true);
  14152. auto res = cli.Get("/");
  14153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14154. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14155. }
  14156. // The system CA policy must carry over to the client created internally for
  14157. // following a cross-host HTTPS redirect
  14158. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  14159. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14160. ASSERT_TRUE(svr.is_valid());
  14161. svr.Get("/index", [&](const Request &, Response &res) {
  14162. res.set_redirect("https://www.google.com/");
  14163. });
  14164. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14165. auto se = detail::scope_exit([&] {
  14166. svr.stop();
  14167. t.join();
  14168. ASSERT_FALSE(svr.is_running());
  14169. });
  14170. svr.wait_until_ready();
  14171. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14172. std::string cert;
  14173. read_file(SERVER_CERT2_FILE, cert);
  14174. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14175. cli.enable_system_ca(true);
  14176. cli.enable_server_certificate_verification(true);
  14177. cli.set_follow_location(true);
  14178. cli.set_connection_timeout(30);
  14179. // Receiving any response proves the redirect client completed the TLS
  14180. // handshake with a system-CA-signed host
  14181. auto res = cli.Get("/index");
  14182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14183. }
  14184. TEST(MultipartFormDataTest, LargeData) {
  14185. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14186. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  14187. const ContentReader &content_reader) {
  14188. if (req.is_multipart_form_data()) {
  14189. std::vector<FormData> items;
  14190. content_reader(
  14191. [&](const FormData &file) {
  14192. items.push_back(file);
  14193. return true;
  14194. },
  14195. [&](const char *data, size_t data_length) {
  14196. items.back().content.append(data, data_length);
  14197. return true;
  14198. });
  14199. EXPECT_TRUE(std::string(items[0].name) == "document");
  14200. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14201. EXPECT_TRUE(items[0].filename == "2MB_data");
  14202. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14203. EXPECT_TRUE(items[1].name == "hello");
  14204. EXPECT_TRUE(items[1].content == "world");
  14205. EXPECT_TRUE(items[1].filename == "");
  14206. EXPECT_TRUE(items[1].content_type == "");
  14207. } else {
  14208. std::string body;
  14209. content_reader([&](const char *data, size_t data_length) {
  14210. body.append(data, data_length);
  14211. return true;
  14212. });
  14213. }
  14214. });
  14215. auto port = svr.bind_to_any_port(HOST);
  14216. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14217. auto se = detail::scope_exit([&] {
  14218. svr.stop();
  14219. t.join();
  14220. ASSERT_FALSE(svr.is_running());
  14221. });
  14222. svr.wait_until_ready();
  14223. {
  14224. std::string data(1024 * 1024 * 2, '.');
  14225. std::stringstream buffer;
  14226. buffer << data;
  14227. SSLClient cli(HOST, port);
  14228. cli.enable_server_certificate_verification(false);
  14229. UploadFormDataItems items{
  14230. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14231. {"hello", "world", "", ""},
  14232. };
  14233. auto res = cli.Post("/post", items);
  14234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14235. ASSERT_EQ(StatusCode::OK_200, res->status);
  14236. }
  14237. }
  14238. TEST(MultipartFormDataTest, DataProviderItems) {
  14239. std::random_device seed_gen;
  14240. std::mt19937 random(seed_gen());
  14241. std::string rand1;
  14242. rand1.resize(1000);
  14243. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  14244. std::string rand2;
  14245. rand2.resize(3000);
  14246. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  14247. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14248. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  14249. const ContentReader &content_reader) {
  14250. ASSERT_FALSE(req.is_multipart_form_data());
  14251. std::string body;
  14252. content_reader([&](const char *data, size_t data_length) {
  14253. body.append(data, data_length);
  14254. return true;
  14255. });
  14256. EXPECT_EQ(body, "");
  14257. });
  14258. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  14259. const ContentReader &content_reader) {
  14260. ASSERT_TRUE(req.is_multipart_form_data());
  14261. std::vector<FormData> items;
  14262. content_reader(
  14263. [&](const FormData &file) {
  14264. items.push_back(file);
  14265. return true;
  14266. },
  14267. [&](const char *data, size_t data_length) {
  14268. items.back().content.append(data, data_length);
  14269. return true;
  14270. });
  14271. ASSERT_TRUE(items.size() == 2);
  14272. EXPECT_EQ(std::string(items[0].name), "name1");
  14273. EXPECT_EQ(items[0].content, "Testing123");
  14274. EXPECT_EQ(items[0].filename, "filename1");
  14275. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14276. EXPECT_EQ(items[1].name, "name2");
  14277. EXPECT_EQ(items[1].content, "Testing456");
  14278. EXPECT_EQ(items[1].filename, "");
  14279. EXPECT_EQ(items[1].content_type, "");
  14280. });
  14281. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  14282. const ContentReader &content_reader) {
  14283. ASSERT_TRUE(req.is_multipart_form_data());
  14284. std::vector<FormData> items;
  14285. content_reader(
  14286. [&](const FormData &file) {
  14287. items.push_back(file);
  14288. return true;
  14289. },
  14290. [&](const char *data, size_t data_length) {
  14291. items.back().content.append(data, data_length);
  14292. return true;
  14293. });
  14294. ASSERT_TRUE(items.size() == 2);
  14295. EXPECT_EQ(items[0].name, "name3");
  14296. EXPECT_EQ(items[0].content, rand1);
  14297. EXPECT_EQ(items[0].filename, "filename3");
  14298. EXPECT_EQ(items[0].content_type, "");
  14299. EXPECT_EQ(items[1].name, "name4");
  14300. EXPECT_EQ(items[1].content, rand2);
  14301. EXPECT_EQ(items[1].filename, "filename4");
  14302. EXPECT_EQ(items[1].content_type, "");
  14303. });
  14304. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  14305. const ContentReader &content_reader) {
  14306. ASSERT_TRUE(req.is_multipart_form_data());
  14307. std::vector<FormData> items;
  14308. content_reader(
  14309. [&](const FormData &file) {
  14310. items.push_back(file);
  14311. return true;
  14312. },
  14313. [&](const char *data, size_t data_length) {
  14314. items.back().content.append(data, data_length);
  14315. return true;
  14316. });
  14317. ASSERT_TRUE(items.size() == 4);
  14318. EXPECT_EQ(std::string(items[0].name), "name1");
  14319. EXPECT_EQ(items[0].content, "Testing123");
  14320. EXPECT_EQ(items[0].filename, "filename1");
  14321. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14322. EXPECT_EQ(items[1].name, "name2");
  14323. EXPECT_EQ(items[1].content, "Testing456");
  14324. EXPECT_EQ(items[1].filename, "");
  14325. EXPECT_EQ(items[1].content_type, "");
  14326. EXPECT_EQ(items[2].name, "name3");
  14327. EXPECT_EQ(items[2].content, rand1);
  14328. EXPECT_EQ(items[2].filename, "filename3");
  14329. EXPECT_EQ(items[2].content_type, "");
  14330. EXPECT_EQ(items[3].name, "name4");
  14331. EXPECT_EQ(items[3].content, rand2);
  14332. EXPECT_EQ(items[3].filename, "filename4");
  14333. EXPECT_EQ(items[3].content_type, "");
  14334. });
  14335. auto port = svr.bind_to_any_port("localhost");
  14336. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14337. auto se = detail::scope_exit([&] {
  14338. svr.stop();
  14339. t.join();
  14340. ASSERT_FALSE(svr.is_running());
  14341. });
  14342. svr.wait_until_ready();
  14343. {
  14344. SSLClient cli("localhost", port);
  14345. cli.enable_server_certificate_verification(false);
  14346. UploadFormDataItems items{
  14347. {"name1", "Testing123", "filename1", "application/octet-stream"},
  14348. {"name2", "Testing456", "", ""}, // not a file
  14349. };
  14350. {
  14351. auto res = cli.Post("/post-none", {}, {}, {});
  14352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14353. ASSERT_EQ(StatusCode::OK_200, res->status);
  14354. }
  14355. FormDataProviderItems providers;
  14356. {
  14357. auto res =
  14358. cli.Post("/post-items", {}, items, providers); // empty providers
  14359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14360. ASSERT_EQ(StatusCode::OK_200, res->status);
  14361. }
  14362. providers.push_back({"name3",
  14363. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14364. // test the offset is given correctly at each step
  14365. if (!offset)
  14366. sink.os.write(rand1.data(), 30);
  14367. else if (offset == 30)
  14368. sink.os.write(rand1.data() + 30, 300);
  14369. else if (offset == 330)
  14370. sink.os.write(rand1.data() + 330, 670);
  14371. else if (offset == rand1.size())
  14372. sink.done();
  14373. return true;
  14374. },
  14375. "filename3",
  14376. {}});
  14377. providers.push_back({"name4",
  14378. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14379. // test the offset is given correctly at each step
  14380. if (!offset)
  14381. sink.os.write(rand2.data(), 2000);
  14382. else if (offset == 2000)
  14383. sink.os.write(rand2.data() + 2000, 1);
  14384. else if (offset == 2001)
  14385. sink.os.write(rand2.data() + 2001, 999);
  14386. else if (offset == rand2.size())
  14387. sink.done();
  14388. return true;
  14389. },
  14390. "filename4",
  14391. {}});
  14392. {
  14393. auto res = cli.Post("/post-providers", {}, {}, providers);
  14394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14395. ASSERT_EQ(StatusCode::OK_200, res->status);
  14396. }
  14397. {
  14398. auto res = cli.Post("/post-both", {}, items, providers);
  14399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14400. ASSERT_EQ(StatusCode::OK_200, res->status);
  14401. }
  14402. }
  14403. }
  14404. TEST(MultipartFormDataTest, BadHeader) {
  14405. Server svr;
  14406. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14407. res.set_content("ok", "text/plain");
  14408. });
  14409. thread t = thread([&] { svr.listen(HOST, PORT); });
  14410. auto se = detail::scope_exit([&] {
  14411. svr.stop();
  14412. t.join();
  14413. ASSERT_FALSE(svr.is_running());
  14414. });
  14415. svr.wait_until_ready();
  14416. const std::string body =
  14417. "This is the preamble. It is to be ignored, though it\r\n"
  14418. "is a handy place for composition agents to include an\r\n"
  14419. "explanatory note to non-MIME conformant readers.\r\n"
  14420. "\r\n"
  14421. "\r\n"
  14422. "--simple boundary\r\n"
  14423. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14424. ": BAD...\r\n"
  14425. "\r\n"
  14426. "value1\r\n"
  14427. "--simple boundary\r\n"
  14428. "Content-Disposition: form-data; name=\"field2\"; "
  14429. "filename=\"example.txt\"\r\n"
  14430. "\r\n"
  14431. "value2\r\n"
  14432. "--simple boundary--\r\n"
  14433. "This is the epilogue. It is also to be ignored.\r\n";
  14434. std::string content_type =
  14435. R"(multipart/form-data; boundary="simple boundary")";
  14436. Client cli(HOST, PORT);
  14437. auto res = cli.Post("/post", body, content_type.c_str());
  14438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14439. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14440. }
  14441. TEST(MultipartFormDataTest, WithPreamble) {
  14442. Server svr;
  14443. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14444. res.set_content("ok", "text/plain");
  14445. });
  14446. thread t = thread([&] { svr.listen(HOST, PORT); });
  14447. auto se = detail::scope_exit([&] {
  14448. svr.stop();
  14449. t.join();
  14450. ASSERT_FALSE(svr.is_running());
  14451. });
  14452. svr.wait_until_ready();
  14453. const std::string body =
  14454. "This is the preamble. It is to be ignored, though it\r\n"
  14455. "is a handy place for composition agents to include an\r\n"
  14456. "explanatory note to non-MIME conformant readers.\r\n"
  14457. "\r\n"
  14458. "\r\n"
  14459. "--simple boundary\r\n"
  14460. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14461. "\r\n"
  14462. "value1\r\n"
  14463. "--simple boundary\r\n"
  14464. "Content-Disposition: form-data; name=\"field2\"; "
  14465. "filename=\"example.txt\"\r\n"
  14466. "\r\n"
  14467. "value2\r\n"
  14468. "--simple boundary--\r\n"
  14469. "This is the epilogue. It is also to be ignored.\r\n";
  14470. std::string content_type =
  14471. R"(multipart/form-data; boundary="simple boundary")";
  14472. Client cli(HOST, PORT);
  14473. auto res = cli.Post("/post", body, content_type.c_str());
  14474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14475. EXPECT_EQ(StatusCode::OK_200, res->status);
  14476. }
  14477. TEST(MultipartFormDataTest, PostCustomBoundary) {
  14478. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14479. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  14480. const ContentReader &content_reader) {
  14481. if (req.is_multipart_form_data()) {
  14482. std::vector<FormData> items;
  14483. content_reader(
  14484. [&](const FormData &file) {
  14485. items.push_back(file);
  14486. return true;
  14487. },
  14488. [&](const char *data, size_t data_length) {
  14489. items.back().content.append(data, data_length);
  14490. return true;
  14491. });
  14492. EXPECT_TRUE(std::string(items[0].name) == "document");
  14493. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14494. EXPECT_TRUE(items[0].filename == "2MB_data");
  14495. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14496. EXPECT_TRUE(items[1].name == "hello");
  14497. EXPECT_TRUE(items[1].content == "world");
  14498. EXPECT_TRUE(items[1].filename == "");
  14499. EXPECT_TRUE(items[1].content_type == "");
  14500. } else {
  14501. std::string body;
  14502. content_reader([&](const char *data, size_t data_length) {
  14503. body.append(data, data_length);
  14504. return true;
  14505. });
  14506. }
  14507. });
  14508. auto port = svr.bind_to_any_port("localhost");
  14509. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14510. auto se = detail::scope_exit([&] {
  14511. svr.stop();
  14512. t.join();
  14513. ASSERT_FALSE(svr.is_running());
  14514. });
  14515. svr.wait_until_ready();
  14516. {
  14517. std::string data(1024 * 1024 * 2, '.');
  14518. std::stringstream buffer;
  14519. buffer << data;
  14520. SSLClient cli("localhost", port);
  14521. cli.enable_server_certificate_verification(false);
  14522. UploadFormDataItems items{
  14523. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14524. {"hello", "world", "", ""},
  14525. };
  14526. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  14527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14528. ASSERT_EQ(StatusCode::OK_200, res->status);
  14529. }
  14530. }
  14531. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  14532. std::string data(1024 * 1024 * 2, '&');
  14533. std::stringstream buffer;
  14534. buffer << data;
  14535. Client cli("https://localhost:8080");
  14536. UploadFormDataItems items{
  14537. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14538. {"hello", "world", "", ""},
  14539. };
  14540. for (const char &c : " \t\r\n") {
  14541. auto res =
  14542. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  14543. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14544. ASSERT_FALSE(res);
  14545. }
  14546. }
  14547. TEST(MultipartFormDataTest, PutFormData) {
  14548. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14549. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  14550. const ContentReader &content_reader) {
  14551. if (req.is_multipart_form_data()) {
  14552. std::vector<FormData> items;
  14553. content_reader(
  14554. [&](const FormData &file) {
  14555. items.push_back(file);
  14556. return true;
  14557. },
  14558. [&](const char *data, size_t data_length) {
  14559. items.back().content.append(data, data_length);
  14560. return true;
  14561. });
  14562. EXPECT_TRUE(std::string(items[0].name) == "document");
  14563. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14564. EXPECT_TRUE(items[0].filename == "2MB_data");
  14565. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14566. EXPECT_TRUE(items[1].name == "hello");
  14567. EXPECT_TRUE(items[1].content == "world");
  14568. EXPECT_TRUE(items[1].filename == "");
  14569. EXPECT_TRUE(items[1].content_type == "");
  14570. } else {
  14571. std::string body;
  14572. content_reader([&](const char *data, size_t data_length) {
  14573. body.append(data, data_length);
  14574. return true;
  14575. });
  14576. }
  14577. });
  14578. auto port = svr.bind_to_any_port("localhost");
  14579. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14580. auto se = detail::scope_exit([&] {
  14581. svr.stop();
  14582. t.join();
  14583. ASSERT_FALSE(svr.is_running());
  14584. });
  14585. svr.wait_until_ready();
  14586. {
  14587. std::string data(1024 * 1024 * 2, '&');
  14588. std::stringstream buffer;
  14589. buffer << data;
  14590. SSLClient cli("localhost", port);
  14591. cli.enable_server_certificate_verification(false);
  14592. UploadFormDataItems items{
  14593. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14594. {"hello", "world", "", ""},
  14595. };
  14596. auto res = cli.Put("/put", items);
  14597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14598. ASSERT_EQ(StatusCode::OK_200, res->status);
  14599. }
  14600. }
  14601. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  14602. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14603. svr.Put("/put_customboundary",
  14604. [&](const Request &req, const Response & /*res*/,
  14605. const ContentReader &content_reader) {
  14606. if (req.is_multipart_form_data()) {
  14607. std::vector<FormData> items;
  14608. content_reader(
  14609. [&](const FormData &file) {
  14610. items.push_back(file);
  14611. return true;
  14612. },
  14613. [&](const char *data, size_t data_length) {
  14614. items.back().content.append(data, data_length);
  14615. return true;
  14616. });
  14617. EXPECT_TRUE(std::string(items[0].name) == "document");
  14618. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14619. EXPECT_TRUE(items[0].filename == "2MB_data");
  14620. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14621. EXPECT_TRUE(items[1].name == "hello");
  14622. EXPECT_TRUE(items[1].content == "world");
  14623. EXPECT_TRUE(items[1].filename == "");
  14624. EXPECT_TRUE(items[1].content_type == "");
  14625. } else {
  14626. std::string body;
  14627. content_reader([&](const char *data, size_t data_length) {
  14628. body.append(data, data_length);
  14629. return true;
  14630. });
  14631. }
  14632. });
  14633. auto port = svr.bind_to_any_port("localhost");
  14634. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14635. auto se = detail::scope_exit([&] {
  14636. svr.stop();
  14637. t.join();
  14638. ASSERT_FALSE(svr.is_running());
  14639. });
  14640. svr.wait_until_ready();
  14641. {
  14642. std::string data(1024 * 1024 * 2, '&');
  14643. std::stringstream buffer;
  14644. buffer << data;
  14645. SSLClient cli("localhost", port);
  14646. cli.enable_server_certificate_verification(false);
  14647. UploadFormDataItems items{
  14648. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14649. {"hello", "world", "", ""},
  14650. };
  14651. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  14652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14653. ASSERT_EQ(StatusCode::OK_200, res->status);
  14654. }
  14655. }
  14656. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  14657. std::string data(1024 * 1024 * 2, '&');
  14658. std::stringstream buffer;
  14659. buffer << data;
  14660. Client cli("https://localhost:8080");
  14661. cli.enable_server_certificate_verification(false);
  14662. UploadFormDataItems items{
  14663. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14664. {"hello", "world", "", ""},
  14665. };
  14666. for (const char &c : " \t\r\n") {
  14667. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  14668. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14669. ASSERT_FALSE(res);
  14670. }
  14671. }
  14672. TEST(MultipartFormDataTest, AlternateFilename) {
  14673. auto handled = false;
  14674. Server svr;
  14675. svr.Post("/test", [&](const Request &req, Response &res) {
  14676. ASSERT_EQ(2u, req.form.files.size());
  14677. ASSERT_EQ(1u, req.form.fields.size());
  14678. // Test files
  14679. const auto &file1 = req.form.get_file("file1");
  14680. ASSERT_EQ("file1", file1.name);
  14681. ASSERT_EQ("A.txt", file1.filename);
  14682. ASSERT_EQ("text/plain", file1.content_type);
  14683. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  14684. const auto &file2 = req.form.get_file("file2");
  14685. ASSERT_EQ("file2", file2.name);
  14686. ASSERT_EQ("a.html", file2.filename);
  14687. ASSERT_EQ("text/html", file2.content_type);
  14688. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  14689. file2.content);
  14690. // Test text field
  14691. const auto &text = req.form.get_field("text");
  14692. ASSERT_EQ("text default", text);
  14693. res.set_content("ok", "text/plain");
  14694. handled = true;
  14695. });
  14696. thread t = thread([&] { svr.listen(HOST, PORT); });
  14697. auto se = detail::scope_exit([&] {
  14698. svr.stop();
  14699. t.join();
  14700. ASSERT_FALSE(svr.is_running());
  14701. ASSERT_TRUE(handled);
  14702. });
  14703. svr.wait_until_ready();
  14704. auto req = "POST /test HTTP/1.1\r\n"
  14705. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14706. "Content-Length: 399\r\n"
  14707. "\r\n"
  14708. "----------\r\n"
  14709. "Content-Disposition: form-data; name=\"text\"\r\n"
  14710. "\r\n"
  14711. "text default\r\n"
  14712. "----------\r\n"
  14713. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  14714. "filename=\"a.txt\"; name=\"file1\"\r\n"
  14715. "Content-Type: text/plain\r\n"
  14716. "\r\n"
  14717. "Content of a.txt.\r\n"
  14718. "\r\n"
  14719. "----------\r\n"
  14720. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  14721. "\"a.html\"\r\n"
  14722. "Content-Type: text/html\r\n"
  14723. "\r\n"
  14724. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  14725. "\r\n"
  14726. "------------\r\n";
  14727. ASSERT_TRUE(send_request(1, req));
  14728. }
  14729. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  14730. auto handled = false;
  14731. Server svr;
  14732. svr.Post("/test", [&](const Request &req, Response &res) {
  14733. // Case-insensitive "utf-8''" prefix with a long value
  14734. const auto &file = req.form.get_file("file1");
  14735. ASSERT_EQ("file1", file.name);
  14736. // 8000 chars exercises both the Content-Disposition parser and the
  14737. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  14738. // Prior to the fix, std::regex_match on this header would cause O(N)
  14739. // stack recursion in libstdc++, leading to SIGSEGV.
  14740. std::string expected_filename(8000, 'A');
  14741. ASSERT_EQ(expected_filename, file.filename);
  14742. res.set_content("ok", "text/plain");
  14743. handled = true;
  14744. });
  14745. thread t = thread([&] { svr.listen(HOST, PORT); });
  14746. auto se = detail::scope_exit([&] {
  14747. svr.stop();
  14748. t.join();
  14749. ASSERT_FALSE(svr.is_running());
  14750. ASSERT_TRUE(handled);
  14751. });
  14752. svr.wait_until_ready();
  14753. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  14754. // Regression test for GHSA-qq6v-r583-3h69
  14755. std::string long_filename(8000, 'A');
  14756. std::string body = "----------\r\n"
  14757. "Content-Disposition: form-data; name=\"file1\"; "
  14758. "filename*=\"Utf-8''" +
  14759. long_filename +
  14760. "\"\r\n"
  14761. "\r\n"
  14762. "hello\r\n"
  14763. "------------\r\n";
  14764. auto req = "POST /test HTTP/1.1\r\n"
  14765. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14766. "Content-Length: " +
  14767. std::to_string(body.size()) + "\r\n\r\n" + body;
  14768. ASSERT_TRUE(send_request(1, req));
  14769. }
  14770. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  14771. auto handled = false;
  14772. Server svr;
  14773. svr.Post("/test", [&](const Request &req, Response &) {
  14774. ASSERT_EQ(2u, req.form.fields.size());
  14775. const auto &text1 = req.form.get_field("text1");
  14776. ASSERT_EQ("text1", text1);
  14777. const auto &text2 = req.form.get_field("text2");
  14778. ASSERT_EQ("text2", text2);
  14779. handled = true;
  14780. });
  14781. thread t = thread([&] { svr.listen(HOST, PORT); });
  14782. auto se = detail::scope_exit([&] {
  14783. svr.stop();
  14784. t.join();
  14785. ASSERT_FALSE(svr.is_running());
  14786. ASSERT_TRUE(handled);
  14787. });
  14788. svr.wait_until_ready();
  14789. auto req = "POST /test HTTP/1.1\r\n"
  14790. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14791. "Content-Length: 146\r\n"
  14792. "\r\n----------\r\n"
  14793. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14794. "\r\n"
  14795. "text1"
  14796. "\r\n----------\r\n"
  14797. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14798. "\r\n"
  14799. "text2"
  14800. "\r\n------------";
  14801. std::string response;
  14802. ASSERT_TRUE(send_request(1, req, &response));
  14803. ASSERT_EQ("200", response.substr(9, 3));
  14804. }
  14805. TEST(MultipartFormDataTest, ContentLength) {
  14806. auto handled = false;
  14807. Server svr;
  14808. svr.Post("/test", [&](const Request &req, Response &) {
  14809. ASSERT_EQ(2u, req.form.fields.size());
  14810. const auto &text1 = req.form.get_field("text1");
  14811. ASSERT_EQ("text1", text1);
  14812. const auto &text2 = req.form.get_field("text2");
  14813. ASSERT_EQ("text2", text2);
  14814. handled = true;
  14815. });
  14816. thread t = thread([&] { svr.listen(HOST, PORT); });
  14817. auto se = detail::scope_exit([&] {
  14818. svr.stop();
  14819. t.join();
  14820. ASSERT_FALSE(svr.is_running());
  14821. ASSERT_TRUE(handled);
  14822. });
  14823. svr.wait_until_ready();
  14824. auto req = "POST /test HTTP/1.1\r\n"
  14825. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14826. "Content-Length: 167\r\n"
  14827. "\r\n----------\r\n"
  14828. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14829. "Content-Length: 5\r\n"
  14830. "\r\n"
  14831. "text1"
  14832. "\r\n----------\r\n"
  14833. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14834. "\r\n"
  14835. "text2"
  14836. "\r\n------------\r\n";
  14837. std::string response;
  14838. ASSERT_TRUE(send_request(1, req, &response));
  14839. ASSERT_EQ("200", response.substr(9, 3));
  14840. }
  14841. TEST(MultipartFormDataTest, AccessPartHeaders) {
  14842. auto handled = false;
  14843. Server svr;
  14844. svr.Post("/test", [&](const Request &req, Response &) {
  14845. ASSERT_EQ(2u, req.form.fields.size());
  14846. const auto &text1 = req.form.get_field("text1");
  14847. ASSERT_EQ("text1", text1);
  14848. // TODO: Add header access for text fields if needed
  14849. const auto &text2 = req.form.get_field("text2");
  14850. ASSERT_EQ("text2", text2);
  14851. // TODO: Header access for text fields needs to be implemented
  14852. // auto &headers = it->second.headers;
  14853. // ASSERT_EQ(3U, headers.size());
  14854. // auto custom_header = headers.find("x-whatever");
  14855. // ASSERT_TRUE(custom_header != headers.end());
  14856. // ASSERT_NE("customvalue", custom_header->second);
  14857. // ASSERT_EQ("CustomValue", custom_header->second);
  14858. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  14859. handled = true;
  14860. });
  14861. thread t = thread([&] { svr.listen(HOST, PORT); });
  14862. auto se = detail::scope_exit([&] {
  14863. svr.stop();
  14864. t.join();
  14865. ASSERT_FALSE(svr.is_running());
  14866. ASSERT_TRUE(handled);
  14867. });
  14868. svr.wait_until_ready();
  14869. auto req = "POST /test HTTP/1.1\r\n"
  14870. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14871. "Content-Length: 232\r\n"
  14872. "\r\n----------\r\n"
  14873. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14874. "Content-Length: 5\r\n"
  14875. "X-Test: 1\r\n"
  14876. "\r\n"
  14877. "text1"
  14878. "\r\n----------\r\n"
  14879. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14880. "Content-Type: text/plain\r\n"
  14881. "X-Whatever: CustomValue\r\n"
  14882. "\r\n"
  14883. "text2"
  14884. "\r\n------------\r\n"
  14885. "That should be disregarded. Not even read";
  14886. std::string response;
  14887. ASSERT_TRUE(send_request(1, req, &response));
  14888. ASSERT_EQ("200", response.substr(9, 3));
  14889. }
  14890. TEST(MultipartFormDataTest, LargeHeader) {
  14891. auto handled = false;
  14892. Server svr;
  14893. svr.Post("/test", [&](const Request &req, Response &) {
  14894. ASSERT_EQ(1u, req.form.fields.size());
  14895. const auto &text = req.form.get_field("name1");
  14896. ASSERT_EQ("text1", text);
  14897. handled = true;
  14898. });
  14899. thread t = thread([&] { svr.listen(HOST, PORT); });
  14900. auto se = detail::scope_exit([&] {
  14901. svr.stop();
  14902. t.join();
  14903. ASSERT_FALSE(svr.is_running());
  14904. ASSERT_TRUE(handled);
  14905. });
  14906. svr.wait_until_ready();
  14907. auto boundary = std::string("cpp-httplib-multipart-data");
  14908. std::string content = "--" + boundary +
  14909. "\r\n"
  14910. "Content-Disposition: form-data; name=\"name1\"\r\n"
  14911. "\r\n"
  14912. "text1\r\n"
  14913. "--" +
  14914. boundary + "--\r\n";
  14915. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  14916. "Content-Type: multipart/form-data;boundary=" +
  14917. boundary +
  14918. "\r\n"
  14919. "Content-Length: " +
  14920. std::to_string(content.size()) +
  14921. "\r\n"
  14922. "Dummy-Header: ";
  14923. std::string header_suffix = "\r\n"
  14924. "\r\n";
  14925. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  14926. size_t header_dummy_size =
  14927. read_buff_size -
  14928. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  14929. auto header_dummy = std::string(header_dummy_size, '@');
  14930. auto req = header_prefix + header_dummy + header_suffix + content;
  14931. std::string response;
  14932. ASSERT_TRUE(send_request(1, req, &response));
  14933. ASSERT_EQ("200", response.substr(9, 3));
  14934. }
  14935. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  14936. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  14937. // (not chunked Transfer-Encoding) after the streaming refactor.
  14938. auto handled = false;
  14939. Server svr;
  14940. svr.Post("/upload", [&](const Request &req, Response &res) {
  14941. auto cl_it = req.headers.find("Content-Length");
  14942. EXPECT_TRUE(cl_it != req.headers.end());
  14943. auto te_it = req.headers.find("Transfer-Encoding");
  14944. EXPECT_TRUE(te_it == req.headers.end());
  14945. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  14946. res.set_content("ok", "text/plain");
  14947. handled = true;
  14948. });
  14949. auto port = svr.bind_to_any_port(HOST);
  14950. auto t = thread([&] { svr.listen_after_bind(); });
  14951. auto se = detail::scope_exit([&] {
  14952. svr.stop();
  14953. t.join();
  14954. ASSERT_FALSE(svr.is_running());
  14955. ASSERT_TRUE(handled);
  14956. });
  14957. svr.wait_until_ready();
  14958. UploadFormDataItems items = {
  14959. {"field1", "hello", "", "text/plain"},
  14960. {"file1", "world", "test.txt", "application/octet-stream"},
  14961. };
  14962. Client cli(HOST, port);
  14963. auto res = cli.Post("/upload", {}, items);
  14964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14965. EXPECT_EQ(StatusCode::OK_200, res->status);
  14966. }
  14967. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  14968. // Verify that make_multipart_content_provider coalesces many small segments
  14969. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  14970. constexpr size_t kItemCount = 1000;
  14971. UploadFormDataItems items;
  14972. items.reserve(kItemCount);
  14973. for (size_t i = 0; i < kItemCount; i++) {
  14974. items.push_back(
  14975. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14976. }
  14977. const std::string boundary = "----test-boundary";
  14978. auto content_length = detail::get_multipart_content_length(items, boundary);
  14979. auto provider = detail::make_multipart_content_provider(items, boundary);
  14980. // Drive the provider the same way write_content_with_progress does
  14981. size_t write_count = 0;
  14982. size_t total_bytes = 0;
  14983. DataSink sink;
  14984. size_t offset = 0;
  14985. sink.write = [&](const char *d, size_t l) -> bool {
  14986. (void)d;
  14987. write_count++;
  14988. total_bytes += l;
  14989. offset += l;
  14990. return true;
  14991. };
  14992. sink.is_writable = []() -> bool { return true; };
  14993. while (offset < content_length) {
  14994. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  14995. }
  14996. EXPECT_EQ(content_length, total_bytes);
  14997. // The total number of segments is 3 * kItemCount + 1 = 3001.
  14998. // With buffering into 64KB blocks, write_count should be much smaller.
  14999. auto segment_count = 3 * kItemCount + 1;
  15000. EXPECT_LT(write_count, segment_count / 10);
  15001. }
  15002. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  15003. // Integration test: send many UploadFormDataItems and verify the server
  15004. // receives all of them correctly (#2410).
  15005. constexpr size_t kItemCount = 500;
  15006. auto handled = false;
  15007. Server svr;
  15008. svr.Post("/upload", [&](const Request &req, Response &res) {
  15009. EXPECT_EQ(kItemCount, req.form.fields.size());
  15010. for (size_t i = 0; i < kItemCount; i++) {
  15011. auto key = "field" + std::to_string(i);
  15012. auto val = "value" + std::to_string(i);
  15013. auto it = req.form.fields.find(key);
  15014. if (it != req.form.fields.end()) {
  15015. EXPECT_EQ(val, it->second.content);
  15016. } else {
  15017. ADD_FAILURE() << "Missing field: " << key;
  15018. }
  15019. }
  15020. res.set_content("ok", "text/plain");
  15021. handled = true;
  15022. });
  15023. auto port = svr.bind_to_any_port(HOST);
  15024. auto t = thread([&] { svr.listen_after_bind(); });
  15025. auto se = detail::scope_exit([&] {
  15026. svr.stop();
  15027. t.join();
  15028. ASSERT_FALSE(svr.is_running());
  15029. ASSERT_TRUE(handled);
  15030. });
  15031. svr.wait_until_ready();
  15032. UploadFormDataItems items;
  15033. items.reserve(kItemCount);
  15034. for (size_t i = 0; i < kItemCount; i++) {
  15035. items.push_back(
  15036. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15037. }
  15038. Client cli(HOST, port);
  15039. auto res = cli.Post("/upload", items);
  15040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15041. EXPECT_EQ(StatusCode::OK_200, res->status);
  15042. }
  15043. TEST(MultipartFormDataTest, MakeFileProvider) {
  15044. // Verify make_file_provider sends a file's contents correctly.
  15045. const std::string file_content(4096, 'Z');
  15046. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  15047. {
  15048. std::ofstream ofs(tmp_path, std::ios::binary);
  15049. ofs.write(file_content.data(),
  15050. static_cast<std::streamsize>(file_content.size()));
  15051. }
  15052. auto handled = false;
  15053. Server svr;
  15054. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  15055. const ContentReader &content_reader) {
  15056. ASSERT_TRUE(req.is_multipart_form_data());
  15057. std::vector<FormData> items;
  15058. content_reader(
  15059. [&](const FormData &file) {
  15060. items.push_back(file);
  15061. return true;
  15062. },
  15063. [&](const char *data, size_t data_length) {
  15064. items.back().content.append(data, data_length);
  15065. return true;
  15066. });
  15067. ASSERT_EQ(1u, items.size());
  15068. EXPECT_EQ("myfile", items[0].name);
  15069. EXPECT_EQ("data.bin", items[0].filename);
  15070. EXPECT_EQ("application/octet-stream", items[0].content_type);
  15071. EXPECT_EQ(file_content, items[0].content);
  15072. handled = true;
  15073. });
  15074. auto port = svr.bind_to_any_port(HOST);
  15075. auto t = thread([&] { svr.listen_after_bind(); });
  15076. auto se = detail::scope_exit([&] {
  15077. svr.stop();
  15078. t.join();
  15079. ASSERT_FALSE(svr.is_running());
  15080. ASSERT_TRUE(handled);
  15081. std::remove(tmp_path.c_str());
  15082. });
  15083. svr.wait_until_ready();
  15084. FormDataProviderItems providers;
  15085. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  15086. "application/octet-stream"));
  15087. Client cli(HOST, port);
  15088. auto res = cli.Post("/upload", {}, {}, providers);
  15089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15090. EXPECT_EQ(StatusCode::OK_200, res->status);
  15091. }
  15092. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  15093. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  15094. // (100) headers is rejected with a 400 Bad Request response.
  15095. Server svr;
  15096. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15097. res.set_content("ok", "text/plain");
  15098. });
  15099. thread t = thread([&] { svr.listen(HOST, PORT); });
  15100. auto se = detail::scope_exit([&] {
  15101. svr.stop();
  15102. t.join();
  15103. ASSERT_FALSE(svr.is_running());
  15104. });
  15105. svr.wait_until_ready();
  15106. // Build a multipart part with 101 custom headers (exceeding
  15107. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  15108. std::stringstream body;
  15109. body << "--simpleboundary\r\n"
  15110. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  15111. for (int i = 0; i < 101; i++) {
  15112. body << "X-Custom-Header-" << i << ": value\r\n";
  15113. }
  15114. body << "\r\n"
  15115. << "value1\r\n"
  15116. << "--simpleboundary--\r\n";
  15117. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  15118. Client cli(HOST, PORT);
  15119. auto res = cli.Post("/post", body.str(), content_type.c_str());
  15120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15121. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15122. }
  15123. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  15124. // A body that never contains the declared boundary must not be accumulated
  15125. // while the parser waits for it. Buffering it would also make every read
  15126. // rescan everything seen so far, which is quadratic in the body size.
  15127. Server svr;
  15128. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15129. res.set_content("ok", "text/plain");
  15130. });
  15131. auto port = svr.bind_to_any_port(HOST);
  15132. thread t = thread([&] { svr.listen_after_bind(); });
  15133. auto se = detail::scope_exit([&] {
  15134. svr.stop();
  15135. t.join();
  15136. ASSERT_FALSE(svr.is_running());
  15137. });
  15138. svr.wait_until_ready();
  15139. Client cli(HOST, port);
  15140. cli.set_read_timeout(60, 0);
  15141. cli.set_write_timeout(60, 0);
  15142. // '-' is the worst case: it matches the first character of the boundary, so
  15143. // every position has to be checked against it.
  15144. auto post_dashes = [&](size_t size) {
  15145. const std::string body(size, '-');
  15146. auto start = std::chrono::steady_clock::now();
  15147. auto res =
  15148. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  15149. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  15150. std::chrono::steady_clock::now() - start)
  15151. .count();
  15152. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15153. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  15154. return ms;
  15155. };
  15156. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  15157. // Windows.
  15158. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  15159. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  15160. // Comparing the two sizes rather than checking an absolute duration keeps
  15161. // this meaningful across build types and CI load, both of which move the
  15162. // absolute numbers by more than an order of magnitude. Four times the bytes
  15163. // costs about four times the time when parsing is linear, and about sixteen
  15164. // times when the body is buffered and rescanned.
  15165. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  15166. EXPECT_LT(ms_16mb, ms_4mb * 10)
  15167. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  15168. << "ms, which suggests the body is being buffered and rescanned";
  15169. }
  15170. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  15171. // A boundary can only be followed by CRLF or by "--", so anything else is
  15172. // malformed no matter what comes next. The parser must say so right away
  15173. // instead of buffering the rest of the declared body.
  15174. Server svr;
  15175. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15176. res.set_content("ok", "text/plain");
  15177. });
  15178. auto port = svr.bind_to_any_port(HOST);
  15179. thread t = thread([&] { svr.listen_after_bind(); });
  15180. auto se = detail::scope_exit([&] {
  15181. svr.stop();
  15182. t.join();
  15183. ASSERT_FALSE(svr.is_running());
  15184. });
  15185. svr.wait_until_ready();
  15186. // Announce a 1 MB body but send only the malformed prefix. A parser that
  15187. // buffers instead of failing would still be waiting for the remaining bytes.
  15188. const std::string body = "--zzzz\r\n"
  15189. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15190. "\r\n"
  15191. "text1"
  15192. "\r\n--zzzzXX";
  15193. const std::string req = "POST /post HTTP/1.1\r\n"
  15194. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15195. "Content-Length: 1048576\r\n"
  15196. "\r\n" +
  15197. body;
  15198. std::string response;
  15199. ASSERT_TRUE(send_request(3, req, &response, port));
  15200. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  15201. EXPECT_EQ("400", response.substr(9, 3));
  15202. }
  15203. // Posts a multipart body split into two writes, so that the server sees the
  15204. // split at whatever offset the caller chose, and expects the single "text1"
  15205. // field to come through.
  15206. static void expect_split_multipart_ok(const std::string &body1,
  15207. const std::string &body2) {
  15208. auto handled = false;
  15209. Server svr;
  15210. svr.Post("/post", [&](const Request &req, Response &) {
  15211. EXPECT_EQ(1u, req.form.fields.size());
  15212. EXPECT_EQ("text1", req.form.get_field("text1"));
  15213. handled = true;
  15214. });
  15215. auto port = svr.bind_to_any_port(HOST);
  15216. thread t = thread([&] { svr.listen_after_bind(); });
  15217. auto se = detail::scope_exit([&] {
  15218. svr.stop();
  15219. t.join();
  15220. ASSERT_FALSE(svr.is_running());
  15221. ASSERT_TRUE(handled);
  15222. });
  15223. svr.wait_until_ready();
  15224. // "Connection: close" makes the server close once it has answered, so the
  15225. // response drain ends immediately instead of idling until the read timeout.
  15226. const std::string head =
  15227. "POST /post HTTP/1.1\r\n"
  15228. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15229. "Connection: close\r\n"
  15230. "Content-Length: " +
  15231. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  15232. std::string response;
  15233. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  15234. ASSERT_GE(response.size(), 12u) << "no response";
  15235. EXPECT_EQ("200", response.substr(9, 3));
  15236. }
  15237. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  15238. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  15239. // ignored, including when it does not arrive in the same read as the
  15240. // close-delimiter itself.
  15241. expect_split_multipart_ok("--zzzz\r\n"
  15242. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15243. "\r\n"
  15244. "text1"
  15245. "\r\n--zzzz--",
  15246. "\r\nthis epilogue must be ignored\r\n");
  15247. }
  15248. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  15249. // The initial boundary may be preceded by a preamble of any length and may
  15250. // straddle a read boundary. Discarding data while waiting for it must not
  15251. // throw away a partial boundary sitting at the end of the buffer.
  15252. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  15253. "zz\r\n"
  15254. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15255. "\r\n"
  15256. "text1"
  15257. "\r\n--zzzz--\r\n");
  15258. }
  15259. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  15260. // The received boundary was only checked for being non-empty, so it could be
  15261. // as long as a header is allowed to be. The parser scans the body for
  15262. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  15263. // costs a nearly full comparison at nearly every position, making the
  15264. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  15265. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  15266. Server svr;
  15267. svr.Post("/post", [](const Request &req, Response &res) {
  15268. EXPECT_EQ(1u, req.form.fields.size());
  15269. EXPECT_EQ("text1", req.form.get_field("text1"));
  15270. res.set_content("ok", "text/plain");
  15271. });
  15272. auto port = svr.bind_to_any_port(HOST);
  15273. thread t = thread([&] { svr.listen_after_bind(); });
  15274. auto se = detail::scope_exit([&] {
  15275. svr.stop();
  15276. t.join();
  15277. ASSERT_FALSE(svr.is_running());
  15278. });
  15279. svr.wait_until_ready();
  15280. Client cli(HOST, port);
  15281. auto post_with_boundary_of_length = [&](size_t len) {
  15282. const std::string boundary(len, 'a');
  15283. const std::string body =
  15284. "--" + boundary +
  15285. "\r\n"
  15286. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15287. "\r\n"
  15288. "text1"
  15289. "\r\n--" +
  15290. boundary + "--\r\n";
  15291. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  15292. };
  15293. auto res = post_with_boundary_of_length(70);
  15294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15295. EXPECT_EQ(StatusCode::OK_200, res->status);
  15296. res = post_with_boundary_of_length(71);
  15297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15298. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15299. }
  15300. TEST(MakeFileBodyTest, Basic) {
  15301. const std::string file_content(4096, 'Z');
  15302. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  15303. {
  15304. std::ofstream ofs(tmp_path, std::ios::binary);
  15305. ofs.write(file_content.data(),
  15306. static_cast<std::streamsize>(file_content.size()));
  15307. }
  15308. auto handled = false;
  15309. Server svr;
  15310. svr.Post("/upload", [&](const Request &req, Response &res) {
  15311. EXPECT_EQ(file_content, req.body);
  15312. handled = true;
  15313. res.status = StatusCode::OK_200;
  15314. });
  15315. auto port = svr.bind_to_any_port(HOST);
  15316. auto t = thread([&] { svr.listen_after_bind(); });
  15317. auto se = detail::scope_exit([&] {
  15318. svr.stop();
  15319. t.join();
  15320. ASSERT_FALSE(svr.is_running());
  15321. ASSERT_TRUE(handled);
  15322. std::remove(tmp_path.c_str());
  15323. });
  15324. svr.wait_until_ready();
  15325. auto fb = make_file_body(tmp_path);
  15326. ASSERT_GT(fb.first, 0u);
  15327. Client cli(HOST, port);
  15328. auto res =
  15329. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  15330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15331. EXPECT_EQ(StatusCode::OK_200, res->status);
  15332. }
  15333. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  15334. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  15335. {
  15336. std::ofstream ofs(path, std::ios::binary);
  15337. const std::string content(100, 'A');
  15338. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15339. }
  15340. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15341. auto body = make_file_body(path);
  15342. ASSERT_EQ(100u, body.first);
  15343. ASSERT_TRUE(static_cast<bool>(body.second));
  15344. // Rewritten shorter after its length was measured - and, on a server, after
  15345. // that length has already gone out as Content-Length.
  15346. {
  15347. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  15348. const std::string content(10, 'A');
  15349. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15350. }
  15351. std::string written;
  15352. DataSink sink;
  15353. sink.write = [&](const char *d, size_t l) {
  15354. written.append(d, l);
  15355. return true;
  15356. };
  15357. // The provider has to report failure. write_content_with_progress() advances
  15358. // its offset only by what was written, so a provider that returns true
  15359. // without completing the length it promised is called again straight away,
  15360. // and again.
  15361. EXPECT_FALSE(body.second(0, body.first, sink));
  15362. EXPECT_EQ(std::string(10, 'A'), written);
  15363. }
  15364. TEST(MakeFileBodyTest, WholeFileIsSent) {
  15365. const std::string path = "./httplib_test_make_file_body_whole.bin";
  15366. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  15367. {
  15368. std::ofstream ofs(path, std::ios::binary);
  15369. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15370. }
  15371. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15372. auto body = make_file_body(path);
  15373. ASSERT_EQ(content.size(), body.first);
  15374. ASSERT_TRUE(static_cast<bool>(body.second));
  15375. std::string written;
  15376. DataSink sink;
  15377. sink.write = [&](const char *d, size_t l) {
  15378. written.append(d, l);
  15379. return true;
  15380. };
  15381. EXPECT_TRUE(body.second(0, body.first, sink));
  15382. EXPECT_EQ(content, written);
  15383. }
  15384. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  15385. static constexpr unsigned int number_of_tasks{1000000};
  15386. std::atomic_uint count{0};
  15387. std::unique_ptr<TaskQueue> task_queue{
  15388. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  15389. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15390. auto queued = task_queue->enqueue(
  15391. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  15392. EXPECT_TRUE(queued);
  15393. }
  15394. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15395. task_queue->shutdown();
  15396. #else
  15397. EXPECT_NO_THROW(task_queue->shutdown());
  15398. #endif
  15399. EXPECT_EQ(number_of_tasks, count.load());
  15400. }
  15401. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  15402. static constexpr unsigned int number_of_tasks{1000000};
  15403. static constexpr unsigned int qlimit{2};
  15404. unsigned int queued_count{0};
  15405. std::atomic_uint count{0};
  15406. std::unique_ptr<TaskQueue> task_queue{
  15407. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  15408. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15409. if (task_queue->enqueue(
  15410. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  15411. queued_count++;
  15412. }
  15413. }
  15414. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15415. task_queue->shutdown();
  15416. #else
  15417. EXPECT_NO_THROW(task_queue->shutdown());
  15418. #endif
  15419. EXPECT_EQ(queued_count, count.load());
  15420. EXPECT_TRUE(queued_count <= number_of_tasks);
  15421. EXPECT_TRUE(queued_count >= qlimit);
  15422. }
  15423. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  15424. // Use a short idle timeout so a dynamic thread spawns, times out and
  15425. // exits during the test, and the pool keeps working afterwards.
  15426. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  15427. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  15428. /*idle_timeout_sec=*/1}};
  15429. std::atomic_uint count{0};
  15430. std::condition_variable cv;
  15431. std::mutex mtx;
  15432. bool release = false;
  15433. // Block the base thread so the second task spawns a dynamic thread.
  15434. EXPECT_TRUE(task_queue->enqueue([&] {
  15435. std::unique_lock<std::mutex> lock(mtx);
  15436. while (!release) {
  15437. cv.wait(lock);
  15438. }
  15439. count++;
  15440. }));
  15441. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15442. // Let the dynamic thread finish its task and exceed the idle timeout.
  15443. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  15444. {
  15445. std::unique_lock<std::mutex> lock(mtx);
  15446. release = true;
  15447. }
  15448. cv.notify_all();
  15449. // The pool must still accept and run tasks after the dynamic thread exited.
  15450. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15451. task_queue->shutdown();
  15452. EXPECT_EQ(3u, count.load());
  15453. }
  15454. TEST(TaskQueueTest, MaxQueuedRequests) {
  15455. static constexpr unsigned int qlimit{3};
  15456. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  15457. std::condition_variable sem_cv;
  15458. std::mutex sem_mtx;
  15459. int credits = 0;
  15460. bool queued;
  15461. /* Fill up the queue with tasks that will block until we give them credits to
  15462. * complete. */
  15463. for (unsigned int n = 0; n <= qlimit;) {
  15464. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  15465. std::unique_lock<std::mutex> lock(sem_mtx);
  15466. while (credits <= 0) {
  15467. sem_cv.wait(lock);
  15468. }
  15469. /* Consume the credit and signal the test code if they are all gone. */
  15470. if (--credits == 0) { sem_cv.notify_one(); }
  15471. });
  15472. if (n < qlimit) {
  15473. /* The first qlimit enqueues must succeed. */
  15474. EXPECT_TRUE(queued);
  15475. } else {
  15476. /* The last one will succeed only when the worker thread
  15477. * starts and dequeues the first blocking task. Although
  15478. * not necessary for the correctness of this test, we sleep for
  15479. * a short while to avoid busy waiting. */
  15480. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15481. }
  15482. if (queued) { n++; }
  15483. }
  15484. /* Further enqueues must fail since the queue is full. */
  15485. for (auto i = 0; i < 4; i++) {
  15486. queued = task_queue->enqueue([] {});
  15487. EXPECT_FALSE(queued);
  15488. }
  15489. /* Give the credits to allow the previous tasks to complete. */
  15490. {
  15491. std::unique_lock<std::mutex> lock(sem_mtx);
  15492. credits += qlimit + 1;
  15493. }
  15494. sem_cv.notify_all();
  15495. /* Wait for all the credits to be consumed. */
  15496. {
  15497. std::unique_lock<std::mutex> lock(sem_mtx);
  15498. while (credits > 0) {
  15499. sem_cv.wait(lock);
  15500. }
  15501. }
  15502. /* Check that we are able again to enqueue at least qlimit tasks. */
  15503. for (unsigned int i = 0; i < qlimit; i++) {
  15504. queued = task_queue->enqueue([] {});
  15505. EXPECT_TRUE(queued);
  15506. }
  15507. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15508. task_queue->shutdown();
  15509. #else
  15510. EXPECT_NO_THROW(task_queue->shutdown());
  15511. #endif
  15512. }
  15513. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  15514. Server svr;
  15515. std::string method;
  15516. std::string body;
  15517. auto has_content_length = false;
  15518. auto has_transfer_encoding = false;
  15519. std::atomic<int> bad_requests{0};
  15520. // Leftover body bytes get parsed as a malformed request and answered with
  15521. // 400
  15522. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  15523. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  15524. });
  15525. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  15526. res.set_redirect("/down", StatusCode::SeeOther_303);
  15527. });
  15528. svr.Get("/down", [&](const Request &req, Response &res) {
  15529. method = req.method;
  15530. body = req.body;
  15531. has_content_length = req.has_header("Content-Length");
  15532. has_transfer_encoding = req.has_header("Transfer-Encoding");
  15533. res.set_content("ok", "text/plain");
  15534. });
  15535. auto port = svr.bind_to_any_port(HOST);
  15536. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15537. auto se = detail::scope_exit([&] {
  15538. svr.stop();
  15539. thread.join();
  15540. ASSERT_FALSE(svr.is_running());
  15541. });
  15542. svr.wait_until_ready();
  15543. const std::string payload = "SECRET-BODY";
  15544. auto check = [&](Client &cli, const Result &res) {
  15545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15546. EXPECT_EQ(StatusCode::OK_200, res->status);
  15547. EXPECT_EQ("ok", res->body);
  15548. EXPECT_EQ("GET", method);
  15549. EXPECT_TRUE(body.empty());
  15550. EXPECT_FALSE(has_content_length);
  15551. EXPECT_FALSE(has_transfer_encoding);
  15552. // Nothing of the original body may be left on the connection
  15553. auto res2 = cli.Get("/down");
  15554. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  15555. EXPECT_EQ(StatusCode::OK_200, res2->status);
  15556. EXPECT_EQ("ok", res2->body);
  15557. EXPECT_EQ(0, bad_requests);
  15558. };
  15559. // With content length
  15560. {
  15561. Client cli(HOST, port);
  15562. cli.set_keep_alive(true);
  15563. cli.set_follow_location(true);
  15564. auto res = cli.Post(
  15565. "/up", payload.size(),
  15566. [&](size_t offset, size_t length, DataSink &sink) {
  15567. return sink.write(payload.data() + offset, length);
  15568. },
  15569. "text/plain");
  15570. check(cli, res);
  15571. }
  15572. // Without content length (chunked)
  15573. {
  15574. Client cli(HOST, port);
  15575. cli.set_keep_alive(true);
  15576. cli.set_follow_location(true);
  15577. auto res = cli.Post(
  15578. "/up",
  15579. [&](size_t /*offset*/, DataSink &sink) {
  15580. sink.write(payload.data(), payload.size());
  15581. sink.done();
  15582. return true;
  15583. },
  15584. "text/plain");
  15585. check(cli, res);
  15586. }
  15587. }
  15588. TEST(RedirectTest, LocationPathIsNotDecoded) {
  15589. Server svr;
  15590. std::string target;
  15591. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  15592. // Echo the still-encoded name back in the Location
  15593. const std::string prefix = "/start/";
  15594. res.status = StatusCode::Found_302;
  15595. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  15596. });
  15597. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  15598. target = req.target;
  15599. res.set_content("ok", "text/plain");
  15600. });
  15601. auto port = svr.bind_to_any_port(HOST);
  15602. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15603. auto se = detail::scope_exit([&] {
  15604. svr.stop();
  15605. thread.join();
  15606. ASSERT_FALSE(svr.is_running());
  15607. });
  15608. svr.wait_until_ready();
  15609. // Decoding the Location path would turn the first four into a path
  15610. // separator, a query delimiter, a fragment delimiter and a different
  15611. // percent-encoded octet. The rest must keep reaching the server as they are.
  15612. const std::vector<std::string> names = {
  15613. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  15614. };
  15615. for (auto path_encode : {true, false}) {
  15616. Client cli(HOST, port);
  15617. cli.set_follow_location(true);
  15618. cli.set_path_encode(path_encode);
  15619. for (const auto &name : names) {
  15620. target.clear();
  15621. auto res = cli.Get("/start/" + name);
  15622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15623. EXPECT_EQ(StatusCode::OK_200, res->status);
  15624. EXPECT_EQ("/dest/" + name, target);
  15625. }
  15626. }
  15627. }
  15628. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  15629. Server svr;
  15630. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15631. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  15632. });
  15633. svr.Get("/hello", [](const Request &req, Response &res) {
  15634. res.set_content(req.get_param_value("key"), "text/plain");
  15635. });
  15636. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15637. auto se = detail::scope_exit([&] {
  15638. svr.stop();
  15639. thread.join();
  15640. ASSERT_FALSE(svr.is_running());
  15641. });
  15642. svr.wait_until_ready();
  15643. {
  15644. Client cli(HOST, PORT);
  15645. cli.set_follow_location(true);
  15646. auto res = cli.Get("/");
  15647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15648. EXPECT_EQ(StatusCode::OK_200, res->status);
  15649. EXPECT_EQ("val&key2=val2", res->body);
  15650. }
  15651. }
  15652. #endif
  15653. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  15654. Server svr;
  15655. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15656. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  15657. });
  15658. svr.Get("/hello", [](const Request &req, Response &res) {
  15659. res.set_content(req.get_param_value("key"), "text/plain");
  15660. });
  15661. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15662. auto se = detail::scope_exit([&] {
  15663. svr.stop();
  15664. thread.join();
  15665. ASSERT_FALSE(svr.is_running());
  15666. });
  15667. svr.wait_until_ready();
  15668. {
  15669. Client cli(HOST, PORT);
  15670. cli.set_follow_location(true);
  15671. auto res = cli.Get("/");
  15672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15673. EXPECT_EQ(StatusCode::OK_200, res->status);
  15674. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  15675. }
  15676. }
  15677. TEST(RedirectTest, RedirectWithPlusInPath) {
  15678. Server svr;
  15679. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15680. res.set_redirect("/a+b");
  15681. });
  15682. // Route pattern uses regex; escape + as \\+
  15683. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  15684. res.set_content(req.path, "text/plain");
  15685. });
  15686. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15687. auto se = detail::scope_exit([&] {
  15688. svr.stop();
  15689. thread.join();
  15690. ASSERT_FALSE(svr.is_running());
  15691. });
  15692. svr.wait_until_ready();
  15693. {
  15694. Client cli(HOST, PORT);
  15695. cli.set_follow_location(true);
  15696. auto res = cli.Get("/");
  15697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15698. EXPECT_EQ(StatusCode::OK_200, res->status);
  15699. EXPECT_EQ("/a+b", res->body);
  15700. }
  15701. }
  15702. TEST(RedirectTest, ResolveRelativeLocation) {
  15703. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  15704. const std::vector<std::pair<std::string, std::string>> cases = {
  15705. {"g", "/b/c/g"},
  15706. {"./g", "/b/c/g"},
  15707. {"g/", "/b/c/g/"},
  15708. {"?y", "/b/c/d;p?y"},
  15709. {"g?y", "/b/c/g?y"},
  15710. {"#s", "/b/c/d;p?q#s"},
  15711. {"g#s", "/b/c/g#s"},
  15712. {"g?y#s", "/b/c/g?y#s"},
  15713. {";x", "/b/c/;x"},
  15714. {"g;x", "/b/c/g;x"},
  15715. {".", "/b/c/"},
  15716. {"./", "/b/c/"},
  15717. {"..", "/b/"},
  15718. {"../", "/b/"},
  15719. {"../g", "/b/g"},
  15720. {"../..", "/"},
  15721. {"../../", "/"},
  15722. {"../../g", "/g"},
  15723. {"../../../g", "/g"},
  15724. {"g.", "/b/c/g."},
  15725. {".g", "/b/c/.g"},
  15726. {"g..", "/b/c/g.."},
  15727. {"..g", "/b/c/..g"},
  15728. {"./../g", "/b/g"},
  15729. {"./g/.", "/b/c/g/"},
  15730. {"g/./h", "/b/c/g/h"},
  15731. {"g/../h", "/b/c/h"},
  15732. {"g;x=1/./y", "/b/c/g;x=1/y"},
  15733. {"g;x=1/../y", "/b/c/y"},
  15734. {"g?y/./x", "/b/c/g?y/./x"},
  15735. {"g#s/../x", "/b/c/g#s/../x"},
  15736. // Not relative-path references, so left for parse_url.
  15737. {"/g", "/g"},
  15738. {"//g", "//g"},
  15739. {"http://g/x", "http://g/x"},
  15740. {"g:h", "g:h"},
  15741. };
  15742. for (const auto &c : cases) {
  15743. EXPECT_EQ(c.second,
  15744. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  15745. << c.first;
  15746. }
  15747. }
  15748. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  15749. Server svr;
  15750. svr.Get("/dir/page", [](const Request &req, Response &res) {
  15751. res.set_redirect(req.get_param_value("to"));
  15752. });
  15753. svr.Get("/dir/next", [](const Request &req, Response &res) {
  15754. res.set_content(req.target, "text/plain");
  15755. });
  15756. svr.Get("/other", [](const Request &req, Response &res) {
  15757. res.set_content(req.target, "text/plain");
  15758. });
  15759. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15760. auto se = detail::scope_exit([&] {
  15761. svr.stop();
  15762. thread.join();
  15763. ASSERT_FALSE(svr.is_running());
  15764. });
  15765. svr.wait_until_ready();
  15766. const std::vector<std::pair<std::string, std::string>> cases = {
  15767. {"next", "/dir/next"},
  15768. {"./next?x=1", "/dir/next?x=1"},
  15769. {"../other", "/other"},
  15770. };
  15771. for (const auto &c : cases) {
  15772. Client cli(HOST, PORT);
  15773. cli.set_follow_location(true);
  15774. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  15775. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  15776. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  15777. EXPECT_EQ(c.second, res->body) << c.first;
  15778. }
  15779. }
  15780. #ifdef CPPHTTPLIB_SSL_ENABLED
  15781. TEST(RedirectTest, Issue2185_Online) {
  15782. SSLClient client("github.com");
  15783. client.set_follow_location(true);
  15784. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  15785. "Coollab-Windows.zip");
  15786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15787. EXPECT_EQ(StatusCode::OK_200, res->status);
  15788. EXPECT_EQ(9920427U, res->body.size());
  15789. }
  15790. #endif
  15791. TEST(VulnerabilityTest, CRLFInjection) {
  15792. Server svr;
  15793. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  15794. res.set_content("Hello 1", "text/plain");
  15795. });
  15796. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  15797. res.set_content("Hello 2", "text/plain");
  15798. });
  15799. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  15800. res.set_content("Hello 3", "text/plain");
  15801. });
  15802. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  15803. res.set_content("Hello 4", "text/plain");
  15804. });
  15805. svr.set_logger([](const Request &req, const Response & /*res*/) {
  15806. for (const auto &x : req.headers) {
  15807. auto key = x.first;
  15808. EXPECT_STRNE("evil", key.c_str());
  15809. }
  15810. });
  15811. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15812. auto se = detail::scope_exit([&] {
  15813. svr.stop();
  15814. thread.join();
  15815. ASSERT_FALSE(svr.is_running());
  15816. });
  15817. svr.wait_until_ready();
  15818. {
  15819. Client cli(HOST, PORT);
  15820. cli.Post("/test1", "A=B",
  15821. "application/x-www-form-urlencoded\r\nevil: hello1");
  15822. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  15823. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  15824. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  15825. }
  15826. }
  15827. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  15828. auto server_thread = std::thread([] {
  15829. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15830. default_socket_options(srv);
  15831. sockaddr_in addr{};
  15832. addr.sin_family = AF_INET;
  15833. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15834. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15835. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  15836. ::listen(srv, 1);
  15837. sockaddr_in cli_addr{};
  15838. socklen_t cli_len = sizeof(cli_addr);
  15839. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15840. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  15841. std::string buf_all;
  15842. char buf[2048];
  15843. ssize_t n;
  15844. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  15845. buf_all.append(buf, static_cast<size_t>(n));
  15846. size_t pos;
  15847. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  15848. auto request_block = buf_all.substr(0, pos + 4); // include separator
  15849. auto e = request_block.find("\r\n");
  15850. if (e != std::string::npos) {
  15851. auto request_line = request_block.substr(0, e);
  15852. std::string msg =
  15853. "CRLF injection detected in request line: '" + request_line + "'";
  15854. EXPECT_FALSE(true) << msg;
  15855. }
  15856. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  15857. ::send(cli,
  15858. #ifdef _WIN32
  15859. static_cast<const char *>(resp.c_str()),
  15860. static_cast<int>(resp.size()),
  15861. #else
  15862. resp.c_str(), resp.size(),
  15863. #endif
  15864. 0);
  15865. buf_all.erase(0, pos + 4);
  15866. }
  15867. }
  15868. detail::close_socket(cli);
  15869. detail::close_socket(srv);
  15870. });
  15871. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15872. auto cli = Client("127.0.0.1", PORT + 1);
  15873. auto headers = Headers{
  15874. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  15875. {"Connection", "keep-alive"}};
  15876. auto res = cli.Get("/hi", headers);
  15877. EXPECT_FALSE(res);
  15878. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15879. server_thread.join();
  15880. }
  15881. // A request rejected before any byte reaches the socket must fail right away
  15882. // instead of waiting for a response the server will never send.
  15883. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  15884. // The kernel completes the TCP handshake from the listen backlog, so the
  15885. // client connects, but nothing ever reads, responds or closes.
  15886. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15887. default_socket_options(srv);
  15888. sockaddr_in addr{};
  15889. addr.sin_family = AF_INET;
  15890. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15891. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15892. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15893. ASSERT_EQ(0, ::listen(srv, 8));
  15894. auto cli = Client("127.0.0.1", PORT + 1);
  15895. cli.set_read_timeout(10, 0);
  15896. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  15897. return std::chrono::duration_cast<std::chrono::milliseconds>(
  15898. std::chrono::steady_clock::now() - start)
  15899. .count();
  15900. };
  15901. {
  15902. Request req;
  15903. req.method = "GE T";
  15904. req.path = "/";
  15905. auto start = std::chrono::steady_clock::now();
  15906. auto res = cli.send(req);
  15907. EXPECT_FALSE(res);
  15908. EXPECT_EQ(Error::Write, res.error());
  15909. EXPECT_LT(elapsed_ms(start), 1000);
  15910. }
  15911. {
  15912. auto start = std::chrono::steady_clock::now();
  15913. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  15914. EXPECT_FALSE(res);
  15915. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15916. EXPECT_LT(elapsed_ms(start), 1000);
  15917. }
  15918. EXPECT_FALSE(cli.is_socket_open());
  15919. detail::close_socket(srv);
  15920. }
  15921. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  15922. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15923. default_socket_options(srv);
  15924. sockaddr_in addr{};
  15925. addr.sin_family = AF_INET;
  15926. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15927. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15928. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15929. ASSERT_EQ(0, ::listen(srv, 1));
  15930. std::string received;
  15931. auto server_thread = std::thread([&] {
  15932. auto sock = ::accept(srv, nullptr, nullptr);
  15933. if (sock == INVALID_SOCKET) { return; }
  15934. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  15935. char buf[2048];
  15936. ssize_t n;
  15937. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  15938. received.append(buf, static_cast<size_t>(n));
  15939. }
  15940. detail::close_socket(sock);
  15941. });
  15942. {
  15943. auto cli = Client("127.0.0.1", PORT + 1);
  15944. // "Z" sorts after the default headers, so writing straight to the socket
  15945. // would have sent the request line and those headers before the rejection.
  15946. auto handle =
  15947. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  15948. EXPECT_FALSE(handle.is_valid());
  15949. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  15950. }
  15951. server_thread.join();
  15952. detail::close_socket(srv);
  15953. EXPECT_TRUE(received.empty()) << received;
  15954. }
  15955. TEST(PathParamsTest, StaticMatch) {
  15956. const auto pattern = "/users/all";
  15957. detail::PathParamsMatcher matcher(pattern);
  15958. Request request;
  15959. request.path = "/users/all";
  15960. ASSERT_TRUE(matcher.match(request));
  15961. std::unordered_map<std::string, std::string> expected_params = {};
  15962. EXPECT_EQ(request.path_params, expected_params);
  15963. }
  15964. TEST(PathParamsTest, StaticMismatch) {
  15965. const auto pattern = "/users/all";
  15966. detail::PathParamsMatcher matcher(pattern);
  15967. Request request;
  15968. request.path = "/users/1";
  15969. ASSERT_FALSE(matcher.match(request));
  15970. }
  15971. TEST(PathParamsTest, SingleParamInTheMiddle) {
  15972. const auto pattern = "/users/:id/subscriptions";
  15973. detail::PathParamsMatcher matcher(pattern);
  15974. Request request;
  15975. request.path = "/users/42/subscriptions";
  15976. ASSERT_TRUE(matcher.match(request));
  15977. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15978. EXPECT_EQ(request.path_params, expected_params);
  15979. }
  15980. TEST(PathParamsTest, SingleParamInTheEnd) {
  15981. const auto pattern = "/users/:id";
  15982. detail::PathParamsMatcher matcher(pattern);
  15983. Request request;
  15984. request.path = "/users/24";
  15985. ASSERT_TRUE(matcher.match(request));
  15986. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  15987. EXPECT_EQ(request.path_params, expected_params);
  15988. }
  15989. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  15990. const auto pattern = "/users/:id/";
  15991. detail::PathParamsMatcher matcher(pattern);
  15992. Request request;
  15993. request.path = "/users/42/";
  15994. ASSERT_TRUE(matcher.match(request));
  15995. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15996. EXPECT_EQ(request.path_params, expected_params);
  15997. }
  15998. TEST(PathParamsTest, EmptyParam) {
  15999. const auto pattern = "/users/:id/";
  16000. detail::PathParamsMatcher matcher(pattern);
  16001. Request request;
  16002. request.path = "/users//";
  16003. ASSERT_TRUE(matcher.match(request));
  16004. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  16005. EXPECT_EQ(request.path_params, expected_params);
  16006. }
  16007. TEST(PathParamsTest, FragmentMismatch) {
  16008. const auto pattern = "/users/:id/";
  16009. detail::PathParamsMatcher matcher(pattern);
  16010. Request request;
  16011. request.path = "/admins/24/";
  16012. ASSERT_FALSE(matcher.match(request));
  16013. }
  16014. TEST(PathParamsTest, ExtraFragments) {
  16015. const auto pattern = "/users/:id";
  16016. detail::PathParamsMatcher matcher(pattern);
  16017. Request request;
  16018. request.path = "/users/42/subscriptions";
  16019. ASSERT_FALSE(matcher.match(request));
  16020. }
  16021. TEST(PathParamsTest, MissingTrailingParam) {
  16022. const auto pattern = "/users/:id";
  16023. detail::PathParamsMatcher matcher(pattern);
  16024. Request request;
  16025. request.path = "/users";
  16026. ASSERT_FALSE(matcher.match(request));
  16027. }
  16028. TEST(PathParamsTest, MissingParamInTheMiddle) {
  16029. const auto pattern = "/users/:id/subscriptions";
  16030. detail::PathParamsMatcher matcher(pattern);
  16031. Request request;
  16032. request.path = "/users/subscriptions";
  16033. ASSERT_FALSE(matcher.match(request));
  16034. }
  16035. TEST(PathParamsTest, MultipleParams) {
  16036. const auto pattern = "/users/:userid/subscriptions/:subid";
  16037. detail::PathParamsMatcher matcher(pattern);
  16038. Request request;
  16039. request.path = "/users/42/subscriptions/2";
  16040. ASSERT_TRUE(matcher.match(request));
  16041. std::unordered_map<std::string, std::string> expected_params = {
  16042. {"userid", "42"}, {"subid", "2"}};
  16043. EXPECT_EQ(request.path_params, expected_params);
  16044. }
  16045. TEST(PathParamsTest, SequenceOfParams) {
  16046. const auto pattern = "/values/:x/:y/:z";
  16047. detail::PathParamsMatcher matcher(pattern);
  16048. Request request;
  16049. request.path = "/values/1/2/3";
  16050. ASSERT_TRUE(matcher.match(request));
  16051. std::unordered_map<std::string, std::string> expected_params = {
  16052. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  16053. EXPECT_EQ(request.path_params, expected_params);
  16054. }
  16055. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  16056. const auto pattern = "/prefix:suffix";
  16057. detail::PathParamsMatcher matcher(pattern);
  16058. Request request;
  16059. request.path = "/prefix:suffix";
  16060. ASSERT_TRUE(matcher.match(request));
  16061. const std::unordered_map<std::string, std::string> expected_params = {};
  16062. EXPECT_EQ(request.path_params, expected_params);
  16063. }
  16064. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  16065. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  16066. // calling thread's stack on a long enough path for a quantified pattern;
  16067. // RegexMatcher must refuse to run regex matching on paths beyond
  16068. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  16069. detail::RegexMatcher matcher("/files/(.*)");
  16070. Request within_limit;
  16071. within_limit.path = "/files/" + std::string(10, 'A');
  16072. EXPECT_TRUE(matcher.match(within_limit));
  16073. Request over_limit;
  16074. over_limit.path =
  16075. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  16076. EXPECT_FALSE(matcher.match(over_limit));
  16077. }
  16078. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  16079. Server svr;
  16080. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  16081. res.set_content("ok", "text/plain");
  16082. });
  16083. auto port = svr.bind_to_any_port(HOST);
  16084. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16085. auto se = detail::scope_exit([&] {
  16086. svr.stop();
  16087. thread.join();
  16088. ASSERT_FALSE(svr.is_running());
  16089. });
  16090. svr.wait_until_ready();
  16091. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  16092. // request URI limit; this used to be able to crash the process.
  16093. std::string path =
  16094. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  16095. std::string req = "GET " + path +
  16096. " HTTP/1.1\r\n"
  16097. "Host: " +
  16098. std::string(HOST) + ":" + std::to_string(port) +
  16099. "\r\n"
  16100. "Connection: close\r\n"
  16101. "\r\n";
  16102. std::string response;
  16103. ASSERT_TRUE(send_request(5, req, &response, port));
  16104. EXPECT_NE(std::string::npos, response.find("404"));
  16105. }
  16106. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  16107. Server svr;
  16108. auto handler = [](const Request & /*req*/, Response &res) {
  16109. res.set_content("hit", "text/plain");
  16110. };
  16111. // No regex metacharacter, so this one is compared literally
  16112. svr.Get("/literal/route", handler);
  16113. // '.' is a regex metacharacter, so this one must keep regex semantics
  16114. svr.Get("/a.c", handler);
  16115. auto port = svr.bind_to_any_port(HOST);
  16116. std::thread t([&]() { svr.listen_after_bind(); });
  16117. auto se = detail::scope_exit([&] {
  16118. svr.stop();
  16119. t.join();
  16120. ASSERT_FALSE(svr.is_running());
  16121. });
  16122. svr.wait_until_ready();
  16123. Client cli(HOST, port);
  16124. struct {
  16125. const char *path;
  16126. int status;
  16127. } cases[] = {
  16128. {"/literal/route", StatusCode::OK_200},
  16129. {"/literal/routes", StatusCode::NotFound_404},
  16130. {"/literal/rout", StatusCode::NotFound_404},
  16131. {"/abc", StatusCode::OK_200},
  16132. {"/a.c", StatusCode::OK_200},
  16133. };
  16134. for (const auto &x : cases) {
  16135. auto res = cli.Get(x.path);
  16136. ASSERT_TRUE(res) << x.path;
  16137. EXPECT_EQ(x.status, res->status) << x.path;
  16138. }
  16139. }
  16140. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  16141. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  16142. // from exhausting the stack, so it must only constrain routes that actually
  16143. // run a regular expression. A literal route is matched by comparison and
  16144. // stays usable at any length.
  16145. Server svr;
  16146. const std::string pattern =
  16147. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  16148. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  16149. res.set_content("hit", "text/plain");
  16150. });
  16151. auto port = svr.bind_to_any_port(HOST);
  16152. std::thread t([&]() { svr.listen_after_bind(); });
  16153. auto se = detail::scope_exit([&] {
  16154. svr.stop();
  16155. t.join();
  16156. ASSERT_FALSE(svr.is_running());
  16157. });
  16158. svr.wait_until_ready();
  16159. Client cli(HOST, port);
  16160. auto res = cli.Get(pattern);
  16161. ASSERT_TRUE(res);
  16162. EXPECT_EQ(StatusCode::OK_200, res->status);
  16163. }
  16164. TEST(ParseUrlTest, VariousPatterns) {
  16165. {
  16166. detail::UrlComponents uc;
  16167. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  16168. EXPECT_EQ("http", uc.scheme);
  16169. EXPECT_EQ("example.com", uc.host);
  16170. EXPECT_EQ("8080", uc.port);
  16171. EXPECT_EQ("/path", uc.path);
  16172. EXPECT_EQ("?q=1", uc.query);
  16173. }
  16174. {
  16175. detail::UrlComponents uc;
  16176. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  16177. EXPECT_EQ("https", uc.scheme);
  16178. EXPECT_EQ("example.com", uc.host);
  16179. EXPECT_TRUE(uc.port.empty());
  16180. EXPECT_EQ("/path", uc.path);
  16181. }
  16182. {
  16183. detail::UrlComponents uc;
  16184. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  16185. EXPECT_EQ("::1", uc.host);
  16186. EXPECT_EQ("8080", uc.port);
  16187. EXPECT_EQ("/path", uc.path);
  16188. }
  16189. {
  16190. detail::UrlComponents uc;
  16191. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  16192. }
  16193. {
  16194. // Bytes after the IPv6 literal must be a delimiter, not folded into
  16195. // the path while the connection still targets the bracketed host.
  16196. detail::UrlComponents uc;
  16197. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  16198. }
  16199. {
  16200. detail::UrlComponents uc;
  16201. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  16202. }
  16203. {
  16204. detail::UrlComponents uc;
  16205. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  16206. EXPECT_EQ("::1", uc.host);
  16207. EXPECT_TRUE(uc.port.empty());
  16208. EXPECT_EQ("/path", uc.path);
  16209. }
  16210. {
  16211. detail::UrlComponents uc;
  16212. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  16213. EXPECT_TRUE(uc.scheme.empty());
  16214. EXPECT_EQ("example.com", uc.host);
  16215. EXPECT_EQ("/path", uc.path);
  16216. EXPECT_EQ("?q=1", uc.query);
  16217. }
  16218. {
  16219. detail::UrlComponents uc;
  16220. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  16221. EXPECT_TRUE(uc.host.empty());
  16222. EXPECT_EQ("/path", uc.path);
  16223. EXPECT_EQ("?q=1", uc.query);
  16224. }
  16225. {
  16226. detail::UrlComponents uc;
  16227. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  16228. EXPECT_EQ("example.com", uc.host);
  16229. EXPECT_EQ("8080", uc.port);
  16230. }
  16231. {
  16232. // Unix socket path — must not be parsed as host
  16233. detail::UrlComponents uc;
  16234. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  16235. EXPECT_TRUE(uc.host.empty());
  16236. }
  16237. {
  16238. detail::UrlComponents uc;
  16239. ASSERT_TRUE(detail::parse_url("", uc));
  16240. EXPECT_TRUE(uc.host.empty());
  16241. EXPECT_TRUE(uc.path.empty());
  16242. }
  16243. {
  16244. detail::UrlComponents uc;
  16245. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  16246. }
  16247. {
  16248. detail::UrlComponents uc;
  16249. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  16250. }
  16251. {
  16252. // Accepted by parse_url; callers restrict to http/https
  16253. detail::UrlComponents uc;
  16254. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  16255. EXPECT_EQ("ftp", uc.scheme);
  16256. }
  16257. {
  16258. detail::UrlComponents uc;
  16259. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  16260. }
  16261. {
  16262. detail::UrlComponents uc;
  16263. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  16264. }
  16265. }
  16266. TEST(ParseUrlTest, FragmentHandling) {
  16267. {
  16268. detail::UrlComponents uc;
  16269. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  16270. EXPECT_EQ("/path", uc.path);
  16271. EXPECT_TRUE(uc.query.empty());
  16272. }
  16273. {
  16274. detail::UrlComponents uc;
  16275. ASSERT_TRUE(detail::parse_url("#frag", uc));
  16276. EXPECT_TRUE(uc.path.empty());
  16277. EXPECT_TRUE(uc.query.empty());
  16278. }
  16279. }
  16280. TEST(ParseUrlTest, UserinfoHandling) {
  16281. // Userinfo with @ but no colon — host includes @
  16282. detail::UrlComponents uc;
  16283. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  16284. EXPECT_EQ("user@host.com", uc.host);
  16285. EXPECT_EQ("/path", uc.path);
  16286. }
  16287. TEST(ParseUrlTest, IPv6EdgeCases) {
  16288. {
  16289. detail::UrlComponents uc;
  16290. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  16291. EXPECT_TRUE(uc.scheme.empty());
  16292. EXPECT_EQ("::1", uc.host);
  16293. EXPECT_EQ("8080", uc.port);
  16294. }
  16295. {
  16296. // Zone ID '%25' is not in [a-fA-F0-9:]
  16297. detail::UrlComponents uc;
  16298. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  16299. }
  16300. }
  16301. TEST(ParseUrlTest, SchemeEdgeCases) {
  16302. {
  16303. detail::UrlComponents uc;
  16304. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  16305. }
  16306. {
  16307. detail::UrlComponents uc;
  16308. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  16309. }
  16310. {
  16311. detail::UrlComponents uc;
  16312. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  16313. }
  16314. }
  16315. TEST(ParseUrlTest, PortEdgeCases) {
  16316. {
  16317. detail::UrlComponents uc;
  16318. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  16319. EXPECT_TRUE(uc.port.empty());
  16320. EXPECT_EQ("/path", uc.path);
  16321. }
  16322. {
  16323. // parse_url accepts any port string; validation is done by parse_port
  16324. detail::UrlComponents uc;
  16325. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  16326. EXPECT_EQ("abc", uc.port);
  16327. }
  16328. }
  16329. TEST(ParseUrlTest, WebSocketPatterns) {
  16330. {
  16331. detail::UrlComponents uc;
  16332. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  16333. EXPECT_EQ("ws", uc.scheme);
  16334. EXPECT_EQ("echo.example.com", uc.host);
  16335. EXPECT_EQ("8080", uc.port);
  16336. EXPECT_EQ("/ws", uc.path);
  16337. }
  16338. {
  16339. detail::UrlComponents uc;
  16340. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  16341. EXPECT_EQ("wss", uc.scheme);
  16342. EXPECT_EQ("echo.example.com", uc.host);
  16343. EXPECT_TRUE(uc.port.empty());
  16344. EXPECT_EQ("/ws", uc.path);
  16345. }
  16346. }
  16347. TEST(ParseUrlTest, QueryOnly) {
  16348. detail::UrlComponents uc;
  16349. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  16350. EXPECT_TRUE(uc.host.empty());
  16351. EXPECT_TRUE(uc.path.empty());
  16352. EXPECT_EQ("?q=1&r=2", uc.query);
  16353. }
  16354. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  16355. detail::UrlComponents uc;
  16356. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  16357. EXPECT_TRUE(uc.scheme.empty());
  16358. EXPECT_EQ("example.com", uc.host);
  16359. EXPECT_EQ("443", uc.port);
  16360. EXPECT_EQ("/path", uc.path);
  16361. }
  16362. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  16363. // If ipv6 regex working, regex match codepath is taken.
  16364. // else port will default to 80 in Client impl
  16365. int clientImplMagicPort = 80;
  16366. int port = 4321;
  16367. // above ports must be different to avoid false negative
  16368. EXPECT_NE(clientImplMagicPort, port);
  16369. std::string ipV6TestURL = "http://[ff06::c3]";
  16370. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  16371. CLIENT_PRIVATE_KEY_FILE);
  16372. EXPECT_EQ(cli.port(), port);
  16373. }
  16374. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  16375. auto file_path = "./www/dir/index.html";
  16376. auto dir_path = "./www/dir";
  16377. detail::FileStat stat_file(file_path);
  16378. EXPECT_TRUE(stat_file.is_file());
  16379. EXPECT_FALSE(stat_file.is_dir());
  16380. detail::FileStat stat_dir(dir_path);
  16381. EXPECT_FALSE(stat_dir.is_file());
  16382. EXPECT_TRUE(stat_dir.is_dir());
  16383. }
  16384. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  16385. // IPv4 with default HTTP port (80)
  16386. EXPECT_EQ("example.com",
  16387. detail::make_host_and_port_string("example.com", 80, false));
  16388. // IPv4 with default HTTPS port (443)
  16389. EXPECT_EQ("example.com",
  16390. detail::make_host_and_port_string("example.com", 443, true));
  16391. // IPv4 with non-default HTTP port
  16392. EXPECT_EQ("example.com:8080",
  16393. detail::make_host_and_port_string("example.com", 8080, false));
  16394. // IPv4 with non-default HTTPS port
  16395. EXPECT_EQ("example.com:8443",
  16396. detail::make_host_and_port_string("example.com", 8443, true));
  16397. // IPv6 with default HTTP port (80)
  16398. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  16399. // IPv6 with default HTTPS port (443)
  16400. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  16401. // IPv6 with non-default HTTP port
  16402. EXPECT_EQ("[::1]:8080",
  16403. detail::make_host_and_port_string("::1", 8080, false));
  16404. // IPv6 with non-default HTTPS port
  16405. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  16406. // IPv6 full address with default port
  16407. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  16408. detail::make_host_and_port_string(
  16409. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  16410. // IPv6 full address with non-default port
  16411. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  16412. detail::make_host_and_port_string(
  16413. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  16414. // IPv6 localhost with non-default port
  16415. EXPECT_EQ("[::1]:3000",
  16416. detail::make_host_and_port_string("::1", 3000, false));
  16417. // IPv6 with zone ID (link-local address) with default port
  16418. EXPECT_EQ("[fe80::1%eth0]",
  16419. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  16420. // IPv6 with zone ID (link-local address) with non-default port
  16421. EXPECT_EQ("[fe80::1%eth0]:8080",
  16422. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  16423. // Edge case: Port 443 with is_ssl=false (should add port)
  16424. EXPECT_EQ("example.com:443",
  16425. detail::make_host_and_port_string("example.com", 443, false));
  16426. // Edge case: Port 80 with is_ssl=true (should add port)
  16427. EXPECT_EQ("example.com:80",
  16428. detail::make_host_and_port_string("example.com", 80, true));
  16429. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  16430. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  16431. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  16432. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  16433. // Security fix: Already bracketed IPv6 should not get double brackets
  16434. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  16435. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  16436. EXPECT_EQ("[::1]:8080",
  16437. detail::make_host_and_port_string("[::1]", 8080, false));
  16438. EXPECT_EQ("[2001:db8::1]:8080",
  16439. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  16440. EXPECT_EQ("[fe80::1%eth0]",
  16441. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  16442. EXPECT_EQ("[fe80::1%eth0]:8080",
  16443. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  16444. // Edge case: Empty host (should return as-is)
  16445. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  16446. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  16447. // This is a known limitation but shouldn't crash
  16448. EXPECT_EQ("[host:name]",
  16449. detail::make_host_and_port_string("host:name", 80, false));
  16450. // Port number edge cases (no validation, but should not crash)
  16451. EXPECT_EQ("example.com:0",
  16452. detail::make_host_and_port_string("example.com", 0, false));
  16453. EXPECT_EQ("example.com:-1",
  16454. detail::make_host_and_port_string("example.com", -1, false));
  16455. EXPECT_EQ("example.com:65535",
  16456. detail::make_host_and_port_string("example.com", 65535, false));
  16457. EXPECT_EQ("example.com:65536",
  16458. detail::make_host_and_port_string("example.com", 65536, false));
  16459. }
  16460. #ifdef CPPHTTPLIB_SSL_ENABLED
  16461. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  16462. httplib::SSLClient cli("roblox.com", 443);
  16463. cli.set_follow_location(true);
  16464. auto res = cli.Get("/");
  16465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16466. EXPECT_EQ(StatusCode::OK_200, res->status);
  16467. }
  16468. #endif
  16469. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  16470. Server svr;
  16471. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16472. EXPECT_EQ(res.status, 400);
  16473. });
  16474. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16475. auto se = detail::scope_exit([&] {
  16476. svr.stop();
  16477. thread.join();
  16478. ASSERT_FALSE(svr.is_running());
  16479. });
  16480. svr.wait_until_ready();
  16481. Client cli(HOST, PORT);
  16482. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  16483. }
  16484. TEST(InvalidHeaderCharsTest, is_field_name) {
  16485. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  16486. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  16487. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  16488. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  16489. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  16490. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  16491. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  16492. EXPECT_FALSE(detail::fields::is_field_name(""));
  16493. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  16494. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  16495. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  16496. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  16497. }
  16498. TEST(InvalidHeaderCharsTest, is_field_value) {
  16499. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  16500. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  16501. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  16502. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  16503. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  16504. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  16505. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  16506. EXPECT_TRUE(detail::fields::is_field_value(""));
  16507. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  16508. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  16509. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  16510. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  16511. EXPECT_TRUE(detail::fields::is_field_value("0"));
  16512. }
  16513. TEST(InvalidHeaderCharsTest, OnServer) {
  16514. Server svr;
  16515. svr.Get("/test_name", [&](const Request &req, Response &res) {
  16516. std::string header = "Not Set";
  16517. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16518. res.set_header(header, "value");
  16519. res.set_content("Page Content Page Content", "text/plain");
  16520. });
  16521. svr.Get("/test_value", [&](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("X-Test", header);
  16525. res.set_content("Page Content Page Content", "text/plain");
  16526. });
  16527. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16528. auto se = detail::scope_exit([&] {
  16529. svr.stop();
  16530. thread.join();
  16531. ASSERT_FALSE(svr.is_running());
  16532. });
  16533. svr.wait_until_ready();
  16534. Client cli(HOST, PORT);
  16535. {
  16536. auto res = cli.Get(
  16537. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16539. EXPECT_EQ("Page Content Page Content", res->body);
  16540. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16541. }
  16542. {
  16543. auto res = cli.Get(
  16544. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16546. EXPECT_EQ("Page Content Page Content", res->body);
  16547. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16548. }
  16549. }
  16550. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  16551. auto handled = false;
  16552. Server svr;
  16553. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16554. thread t = thread([&] { svr.listen(HOST, PORT); });
  16555. auto se = detail::scope_exit([&] {
  16556. svr.stop();
  16557. t.join();
  16558. ASSERT_FALSE(svr.is_running());
  16559. ASSERT_FALSE(handled);
  16560. });
  16561. svr.wait_until_ready();
  16562. auto req = "POST /test HTTP/1.1\r\n"
  16563. "Content-Length: x\r\n"
  16564. "\r\n";
  16565. std::string response;
  16566. ASSERT_TRUE(send_request(1, req, &response));
  16567. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16568. response.substr(0, response.find("\r\n")));
  16569. }
  16570. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  16571. // case-insensitive, and a server that receives a 100-continue expectation in
  16572. // an HTTP/1.0 request MUST ignore it.
  16573. static void probe_expect(int port, const std::string &req, bool *got_100) {
  16574. std::string response;
  16575. ASSERT_TRUE(send_request(1, req, &response, port));
  16576. *got_100 = response.find("100 Continue") != std::string::npos;
  16577. }
  16578. class ExpectTokenTest : public ::testing::Test {
  16579. protected:
  16580. void SetUp() override {
  16581. svr_.Post("/p", [](const Request &, Response &res) {
  16582. res.set_content("ok", "text/plain");
  16583. });
  16584. port_ = svr_.bind_to_any_port(HOST);
  16585. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16586. svr_.wait_until_ready();
  16587. }
  16588. void TearDown() override {
  16589. svr_.stop();
  16590. if (thread_.joinable()) { thread_.join(); }
  16591. }
  16592. std::string request(const char *version, const char *expect_value) const {
  16593. return std::string("POST /p ") + version +
  16594. "\r\n"
  16595. "Host: localhost\r\n"
  16596. "Content-Length: 2\r\n"
  16597. "Connection: close\r\n"
  16598. "Expect: " +
  16599. expect_value +
  16600. "\r\n"
  16601. "\r\n"
  16602. "hi";
  16603. }
  16604. Server svr_;
  16605. int port_ = 0;
  16606. thread thread_;
  16607. };
  16608. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  16609. bool got_100 = false;
  16610. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  16611. EXPECT_TRUE(got_100);
  16612. }
  16613. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  16614. bool got_100 = true;
  16615. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  16616. EXPECT_FALSE(got_100);
  16617. }
  16618. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  16619. bool got_100 = false;
  16620. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  16621. EXPECT_TRUE(got_100);
  16622. }
  16623. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  16624. bool got_100 = false;
  16625. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  16626. EXPECT_TRUE(got_100);
  16627. }
  16628. // `100 Continue` is sent only when the server starts reading the body, so a
  16629. // request rejected before that never invites the client to send it. The
  16630. // requests below carry the expectation but withhold the body, as a client
  16631. // waiting for `100 Continue` would.
  16632. // A POST that expects `100 Continue` and withholds its two-byte body.
  16633. static std::string expect_headers_only(const std::string &path) {
  16634. return "POST " + path +
  16635. " HTTP/1.1\r\n"
  16636. "Host: localhost\r\n"
  16637. "Content-Length: 2\r\n"
  16638. "Expect: 100-continue\r\n"
  16639. "\r\n";
  16640. }
  16641. class ExpectLazyContinueTest : public ::testing::Test {
  16642. protected:
  16643. void SetUp() override {
  16644. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  16645. if (req.path == "/pre-routing") {
  16646. res.status = StatusCode::Unauthorized_401;
  16647. return Server::HandlerResponse::Handled;
  16648. }
  16649. return Server::HandlerResponse::Unhandled;
  16650. });
  16651. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  16652. if (req.matched_route == "/pre-request") {
  16653. res.status = StatusCode::Forbidden_403;
  16654. return Server::HandlerResponse::Handled;
  16655. }
  16656. return Server::HandlerResponse::Unhandled;
  16657. });
  16658. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  16659. res.set_content("ok", "text/plain");
  16660. });
  16661. svr_.Post("/pre-request", [](const Request &, Response &res) {
  16662. res.set_content("ok", "text/plain");
  16663. });
  16664. svr_.Post("/reader-used", [](const Request &, Response &res,
  16665. const ContentReader &content_reader) {
  16666. std::string body;
  16667. content_reader([&](const char *data, size_t len) {
  16668. body.append(data, len);
  16669. return true;
  16670. });
  16671. res.set_content(body, "text/plain");
  16672. });
  16673. svr_.Post("/reader-unused",
  16674. [](const Request &, Response &res, const ContentReader &) {
  16675. res.set_content("ignored", "text/plain");
  16676. });
  16677. port_ = svr_.bind_to_any_port(HOST);
  16678. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16679. svr_.wait_until_ready();
  16680. }
  16681. void TearDown() override {
  16682. svr_.stop();
  16683. if (thread_.joinable()) { thread_.join(); }
  16684. }
  16685. // Sends `req` and reads until the server closes the connection. Returns
  16686. // false if the read had to wait for the client-side timeout instead.
  16687. bool send_until_closed(const std::string &req, std::string *resp) const {
  16688. auto start = std::chrono::steady_clock::now();
  16689. if (!send_request(3, req, resp, port_)) { return false; }
  16690. auto elapsed = std::chrono::steady_clock::now() - start;
  16691. return elapsed < std::chrono::seconds(2);
  16692. }
  16693. // The final response comes without `100 Continue`, and the server closes
  16694. // the connection since the body may or may not follow.
  16695. void expect_final_without_interim(const std::string &path,
  16696. const char *status_line) const {
  16697. std::string resp;
  16698. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  16699. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  16700. EXPECT_EQ(0u, resp.find(status_line));
  16701. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16702. }
  16703. Server svr_;
  16704. int port_ = 0;
  16705. thread thread_;
  16706. };
  16707. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  16708. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  16709. }
  16710. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  16711. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  16712. }
  16713. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  16714. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  16715. }
  16716. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  16717. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  16718. }
  16719. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  16720. // The body follows once `100 Continue` has had time to arrive.
  16721. auto req = expect_headers_only("/reader-used");
  16722. req.insert(req.size() - 2, "Connection: close\r\n");
  16723. std::string resp;
  16724. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  16725. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  16726. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  16727. EXPECT_NE(std::string::npos, resp.find("hi"));
  16728. }
  16729. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  16730. // Large enough for the client to add `Expect: 100-continue` itself.
  16731. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  16732. std::atomic<bool> body_sent{false};
  16733. Client cli(HOST, port_);
  16734. auto res = cli.Post(
  16735. "/pre-request", length,
  16736. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  16737. body_sent = true;
  16738. std::string chunk(len, 'x');
  16739. sink.write(chunk.data(), chunk.size());
  16740. return true;
  16741. },
  16742. "application/octet-stream");
  16743. ASSERT_TRUE(res);
  16744. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16745. EXPECT_FALSE(body_sent);
  16746. }
  16747. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  16748. Server svr;
  16749. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  16750. return StatusCode::ExpectationFailed_417;
  16751. });
  16752. svr.Post("/p", [](const Request &, Response &res) {
  16753. res.set_content("ok", "text/plain");
  16754. });
  16755. auto port = svr.bind_to_any_port(HOST);
  16756. thread t = thread([&] { svr.listen_after_bind(); });
  16757. auto se = detail::scope_exit([&] {
  16758. svr.stop();
  16759. t.join();
  16760. });
  16761. svr.wait_until_ready();
  16762. std::string resp;
  16763. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  16764. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  16765. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16766. // Exactly one response: the route handler must not run after the 417.
  16767. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  16768. }
  16769. #ifndef _WIN32
  16770. TEST(Expect100ContinueTest, ServerClosesConnection) {
  16771. static constexpr char reject[] = "Unauthorized";
  16772. static constexpr char accept[] = "Upload accepted";
  16773. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  16774. Server svr;
  16775. svr.set_expect_100_continue_handler(
  16776. [](const Request & /*req*/, Response &res) {
  16777. res.status = StatusCode::Unauthorized_401;
  16778. res.set_content(reject, "text/plain");
  16779. return res.status;
  16780. });
  16781. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  16782. res.set_content(accept, "text/plain");
  16783. });
  16784. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16785. auto se = detail::scope_exit([&] {
  16786. svr.stop();
  16787. thread.join();
  16788. ASSERT_FALSE(svr.is_running());
  16789. });
  16790. svr.wait_until_ready();
  16791. {
  16792. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  16793. curl_easy_init(), &curl_easy_cleanup};
  16794. ASSERT_NE(curl, nullptr);
  16795. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  16796. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  16797. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  16798. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  16799. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  16800. &curl_slist_free_all};
  16801. ASSERT_NE(list, nullptr);
  16802. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  16803. struct read_data {
  16804. size_t read_size;
  16805. size_t total_size;
  16806. } data = {0, total_size};
  16807. using read_callback_t =
  16808. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16809. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  16810. void *userdata) -> size_t {
  16811. read_data *d = (read_data *)userdata;
  16812. if (!userdata || d->read_size >= d->total_size) { return 0; }
  16813. std::fill_n(ptr, size * nmemb, 'A');
  16814. d->read_size += size * nmemb;
  16815. return size * nmemb;
  16816. };
  16817. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  16818. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  16819. std::vector<char> buffer;
  16820. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  16821. using write_callback_t =
  16822. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16823. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  16824. void *userdata) -> size_t {
  16825. std::vector<char> *buf = (std::vector<char> *)userdata;
  16826. buf->reserve(buf->size() + size * nmemb + 1);
  16827. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  16828. return size * nmemb;
  16829. };
  16830. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  16831. {
  16832. const auto res = curl_easy_perform(curl.get());
  16833. ASSERT_EQ(res, CURLE_OK);
  16834. }
  16835. {
  16836. auto response_code = long{};
  16837. const auto res =
  16838. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  16839. ASSERT_EQ(res, CURLE_OK);
  16840. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  16841. }
  16842. {
  16843. auto dl = curl_off_t{};
  16844. const auto res =
  16845. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  16846. ASSERT_EQ(res, CURLE_OK);
  16847. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  16848. }
  16849. {
  16850. buffer.push_back('\0');
  16851. ASSERT_STRCASEEQ(buffer.data(), reject);
  16852. }
  16853. }
  16854. }
  16855. #endif
  16856. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  16857. // Regression test for #2458.
  16858. //
  16859. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  16860. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  16861. // ticket can make the client socket spuriously readable during the
  16862. // 100-continue wait. If the readiness is mistaken for an incoming response,
  16863. // the client withholds the body and then blocks reading a response that never
  16864. // comes, failing with `Failed to read connection`.
  16865. //
  16866. // A correct client (like curl) sends the body once no `100 Continue` arrives
  16867. // within the timeout. This raw OpenSSL server deliberately never sends
  16868. // `100 Continue`; the client must still deliver the body and receive 200.
  16869. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  16870. signal(SIGPIPE, SIG_IGN);
  16871. const auto port = PORT + 4;
  16872. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16873. ASSERT_NE(srv, INVALID_SOCKET);
  16874. int opt = 1;
  16875. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  16876. sockaddr_in addr{};
  16877. addr.sin_family = AF_INET;
  16878. addr.sin_port = htons(static_cast<uint16_t>(port));
  16879. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16880. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16881. ASSERT_EQ(0, ::listen(srv, 1));
  16882. std::atomic<size_t> server_body_bytes{0};
  16883. auto server_thread = std::thread([&] {
  16884. sockaddr_in cli_addr{};
  16885. socklen_t cli_len = sizeof(cli_addr);
  16886. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16887. if (cli == INVALID_SOCKET) { return; }
  16888. // Bound the lifetime of the server side so a buggy client (which never
  16889. // sends the body) cannot make this thread block forever on join.
  16890. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  16891. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  16892. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  16893. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  16894. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  16895. SSL *ssl = SSL_new(ctx);
  16896. SSL_set_fd(ssl, static_cast<int>(cli));
  16897. if (SSL_accept(ssl) > 0) {
  16898. // Read the request headers. Reading here also flushes the TLS 1.3
  16899. // session tickets to the client. Deliberately do NOT send
  16900. // `100 Continue`.
  16901. std::string buf;
  16902. char tmp[1024];
  16903. while (buf.find("\r\n\r\n") == std::string::npos) {
  16904. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16905. if (n <= 0) { break; }
  16906. buf.append(tmp, static_cast<size_t>(n));
  16907. }
  16908. // A correct client sends the body now; count what arrives.
  16909. auto pos = buf.find("\r\n\r\n");
  16910. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  16911. while (body < 4096) {
  16912. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16913. if (n <= 0) { break; }
  16914. body += static_cast<size_t>(n);
  16915. }
  16916. server_body_bytes = body;
  16917. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  16918. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  16919. SSL_shutdown(ssl);
  16920. }
  16921. SSL_free(ssl);
  16922. detail::close_socket(cli);
  16923. SSL_CTX_free(ctx);
  16924. });
  16925. auto se = detail::scope_exit([&] {
  16926. server_thread.join();
  16927. detail::close_socket(srv);
  16928. });
  16929. SSLClient cli("127.0.0.1", port);
  16930. cli.enable_server_certificate_verification(false);
  16931. cli.set_connection_timeout(5, 0);
  16932. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  16933. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  16934. std::string body(4096, 'A');
  16935. auto res = cli.Put("/api/test", body, "application/json");
  16936. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  16937. EXPECT_EQ(StatusCode::OK_200, res->status);
  16938. EXPECT_EQ(body.size(), server_body_bytes.load());
  16939. }
  16940. #endif
  16941. template <typename S, typename C>
  16942. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  16943. svr.Get("/stream", [&](const Request &, Response &res) {
  16944. auto data = new std::string("01234567890123456789");
  16945. res.set_content_provider(
  16946. data->size(), "text/plain",
  16947. [&, data](size_t offset, size_t length, DataSink &sink) {
  16948. const size_t DATA_CHUNK_SIZE = 4;
  16949. const auto &d = *data;
  16950. std::this_thread::sleep_for(std::chrono::seconds(1));
  16951. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  16952. return true;
  16953. },
  16954. [data](bool success) {
  16955. EXPECT_FALSE(success);
  16956. delete data;
  16957. });
  16958. });
  16959. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  16960. auto i = new size_t(0);
  16961. res.set_content_provider(
  16962. "text/plain",
  16963. [i](size_t, DataSink &sink) {
  16964. if (*i < 5) {
  16965. std::this_thread::sleep_for(std::chrono::seconds(1));
  16966. sink.write("abcd", 4);
  16967. (*i)++;
  16968. } else {
  16969. sink.done();
  16970. }
  16971. return true;
  16972. },
  16973. [i](bool success) {
  16974. EXPECT_FALSE(success);
  16975. delete i;
  16976. });
  16977. });
  16978. svr.Get("/chunked", [&](const Request &, Response &res) {
  16979. auto i = new size_t(0);
  16980. res.set_chunked_content_provider(
  16981. "text/plain",
  16982. [i](size_t, DataSink &sink) {
  16983. if (*i < 5) {
  16984. std::this_thread::sleep_for(std::chrono::seconds(1));
  16985. sink.os << "abcd";
  16986. (*i)++;
  16987. } else {
  16988. sink.done();
  16989. }
  16990. return true;
  16991. },
  16992. [i](bool success) {
  16993. EXPECT_FALSE(success);
  16994. delete i;
  16995. });
  16996. });
  16997. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16998. auto se = detail::scope_exit([&] {
  16999. svr.stop();
  17000. listen_thread.join();
  17001. ASSERT_FALSE(svr.is_running());
  17002. });
  17003. svr.wait_until_ready();
  17004. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  17005. {
  17006. auto start = std::chrono::steady_clock::now();
  17007. auto res = cli.Get("/stream");
  17008. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17009. std::chrono::steady_clock::now() - start)
  17010. .count();
  17011. ASSERT_FALSE(res);
  17012. EXPECT_EQ(Error::Read, res.error());
  17013. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17014. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17015. }
  17016. {
  17017. auto start = std::chrono::steady_clock::now();
  17018. auto res = cli.Get("/stream_without_length");
  17019. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17020. std::chrono::steady_clock::now() - start)
  17021. .count();
  17022. ASSERT_FALSE(res);
  17023. EXPECT_EQ(Error::Read, res.error());
  17024. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17025. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17026. }
  17027. {
  17028. auto start = std::chrono::steady_clock::now();
  17029. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  17030. EXPECT_EQ("abcd", string(data, data_length));
  17031. return true;
  17032. });
  17033. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17034. std::chrono::steady_clock::now() - start)
  17035. .count();
  17036. ASSERT_FALSE(res);
  17037. EXPECT_EQ(Error::Read, res.error());
  17038. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17039. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17040. }
  17041. }
  17042. TEST(MaxTimeoutTest, ContentStream) {
  17043. time_t timeout = 2000;
  17044. time_t threshold = 200;
  17045. Server svr;
  17046. Client cli("localhost", PORT);
  17047. max_timeout_test(svr, cli, timeout, threshold);
  17048. }
  17049. #ifdef CPPHTTPLIB_SSL_ENABLED
  17050. TEST(MaxTimeoutTest, ContentStreamSSL) {
  17051. time_t timeout = 2000;
  17052. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  17053. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17054. SSLClient cli("localhost", PORT);
  17055. cli.enable_server_certificate_verification(false);
  17056. max_timeout_test(svr, cli, timeout, threshold);
  17057. }
  17058. #endif
  17059. class EventDispatcher {
  17060. public:
  17061. EventDispatcher() {}
  17062. bool wait_event(DataSink *sink) {
  17063. unique_lock<mutex> lk(m_);
  17064. int id = id_;
  17065. // Wait with timeout to prevent hanging if client disconnects
  17066. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  17067. [&] { return cid_ == id; })) {
  17068. return false; // Timeout occurred
  17069. }
  17070. sink->write(message_.data(), message_.size());
  17071. return true;
  17072. }
  17073. void send_event(const string &message) {
  17074. lock_guard<mutex> lk(m_);
  17075. cid_ = id_++;
  17076. message_ = message;
  17077. cv_.notify_all();
  17078. }
  17079. private:
  17080. mutex m_;
  17081. condition_variable cv_;
  17082. atomic_int id_{0};
  17083. atomic_int cid_{-1};
  17084. string message_;
  17085. };
  17086. TEST(ClientInThreadTest, Issue2068) {
  17087. EventDispatcher ed;
  17088. Server svr;
  17089. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  17090. res.set_chunked_content_provider("text/event-stream",
  17091. [&](size_t /*offset*/, DataSink &sink) {
  17092. return ed.wait_event(&sink);
  17093. });
  17094. });
  17095. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  17096. svr.wait_until_ready();
  17097. thread event_thread([&] {
  17098. int id = 0;
  17099. while (svr.is_running()) {
  17100. this_thread::sleep_for(chrono::milliseconds(500));
  17101. std::stringstream ss;
  17102. ss << "data: " << id << "\n\n";
  17103. ed.send_event(ss.str());
  17104. id++;
  17105. }
  17106. });
  17107. auto se = detail::scope_exit([&] {
  17108. svr.stop();
  17109. listen_thread.join();
  17110. event_thread.join();
  17111. ASSERT_FALSE(svr.is_running());
  17112. });
  17113. {
  17114. auto client = detail::make_unique<Client>(HOST, PORT);
  17115. client->set_read_timeout(std::chrono::minutes(10));
  17116. std::atomic<bool> stop{false};
  17117. std::thread t([&] {
  17118. client->Get("/event1",
  17119. [&](const char *, size_t) -> bool { return !stop; });
  17120. });
  17121. std::this_thread::sleep_for(std::chrono::seconds(2));
  17122. stop = true;
  17123. client->stop();
  17124. t.join();
  17125. // Reset client after thread has finished
  17126. client.reset();
  17127. }
  17128. }
  17129. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  17130. auto handled = false;
  17131. Server svr;
  17132. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17133. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17134. auto se = detail::scope_exit([&] {
  17135. svr.stop();
  17136. t.join();
  17137. ASSERT_FALSE(svr.is_running());
  17138. ASSERT_FALSE(handled);
  17139. });
  17140. svr.wait_until_ready();
  17141. // Two Content-Length headers with different values — must be rejected
  17142. auto req = "POST /test HTTP/1.1\r\n"
  17143. "Content-Length: 5\r\n"
  17144. "Content-Length: 10\r\n"
  17145. "\r\n"
  17146. "hello";
  17147. std::string response;
  17148. ASSERT_TRUE(send_request(1, req, &response));
  17149. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17150. response.substr(0, response.find("\r\n")));
  17151. }
  17152. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  17153. auto handled = false;
  17154. Server svr;
  17155. svr.Post("/test", [&](const Request &, Response &res) {
  17156. handled = true;
  17157. res.set_content("ok", "text/plain");
  17158. });
  17159. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17160. auto se = detail::scope_exit([&] {
  17161. svr.stop();
  17162. t.join();
  17163. ASSERT_FALSE(svr.is_running());
  17164. ASSERT_TRUE(handled);
  17165. });
  17166. svr.wait_until_ready();
  17167. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  17168. auto req = "POST /test HTTP/1.1\r\n"
  17169. "Content-Length: 5\r\n"
  17170. "Content-Length: 5\r\n"
  17171. "\r\n"
  17172. "hello";
  17173. std::string response;
  17174. ASSERT_TRUE(send_request(1, req, &response));
  17175. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  17176. }
  17177. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  17178. Server svr;
  17179. svr.Get("/test", [](const Request &, Response &res) {
  17180. res.set_content("ok", "text/plain");
  17181. });
  17182. auto port = svr.bind_to_any_port(HOST);
  17183. thread t = thread([&] { svr.listen_after_bind(); });
  17184. auto se = detail::scope_exit([&] {
  17185. svr.stop();
  17186. t.join();
  17187. ASSERT_FALSE(svr.is_running());
  17188. });
  17189. svr.wait_until_ready();
  17190. auto status_line = [&](const std::string &host_lines) {
  17191. std::string res;
  17192. send_request(
  17193. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  17194. &res, port);
  17195. return res.substr(0, res.find("\r\n"));
  17196. };
  17197. const char *accepted[] = {
  17198. "Host: localhost\r\n",
  17199. "Host: a.example:8080\r\n",
  17200. "Host: my_service\r\n",
  17201. "Host: [::1]:8080\r\n",
  17202. "Host: [fe80::1%25eth0]\r\n",
  17203. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  17204. };
  17205. for (auto host_lines : accepted) {
  17206. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  17207. }
  17208. const char *rejected[] = {
  17209. "Host: a.example\r\nHost: b.example\r\n",
  17210. "Host: a.example\r\nHost: a.example\r\n",
  17211. "Host: a@b.example\r\n",
  17212. "Host: a.example/b\r\n",
  17213. "Host: a.example\\b\r\n",
  17214. "Host: a.example?b\r\n",
  17215. "Host: a.example#b\r\n",
  17216. "Host: a.example b.example\r\n",
  17217. };
  17218. for (auto host_lines : rejected) {
  17219. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  17220. << host_lines;
  17221. }
  17222. }
  17223. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  17224. Server svr;
  17225. svr.Get("/", [](const Request &req, Response &res) {
  17226. EXPECT_EQ(2U, req.trailers.size());
  17227. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  17228. // Denied
  17229. EXPECT_FALSE(req.has_trailer("Content-Length"));
  17230. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  17231. // Accepted
  17232. EXPECT_TRUE(req.has_trailer("X-Hello"));
  17233. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  17234. EXPECT_TRUE(req.has_trailer("X-World"));
  17235. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  17236. res.set_content("ok", "text/plain");
  17237. });
  17238. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17239. auto se = detail::scope_exit([&] {
  17240. svr.stop();
  17241. t.join();
  17242. ASSERT_FALSE(svr.is_running());
  17243. });
  17244. svr.wait_until_ready();
  17245. const std::string req = "GET / HTTP/1.1\r\n"
  17246. "Transfer-Encoding: chunked\r\n"
  17247. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  17248. "\r\n"
  17249. "0\r\n"
  17250. "Content-Length: 10\r\n"
  17251. "Host: internal.local\r\n"
  17252. "Content-Type: malicious/content\r\n"
  17253. "Cookie: any\r\n"
  17254. "Set-Cookie: any\r\n"
  17255. "X-Forwarded-For: attacker.com\r\n"
  17256. "X-Real-Ip: 1.1.1.1\r\n"
  17257. "X-Hello: hello\r\n"
  17258. "X-World: world\r\n"
  17259. "\r\n";
  17260. std::string res;
  17261. ASSERT_TRUE(send_request(1, req, &res));
  17262. }
  17263. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  17264. // several field lines, and the combined value is what has to be parsed. A
  17265. // Trailer field split across lines therefore declares every name it lists;
  17266. // reading only the first line silently drops the trailers the later lines
  17267. // declare. The prohibited-trailer filter still applies to every line.
  17268. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  17269. Server svr;
  17270. size_t observed_trailer_count = 0;
  17271. std::string observed_hello;
  17272. std::string observed_world;
  17273. bool observed_content_length = true;
  17274. svr.Get("/", [&](const Request &req, Response &res) {
  17275. observed_trailer_count = req.trailers.size();
  17276. observed_hello = req.get_trailer_value("X-Hello");
  17277. observed_world = req.get_trailer_value("X-World");
  17278. observed_content_length = req.has_trailer("Content-Length");
  17279. res.set_content("ok", "text/plain");
  17280. });
  17281. auto port = svr.bind_to_any_port(HOST);
  17282. thread t = thread([&]() { svr.listen_after_bind(); });
  17283. auto se = detail::scope_exit([&] {
  17284. svr.stop();
  17285. t.join();
  17286. ASSERT_FALSE(svr.is_running());
  17287. });
  17288. svr.wait_until_ready();
  17289. const std::string req = "GET / HTTP/1.1\r\n"
  17290. "Transfer-Encoding: chunked\r\n"
  17291. "Trailer: X-Hello\r\n"
  17292. "Trailer: X-World, Content-Length\r\n"
  17293. "\r\n"
  17294. "0\r\n"
  17295. "X-Hello: hello\r\n"
  17296. "X-World: world\r\n"
  17297. "Content-Length: 10\r\n"
  17298. "\r\n";
  17299. std::string res;
  17300. ASSERT_TRUE(send_request(1, req, &res, port));
  17301. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  17302. // Accepted: both field lines contribute to the declared set
  17303. EXPECT_EQ(2U, observed_trailer_count);
  17304. EXPECT_EQ(observed_hello, "hello");
  17305. EXPECT_EQ(observed_world, "world");
  17306. // Denied: a prohibited name stays prohibited on a later field line
  17307. EXPECT_FALSE(observed_content_length);
  17308. }
  17309. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  17310. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  17311. // unbounded run of fields that are never declared, because the counter would
  17312. // only advance for declared fields.
  17313. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  17314. Server svr;
  17315. bool handler_called = false;
  17316. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  17317. handler_called = true;
  17318. res.set_content("ok", "text/plain");
  17319. });
  17320. auto port = svr.bind_to_any_port(HOST);
  17321. thread t = thread([&]() { svr.listen_after_bind(); });
  17322. auto se = detail::scope_exit([&] {
  17323. svr.stop();
  17324. t.join();
  17325. ASSERT_FALSE(svr.is_running());
  17326. });
  17327. svr.wait_until_ready();
  17328. // Declare nothing, then send far more undeclared trailer fields than the
  17329. // header-count limit. Parsing must stop and reject the request rather than
  17330. // read every line.
  17331. std::string req = "GET / HTTP/1.1\r\n"
  17332. "Transfer-Encoding: chunked\r\n"
  17333. "\r\n"
  17334. "0\r\n";
  17335. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  17336. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  17337. }
  17338. req += "\r\n";
  17339. std::string res;
  17340. ASSERT_TRUE(send_request(1, req, &res, port));
  17341. // The request is rejected before the handler runs.
  17342. EXPECT_FALSE(handler_called);
  17343. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  17344. }
  17345. // The set of declared trailer names is capped so a peer cannot grow it without
  17346. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  17347. // declared past the cap is not honored, even if the field is actually sent.
  17348. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  17349. Server svr;
  17350. // One name inside the cap and one past it, so the test tracks the cap rather
  17351. // than a fixed count.
  17352. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  17353. const std::string within_cap_name = "X-T-0";
  17354. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  17355. bool observed_within_cap = false;
  17356. bool observed_past_cap = false;
  17357. svr.Get("/", [&](const Request &req, Response &res) {
  17358. observed_within_cap = req.has_trailer(within_cap_name);
  17359. observed_past_cap = req.has_trailer(past_cap_name);
  17360. res.set_content("ok", "text/plain");
  17361. });
  17362. auto port = svr.bind_to_any_port(HOST);
  17363. thread t = thread([&]() { svr.listen_after_bind(); });
  17364. auto se = detail::scope_exit([&] {
  17365. svr.stop();
  17366. t.join();
  17367. ASSERT_FALSE(svr.is_running());
  17368. });
  17369. svr.wait_until_ready();
  17370. // Declare more trailer names than the cap in a single Trailer field, then
  17371. // actually send the first (within the cap) and the last (past it).
  17372. std::string trailer_decl = "Trailer: ";
  17373. for (int i = 0; i < declared_count; i++) {
  17374. if (i != 0) { trailer_decl += ", "; }
  17375. trailer_decl += "X-T-" + std::to_string(i);
  17376. }
  17377. trailer_decl += "\r\n";
  17378. const std::string req = "GET / HTTP/1.1\r\n"
  17379. "Transfer-Encoding: chunked\r\n" +
  17380. trailer_decl +
  17381. "\r\n"
  17382. "0\r\n" +
  17383. within_cap_name + ": a\r\n" + past_cap_name +
  17384. ": b\r\n"
  17385. "\r\n";
  17386. std::string res;
  17387. ASSERT_TRUE(send_request(1, req, &res, port));
  17388. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  17389. // A name within the cap is honored; one declared past the cap is dropped.
  17390. EXPECT_TRUE(observed_within_cap);
  17391. EXPECT_FALSE(observed_past_cap);
  17392. }
  17393. // A direct client that is not listed in trusted_proxies must not be able to
  17394. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  17395. // the peer address on the actual TCP connection determines whether the
  17396. // header is honored.
  17397. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  17398. Server svr;
  17399. // Deliberately does NOT include the loopback address the test client
  17400. // actually connects from, so the direct connection is not a trusted proxy.
  17401. svr.set_trusted_proxies({"203.0.113.66"});
  17402. std::string observed_remote_addr;
  17403. svr.Get("/ip", [&](const Request &req, Response &res) {
  17404. observed_remote_addr = req.remote_addr;
  17405. res.set_content("ok", "text/plain");
  17406. });
  17407. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17408. auto se = detail::scope_exit([&] {
  17409. svr.stop();
  17410. t.join();
  17411. ASSERT_FALSE(svr.is_running());
  17412. });
  17413. svr.wait_until_ready();
  17414. Client cli(HOST, PORT);
  17415. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  17416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17417. EXPECT_EQ(StatusCode::OK_200, res->status);
  17418. // The connecting peer is not a trusted proxy, so the spoofed header must be
  17419. // ignored entirely and the real connection-level address retained.
  17420. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17421. observed_remote_addr == "127.0.0.1");
  17422. }
  17423. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  17424. Server svr;
  17425. std::string observed_remote_addr;
  17426. std::string observed_xff;
  17427. svr.Get("/ip", [&](const Request &req, Response &res) {
  17428. observed_remote_addr = req.remote_addr;
  17429. observed_xff = req.get_header_value("X-Forwarded-For");
  17430. res.set_content("ok", "text/plain");
  17431. });
  17432. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17433. auto se = detail::scope_exit([&] {
  17434. svr.stop();
  17435. t.join();
  17436. ASSERT_FALSE(svr.is_running());
  17437. });
  17438. svr.wait_until_ready();
  17439. Client cli(HOST, PORT);
  17440. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  17441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17442. EXPECT_EQ(StatusCode::OK_200, res->status);
  17443. EXPECT_EQ(observed_xff, "203.0.113.66");
  17444. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17445. observed_remote_addr == "127.0.0.1");
  17446. }
  17447. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  17448. Server svr;
  17449. svr.set_trusted_proxies({"203.0.113.66"});
  17450. std::string observed_remote_addr;
  17451. std::string observed_xff;
  17452. svr.Get("/ip", [&](const Request &req, Response &res) {
  17453. observed_remote_addr = req.remote_addr;
  17454. observed_xff = req.get_header_value("X-Forwarded-For");
  17455. res.set_content("ok", "text/plain");
  17456. });
  17457. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17458. auto se = detail::scope_exit([&] {
  17459. svr.stop();
  17460. t.join();
  17461. ASSERT_FALSE(svr.is_running());
  17462. });
  17463. svr.wait_until_ready();
  17464. Client cli(HOST, PORT);
  17465. auto res = cli.Get("/ip");
  17466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17467. EXPECT_EQ(StatusCode::OK_200, res->status);
  17468. EXPECT_EQ(observed_xff, "");
  17469. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17470. observed_remote_addr == "127.0.0.1");
  17471. }
  17472. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  17473. Server svr;
  17474. // Include the loopback address the test client actually connects from, so
  17475. // the direct connection itself is recognized as the trusted proxy hop.
  17476. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  17477. std::string observed_remote_addr;
  17478. std::string observed_xff;
  17479. svr.Get("/ip", [&](const Request &req, Response &res) {
  17480. observed_remote_addr = req.remote_addr;
  17481. observed_xff = req.get_header_value("X-Forwarded-For");
  17482. res.set_content("ok", "text/plain");
  17483. });
  17484. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17485. auto se = detail::scope_exit([&] {
  17486. svr.stop();
  17487. t.join();
  17488. ASSERT_FALSE(svr.is_running());
  17489. });
  17490. svr.wait_until_ready();
  17491. Client cli(HOST, PORT);
  17492. auto res = cli.Get(
  17493. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  17494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17495. EXPECT_EQ(StatusCode::OK_200, res->status);
  17496. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  17497. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17498. }
  17499. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  17500. Server svr;
  17501. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  17502. std::string observed_remote_addr;
  17503. std::string observed_xff;
  17504. svr.Get("/ip", [&](const Request &req, Response &res) {
  17505. observed_remote_addr = req.remote_addr;
  17506. observed_xff = req.get_header_value("X-Forwarded-For");
  17507. res.set_content("ok", "text/plain");
  17508. });
  17509. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17510. auto se = detail::scope_exit([&] {
  17511. svr.stop();
  17512. t.join();
  17513. ASSERT_FALSE(svr.is_running());
  17514. });
  17515. svr.wait_until_ready();
  17516. Client cli(HOST, PORT);
  17517. auto res = cli.Get(
  17518. "/ip",
  17519. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17521. EXPECT_EQ(StatusCode::OK_200, res->status);
  17522. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17523. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17524. }
  17525. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  17526. Server svr;
  17527. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17528. std::string observed_remote_addr;
  17529. std::string observed_xff;
  17530. svr.Get("/ip", [&](const Request &req, Response &res) {
  17531. observed_remote_addr = req.remote_addr;
  17532. observed_xff = req.get_header_value("X-Forwarded-For");
  17533. res.set_content("ok", "text/plain");
  17534. });
  17535. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17536. auto se = detail::scope_exit([&] {
  17537. svr.stop();
  17538. t.join();
  17539. ASSERT_FALSE(svr.is_running());
  17540. });
  17541. svr.wait_until_ready();
  17542. Client cli(HOST, PORT);
  17543. auto res = cli.Get(
  17544. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  17545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17546. EXPECT_EQ(StatusCode::OK_200, res->status);
  17547. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  17548. // by the closest hop) is used. The leftmost entry is fully client-controlled
  17549. // and must not be selected.
  17550. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  17551. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  17552. }
  17553. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  17554. Server svr;
  17555. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  17556. std::string observed_remote_addr;
  17557. svr.Get("/ip", [&](const Request &req, Response &res) {
  17558. observed_remote_addr = req.remote_addr;
  17559. res.set_content("ok", "text/plain");
  17560. });
  17561. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17562. auto se = detail::scope_exit([&] {
  17563. svr.stop();
  17564. t.join();
  17565. ASSERT_FALSE(svr.is_running());
  17566. });
  17567. svr.wait_until_ready();
  17568. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  17569. // a forged address and the trusted proxy's own address; the forged value must
  17570. // not win over the address the trusted proxy actually recorded.
  17571. Client cli(HOST, PORT);
  17572. auto res = cli.Get(
  17573. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  17574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17575. EXPECT_EQ(StatusCode::OK_200, res->status);
  17576. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  17577. }
  17578. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  17579. Server svr;
  17580. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17581. std::string observed_remote_addr;
  17582. std::string observed_xff;
  17583. svr.Get("/ip", [&](const Request &req, Response &res) {
  17584. observed_remote_addr = req.remote_addr;
  17585. observed_xff = req.get_header_value("X-Forwarded-For");
  17586. res.set_content("ok", "text/plain");
  17587. });
  17588. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17589. auto se = detail::scope_exit([&] {
  17590. svr.stop();
  17591. t.join();
  17592. ASSERT_FALSE(svr.is_running());
  17593. });
  17594. svr.wait_until_ready();
  17595. Client cli(HOST, PORT);
  17596. auto res = cli.Get(
  17597. "/ip",
  17598. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17600. EXPECT_EQ(StatusCode::OK_200, res->status);
  17601. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17602. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17603. }
  17604. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  17605. Server svr;
  17606. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17607. std::string observed_remote_addr;
  17608. std::string observed_xff;
  17609. svr.Get("/ip", [&](const Request &req, Response &res) {
  17610. observed_remote_addr = req.remote_addr;
  17611. observed_xff = req.get_header_value("X-Forwarded-For");
  17612. res.set_content("ok", "text/plain");
  17613. });
  17614. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17615. auto se = detail::scope_exit([&] {
  17616. svr.stop();
  17617. t.join();
  17618. ASSERT_FALSE(svr.is_running());
  17619. });
  17620. svr.wait_until_ready();
  17621. std::string raw_req =
  17622. "GET /ip HTTP/1.1\r\n"
  17623. "Host: localhost\r\n"
  17624. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  17625. "Connection: close\r\n"
  17626. "\r\n";
  17627. std::string out;
  17628. ASSERT_TRUE(send_request(5, raw_req, &out));
  17629. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17630. // Header parser trims surrounding whitespace of the header value
  17631. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  17632. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17633. }
  17634. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  17635. // one comma-joined value, in the order received. Proxies such as HAProxy append
  17636. // their own X-Forwarded-For as a separate field line rather than extending the
  17637. // one the client sent, so every occurrence has to be taken into account.
  17638. // Reading only the first one hands back the address the client chose.
  17639. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  17640. Server svr;
  17641. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17642. std::string observed_remote_addr;
  17643. size_t observed_xff_count = 0;
  17644. svr.Get("/ip", [&](const Request &req, Response &res) {
  17645. observed_remote_addr = req.remote_addr;
  17646. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  17647. res.set_content("ok", "text/plain");
  17648. });
  17649. auto port = svr.bind_to_any_port(HOST);
  17650. thread t = thread([&]() { svr.listen_after_bind(); });
  17651. auto se = detail::scope_exit([&] {
  17652. svr.stop();
  17653. t.join();
  17654. ASSERT_FALSE(svr.is_running());
  17655. });
  17656. svr.wait_until_ready();
  17657. // The client supplies the first field line; the trusted proxy appends the
  17658. // address it observed as a second one.
  17659. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  17660. "Host: localhost\r\n"
  17661. "X-Forwarded-For: 1.2.3.4\r\n"
  17662. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  17663. "Connection: close\r\n"
  17664. "\r\n";
  17665. std::string out;
  17666. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17667. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17668. EXPECT_EQ(observed_xff_count, 2U);
  17669. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17670. // The same chain spread over one field line per hop derives the same client
  17671. // address, i.e. the split and the comma-joined representations agree.
  17672. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  17673. "Host: localhost\r\n"
  17674. "X-Forwarded-For: 1.2.3.4\r\n"
  17675. "X-Forwarded-For: 198.51.100.23\r\n"
  17676. "X-Forwarded-For: 192.0.2.45\r\n"
  17677. "Connection: close\r\n"
  17678. "\r\n";
  17679. out.clear();
  17680. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  17681. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17682. EXPECT_EQ(observed_xff_count, 3U);
  17683. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17684. }
  17685. // An X-Forwarded-For header whose value parses to zero IP segments must not
  17686. // crash the server (it used to call front() on an empty vector inside
  17687. // get_client_ip). The connection-level remote address must be retained instead.
  17688. static void run_malformed_xff_test(const std::string &xff_value) {
  17689. Server svr;
  17690. svr.set_trusted_proxies({"192.0.2.45"});
  17691. std::string observed_remote_addr;
  17692. svr.Get("/ip", [&](const Request &req, Response &res) {
  17693. observed_remote_addr = req.remote_addr;
  17694. res.set_content("ok", "text/plain");
  17695. });
  17696. int port = 0;
  17697. thread t = thread([&]() {
  17698. port = svr.bind_to_any_port(HOST);
  17699. svr.listen_after_bind();
  17700. });
  17701. auto se = detail::scope_exit([&] {
  17702. svr.stop();
  17703. t.join();
  17704. ASSERT_FALSE(svr.is_running());
  17705. });
  17706. svr.wait_until_ready();
  17707. Client cli(HOST, port);
  17708. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  17709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17710. EXPECT_EQ(StatusCode::OK_200, res->status);
  17711. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17712. observed_remote_addr == "127.0.0.1");
  17713. }
  17714. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  17715. run_malformed_xff_test("");
  17716. }
  17717. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  17718. run_malformed_xff_test(",");
  17719. }
  17720. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  17721. run_malformed_xff_test(", , ,");
  17722. }
  17723. // The same rule applies to Accept: a request whose acceptable types are spread
  17724. // over several field lines must be negotiated against all of them.
  17725. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  17726. // case-insensitive connection options. Comparing the whole field value against
  17727. // one option misses a client that sends several of them, and misses every
  17728. // casing but the one written in the comparison.
  17729. //
  17730. // Sends req, reads the response, then reuses the same socket for a second
  17731. // request to find out whether the server kept the connection.
  17732. static void probe_connection_reuse(int port, const std::string &req,
  17733. bool *announced_close, bool *reusable) {
  17734. auto error = Error::Success;
  17735. auto sock = detail::create_client_socket(
  17736. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17737. /*connection_timeout_sec=*/5, 0,
  17738. /*read_timeout_sec=*/1, 0,
  17739. /*write_timeout_sec=*/5, 0, std::string(), error);
  17740. ASSERT_NE(sock, INVALID_SOCKET);
  17741. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  17742. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  17743. "Host: localhost\r\n"
  17744. "Connection: close\r\n"
  17745. "\r\n";
  17746. std::string first_response;
  17747. std::string second_response;
  17748. detail::process_client_socket(
  17749. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  17750. [&](Stream &strm) {
  17751. if (strm.write(req.data(), req.size()) !=
  17752. static_cast<ssize_t>(req.size())) {
  17753. return false;
  17754. }
  17755. char buf[512];
  17756. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  17757. // Headers plus the two-byte body of the handler below
  17758. while (reader.getline()) {
  17759. first_response += reader.ptr();
  17760. if (first_response.find("ok") != std::string::npos) { break; }
  17761. }
  17762. if (strm.write(second.data(), second.size()) !=
  17763. static_cast<ssize_t>(second.size())) {
  17764. return true;
  17765. }
  17766. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  17767. while (reader2.getline()) {
  17768. second_response += reader2.ptr();
  17769. if (second_response.find("ok") != std::string::npos) { break; }
  17770. }
  17771. return true;
  17772. });
  17773. *announced_close =
  17774. first_response.find("Connection: close") != std::string::npos;
  17775. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  17776. }
  17777. class ConnectionTokenTest : public ::testing::Test {
  17778. protected:
  17779. void SetUp() override {
  17780. svr_.Get("/keepalive", [](const Request &, Response &res) {
  17781. res.set_content("ok", "text/plain");
  17782. });
  17783. port_ = svr_.bind_to_any_port(HOST);
  17784. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17785. svr_.wait_until_ready();
  17786. }
  17787. void TearDown() override {
  17788. svr_.stop();
  17789. if (thread_.joinable()) { thread_.join(); }
  17790. }
  17791. Server svr_;
  17792. int port_ = 0;
  17793. thread thread_;
  17794. };
  17795. // "close" alongside another option still closes the connection, and the
  17796. // response says so rather than leaving the peer to discover it.
  17797. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  17798. bool announced_close = false;
  17799. bool reusable = true;
  17800. probe_connection_reuse(port_,
  17801. "GET /keepalive HTTP/1.1\r\n"
  17802. "Host: localhost\r\n"
  17803. "Connection: keep-alive, close\r\n"
  17804. "\r\n",
  17805. &announced_close, &reusable);
  17806. EXPECT_TRUE(announced_close);
  17807. EXPECT_FALSE(reusable);
  17808. }
  17809. // "close" split over two field lines is the same list, so it is honored too.
  17810. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  17811. bool announced_close = false;
  17812. bool reusable = true;
  17813. probe_connection_reuse(port_,
  17814. "GET /keepalive HTTP/1.1\r\n"
  17815. "Host: localhost\r\n"
  17816. "Connection: keep-alive\r\n"
  17817. "Connection: close\r\n"
  17818. "\r\n",
  17819. &announced_close, &reusable);
  17820. EXPECT_TRUE(announced_close);
  17821. EXPECT_FALSE(reusable);
  17822. }
  17823. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  17824. // keep-alive in the spelling everyone actually sends keeps its connection.
  17825. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  17826. bool announced_close = false;
  17827. bool reusable = false;
  17828. probe_connection_reuse(port_,
  17829. "GET /keepalive HTTP/1.0\r\n"
  17830. "Host: localhost\r\n"
  17831. "Connection: keep-alive\r\n"
  17832. "\r\n",
  17833. &announced_close, &reusable);
  17834. EXPECT_FALSE(announced_close);
  17835. EXPECT_TRUE(reusable);
  17836. }
  17837. // A token the value merely contains is not the token itself.
  17838. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  17839. bool announced_close = false;
  17840. bool reusable = false;
  17841. probe_connection_reuse(port_,
  17842. "GET /keepalive HTTP/1.1\r\n"
  17843. "Host: localhost\r\n"
  17844. "Connection: notclose\r\n"
  17845. "\r\n",
  17846. &announced_close, &reusable);
  17847. EXPECT_FALSE(announced_close);
  17848. EXPECT_TRUE(reusable);
  17849. }
  17850. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  17851. Server svr;
  17852. std::vector<std::string> observed_types;
  17853. svr.Get("/", [&](const Request &req, Response &res) {
  17854. observed_types = req.accept_content_types;
  17855. res.set_content("ok", "text/plain");
  17856. });
  17857. auto port = svr.bind_to_any_port(HOST);
  17858. thread t = thread([&]() { svr.listen_after_bind(); });
  17859. auto se = detail::scope_exit([&] {
  17860. svr.stop();
  17861. t.join();
  17862. ASSERT_FALSE(svr.is_running());
  17863. });
  17864. svr.wait_until_ready();
  17865. Client cli(HOST, port);
  17866. Headers headers;
  17867. headers.emplace("Accept", "text/plain;q=0.5");
  17868. headers.emplace("Accept", "application/json");
  17869. auto res = cli.Get("/", headers);
  17870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17871. EXPECT_EQ(StatusCode::OK_200, res->status);
  17872. // Sorted by q-value, so the second field line's type comes first
  17873. ASSERT_EQ(2U, observed_types.size());
  17874. EXPECT_EQ("application/json", observed_types[0]);
  17875. EXPECT_EQ("text/plain", observed_types[1]);
  17876. }
  17877. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  17878. // empty field line must not contribute a bare comma to the combined value.
  17879. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  17880. Server svr;
  17881. std::vector<std::string> observed_types;
  17882. svr.Get("/", [&](const Request &req, Response &res) {
  17883. observed_types = req.accept_content_types;
  17884. res.set_content("ok", "text/plain");
  17885. });
  17886. auto port = svr.bind_to_any_port(HOST);
  17887. thread t = thread([&]() { svr.listen_after_bind(); });
  17888. auto se = detail::scope_exit([&] {
  17889. svr.stop();
  17890. t.join();
  17891. ASSERT_FALSE(svr.is_running());
  17892. });
  17893. svr.wait_until_ready();
  17894. // Empty first field line, then a real one
  17895. std::string raw_req = "GET / HTTP/1.1\r\n"
  17896. "Host: localhost\r\n"
  17897. "Accept:\r\n"
  17898. "Accept: application/json\r\n"
  17899. "Connection: close\r\n"
  17900. "\r\n";
  17901. std::string out;
  17902. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17903. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17904. ASSERT_EQ(1U, observed_types.size());
  17905. EXPECT_EQ("application/json", observed_types[0]);
  17906. }
  17907. // The skip in get_combined_header_value() is what keeps an empty field line
  17908. // from contributing a bare comma. Only a trailing empty field line exercises
  17909. // it: a leading one is already covered by the "combined is still empty" check,
  17910. // and parse_accept_header() now ignores the empty element either way, so the
  17911. // request-level test above can no longer tell the two apart.
  17912. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  17913. Headers headers;
  17914. headers.emplace("Accept", "text/html");
  17915. headers.emplace("Accept", "");
  17916. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  17917. headers.clear();
  17918. headers.emplace("Accept", "");
  17919. headers.emplace("Accept", "application/json");
  17920. EXPECT_EQ("application/json",
  17921. detail::get_combined_header_value(headers, "Accept"));
  17922. }
  17923. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17924. // An encoding offered on a later Accept-Encoding field line is still offered.
  17925. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  17926. Server svr;
  17927. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17928. res.set_content(std::string(1024, 'x'), "text/plain");
  17929. });
  17930. auto port = svr.bind_to_any_port(HOST);
  17931. thread t = thread([&]() { svr.listen_after_bind(); });
  17932. auto se = detail::scope_exit([&] {
  17933. svr.stop();
  17934. t.join();
  17935. ASSERT_FALSE(svr.is_running());
  17936. });
  17937. svr.wait_until_ready();
  17938. Client cli(HOST, port);
  17939. cli.set_decompress(false);
  17940. Headers headers;
  17941. headers.emplace("Accept-Encoding", "identity");
  17942. headers.emplace("Accept-Encoding", "gzip");
  17943. auto res = cli.Get("/", headers);
  17944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17945. EXPECT_EQ(StatusCode::OK_200, res->status);
  17946. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  17947. }
  17948. #endif
  17949. #ifndef _WIN32
  17950. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  17951. Server svr;
  17952. svr.Post("/post", [&](const Request &req, Response &res) {
  17953. res.set_content(req.body, "text/plain");
  17954. });
  17955. svr.Put("/put", [&](const Request &req, Response &res) {
  17956. res.set_content(req.body, "text/plain");
  17957. });
  17958. svr.Patch("/patch", [&](const Request &req, Response &res) {
  17959. res.set_content(req.body, "text/plain");
  17960. });
  17961. svr.Delete("/delete", [&](const Request &req, Response &res) {
  17962. res.set_content(req.body, "text/plain");
  17963. });
  17964. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17965. auto se = detail::scope_exit([&] {
  17966. svr.stop();
  17967. t.join();
  17968. ASSERT_FALSE(svr.is_running());
  17969. });
  17970. svr.wait_until_ready();
  17971. std::string resp;
  17972. // POST without Content-Length
  17973. ASSERT_TRUE(send_request(5,
  17974. "POST /post HTTP/1.1\r\n"
  17975. "Host: localhost\r\n"
  17976. "Connection: close\r\n"
  17977. "\r\n",
  17978. &resp));
  17979. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17980. // PUT without Content-Length
  17981. resp.clear();
  17982. ASSERT_TRUE(send_request(5,
  17983. "PUT /put HTTP/1.1\r\n"
  17984. "Host: localhost\r\n"
  17985. "Connection: close\r\n"
  17986. "\r\n",
  17987. &resp));
  17988. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17989. // PATCH without Content-Length
  17990. resp.clear();
  17991. ASSERT_TRUE(send_request(5,
  17992. "PATCH /patch HTTP/1.1\r\n"
  17993. "Host: localhost\r\n"
  17994. "Connection: close\r\n"
  17995. "\r\n",
  17996. &resp));
  17997. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17998. // DELETE without Content-Length
  17999. resp.clear();
  18000. ASSERT_TRUE(send_request(5,
  18001. "DELETE /delete HTTP/1.1\r\n"
  18002. "Host: localhost\r\n"
  18003. "Connection: close\r\n"
  18004. "\r\n",
  18005. &resp));
  18006. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18007. }
  18008. #endif
  18009. //==============================================================================
  18010. // open_stream() Tests
  18011. //==============================================================================
  18012. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  18013. std::string result;
  18014. char buf[8192];
  18015. ssize_t n;
  18016. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18017. result.append(buf, static_cast<size_t>(n));
  18018. }
  18019. return result;
  18020. }
  18021. // Mock stream for unit tests
  18022. class MockStream : public Stream {
  18023. public:
  18024. std::string data;
  18025. size_t pos = 0;
  18026. ssize_t error_after = -1; // -1 = no error
  18027. explicit MockStream(const std::string &d, ssize_t err = -1)
  18028. : data(d), error_after(err) {}
  18029. bool is_readable() const override { return true; }
  18030. bool wait_readable() const override { return true; }
  18031. bool wait_writable() const override { return true; }
  18032. ssize_t read(char *ptr, size_t size) override {
  18033. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  18034. if (pos >= data.size()) return 0;
  18035. size_t limit =
  18036. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  18037. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  18038. std::memcpy(ptr, data.data() + pos, to_read);
  18039. pos += to_read;
  18040. return static_cast<ssize_t>(to_read);
  18041. }
  18042. ssize_t write(const char *, size_t) override { return -1; }
  18043. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  18044. ip = "127.0.0.1";
  18045. port = 0;
  18046. }
  18047. void get_local_ip_and_port(std::string &ip, int &port) const override {
  18048. ip = "127.0.0.1";
  18049. port = 0;
  18050. }
  18051. socket_t socket() const override { return INVALID_SOCKET; }
  18052. time_t duration() const override { return 0; }
  18053. };
  18054. TEST(StreamHandleTest, Basic) {
  18055. ClientImpl::StreamHandle handle;
  18056. EXPECT_FALSE(handle.is_valid());
  18057. handle.response = detail::make_unique<Response>();
  18058. handle.error = Error::Connection;
  18059. EXPECT_FALSE(handle.is_valid());
  18060. handle.error = Error::Success;
  18061. EXPECT_TRUE(handle.is_valid());
  18062. }
  18063. TEST(BodyReaderTest, Basic) {
  18064. MockStream stream("Hello, World!");
  18065. detail::BodyReader reader;
  18066. reader.stream = &stream;
  18067. reader.content_length = 13;
  18068. char buf[32];
  18069. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  18070. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  18071. EXPECT_TRUE(reader.eof);
  18072. }
  18073. TEST(BodyReaderTest, NoStream) {
  18074. detail::BodyReader reader;
  18075. char buf[32];
  18076. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18077. EXPECT_EQ(Error::Connection, reader.last_error);
  18078. }
  18079. TEST(BodyReaderTest, Error) {
  18080. MockStream stream("Hello, World!", 5);
  18081. detail::BodyReader reader;
  18082. reader.stream = &stream;
  18083. reader.content_length = 13;
  18084. char buf[32];
  18085. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  18086. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18087. EXPECT_EQ(Error::Read, reader.last_error);
  18088. }
  18089. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  18090. // Mock-based StreamHandle tests relying on private internals are removed.
  18091. class OpenStreamTest : public ::testing::Test {
  18092. protected:
  18093. void SetUp() override {
  18094. svr_.Get("/hello", [](const Request &, Response &res) {
  18095. res.set_content("Hello World!", "text/plain");
  18096. });
  18097. svr_.Get("/large", [](const Request &, Response &res) {
  18098. res.set_content(std::string(10000, 'X'), "text/plain");
  18099. });
  18100. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  18101. res.set_content("Hello World!", "image/jpeg");
  18102. res.set_header("Content-Encoding", "UTF-8");
  18103. });
  18104. svr_.Get("/chunked", [](const Request &, Response &res) {
  18105. res.set_chunked_content_provider("text/plain",
  18106. [](size_t offset, DataSink &sink) {
  18107. if (offset < 15) {
  18108. sink.write("chunk", 5);
  18109. return true;
  18110. }
  18111. sink.done();
  18112. return true;
  18113. });
  18114. });
  18115. svr_.Get("/compressible", [](const Request &, Response &res) {
  18116. res.set_chunked_content_provider("text/plain", [](size_t offset,
  18117. DataSink &sink) {
  18118. if (offset < 100 * 1024) {
  18119. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  18120. sink.write(chunk.data(), chunk.size());
  18121. return true;
  18122. }
  18123. sink.done();
  18124. return true;
  18125. });
  18126. });
  18127. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  18128. [](const Request & /*req*/, Response &res) {
  18129. auto i = new int(0);
  18130. res.set_header("Trailer", "Content-Length, X-Allowed");
  18131. res.set_chunked_content_provider(
  18132. "text/plain",
  18133. [i](size_t /*offset*/, DataSink &sink) {
  18134. switch (*i) {
  18135. case 0: sink.os << "123"; break;
  18136. case 1: sink.os << "456"; break;
  18137. case 2: sink.os << "789"; break;
  18138. case 3: {
  18139. sink.done_with_trailer(
  18140. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  18141. } break;
  18142. }
  18143. (*i)++;
  18144. return true;
  18145. },
  18146. [i](bool success) {
  18147. EXPECT_TRUE(success);
  18148. delete i;
  18149. });
  18150. });
  18151. // Echo headers endpoint for header-related tests
  18152. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  18153. std::string body;
  18154. for (const auto &h : req.headers) {
  18155. body.append(h.first);
  18156. body.push_back(':');
  18157. body.append(h.second);
  18158. body.push_back('\n');
  18159. }
  18160. res.set_content(body, "text/plain");
  18161. });
  18162. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  18163. std::string body;
  18164. for (const auto &h : req.headers) {
  18165. body.append(h.first);
  18166. body.push_back(':');
  18167. body.append(h.second);
  18168. body.push_back('\n');
  18169. }
  18170. res.set_content(body, "text/plain");
  18171. });
  18172. port_ = svr_.bind_to_any_port("127.0.0.1");
  18173. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18174. svr_.wait_until_ready();
  18175. }
  18176. void TearDown() override {
  18177. svr_.stop();
  18178. if (thread_.joinable()) thread_.join();
  18179. }
  18180. Server svr_;
  18181. std::thread thread_;
  18182. int port_ = 0;
  18183. };
  18184. TEST_F(OpenStreamTest, Basic) {
  18185. Client cli("127.0.0.1", port_);
  18186. auto handle = cli.open_stream("GET", "/hello");
  18187. EXPECT_TRUE(handle.is_valid());
  18188. EXPECT_EQ("Hello World!", read_all(handle));
  18189. }
  18190. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  18191. Client cli("127.0.0.1", port_);
  18192. auto handle = cli.open_stream("GET", "/unknown-encoding");
  18193. ASSERT_TRUE(handle.is_valid());
  18194. EXPECT_EQ("Hello World!", read_all(handle));
  18195. }
  18196. TEST_F(OpenStreamTest, SmallBuffer) {
  18197. Client cli("127.0.0.1", port_);
  18198. auto handle = cli.open_stream("GET", "/hello");
  18199. std::string result;
  18200. char buf[4];
  18201. ssize_t n;
  18202. while ((n = handle.read(buf, sizeof(buf))) > 0)
  18203. result.append(buf, static_cast<size_t>(n));
  18204. EXPECT_EQ("Hello World!", result);
  18205. }
  18206. TEST_F(OpenStreamTest, DefaultHeaders) {
  18207. Client cli("127.0.0.1", port_);
  18208. // open_stream GET should include Host, User-Agent and Accept-Encoding
  18209. {
  18210. auto handle = cli.open_stream("GET", "/echo-headers");
  18211. ASSERT_TRUE(handle.is_valid());
  18212. auto body = read_all(handle);
  18213. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  18214. std::string::npos);
  18215. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  18216. std::string::npos);
  18217. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  18218. }
  18219. // open_stream POST with body and no explicit content_type should NOT add
  18220. // text/plain Content-Type (behavior differs from non-streaming path), but
  18221. // should include Content-Length
  18222. {
  18223. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  18224. ASSERT_TRUE(handle.is_valid());
  18225. auto body = read_all(handle);
  18226. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  18227. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  18228. }
  18229. // open_stream POST with explicit Content-Type should preserve it
  18230. {
  18231. auto handle = cli.open_stream("POST", "/echo-headers", {},
  18232. {{"Content-Type", "application/custom"}},
  18233. "{}", "application/custom");
  18234. ASSERT_TRUE(handle.is_valid());
  18235. auto body = read_all(handle);
  18236. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  18237. }
  18238. // User-specified User-Agent must not be overwritten for stream API
  18239. {
  18240. auto handle = cli.open_stream("GET", "/echo-headers", {},
  18241. {{"User-Agent", "MyAgent/1.2"}});
  18242. ASSERT_TRUE(handle.is_valid());
  18243. auto body = read_all(handle);
  18244. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  18245. }
  18246. }
  18247. TEST_F(OpenStreamTest, Large) {
  18248. Client cli("127.0.0.1", port_);
  18249. auto handle = cli.open_stream("GET", "/large");
  18250. EXPECT_EQ(10000u, read_all(handle).size());
  18251. }
  18252. TEST_F(OpenStreamTest, ConnectionError) {
  18253. Client cli("127.0.0.1", 9999);
  18254. auto handle = cli.open_stream("GET", "/hello");
  18255. EXPECT_FALSE(handle.is_valid());
  18256. }
  18257. TEST_F(OpenStreamTest, Chunked) {
  18258. Client cli("127.0.0.1", port_);
  18259. auto handle = cli.open_stream("GET", "/chunked");
  18260. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18261. "Transfer-Encoding") == "chunked");
  18262. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  18263. }
  18264. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  18265. Client cli("127.0.0.1", port_);
  18266. auto handle =
  18267. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  18268. ASSERT_TRUE(handle.is_valid());
  18269. // Consume body to allow trailers to be received/parsed
  18270. auto body = read_all(handle);
  18271. // Explicitly parse trailers (ensure trailers are available for assertion)
  18272. handle.parse_trailers_if_needed();
  18273. EXPECT_EQ(std::string("123456789"), body);
  18274. // The response should include a Trailer header declaring both names
  18275. ASSERT_TRUE(handle.response);
  18276. EXPECT_TRUE(handle.response->has_header("Trailer"));
  18277. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  18278. handle.response->get_header_value("Trailer"));
  18279. // Prohibited trailer must not be present
  18280. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  18281. // Allowed trailer should be present
  18282. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  18283. EXPECT_EQ(std::string("yes"),
  18284. handle.response->get_trailer_value("X-Allowed"));
  18285. // Verify trailers are NOT present as regular headers
  18286. EXPECT_EQ(std::string(""),
  18287. handle.response->get_header_value("Content-Length"));
  18288. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  18289. }
  18290. static std::thread serve_single_response(std::promise<int> &port_promise,
  18291. const std::string &response) {
  18292. return std::thread([&port_promise, response] {
  18293. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18294. default_socket_options(srv);
  18295. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18296. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  18297. sockaddr_in addr{};
  18298. addr.sin_family = AF_INET;
  18299. addr.sin_port = htons(0); // Let OS assign a free port
  18300. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18301. int opt = 1;
  18302. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  18303. #ifdef _WIN32
  18304. reinterpret_cast<const char *>(&opt),
  18305. #else
  18306. &opt,
  18307. #endif
  18308. sizeof(opt));
  18309. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  18310. ::listen(srv, 1) != 0) {
  18311. port_promise.set_value(-1);
  18312. detail::close_socket(srv);
  18313. return;
  18314. }
  18315. socklen_t addr_len = sizeof(addr);
  18316. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  18317. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  18318. sockaddr_in cli_addr{};
  18319. socklen_t cli_len = sizeof(cli_addr);
  18320. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18321. if (cli != INVALID_SOCKET) {
  18322. // Read the complete HTTP request (until the blank line that terminates
  18323. // headers) before sending the response. If the server closes the socket
  18324. // while the client's request data is still unread in the kernel receive
  18325. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  18326. // connection on both sides: it discards the client's receive buffer
  18327. // (which already holds our response) and causes any in-progress write on
  18328. // the client to fail with ECONNRESET. Reading all request data first
  18329. // ensures close() emits a graceful FIN.
  18330. {
  18331. char rbuf[256];
  18332. std::string req;
  18333. while (req.find("\r\n\r\n") == std::string::npos) {
  18334. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  18335. if (n <= 0) { break; }
  18336. req.append(rbuf, static_cast<size_t>(n));
  18337. }
  18338. }
  18339. ::send(cli,
  18340. #ifdef _WIN32
  18341. static_cast<const char *>(response.c_str()),
  18342. static_cast<int>(response.size()),
  18343. #else
  18344. response.c_str(), response.size(),
  18345. #endif
  18346. 0);
  18347. detail::close_socket(cli);
  18348. }
  18349. detail::close_socket(srv);
  18350. });
  18351. }
  18352. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  18353. #ifndef _WIN32
  18354. signal(SIGPIPE, SIG_IGN);
  18355. #endif
  18356. std::promise<int> port_promise;
  18357. auto port_future = port_promise.get_future();
  18358. auto server_thread =
  18359. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  18360. "Content-Type: text/plain\r\n"
  18361. "Content-Length: not-a-number\r\n"
  18362. "Connection: close\r\n"
  18363. "\r\n"
  18364. "hello");
  18365. auto port = port_future.get();
  18366. ASSERT_GT(port, 0);
  18367. Client cli("127.0.0.1", port);
  18368. auto handle = cli.open_stream("GET", "/");
  18369. EXPECT_FALSE(handle.is_valid());
  18370. server_thread.join();
  18371. }
  18372. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  18373. #ifndef _WIN32
  18374. signal(SIGPIPE, SIG_IGN);
  18375. #endif
  18376. std::promise<int> port_promise;
  18377. auto port_future = port_promise.get_future();
  18378. auto server_thread = serve_single_response(
  18379. port_promise, "HTTP/1.1 200 OK\r\n"
  18380. "Content-Type: text/plain\r\n"
  18381. "Content-Length: 99999999999999999999999999\r\n"
  18382. "Connection: close\r\n"
  18383. "\r\n"
  18384. "hello");
  18385. auto port = port_future.get();
  18386. ASSERT_GT(port, 0);
  18387. // Historically std::stoull would throw std::out_of_range here and crash
  18388. // the process, then parsing silently clamped to a bogus framing length and
  18389. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  18390. // so the stream fails to open, matching the not-a-number case above. The
  18391. // process still must NOT terminate.
  18392. Client cli("127.0.0.1", port);
  18393. auto handle = cli.open_stream("GET", "/");
  18394. EXPECT_FALSE(handle.is_valid());
  18395. server_thread.join();
  18396. }
  18397. // Serves `response` to the single request `fn` makes with a fresh client.
  18398. template <typename Fn>
  18399. static void with_single_response(const std::string &response, Fn fn) {
  18400. #ifndef _WIN32
  18401. signal(SIGPIPE, SIG_IGN);
  18402. #endif
  18403. std::promise<int> port_promise;
  18404. auto port_future = port_promise.get_future();
  18405. auto server_thread = serve_single_response(port_promise, response);
  18406. auto se = detail::scope_exit([&] { server_thread.join(); });
  18407. auto port = port_future.get();
  18408. ASSERT_GT(port, 0);
  18409. Client cli("127.0.0.1", port);
  18410. fn(cli);
  18411. }
  18412. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  18413. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  18414. // the chunked coding and drop Content-Length, so a front-end that trusts
  18415. // Content-Length would disagree about where the body ends (response
  18416. // smuggling). The client must reject such a response.
  18417. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  18418. for (const char *te : {"chunked", "gzip, chunked"}) {
  18419. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  18420. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  18421. "\r\n" + "Connection: close\r\n" + "\r\n" +
  18422. "5\r\nhello\r\n0\r\n\r\n";
  18423. with_single_response(response, [&](Client &cli) {
  18424. auto res = cli.Get("/");
  18425. EXPECT_FALSE(static_cast<bool>(res)) << te;
  18426. EXPECT_EQ(Error::Read, res.error()) << te;
  18427. });
  18428. with_single_response(response, [&](Client &cli) {
  18429. auto handle = cli.open_stream("GET", "/");
  18430. EXPECT_FALSE(handle.is_valid()) << te;
  18431. EXPECT_EQ(Error::Read, handle.error) << te;
  18432. });
  18433. }
  18434. }
  18435. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  18436. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  18437. // closing the connection (unlike a request, which must be rejected).
  18438. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  18439. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18440. "Transfer-Encoding: chunked\r\n"
  18441. "Connection: close\r\n"
  18442. "\r\n"
  18443. "5\r\nhello\r\n0\r\n\r\n",
  18444. "HTTP/1.1 200 OK\r\n"
  18445. "Transfer-Encoding: gzip\r\n"
  18446. "Connection: close\r\n"
  18447. "\r\n"
  18448. "hello"}) {
  18449. with_single_response(response, [&](Client &cli) {
  18450. auto res = cli.Get("/");
  18451. ASSERT_TRUE(static_cast<bool>(res)) << response;
  18452. EXPECT_EQ("hello", res->body);
  18453. });
  18454. with_single_response(response, [&](Client &cli) {
  18455. auto handle = cli.open_stream("GET", "/");
  18456. ASSERT_TRUE(handle.is_valid()) << response;
  18457. EXPECT_EQ("hello", read_all(handle));
  18458. });
  18459. }
  18460. }
  18461. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  18462. // framing headers describe nothing to read and must not be rejected.
  18463. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  18464. const std::string framing = "Content-Length: 5\r\n"
  18465. "Transfer-Encoding: chunked\r\n"
  18466. "Connection: close\r\n"
  18467. "\r\n";
  18468. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18469. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  18470. });
  18471. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18472. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  18473. });
  18474. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  18475. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  18476. with_single_response(response, [&](Client &cli) {
  18477. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  18478. });
  18479. with_single_response(response, [&](Client &cli) {
  18480. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  18481. });
  18482. }
  18483. }
  18484. // A payload max length of 0 means no limit, however the body is framed.
  18485. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  18486. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18487. "Transfer-Encoding: chunked\r\n"
  18488. "\r\n"
  18489. "5\r\nhello\r\n0\r\n\r\n",
  18490. "HTTP/1.1 200 OK\r\n"
  18491. "Connection: close\r\n"
  18492. "\r\n"
  18493. "hello"}) {
  18494. with_single_response(response, [&](Client &cli) {
  18495. cli.set_payload_max_length(0);
  18496. auto res = cli.Get("/");
  18497. ASSERT_TRUE(res) << response;
  18498. EXPECT_EQ("hello", res->body) << response;
  18499. });
  18500. }
  18501. }
  18502. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  18503. Server svr;
  18504. svr.set_payload_max_length(0);
  18505. svr.Post("/echo", [](const Request &req, Response &res) {
  18506. res.set_content(req.body, "text/plain");
  18507. });
  18508. auto port = svr.bind_to_any_port(HOST);
  18509. thread t = thread([&] { svr.listen_after_bind(); });
  18510. auto se = detail::scope_exit([&] {
  18511. svr.stop();
  18512. t.join();
  18513. ASSERT_FALSE(svr.is_running());
  18514. });
  18515. svr.wait_until_ready();
  18516. Client cli(HOST, port);
  18517. auto res = cli.Post(
  18518. "/echo",
  18519. [](size_t /*offset*/, DataSink &sink) {
  18520. sink.write("hello", 5);
  18521. sink.done();
  18522. return true;
  18523. },
  18524. "text/plain");
  18525. ASSERT_TRUE(res);
  18526. EXPECT_EQ(StatusCode::OK_200, res->status);
  18527. EXPECT_EQ("hello", res->body);
  18528. }
  18529. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18530. TEST_F(OpenStreamTest, Gzip) {
  18531. Client cli("127.0.0.1", port_);
  18532. auto handle = cli.open_stream("GET", "/compressible", {},
  18533. {{"Accept-Encoding", "gzip"}});
  18534. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  18535. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18536. }
  18537. #endif
  18538. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18539. TEST_F(OpenStreamTest, Brotli) {
  18540. Client cli("127.0.0.1", port_);
  18541. auto handle =
  18542. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  18543. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  18544. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18545. }
  18546. #endif
  18547. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18548. TEST_F(OpenStreamTest, Zstd) {
  18549. Client cli("127.0.0.1", port_);
  18550. auto handle = cli.open_stream("GET", "/compressible", {},
  18551. {{"Accept-Encoding", "zstd"}});
  18552. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  18553. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18554. }
  18555. #endif
  18556. #ifdef CPPHTTPLIB_SSL_ENABLED
  18557. class SSLOpenStreamTest : public ::testing::Test {
  18558. protected:
  18559. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  18560. void SetUp() override {
  18561. svr_.Get("/hello", [](const Request &, Response &res) {
  18562. res.set_content("Hello SSL World!", "text/plain");
  18563. });
  18564. svr_.Get("/chunked", [](const Request &, Response &res) {
  18565. res.set_chunked_content_provider("text/plain",
  18566. [](size_t offset, DataSink &sink) {
  18567. if (offset < 15) {
  18568. sink.write("chunk", 5);
  18569. return true;
  18570. }
  18571. sink.done();
  18572. return true;
  18573. });
  18574. });
  18575. svr_.Post("/echo", [](const Request &req, Response &res) {
  18576. res.set_content(req.body, req.get_header_value("Content-Type"));
  18577. });
  18578. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  18579. std::string body = req.body;
  18580. res.set_chunked_content_provider(
  18581. "text/plain", [body](size_t offset, DataSink &sink) {
  18582. if (offset < body.size()) {
  18583. sink.write(body.data() + offset, body.size() - offset);
  18584. }
  18585. sink.done();
  18586. return true;
  18587. });
  18588. });
  18589. port_ = svr_.bind_to_any_port("127.0.0.1");
  18590. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18591. svr_.wait_until_ready();
  18592. }
  18593. void TearDown() override {
  18594. svr_.stop();
  18595. if (thread_.joinable()) thread_.join();
  18596. }
  18597. SSLServer svr_;
  18598. std::thread thread_;
  18599. int port_ = 0;
  18600. };
  18601. TEST_F(SSLOpenStreamTest, Basic) {
  18602. SSLClient cli("127.0.0.1", port_);
  18603. cli.enable_server_certificate_verification(false);
  18604. auto handle = cli.open_stream("GET", "/hello");
  18605. ASSERT_TRUE(handle.is_valid());
  18606. EXPECT_EQ("Hello SSL World!", read_all(handle));
  18607. }
  18608. TEST_F(SSLOpenStreamTest, Chunked) {
  18609. SSLClient cli("127.0.0.1", port_);
  18610. cli.enable_server_certificate_verification(false);
  18611. auto handle = cli.open_stream("GET", "/chunked");
  18612. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18613. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18614. "Transfer-Encoding") == "chunked");
  18615. auto body = read_all(handle);
  18616. EXPECT_EQ("chunkchunkchunk", body);
  18617. }
  18618. TEST_F(SSLOpenStreamTest, Post) {
  18619. SSLClient cli("127.0.0.1", port_);
  18620. cli.enable_server_certificate_verification(false);
  18621. auto handle =
  18622. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  18623. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18624. EXPECT_EQ(200, handle.response->status);
  18625. auto body = read_all(handle);
  18626. EXPECT_EQ("Hello SSL POST", body);
  18627. }
  18628. TEST_F(SSLOpenStreamTest, PostChunked) {
  18629. SSLClient cli("127.0.0.1", port_);
  18630. cli.enable_server_certificate_verification(false);
  18631. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  18632. "Chunked SSL Data", "text/plain");
  18633. ASSERT_TRUE(handle.is_valid());
  18634. EXPECT_EQ(200, handle.response->status);
  18635. auto body = read_all(handle);
  18636. EXPECT_EQ("Chunked SSL Data", body);
  18637. }
  18638. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  18639. // Content-Length is terminated by the server closing the connection. When the
  18640. // SSL peer sends a close_notify after the body, the client must treat it as a
  18641. // clean EOF and return a successful response rather than an error.
  18642. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  18643. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18644. ASSERT_TRUE(svr.is_valid());
  18645. svr.set_keep_alive_max_count(1);
  18646. const std::string expected_body = "Hello from connection-close response!";
  18647. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  18648. res.set_content_provider("text/plain",
  18649. [&](size_t offset, DataSink &sink) -> bool {
  18650. if (offset < expected_body.size()) {
  18651. sink.write(expected_body.data() + offset,
  18652. expected_body.size() - offset);
  18653. }
  18654. sink.done();
  18655. return true;
  18656. });
  18657. });
  18658. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  18659. auto se = detail::scope_exit([&] {
  18660. svr.stop();
  18661. listen_thread.join();
  18662. ASSERT_FALSE(svr.is_running());
  18663. });
  18664. svr.wait_until_ready();
  18665. SSLClient cli(HOST, PORT);
  18666. cli.enable_server_certificate_verification(false);
  18667. auto res = cli.Get("/no-content-length");
  18668. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  18669. EXPECT_EQ(StatusCode::OK_200, res->status);
  18670. EXPECT_EQ(expected_body, res->body);
  18671. }
  18672. #endif // CPPHTTPLIB_SSL_ENABLED
  18673. //==============================================================================
  18674. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  18675. // results for various scenarios.
  18676. //==============================================================================
  18677. TEST(ParityTest, GetVsOpenStream) {
  18678. Server svr;
  18679. const std::string path = "/parity";
  18680. const std::string content = "Parity test content: hello world";
  18681. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18682. res.set_content(content, "text/plain");
  18683. });
  18684. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18685. auto se = detail::scope_exit([&] {
  18686. svr.stop();
  18687. t.join();
  18688. ASSERT_FALSE(svr.is_running());
  18689. });
  18690. svr.wait_until_ready();
  18691. Client cli(HOST, PORT);
  18692. // Non-stream path
  18693. auto r1 = cli.Get(path);
  18694. ASSERT_TRUE(r1);
  18695. EXPECT_EQ(StatusCode::OK_200, r1->status);
  18696. // Stream path
  18697. auto h = cli.open_stream("GET", path);
  18698. ASSERT_TRUE(h.is_valid());
  18699. EXPECT_EQ(r1->body, read_all(h));
  18700. }
  18701. // Helper to compress data with provided compressor type T
  18702. template <typename Compressor>
  18703. static std::string compress_payload_for_parity(const std::string &in) {
  18704. std::string out;
  18705. Compressor compressor;
  18706. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  18707. [&](const char *data, size_t n) {
  18708. out.append(data, n);
  18709. return true;
  18710. });
  18711. EXPECT_TRUE(ok);
  18712. return out;
  18713. }
  18714. // Helper function for compression parity tests
  18715. template <typename Compressor>
  18716. static void test_compression_parity(const std::string &original,
  18717. const std::string &path,
  18718. const std::string &encoding) {
  18719. const std::string compressed =
  18720. compress_payload_for_parity<Compressor>(original);
  18721. Server svr;
  18722. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18723. res.set_content(compressed, "application/octet-stream");
  18724. res.set_header("Content-Encoding", encoding);
  18725. });
  18726. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  18727. auto se = detail::scope_exit([&] {
  18728. svr.stop();
  18729. t.join();
  18730. ASSERT_FALSE(svr.is_running());
  18731. });
  18732. svr.wait_until_ready();
  18733. Client cli(HOST, PORT);
  18734. // Non-streaming
  18735. {
  18736. auto res = cli.Get(path);
  18737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18738. EXPECT_EQ(StatusCode::OK_200, res->status);
  18739. EXPECT_EQ(original, res->body);
  18740. }
  18741. // Streaming
  18742. {
  18743. auto h = cli.open_stream("GET", path);
  18744. ASSERT_TRUE(h.is_valid());
  18745. EXPECT_EQ(original, read_all(h));
  18746. }
  18747. }
  18748. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18749. TEST(ParityTest, Gzip) {
  18750. test_compression_parity<detail::gzip_compressor>(
  18751. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  18752. }
  18753. #endif
  18754. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18755. TEST(ParityTest, Brotli) {
  18756. test_compression_parity<detail::brotli_compressor>(
  18757. "Hello, brotli parity test payload", "/parity-br", "br");
  18758. }
  18759. #endif
  18760. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18761. TEST(ParityTest, Zstd) {
  18762. test_compression_parity<detail::zstd_compressor>(
  18763. "Zstandard parity test payload", "/parity-zstd", "zstd");
  18764. }
  18765. #endif
  18766. //==============================================================================
  18767. // New Stream API Tests
  18768. //==============================================================================
  18769. inline std::string read_body(httplib::stream::Result &result) {
  18770. std::string body;
  18771. while (result.next()) {
  18772. body.append(result.data(), result.size());
  18773. }
  18774. return body;
  18775. }
  18776. TEST(ClientConnectionTest, Basic) {
  18777. httplib::ClientConnection conn;
  18778. EXPECT_FALSE(conn.is_open());
  18779. conn.sock = 1;
  18780. EXPECT_TRUE(conn.is_open());
  18781. httplib::ClientConnection conn2(std::move(conn));
  18782. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  18783. conn2.sock = INVALID_SOCKET;
  18784. }
  18785. // Unified test server for all stream::* tests
  18786. class StreamApiTest : public ::testing::Test {
  18787. protected:
  18788. void SetUp() override {
  18789. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18790. res.set_content("Hello World!", "text/plain");
  18791. });
  18792. svr_.Get("/echo-params",
  18793. [](const httplib::Request &req, httplib::Response &res) {
  18794. std::string r;
  18795. for (const auto &p : req.params) {
  18796. if (!r.empty()) r += "&";
  18797. r += p.first + "=" + p.second;
  18798. }
  18799. res.set_content(r, "text/plain");
  18800. });
  18801. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18802. res.set_content(req.body, req.get_header_value("Content-Type"));
  18803. });
  18804. svr_.Post("/echo-headers",
  18805. [](const httplib::Request &req, httplib::Response &res) {
  18806. std::string r;
  18807. for (const auto &h : req.headers)
  18808. r += h.first + ": " + h.second + "\n";
  18809. res.set_content(r, "text/plain");
  18810. });
  18811. svr_.Post("/echo-params",
  18812. [](const httplib::Request &req, httplib::Response &res) {
  18813. std::string r = "params:";
  18814. for (const auto &p : req.params)
  18815. r += p.first + "=" + p.second + ";";
  18816. res.set_content(r + " body:" + req.body, "text/plain");
  18817. });
  18818. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  18819. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  18820. });
  18821. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18822. res.set_content("PUT:" + req.body, "text/plain");
  18823. });
  18824. svr_.Patch("/echo",
  18825. [](const httplib::Request &req, httplib::Response &res) {
  18826. res.set_content("PATCH:" + req.body, "text/plain");
  18827. });
  18828. svr_.Delete(
  18829. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  18830. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  18831. "text/plain");
  18832. });
  18833. svr_.Get("/head-test",
  18834. [](const httplib::Request &, httplib::Response &res) {
  18835. res.set_content("body for HEAD", "text/plain");
  18836. });
  18837. svr_.Options("/options",
  18838. [](const httplib::Request &, httplib::Response &res) {
  18839. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  18840. });
  18841. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  18842. svr_.wait_until_ready();
  18843. }
  18844. void TearDown() override {
  18845. svr_.stop();
  18846. if (thread_.joinable()) thread_.join();
  18847. }
  18848. httplib::Server svr_;
  18849. std::thread thread_;
  18850. };
  18851. // stream::Get tests
  18852. TEST_F(StreamApiTest, GetBasic) {
  18853. httplib::Client cli(HOST, PORT);
  18854. auto result = httplib::stream::Get(cli, "/hello");
  18855. ASSERT_TRUE(result.is_valid());
  18856. EXPECT_EQ(200, result.status());
  18857. EXPECT_EQ("Hello World!", read_body(result));
  18858. }
  18859. TEST_F(StreamApiTest, GetWithParams) {
  18860. httplib::Client cli(HOST, PORT);
  18861. httplib::Params params{{"foo", "bar"}};
  18862. auto result = httplib::stream::Get(cli, "/echo-params", params);
  18863. ASSERT_TRUE(result.is_valid());
  18864. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  18865. }
  18866. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18867. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  18868. httplib::Client cli(HOST, PORT);
  18869. cli.set_payload_max_length(0);
  18870. auto result = httplib::stream::Get(cli, "/hello");
  18871. ASSERT_TRUE(result.is_valid());
  18872. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  18873. EXPECT_EQ("Hello World!", read_body(result));
  18874. }
  18875. #endif
  18876. TEST_F(StreamApiTest, GetConnectionError) {
  18877. httplib::Client cli(HOST, 9999);
  18878. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  18879. }
  18880. TEST_F(StreamApiTest, Get404) {
  18881. httplib::Client cli(HOST, PORT);
  18882. auto result = httplib::stream::Get(cli, "/nonexistent");
  18883. EXPECT_TRUE(result.is_valid());
  18884. EXPECT_EQ(404, result.status());
  18885. }
  18886. // stream::Post tests
  18887. TEST_F(StreamApiTest, PostBasic) {
  18888. httplib::Client cli(HOST, PORT);
  18889. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  18890. "application/json");
  18891. ASSERT_TRUE(result.is_valid());
  18892. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  18893. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  18894. }
  18895. TEST_F(StreamApiTest, PostWithHeaders) {
  18896. httplib::Client cli(HOST, PORT);
  18897. httplib::Headers headers{{"X-Custom", "value"}};
  18898. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  18899. "text/plain");
  18900. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  18901. }
  18902. TEST_F(StreamApiTest, PostWithParams) {
  18903. httplib::Client cli(HOST, PORT);
  18904. httplib::Params params{{"k", "v"}};
  18905. auto result =
  18906. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  18907. auto body = read_body(result);
  18908. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  18909. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  18910. }
  18911. TEST_F(StreamApiTest, PostLarge) {
  18912. httplib::Client cli(HOST, PORT);
  18913. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  18914. size_t total = 0;
  18915. while (result.next()) {
  18916. total += result.size();
  18917. }
  18918. EXPECT_EQ(100u * 1024u, total);
  18919. }
  18920. // stream::Put/Patch tests
  18921. TEST_F(StreamApiTest, PutAndPatch) {
  18922. httplib::Client cli(HOST, PORT);
  18923. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  18924. EXPECT_EQ("PUT:test", read_body(put));
  18925. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  18926. EXPECT_EQ("PATCH:test", read_body(patch));
  18927. }
  18928. // stream::Delete tests
  18929. TEST_F(StreamApiTest, Delete) {
  18930. httplib::Client cli(HOST, PORT);
  18931. auto del1 = httplib::stream::Delete(cli, "/resource");
  18932. EXPECT_EQ("Deleted", read_body(del1));
  18933. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  18934. EXPECT_EQ("Deleted:data", read_body(del2));
  18935. }
  18936. // stream::Head/Options tests
  18937. TEST_F(StreamApiTest, HeadAndOptions) {
  18938. httplib::Client cli(HOST, PORT);
  18939. auto head = httplib::stream::Head(cli, "/head-test");
  18940. EXPECT_TRUE(head.is_valid());
  18941. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  18942. auto opts = httplib::stream::Options(cli, "/options");
  18943. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  18944. }
  18945. // SSL stream::* tests
  18946. #ifdef CPPHTTPLIB_SSL_ENABLED
  18947. class SSLStreamApiTest : public ::testing::Test {
  18948. protected:
  18949. void SetUp() override {
  18950. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18951. res.set_content("Hello SSL!", "text/plain");
  18952. });
  18953. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18954. res.set_content(req.body, "text/plain");
  18955. });
  18956. port_ = svr_.bind_to_any_port("127.0.0.1");
  18957. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18958. svr_.wait_until_ready();
  18959. }
  18960. void TearDown() override {
  18961. svr_.stop();
  18962. if (thread_.joinable()) thread_.join();
  18963. }
  18964. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  18965. std::thread thread_;
  18966. int port_ = 0;
  18967. };
  18968. TEST_F(SSLStreamApiTest, GetAndPost) {
  18969. httplib::SSLClient cli("127.0.0.1", port_);
  18970. cli.enable_server_certificate_verification(false);
  18971. auto get = httplib::stream::Get(cli, "/hello");
  18972. EXPECT_EQ("Hello SSL!", read_body(get));
  18973. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  18974. EXPECT_EQ("test", read_body(post));
  18975. }
  18976. #endif
  18977. // Tests for Error::Timeout and Error::ConnectionClosed error types
  18978. // These errors are set in SocketStream/SSLSocketStream and propagated through
  18979. // BodyReader
  18980. TEST(ErrorHandlingTest, StreamReadTimeout) {
  18981. // Test that read timeout during streaming is detected
  18982. // Use a large content-length response where server delays mid-stream
  18983. Server svr;
  18984. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18985. // Send a large response with delay in the middle
  18986. res.set_content_provider(
  18987. 1000, // content_length
  18988. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  18989. if (offset < 100) {
  18990. // Send first 100 bytes immediately
  18991. std::string data(100, 'A');
  18992. sink.write(data.c_str(), data.size());
  18993. return true;
  18994. }
  18995. // Then delay longer than client timeout
  18996. std::this_thread::sleep_for(std::chrono::seconds(3));
  18997. std::string data(900, 'B');
  18998. sink.write(data.c_str(), data.size());
  18999. return true;
  19000. });
  19001. });
  19002. auto port = 8091;
  19003. std::thread t([&]() { svr.listen("localhost", port); });
  19004. svr.wait_until_ready();
  19005. Client cli("localhost", port);
  19006. cli.set_read_timeout(1, 0); // 1 second timeout
  19007. auto handle = cli.open_stream("GET", "/slow-stream");
  19008. ASSERT_TRUE(handle.is_valid());
  19009. char buf[256];
  19010. ssize_t total = 0;
  19011. ssize_t n;
  19012. bool got_error = false;
  19013. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19014. total += n;
  19015. }
  19016. if (n < 0) {
  19017. got_error = true;
  19018. // Should be timeout or read error
  19019. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19020. handle.get_read_error() == Error::Read)
  19021. << "Actual error: " << to_string(handle.get_read_error());
  19022. }
  19023. // Either we got an error, or we got less data than expected
  19024. EXPECT_TRUE(got_error || total < 1000)
  19025. << "Expected timeout but got all " << total << " bytes";
  19026. svr.stop();
  19027. t.join();
  19028. }
  19029. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  19030. // Test connection closed detection via BodyReader
  19031. Server svr;
  19032. std::atomic<bool> close_now{false};
  19033. svr.Get("/will-close", [&](const Request &, Response &res) {
  19034. res.set_content_provider(
  19035. 10000, // Large content_length that we won't fully send
  19036. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19037. if (offset < 100) {
  19038. std::string data(100, 'X');
  19039. sink.write(data.c_str(), data.size());
  19040. return true;
  19041. }
  19042. // Wait for signal then abort
  19043. while (!close_now) {
  19044. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19045. }
  19046. return false; // Abort - server will close connection
  19047. });
  19048. });
  19049. auto port = 8092;
  19050. std::thread t([&]() { svr.listen("localhost", port); });
  19051. svr.wait_until_ready();
  19052. Client cli("localhost", port);
  19053. auto handle = cli.open_stream("GET", "/will-close");
  19054. ASSERT_TRUE(handle.is_valid());
  19055. char buf[256];
  19056. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19057. EXPECT_GT(n, 0) << "First read should succeed";
  19058. // Signal server to close
  19059. close_now = true;
  19060. // Keep reading until error or EOF
  19061. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19062. // Keep reading
  19063. }
  19064. // Should get an error since content_length wasn't satisfied
  19065. if (n < 0) {
  19066. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19067. handle.get_read_error() == Error::Read)
  19068. << "Actual error: " << to_string(handle.get_read_error());
  19069. }
  19070. svr.stop();
  19071. t.join();
  19072. }
  19073. #ifdef CPPHTTPLIB_SSL_ENABLED
  19074. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  19075. // Test that read timeout during SSL streaming is detected
  19076. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19077. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19078. res.set_content_provider(
  19079. 1000, "text/plain",
  19080. [](size_t offset, size_t /*length*/, DataSink &sink) {
  19081. if (offset < 100) {
  19082. std::string data(100, 'A');
  19083. sink.write(data.c_str(), data.size());
  19084. return true;
  19085. }
  19086. std::this_thread::sleep_for(std::chrono::seconds(3));
  19087. std::string data(900, 'B');
  19088. sink.write(data.c_str(), data.size());
  19089. return true;
  19090. });
  19091. });
  19092. auto port = 8093;
  19093. std::thread t([&]() { svr.listen("localhost", port); });
  19094. svr.wait_until_ready();
  19095. SSLClient cli("localhost", port);
  19096. cli.enable_server_certificate_verification(false);
  19097. cli.set_read_timeout(1, 0); // 1 second timeout
  19098. auto handle = cli.open_stream("GET", "/slow-stream");
  19099. ASSERT_TRUE(handle.is_valid());
  19100. char buf[256];
  19101. ssize_t total = 0;
  19102. ssize_t n;
  19103. bool got_error = false;
  19104. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19105. total += n;
  19106. }
  19107. if (n < 0) {
  19108. got_error = true;
  19109. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19110. handle.get_read_error() == Error::Read)
  19111. << "Actual error: " << to_string(handle.get_read_error());
  19112. }
  19113. EXPECT_TRUE(got_error || total < 1000)
  19114. << "Expected timeout but got all " << total << " bytes";
  19115. svr.stop();
  19116. t.join();
  19117. }
  19118. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  19119. // Test SSL connection closed detection
  19120. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19121. std::atomic<bool> close_now{false};
  19122. svr.Get("/will-close", [&](const Request &, Response &res) {
  19123. res.set_content_provider(
  19124. 10000, "text/plain",
  19125. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19126. if (offset < 100) {
  19127. std::string data(100, 'X');
  19128. sink.write(data.c_str(), data.size());
  19129. return true;
  19130. }
  19131. while (!close_now) {
  19132. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19133. }
  19134. return false;
  19135. });
  19136. });
  19137. auto port = 8094;
  19138. std::thread t([&]() { svr.listen("localhost", port); });
  19139. svr.wait_until_ready();
  19140. SSLClient cli("localhost", port);
  19141. cli.enable_server_certificate_verification(false);
  19142. auto handle = cli.open_stream("GET", "/will-close");
  19143. ASSERT_TRUE(handle.is_valid());
  19144. char buf[256];
  19145. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19146. EXPECT_GT(n, 0);
  19147. // Signal server to close
  19148. close_now = true;
  19149. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19150. // Keep reading
  19151. }
  19152. if (n < 0) {
  19153. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19154. handle.get_read_error() == Error::Read)
  19155. << "Actual error: " << to_string(handle.get_read_error());
  19156. }
  19157. svr.stop();
  19158. t.join();
  19159. }
  19160. #endif
  19161. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  19162. using namespace httplib;
  19163. // Create a test file
  19164. const char *fname = "etag_testfile.txt";
  19165. const char *content = "etag-content";
  19166. {
  19167. std::ofstream ofs(fname);
  19168. ofs << content;
  19169. ASSERT_TRUE(ofs.good());
  19170. }
  19171. Server svr;
  19172. svr.set_mount_point("/static", ".");
  19173. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19174. svr.wait_until_ready();
  19175. Client cli(HOST, PORT);
  19176. // First request: should get 200 with ETag header
  19177. auto res1 = cli.Get("/static/etag_testfile.txt");
  19178. ASSERT_TRUE(res1);
  19179. ASSERT_EQ(200, res1->status);
  19180. ASSERT_TRUE(res1->has_header("ETag"));
  19181. std::string etag = res1->get_header_value("ETag");
  19182. EXPECT_FALSE(etag.empty());
  19183. // Verify ETag format: W/"hex-hex"
  19184. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  19185. EXPECT_EQ('W', etag[0]);
  19186. EXPECT_EQ('/', etag[1]);
  19187. EXPECT_EQ('"', etag[2]);
  19188. EXPECT_EQ('"', etag.back());
  19189. // Exact match: expect 304 Not Modified
  19190. Headers h2 = {{"If-None-Match", etag}};
  19191. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  19192. ASSERT_TRUE(res2);
  19193. EXPECT_EQ(304, res2->status);
  19194. // Wildcard match: expect 304 Not Modified
  19195. Headers h3 = {{"If-None-Match", "*"}};
  19196. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  19197. ASSERT_TRUE(res3);
  19198. EXPECT_EQ(304, res3->status);
  19199. // Non-matching ETag: expect 200
  19200. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  19201. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  19202. ASSERT_TRUE(res4);
  19203. EXPECT_EQ(200, res4->status);
  19204. // Multiple ETags with one matching: expect 304
  19205. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  19206. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  19207. ASSERT_TRUE(res5);
  19208. EXPECT_EQ(304, res5->status);
  19209. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  19210. // that equivalent to the single comma-separated list above, so the match on
  19211. // the second line must still be found.
  19212. Headers h6;
  19213. h6.emplace("If-None-Match", "W/\"other\"");
  19214. h6.emplace("If-None-Match", etag);
  19215. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  19216. ASSERT_TRUE(res6);
  19217. EXPECT_EQ(304, res6->status);
  19218. svr.stop();
  19219. t.join();
  19220. std::remove(fname);
  19221. }
  19222. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  19223. using namespace httplib;
  19224. Server svr;
  19225. svr.set_mount_point("/static", ".");
  19226. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19227. svr.wait_until_ready();
  19228. Client cli(HOST, PORT);
  19229. // Send If-None-Match: * to a non-existent file
  19230. Headers h = {{"If-None-Match", "*"}};
  19231. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  19232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19233. EXPECT_EQ(404, res->status);
  19234. svr.stop();
  19235. t.join();
  19236. }
  19237. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  19238. using namespace httplib;
  19239. // Create a test file
  19240. const char *fname = "etag_boundary_testfile.txt";
  19241. const char *content = "boundary-test";
  19242. {
  19243. std::ofstream ofs(fname);
  19244. ofs << content;
  19245. ASSERT_TRUE(ofs.good());
  19246. }
  19247. Server svr;
  19248. svr.set_mount_point("/static", ".");
  19249. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19250. svr.wait_until_ready();
  19251. Client cli(HOST, PORT);
  19252. // Get the actual ETag
  19253. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  19254. ASSERT_TRUE(res1);
  19255. ASSERT_EQ(200, res1->status);
  19256. ASSERT_TRUE(res1->has_header("ETag"));
  19257. std::string etag = res1->get_header_value("ETag");
  19258. // Test 1: Very long ETag value (longer than actual ETag)
  19259. // Should NOT match and return 200 (not trigger out-of-bounds read)
  19260. Headers h1 = {{"If-None-Match", "W/"
  19261. "\"very-long-etag-value-that-is-much-longer-"
  19262. "than-the-actual-etag-value\""}};
  19263. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  19264. ASSERT_TRUE(res2);
  19265. EXPECT_EQ(200, res2->status); // Should not match
  19266. // Test 2: Long string followed by wildcard
  19267. // Should match on "*" and return 304 (without out-of-bounds read on the long
  19268. // string)
  19269. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  19270. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  19271. ASSERT_TRUE(res3);
  19272. EXPECT_EQ(304, res3->status); // Should match on "*"
  19273. // Test 3: Wildcard followed by long string
  19274. // Should match on "*" immediately and return 304
  19275. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  19276. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  19277. ASSERT_TRUE(res4);
  19278. EXPECT_EQ(304, res4->status); // Should match on "*"
  19279. // Test 4: Multiple long non-matching values
  19280. // Should NOT match and return 200 (test that all comparisons are safe)
  19281. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  19282. "W/\"second-long-non-matching-value\", "
  19283. "W/\"third-long-non-matching-value\""}};
  19284. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  19285. ASSERT_TRUE(res5);
  19286. EXPECT_EQ(200, res5->status); // Should not match
  19287. // Test 5: Single character that is not "*" (edge case)
  19288. Headers h5 = {{"If-None-Match", "X"}};
  19289. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  19290. ASSERT_TRUE(res6);
  19291. EXPECT_EQ(200, res6->status); // Should not match
  19292. svr.stop();
  19293. t.join();
  19294. std::remove(fname);
  19295. }
  19296. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  19297. using namespace httplib;
  19298. // Create a test file
  19299. const char *fname = "ims_testfile.txt";
  19300. const char *content = "if-modified-since-test";
  19301. {
  19302. std::ofstream ofs(fname);
  19303. ofs << content;
  19304. ASSERT_TRUE(ofs.good());
  19305. }
  19306. Server svr;
  19307. svr.set_mount_point("/static", ".");
  19308. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19309. svr.wait_until_ready();
  19310. Client cli(HOST, PORT);
  19311. // First request: should get 200 with Last-Modified header
  19312. auto res1 = cli.Get("/static/ims_testfile.txt");
  19313. ASSERT_TRUE(res1);
  19314. ASSERT_EQ(200, res1->status);
  19315. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19316. std::string last_modified = res1->get_header_value("Last-Modified");
  19317. EXPECT_FALSE(last_modified.empty());
  19318. // If-Modified-Since with same time: expect 304
  19319. Headers h2 = {{"If-Modified-Since", last_modified}};
  19320. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  19321. ASSERT_TRUE(res2);
  19322. EXPECT_EQ(304, res2->status);
  19323. // If-Modified-Since with future time: expect 304
  19324. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19325. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  19326. ASSERT_TRUE(res3);
  19327. EXPECT_EQ(304, res3->status);
  19328. // If-Modified-Since with past time: expect 200
  19329. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19330. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  19331. ASSERT_TRUE(res4);
  19332. EXPECT_EQ(200, res4->status);
  19333. // If-None-Match takes precedence over If-Modified-Since
  19334. // (send matching ETag with old If-Modified-Since -> should still be 304)
  19335. ASSERT_TRUE(res1->has_header("ETag"));
  19336. std::string etag = res1->get_header_value("ETag");
  19337. Headers h5 = {{"If-None-Match", etag},
  19338. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19339. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  19340. ASSERT_TRUE(res5);
  19341. EXPECT_EQ(304, res5->status);
  19342. svr.stop();
  19343. t.join();
  19344. std::remove(fname);
  19345. }
  19346. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  19347. using namespace httplib;
  19348. Server svr;
  19349. // Endpoint that returns compressible content
  19350. svr.Get("/compressible", [](const Request &, Response &res) {
  19351. // Return a large enough body to trigger compression
  19352. std::string body(1000, 'a');
  19353. res.set_content(body, "text/plain");
  19354. });
  19355. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19356. svr.wait_until_ready();
  19357. Client cli(HOST, PORT);
  19358. // Request with gzip support: should get Vary header when compressed
  19359. cli.set_compress(true);
  19360. auto res1 = cli.Get("/compressible");
  19361. ASSERT_TRUE(res1);
  19362. EXPECT_EQ(200, res1->status);
  19363. // If Content-Encoding is set, Vary should also be set
  19364. if (res1->has_header("Content-Encoding")) {
  19365. EXPECT_TRUE(res1->has_header("Vary"));
  19366. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  19367. }
  19368. // Request without Accept-Encoding header: should not have compression
  19369. Headers h_no_compress;
  19370. auto res2 = cli.Get("/compressible", h_no_compress);
  19371. ASSERT_TRUE(res2);
  19372. EXPECT_EQ(200, res2->status);
  19373. // Verify Vary header is present when compression is applied
  19374. // (the exact behavior depends on server configuration)
  19375. svr.stop();
  19376. t.join();
  19377. }
  19378. TEST(ETagTest, IfRangeWithETag) {
  19379. using namespace httplib;
  19380. // Create a test file with known content
  19381. const char *fname = "if_range_testfile.txt";
  19382. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  19383. {
  19384. std::ofstream ofs(fname);
  19385. ofs << content;
  19386. ASSERT_TRUE(ofs.good());
  19387. }
  19388. Server svr;
  19389. svr.set_mount_point("/static", ".");
  19390. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19391. svr.wait_until_ready();
  19392. Client cli(HOST, PORT);
  19393. // First request: get ETag
  19394. auto res1 = cli.Get("/static/if_range_testfile.txt");
  19395. ASSERT_TRUE(res1);
  19396. ASSERT_EQ(200, res1->status);
  19397. ASSERT_TRUE(res1->has_header("ETag"));
  19398. std::string etag = res1->get_header_value("ETag");
  19399. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  19400. // Since our server generates weak ETags (W/"..."), If-Range with our
  19401. // ETag should NOT result in partial content - it should return full content.
  19402. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  19403. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  19404. ASSERT_TRUE(res2);
  19405. // Weak ETag in If-Range -> full content (200), not partial (206)
  19406. EXPECT_EQ(200, res2->status);
  19407. EXPECT_EQ(content, res2->body);
  19408. EXPECT_FALSE(res2->has_header("Content-Range"));
  19409. // Range request with non-matching If-Range (ETag): should get 200 (full
  19410. // content)
  19411. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  19412. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  19413. ASSERT_TRUE(res3);
  19414. EXPECT_EQ(200, res3->status);
  19415. EXPECT_EQ(content, res3->body);
  19416. EXPECT_FALSE(res3->has_header("Content-Range"));
  19417. // Range request with strong ETag (hypothetical - our server doesn't generate
  19418. // strong ETags, but if client sends a strong ETag that doesn't match, it
  19419. // should return full content)
  19420. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  19421. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  19422. ASSERT_TRUE(res4);
  19423. EXPECT_EQ(200, res4->status);
  19424. EXPECT_EQ(content, res4->body);
  19425. EXPECT_FALSE(res4->has_header("Content-Range"));
  19426. svr.stop();
  19427. t.join();
  19428. std::remove(fname);
  19429. }
  19430. TEST(ETagTest, IfRangeWithDate) {
  19431. using namespace httplib;
  19432. // Create a test file
  19433. const char *fname = "if_range_date_testfile.txt";
  19434. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  19435. {
  19436. std::ofstream ofs(fname);
  19437. ofs << content;
  19438. ASSERT_TRUE(ofs.good());
  19439. }
  19440. Server svr;
  19441. svr.set_mount_point("/static", ".");
  19442. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19443. svr.wait_until_ready();
  19444. Client cli(HOST, PORT);
  19445. // First request: get Last-Modified
  19446. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  19447. ASSERT_TRUE(res1);
  19448. ASSERT_EQ(200, res1->status);
  19449. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19450. std::string last_modified = res1->get_header_value("Last-Modified");
  19451. // Range request with matching If-Range (date): should get 206
  19452. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  19453. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  19454. ASSERT_TRUE(res2);
  19455. EXPECT_EQ(206, res2->status);
  19456. EXPECT_EQ("FGHIJ", res2->body);
  19457. // Range request with old If-Range date: should get 200 (full content)
  19458. Headers h3 = {{"Range", "bytes=5-9"},
  19459. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19460. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  19461. ASSERT_TRUE(res3);
  19462. EXPECT_EQ(200, res3->status);
  19463. EXPECT_EQ(content, res3->body);
  19464. // Range request with future If-Range date: should get 206
  19465. Headers h4 = {{"Range", "bytes=0-4"},
  19466. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19467. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  19468. ASSERT_TRUE(res4);
  19469. EXPECT_EQ(206, res4->status);
  19470. EXPECT_EQ("ABCDE", res4->body);
  19471. svr.stop();
  19472. t.join();
  19473. std::remove(fname);
  19474. }
  19475. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  19476. using namespace httplib;
  19477. const char *fname = "etag_malformed.txt";
  19478. const char *content = "malformed-etag";
  19479. {
  19480. std::ofstream ofs(fname);
  19481. ofs << content;
  19482. ASSERT_TRUE(ofs.good());
  19483. }
  19484. Server svr;
  19485. svr.set_mount_point("/static", ".");
  19486. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19487. svr.wait_until_ready();
  19488. Client cli(HOST, PORT);
  19489. // baseline: should get 200 and an ETag
  19490. auto res1 = cli.Get("/static/etag_malformed.txt");
  19491. ASSERT_TRUE(res1);
  19492. ASSERT_EQ(200, res1->status);
  19493. ASSERT_TRUE(res1->has_header("ETag"));
  19494. // Malformed ETag value (missing quotes) should be treated as non-matching
  19495. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  19496. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  19497. ASSERT_TRUE(res_bad);
  19498. EXPECT_EQ(200, res_bad->status);
  19499. // Whitespace-only header value should be considered invalid / non-matching
  19500. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  19501. "Host: localhost\r\n"
  19502. "If-None-Match: \r\n"
  19503. "Connection: close\r\n"
  19504. "\r\n";
  19505. std::string out;
  19506. ASSERT_TRUE(send_request(5, raw_req, &out));
  19507. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19508. svr.stop();
  19509. t.join();
  19510. std::remove(fname);
  19511. }
  19512. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  19513. using namespace httplib;
  19514. const char *fname = "ims_invalid_format.txt";
  19515. const char *content = "ims-bad-format";
  19516. {
  19517. std::ofstream ofs(fname);
  19518. ofs << content;
  19519. ASSERT_TRUE(ofs.good());
  19520. }
  19521. Server svr;
  19522. svr.set_mount_point("/static", ".");
  19523. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19524. svr.wait_until_ready();
  19525. Client cli(HOST, PORT);
  19526. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  19527. ASSERT_TRUE(res1);
  19528. ASSERT_EQ(200, res1->status);
  19529. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19530. // If-Modified-Since with invalid format should not result in 304
  19531. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  19532. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  19533. ASSERT_TRUE(res_bad);
  19534. EXPECT_EQ(200, res_bad->status);
  19535. // If-Range with invalid date format should be treated as mismatch -> full
  19536. // content (200)
  19537. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  19538. {"If-Range", "invalid-date"}};
  19539. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  19540. ASSERT_TRUE(res_ifrange);
  19541. EXPECT_EQ(200, res_ifrange->status);
  19542. svr.stop();
  19543. t.join();
  19544. std::remove(fname);
  19545. }
  19546. TEST(ETagTest, IfRangeWithMalformedETag) {
  19547. using namespace httplib;
  19548. const char *fname = "ifrange_malformed.txt";
  19549. const std::string content = "0123456789";
  19550. {
  19551. std::ofstream ofs(fname);
  19552. ofs << content;
  19553. ASSERT_TRUE(ofs.good());
  19554. }
  19555. Server svr;
  19556. svr.set_mount_point("/static", ".");
  19557. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19558. svr.wait_until_ready();
  19559. Client cli(HOST, PORT);
  19560. // First request: get ETag
  19561. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  19562. ASSERT_TRUE(res1);
  19563. ASSERT_EQ(200, res1->status);
  19564. ASSERT_TRUE(res1->has_header("ETag"));
  19565. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  19566. // full content (200)
  19567. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  19568. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  19569. ASSERT_TRUE(res2);
  19570. EXPECT_EQ(200, res2->status);
  19571. EXPECT_EQ(content, res2->body);
  19572. svr.stop();
  19573. t.join();
  19574. std::remove(fname);
  19575. }
  19576. TEST(ETagTest, ExtremeLargeDateValues) {
  19577. using namespace httplib;
  19578. const char *fname = "ims_extreme_date.txt";
  19579. const char *content = "ims-extreme-date";
  19580. {
  19581. std::ofstream ofs(fname);
  19582. ofs << content;
  19583. ASSERT_TRUE(ofs.good());
  19584. }
  19585. Server svr;
  19586. svr.set_mount_point("/static", ".");
  19587. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19588. svr.wait_until_ready();
  19589. Client cli(HOST, PORT);
  19590. auto res1 = cli.Get(std::string("/static/") + fname);
  19591. ASSERT_TRUE(res1);
  19592. ASSERT_EQ(200, res1->status);
  19593. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19594. // Extremely large year that may overflow date parsing routines.
  19595. Headers h_large_date = {
  19596. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19597. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  19598. ASSERT_TRUE(res_bad);
  19599. // Expect server to treat this as invalid/mismatch and return full content
  19600. EXPECT_EQ(200, res_bad->status);
  19601. // If-Range with extremely large date should be treated as mismatch -> full
  19602. // content (200)
  19603. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  19604. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19605. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  19606. ASSERT_TRUE(res_ifrange);
  19607. EXPECT_EQ(200, res_ifrange->status);
  19608. svr.stop();
  19609. t.join();
  19610. std::remove(fname);
  19611. }
  19612. TEST(ETagTest, NegativeFileModificationTime) {
  19613. using namespace httplib;
  19614. const char *fname = "ims_negative_mtime.txt";
  19615. const std::string content = "negative-mtime";
  19616. {
  19617. std::ofstream ofs(fname);
  19618. ofs << content;
  19619. ASSERT_TRUE(ofs.good());
  19620. }
  19621. // Try to set file mtime to a negative value. This may fail on some
  19622. // platforms/filesystems; if it fails, the test will still verify server
  19623. // behaves safely by performing a regular conditional request.
  19624. #if defined(__APPLE__) || defined(__linux__)
  19625. bool set_negative = false;
  19626. do {
  19627. struct timeval times[2];
  19628. // access time: now
  19629. times[0].tv_sec = time(nullptr);
  19630. times[0].tv_usec = 0;
  19631. // modification time: negative (e.g., -1)
  19632. times[1].tv_sec = -1;
  19633. times[1].tv_usec = 0;
  19634. if (utimes(fname, times) == 0) { set_negative = true; }
  19635. } while (0);
  19636. #else
  19637. bool set_negative = false;
  19638. #endif
  19639. Server svr;
  19640. svr.set_mount_point("/static", ".");
  19641. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19642. svr.wait_until_ready();
  19643. Client cli(HOST, PORT);
  19644. auto res1 = cli.Get(std::string("/static/") + fname);
  19645. ASSERT_TRUE(res1);
  19646. ASSERT_EQ(200, res1->status);
  19647. bool has_last_modified = res1->has_header("Last-Modified");
  19648. std::string last_modified;
  19649. if (has_last_modified) {
  19650. last_modified = res1->get_header_value("Last-Modified");
  19651. }
  19652. if (set_negative) {
  19653. // If we successfully set a negative mtime, ensure server returns a
  19654. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  19655. // with an old date and ensure server handles it without crash.
  19656. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  19657. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  19658. ASSERT_TRUE(res2);
  19659. // Behavior may vary; at minimum ensure server responds (200 or 304).
  19660. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  19661. } else {
  19662. // Could not set negative mtime on this platform; fall back to verifying
  19663. // that normal invalid/malformed dates are treated safely (non-304).
  19664. Headers h_bad_date = {
  19665. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19666. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  19667. ASSERT_TRUE(res_bad);
  19668. EXPECT_EQ(200, res_bad->status);
  19669. }
  19670. svr.stop();
  19671. t.join();
  19672. std::remove(fname);
  19673. }
  19674. //==============================================================================
  19675. // Integration Tests with Server
  19676. //==============================================================================
  19677. class SSEIntegrationTest : public ::testing::Test {
  19678. protected:
  19679. void SetUp() override {
  19680. stop_server_.store(false);
  19681. events_.clear();
  19682. server_ = httplib::detail::make_unique<Server>();
  19683. setup_server();
  19684. start_server();
  19685. }
  19686. void TearDown() override {
  19687. stop_server_.store(true);
  19688. event_cv_.notify_all();
  19689. server_->stop();
  19690. if (server_thread_.joinable()) { server_thread_.join(); }
  19691. }
  19692. void setup_server() {
  19693. // Simple SSE endpoint
  19694. server_->Get("/events", [this](const Request &req, Response &res) {
  19695. auto last_id = req.get_header_value("Last-Event-ID");
  19696. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  19697. res.set_chunked_content_provider(
  19698. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  19699. std::unique_lock<std::mutex> lock(event_mutex_);
  19700. if (event_cv_.wait_for(
  19701. lock, std::chrono::milliseconds(200), [this] {
  19702. return !events_.empty() || stop_server_.load();
  19703. })) {
  19704. if (stop_server_.load()) { return false; }
  19705. if (!events_.empty()) {
  19706. std::string event = events_.front();
  19707. events_.erase(events_.begin());
  19708. sink.write(event.data(), event.size());
  19709. return true;
  19710. }
  19711. }
  19712. return !stop_server_.load();
  19713. });
  19714. });
  19715. // Endpoint that returns error
  19716. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  19717. res.status = 500;
  19718. res.set_content("Internal Server Error", "text/plain");
  19719. });
  19720. // Endpoint for custom event types
  19721. server_->Get("/custom-events", [](const Request &, Response &res) {
  19722. res.set_chunked_content_provider(
  19723. "text/event-stream", [](size_t offset, DataSink &sink) {
  19724. if (offset == 0) {
  19725. std::string event = "event: update\ndata: updated\n\n"
  19726. "event: delete\ndata: deleted\n\n";
  19727. sink.write(event.data(), event.size());
  19728. }
  19729. return false; // End stream after sending
  19730. });
  19731. });
  19732. }
  19733. void start_server() {
  19734. port_ = server_->bind_to_any_port(HOST);
  19735. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19736. // Wait for server to start
  19737. while (!server_->is_running()) {
  19738. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19739. }
  19740. }
  19741. int get_port() const { return port_; }
  19742. void send_event(const std::string &event) {
  19743. std::lock_guard<std::mutex> lock(event_mutex_);
  19744. events_.push_back(event);
  19745. event_cv_.notify_all();
  19746. }
  19747. std::unique_ptr<Server> server_;
  19748. std::thread server_thread_;
  19749. std::mutex event_mutex_;
  19750. std::condition_variable event_cv_;
  19751. std::vector<std::string> events_;
  19752. std::atomic<bool> stop_server_{false};
  19753. std::string last_received_event_id_;
  19754. int port_ = 0;
  19755. };
  19756. //==============================================================================
  19757. // SSE Parsing Tests
  19758. //==============================================================================
  19759. class SSEParsingTest : public SSEIntegrationTest {
  19760. protected:
  19761. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  19762. // A trailing sentinel event tells when the whole stream has been parsed.
  19763. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  19764. auto body = stream + "event: end\ndata: end\n\n";
  19765. server_->Get("/parse", [body](const Request &, Response &res) {
  19766. res.set_content(body, "text/event-stream");
  19767. });
  19768. return collect("/parse");
  19769. }
  19770. // Runs SSEClient against path until an "end" event arrives and returns the
  19771. // messages dispatched before it
  19772. std::vector<sse::SSEMessage> collect(const std::string &path) {
  19773. Client client(HOST, get_port());
  19774. sse::SSEClient sse(client, path);
  19775. std::mutex mutex;
  19776. std::condition_variable cv;
  19777. std::vector<sse::SSEMessage> messages;
  19778. auto done = false;
  19779. sse.on_message([&](const sse::SSEMessage &msg) {
  19780. std::lock_guard<std::mutex> lock(mutex);
  19781. // Ignore a replay from a reconnect that races with stop()
  19782. if (!done) { messages.push_back(msg); }
  19783. });
  19784. sse.on_event("end", [&](const sse::SSEMessage &) {
  19785. std::lock_guard<std::mutex> lock(mutex);
  19786. done = true;
  19787. cv.notify_all();
  19788. });
  19789. sse.set_reconnect_interval(100);
  19790. sse.start_async();
  19791. {
  19792. std::unique_lock<std::mutex> lock(mutex);
  19793. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  19794. }
  19795. sse.stop();
  19796. EXPECT_TRUE(done);
  19797. return messages;
  19798. }
  19799. };
  19800. TEST_F(SSEParsingTest, SingleLineData) {
  19801. auto msgs = parse("data: hello\n\n");
  19802. ASSERT_EQ(msgs.size(), 1u);
  19803. EXPECT_EQ(msgs[0].data, "hello");
  19804. EXPECT_EQ(msgs[0].event, "message");
  19805. }
  19806. TEST_F(SSEParsingTest, MultiLineData) {
  19807. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  19808. ASSERT_EQ(msgs.size(), 1u);
  19809. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  19810. }
  19811. TEST_F(SSEParsingTest, CustomEventType) {
  19812. auto msgs = parse("event: update\ndata: payload\n\n");
  19813. ASSERT_EQ(msgs.size(), 1u);
  19814. EXPECT_EQ(msgs[0].event, "update");
  19815. EXPECT_EQ(msgs[0].data, "payload");
  19816. }
  19817. TEST_F(SSEParsingTest, EventIdHandling) {
  19818. auto msgs = parse("id: 12345\ndata: test\n\n");
  19819. ASSERT_EQ(msgs.size(), 1u);
  19820. EXPECT_EQ(msgs[0].id, "12345");
  19821. }
  19822. TEST_F(SSEParsingTest, EmptyEventId) {
  19823. auto msgs = parse("id:\ndata: test\n\n");
  19824. ASSERT_EQ(msgs.size(), 1u);
  19825. EXPECT_EQ(msgs[0].id, "");
  19826. }
  19827. TEST_F(SSEParsingTest, CommentsIgnored) {
  19828. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  19829. ASSERT_EQ(msgs.size(), 1u);
  19830. EXPECT_EQ(msgs[0].data, "hello");
  19831. EXPECT_EQ(msgs[0].event, "message");
  19832. }
  19833. TEST_F(SSEParsingTest, ColonInValue) {
  19834. auto msgs = parse("data: hello:world:test\n\n");
  19835. ASSERT_EQ(msgs.size(), 1u);
  19836. EXPECT_EQ(msgs[0].data, "hello:world:test");
  19837. }
  19838. TEST_F(SSEParsingTest, FieldNameOnly) {
  19839. // A line without a colon is a field name with an empty value
  19840. auto msgs = parse("data\n\n");
  19841. ASSERT_EQ(msgs.size(), 1u);
  19842. EXPECT_EQ(msgs[0].data, "");
  19843. }
  19844. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  19845. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  19846. ASSERT_EQ(msgs.size(), 1u);
  19847. EXPECT_EQ(msgs[0].event, "update");
  19848. EXPECT_EQ(msgs[0].data, "hello");
  19849. }
  19850. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  19851. auto msgs = parse("data\r\n\r\n");
  19852. ASSERT_EQ(msgs.size(), 1u);
  19853. EXPECT_EQ(msgs[0].data, "");
  19854. }
  19855. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  19856. auto msgs = parse("event: update\rdata: hello\r\r");
  19857. ASSERT_EQ(msgs.size(), 1u);
  19858. EXPECT_EQ(msgs[0].event, "update");
  19859. EXPECT_EQ(msgs[0].data, "hello");
  19860. }
  19861. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  19862. // Chunk boundaries fall inside every \r\n and right before the first one
  19863. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  19864. "\n\r", "\nevent: end\ndata: end\n\n"};
  19865. server_->Get("/split", [chunks](const Request &, Response &res) {
  19866. auto i = std::make_shared<size_t>(0);
  19867. res.set_chunked_content_provider(
  19868. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  19869. if (*i == chunks.size()) {
  19870. sink.done();
  19871. } else {
  19872. sink.write(chunks[*i].data(), chunks[*i].size());
  19873. (*i)++;
  19874. }
  19875. return true;
  19876. });
  19877. });
  19878. auto msgs = collect("/split");
  19879. ASSERT_EQ(msgs.size(), 1u);
  19880. EXPECT_EQ(msgs[0].event, "update");
  19881. EXPECT_EQ(msgs[0].data, "hello");
  19882. }
  19883. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  19884. // Only a BOM at the start of the stream is ignored
  19885. auto msgs = parse("\xEF\xBB\xBF"
  19886. "data: first\n\n"
  19887. "\xEF\xBB\xBF"
  19888. "data: second\n\n");
  19889. ASSERT_EQ(msgs.size(), 1u);
  19890. EXPECT_EQ(msgs[0].data, "first");
  19891. }
  19892. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  19893. auto msgs = parse("unknown: value\ndata: hello\n\n");
  19894. ASSERT_EQ(msgs.size(), 1u);
  19895. EXPECT_EQ(msgs[0].data, "hello");
  19896. EXPECT_EQ(msgs[0].event, "message");
  19897. }
  19898. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  19899. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  19900. ASSERT_EQ(msgs.size(), 2u);
  19901. EXPECT_EQ(msgs[0].data, "hello");
  19902. EXPECT_EQ(msgs[1].data, "hello");
  19903. }
  19904. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  19905. // An event without data is not dispatched, and its type must not leak
  19906. // into the next event
  19907. auto msgs = parse("event: update\n\ndata: hello\n\n");
  19908. ASSERT_EQ(msgs.size(), 1u);
  19909. EXPECT_EQ(msgs[0].event, "message");
  19910. EXPECT_EQ(msgs[0].data, "hello");
  19911. }
  19912. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  19913. // The first connection sends only an id; the second echoes back the
  19914. // Last-Event-ID it was reconnected with
  19915. std::atomic<int> connection_count{0};
  19916. server_->Get("/id-only", [&](const Request &req, Response &res) {
  19917. if (connection_count++ == 0) {
  19918. res.set_content("id: 42\n\n", "text/event-stream");
  19919. } else {
  19920. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19921. "\n\nevent: end\ndata: end\n\n",
  19922. "text/event-stream");
  19923. }
  19924. });
  19925. auto msgs = collect("/id-only");
  19926. ASSERT_EQ(msgs.size(), 1u);
  19927. EXPECT_EQ(msgs[0].data, "42");
  19928. }
  19929. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  19930. // The first connection sets an id and then clears it with an empty one; the
  19931. // second reports whether it was reconnected with a Last-Event-ID
  19932. std::atomic<int> connection_count{0};
  19933. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  19934. if (connection_count++ == 0) {
  19935. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  19936. "text/event-stream");
  19937. } else {
  19938. res.set_content(
  19939. std::string("data: ") +
  19940. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  19941. "\n\nevent: end\ndata: end\n\n",
  19942. "text/event-stream");
  19943. }
  19944. });
  19945. auto msgs = collect("/id-clear");
  19946. ASSERT_EQ(msgs.size(), 3u);
  19947. EXPECT_EQ(msgs[0].id, "1");
  19948. EXPECT_EQ(msgs[1].id, "");
  19949. EXPECT_EQ(msgs[2].data, "not sent");
  19950. }
  19951. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  19952. // The first connection sets an id and then sends ids that cannot be carried
  19953. // in a header; the second echoes back the Last-Event-ID it was reconnected
  19954. // with
  19955. std::atomic<int> connection_count{0};
  19956. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  19957. if (connection_count++ == 0) {
  19958. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  19959. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  19960. "text/event-stream");
  19961. } else {
  19962. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19963. "\n\nevent: end\ndata: end\n\n",
  19964. "text/event-stream");
  19965. }
  19966. });
  19967. auto msgs = collect("/id-unsendable");
  19968. ASSERT_EQ(msgs.size(), 1u);
  19969. EXPECT_EQ(msgs[0].data, "42");
  19970. }
  19971. TEST_F(SSEParsingTest, CompleteEventParsing) {
  19972. auto msgs = parse("event: notification\nid: evt-42\n"
  19973. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  19974. ASSERT_EQ(msgs.size(), 1u);
  19975. EXPECT_EQ(msgs[0].event, "notification");
  19976. EXPECT_EQ(msgs[0].id, "evt-42");
  19977. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  19978. }
  19979. TEST(SSEMessageTest, Clear) {
  19980. sse::SSEMessage msg;
  19981. msg.event = "custom";
  19982. msg.data = "some data";
  19983. msg.id = "123";
  19984. msg.clear();
  19985. EXPECT_EQ(msg.event, "message");
  19986. EXPECT_EQ(msg.data, "");
  19987. EXPECT_EQ(msg.id, "");
  19988. }
  19989. //==============================================================================
  19990. // SSE Integration Tests
  19991. //==============================================================================
  19992. // Test: Successful connection and on_open callback
  19993. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  19994. // Add a simple endpoint that sends one event and closes
  19995. server_->Get("/simple-event", [](const Request &, Response &res) {
  19996. res.set_chunked_content_provider(
  19997. "text/event-stream", [](size_t offset, DataSink &sink) {
  19998. if (offset == 0) {
  19999. std::string event = "data: hello\n\n";
  20000. sink.write(event.data(), event.size());
  20001. }
  20002. return false; // Close stream after sending
  20003. });
  20004. });
  20005. Client client("localhost", get_port());
  20006. sse::SSEClient sse(client, "/simple-event");
  20007. std::atomic<bool> open_called{false};
  20008. std::atomic<bool> message_received{false};
  20009. sse.on_open([&open_called]() { open_called.store(true); });
  20010. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  20011. if (msg.data == "hello") { message_received.store(true); }
  20012. });
  20013. sse.set_reconnect_interval(100);
  20014. sse.set_max_reconnect_attempts(1);
  20015. // Start async
  20016. sse.start_async();
  20017. // Wait for message to be processed
  20018. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20019. sse.stop();
  20020. EXPECT_TRUE(open_called.load());
  20021. EXPECT_TRUE(message_received.load());
  20022. }
  20023. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  20024. // A data line that never ends.
  20025. server_->Get("/endless-line", [](const Request &, Response &res) {
  20026. res.set_chunked_content_provider(
  20027. "text/event-stream", [](size_t offset, DataSink &sink) {
  20028. if (offset == 0) { sink.write("data: ", 6); }
  20029. std::string chunk(64 * 1024, 'A');
  20030. return sink.write(chunk.data(), chunk.size());
  20031. });
  20032. });
  20033. Client client("localhost", get_port());
  20034. // A stream that may run forever, so that only the event is bounded.
  20035. client.set_payload_max_length(0);
  20036. sse::SSEClient sse(client, "/endless-line");
  20037. std::atomic<bool> too_long{false};
  20038. sse.on_error([&](Error err) {
  20039. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  20040. });
  20041. sse.set_max_reconnect_attempts(1);
  20042. sse.start_async();
  20043. for (int i = 0; i < 500 && !too_long; i++) {
  20044. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20045. }
  20046. sse.stop();
  20047. EXPECT_TRUE(too_long);
  20048. }
  20049. // Test: on_message callback
  20050. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  20051. // Endpoint that sends multiple events then closes
  20052. server_->Get("/multi-event", [](const Request &, Response &res) {
  20053. res.set_chunked_content_provider(
  20054. "text/event-stream", [](size_t offset, DataSink &sink) {
  20055. if (offset == 0) {
  20056. std::string events = "data: message1\n\ndata: message2\n\n";
  20057. sink.write(events.data(), events.size());
  20058. }
  20059. return false;
  20060. });
  20061. });
  20062. Client client("localhost", get_port());
  20063. sse::SSEClient sse(client, "/multi-event");
  20064. std::vector<std::string> received_messages;
  20065. std::mutex messages_mutex;
  20066. sse.on_message([&](const sse::SSEMessage &msg) {
  20067. std::lock_guard<std::mutex> lock(messages_mutex);
  20068. received_messages.push_back(msg.data);
  20069. });
  20070. sse.set_reconnect_interval(100);
  20071. sse.set_max_reconnect_attempts(1);
  20072. sse.start_async();
  20073. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20074. sse.stop();
  20075. std::lock_guard<std::mutex> lock(messages_mutex);
  20076. EXPECT_GE(received_messages.size(), 2u);
  20077. if (received_messages.size() >= 2) {
  20078. EXPECT_EQ(received_messages[0], "message1");
  20079. EXPECT_EQ(received_messages[1], "message2");
  20080. }
  20081. }
  20082. // Test: on_event for specific types
  20083. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  20084. Client client("localhost", get_port());
  20085. sse::SSEClient sse(client, "/custom-events");
  20086. std::atomic<bool> update_received{false};
  20087. std::atomic<bool> delete_received{false};
  20088. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  20089. if (msg.data == "updated") { update_received.store(true); }
  20090. });
  20091. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  20092. if (msg.data == "deleted") { delete_received.store(true); }
  20093. });
  20094. sse.set_max_reconnect_attempts(1);
  20095. sse.start_async();
  20096. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  20097. sse.stop();
  20098. EXPECT_TRUE(update_received.load());
  20099. EXPECT_TRUE(delete_received.load());
  20100. }
  20101. // Test: on_error callback on connection failure
  20102. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  20103. // Connect to a non-existent port
  20104. Client client("localhost", 59999);
  20105. sse::SSEClient sse(client, "/events");
  20106. std::atomic<bool> error_called{false};
  20107. Error received_error = Error::Success;
  20108. sse.on_error([&](Error err) {
  20109. error_called.store(true);
  20110. received_error = err;
  20111. });
  20112. sse.set_reconnect_interval(50);
  20113. sse.set_max_reconnect_attempts(1);
  20114. sse.start_async();
  20115. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20116. sse.stop();
  20117. EXPECT_TRUE(error_called.load());
  20118. EXPECT_NE(received_error, Error::Success);
  20119. }
  20120. // Test: Last-Event-ID header sent on reconnect
  20121. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  20122. // Endpoint that sends event with ID
  20123. server_->Get("/event-with-id", [](const Request &, Response &res) {
  20124. res.set_chunked_content_provider(
  20125. "text/event-stream", [](size_t offset, DataSink &sink) {
  20126. if (offset == 0) {
  20127. std::string event = "id: evt-123\ndata: test\n\n";
  20128. sink.write(event.data(), event.size());
  20129. }
  20130. return false;
  20131. });
  20132. });
  20133. Client client("localhost", get_port());
  20134. sse::SSEClient sse(client, "/event-with-id");
  20135. std::atomic<bool> id_received{false};
  20136. sse.on_message([&](const sse::SSEMessage &msg) {
  20137. if (!msg.id.empty()) { id_received.store(true); }
  20138. });
  20139. sse.set_reconnect_interval(100);
  20140. sse.set_max_reconnect_attempts(1);
  20141. sse.start_async();
  20142. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20143. sse.stop();
  20144. EXPECT_TRUE(id_received.load());
  20145. EXPECT_EQ(sse.last_event_id(), "evt-123");
  20146. }
  20147. // Test: Manual stop
  20148. TEST_F(SSEIntegrationTest, ManualStop) {
  20149. // Endpoint that sends one event and stays open briefly
  20150. std::atomic<bool> handler_running{true};
  20151. server_->Get("/stay-open", [&handler_running](const Request &,
  20152. Response &res) {
  20153. res.set_chunked_content_provider(
  20154. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  20155. if (offset == 0) {
  20156. std::string event = "data: connected\n\n";
  20157. sink.write(event.data(), event.size());
  20158. }
  20159. // Keep connection open while handler_running is true
  20160. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  20161. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20162. }
  20163. return false;
  20164. });
  20165. });
  20166. Client client("localhost", get_port());
  20167. sse::SSEClient sse(client, "/stay-open");
  20168. std::atomic<bool> connected{false};
  20169. sse.on_open([&connected]() { connected.store(true); });
  20170. sse.set_reconnect_interval(100);
  20171. sse.set_max_reconnect_attempts(1);
  20172. sse.start_async();
  20173. // Wait for connection to establish
  20174. for (int i = 0; i < 20 && !connected.load(); ++i) {
  20175. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20176. }
  20177. EXPECT_TRUE(connected.load());
  20178. EXPECT_TRUE(sse.is_connected());
  20179. // Signal handler to stop
  20180. handler_running.store(false);
  20181. // Stop SSE client
  20182. sse.stop();
  20183. EXPECT_FALSE(sse.is_connected());
  20184. }
  20185. // Test: SSEClient with custom headers
  20186. TEST_F(SSEIntegrationTest, CustomHeaders) {
  20187. // Setup a server endpoint that checks for custom header
  20188. std::atomic<bool> header_received{false};
  20189. server_->Get("/header-check", [&](const Request &req, Response &res) {
  20190. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  20191. header_received.store(true);
  20192. }
  20193. res.set_chunked_content_provider("text/event-stream",
  20194. [](size_t, DataSink &) { return false; });
  20195. });
  20196. Client client("localhost", get_port());
  20197. Headers headers = {{"X-Custom-Header", "custom-value"}};
  20198. sse::SSEClient sse(client, "/header-check", headers);
  20199. sse.set_max_reconnect_attempts(1);
  20200. sse.start_async();
  20201. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20202. sse.stop();
  20203. EXPECT_TRUE(header_received.load());
  20204. }
  20205. // Test: Reconnect interval configuration
  20206. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  20207. Client client("localhost", get_port());
  20208. sse::SSEClient sse(client, "/events");
  20209. auto &result = sse.set_reconnect_interval(500);
  20210. // Builder pattern should return reference to self
  20211. EXPECT_EQ(&result, &sse);
  20212. }
  20213. // Test: Max reconnect attempts
  20214. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  20215. // Connect to non-existent port to force reconnects
  20216. Client client("localhost", 59998);
  20217. sse::SSEClient sse(client, "/events");
  20218. std::atomic<int> error_count{0};
  20219. sse.on_error([&](Error) { error_count.fetch_add(1); });
  20220. sse.set_reconnect_interval(50);
  20221. sse.set_max_reconnect_attempts(2);
  20222. auto start = std::chrono::steady_clock::now();
  20223. sse.start(); // Blocking call
  20224. auto end = std::chrono::steady_clock::now();
  20225. // Should have stopped after 2 failed attempts
  20226. EXPECT_GE(error_count.load(), 2);
  20227. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  20228. auto duration =
  20229. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  20230. #ifdef _WIN32
  20231. // Windows is much slower for socket connection failures
  20232. EXPECT_LT(duration.count(), 7000);
  20233. #else
  20234. EXPECT_LT(duration.count(), 1000);
  20235. #endif
  20236. }
  20237. // Test: Multi-line data in integration
  20238. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  20239. // Endpoint with multi-line data
  20240. server_->Get("/multiline-data", [](const Request &, Response &res) {
  20241. res.set_chunked_content_provider(
  20242. "text/event-stream", [](size_t offset, DataSink &sink) {
  20243. if (offset == 0) {
  20244. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  20245. sink.write(event.data(), event.size());
  20246. }
  20247. return false;
  20248. });
  20249. });
  20250. Client client("localhost", get_port());
  20251. sse::SSEClient sse(client, "/multiline-data");
  20252. std::string received_data;
  20253. std::mutex data_mutex;
  20254. sse.on_message([&](const sse::SSEMessage &msg) {
  20255. std::lock_guard<std::mutex> lock(data_mutex);
  20256. received_data = msg.data;
  20257. });
  20258. sse.set_reconnect_interval(100);
  20259. sse.set_max_reconnect_attempts(1);
  20260. sse.start_async();
  20261. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20262. sse.stop();
  20263. std::lock_guard<std::mutex> lock(data_mutex);
  20264. EXPECT_EQ(received_data, "line1\nline2\nline3");
  20265. }
  20266. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  20267. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  20268. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  20269. DataSink &sink) {
  20270. if (offset == 0) {
  20271. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  20272. sink.write(events.data(), events.size());
  20273. }
  20274. return false;
  20275. });
  20276. });
  20277. Client client("localhost", get_port());
  20278. sse::SSEClient sse(client, "/empty-data-lines");
  20279. std::mutex mutex;
  20280. std::condition_variable cv;
  20281. std::vector<std::string> received;
  20282. sse.on_message([&](const sse::SSEMessage &msg) {
  20283. std::lock_guard<std::mutex> lock(mutex);
  20284. received.push_back(msg.data);
  20285. cv.notify_all();
  20286. });
  20287. sse.set_max_reconnect_attempts(1);
  20288. sse.start_async();
  20289. {
  20290. std::unique_lock<std::mutex> lock(mutex);
  20291. cv.wait_for(lock, std::chrono::seconds(2),
  20292. [&] { return received.size() >= 3; });
  20293. }
  20294. sse.stop();
  20295. ASSERT_GE(received.size(), 3u);
  20296. EXPECT_EQ(received[0], "");
  20297. EXPECT_EQ(received[1], "\nhello");
  20298. EXPECT_EQ(received[2], "");
  20299. }
  20300. // Test: Auto-reconnect after server disconnection
  20301. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  20302. std::atomic<int> connection_count{0};
  20303. std::atomic<int> message_count{0};
  20304. // Endpoint that sends one event and closes, forcing reconnect
  20305. server_->Get("/reconnect-test",
  20306. [&connection_count](const Request &, Response &res) {
  20307. connection_count.fetch_add(1);
  20308. res.set_chunked_content_provider(
  20309. "text/event-stream", [](size_t offset, DataSink &sink) {
  20310. if (offset == 0) {
  20311. std::string event = "data: hello\n\n";
  20312. sink.write(event.data(), event.size());
  20313. }
  20314. return false; // Close connection after sending
  20315. });
  20316. });
  20317. Client client("localhost", get_port());
  20318. sse::SSEClient sse(client, "/reconnect-test");
  20319. sse.on_message([&message_count](const sse::SSEMessage &) {
  20320. message_count.fetch_add(1);
  20321. });
  20322. sse.set_reconnect_interval(100);
  20323. sse.set_max_reconnect_attempts(3);
  20324. sse.start_async();
  20325. // Wait long enough for multiple reconnects
  20326. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20327. sse.stop();
  20328. // Should have connected multiple times (initial + reconnects)
  20329. EXPECT_GE(connection_count.load(), 2);
  20330. // Should have received messages from multiple connections
  20331. EXPECT_GE(message_count.load(), 2);
  20332. }
  20333. // Test: A retry field that is not all ASCII digits is ignored
  20334. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  20335. std::atomic<int> connection_count{0};
  20336. server_->Get("/bad-retry",
  20337. [&connection_count](const Request &, Response &res) {
  20338. connection_count.fetch_add(1);
  20339. res.set_chunked_content_provider(
  20340. "text/event-stream", [](size_t offset, DataSink &sink) {
  20341. if (offset == 0) {
  20342. std::string event = "retry: -1\ndata: hello\n\n";
  20343. sink.write(event.data(), event.size());
  20344. }
  20345. return false;
  20346. });
  20347. });
  20348. Client client("localhost", get_port());
  20349. sse::SSEClient sse(client, "/bad-retry");
  20350. sse.set_reconnect_interval(10000);
  20351. sse.start_async();
  20352. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20353. sse.stop();
  20354. EXPECT_EQ(connection_count.load(), 1);
  20355. }
  20356. // Test: A retry field of all ASCII digits sets the reconnection time
  20357. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  20358. std::mutex mutex;
  20359. std::condition_variable cv;
  20360. std::vector<std::chrono::steady_clock::time_point> connected_at;
  20361. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  20362. {
  20363. std::lock_guard<std::mutex> lock(mutex);
  20364. connected_at.push_back(std::chrono::steady_clock::now());
  20365. cv.notify_all();
  20366. }
  20367. res.set_chunked_content_provider(
  20368. "text/event-stream", [](size_t offset, DataSink &sink) {
  20369. if (offset == 0) {
  20370. std::string event = "retry: 0\ndata: hello\n\n";
  20371. sink.write(event.data(), event.size());
  20372. }
  20373. return false;
  20374. });
  20375. });
  20376. Client client("localhost", get_port());
  20377. sse::SSEClient sse(client, "/zero-retry");
  20378. sse.set_reconnect_interval(10000);
  20379. sse.start_async();
  20380. {
  20381. std::unique_lock<std::mutex> lock(mutex);
  20382. cv.wait_for(lock, std::chrono::seconds(5),
  20383. [&] { return connected_at.size() >= 2; });
  20384. }
  20385. sse.stop();
  20386. // The server-supplied interval is applied, but never below 100ms, so
  20387. // "retry: 0" does not cause a busy reconnect loop
  20388. std::lock_guard<std::mutex> lock(mutex);
  20389. ASSERT_GE(connected_at.size(), 2u);
  20390. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  20391. connected_at[1] - connected_at[0])
  20392. .count();
  20393. EXPECT_GE(interval_ms, 100);
  20394. }
  20395. // Test: Last-Event-ID sent on reconnect
  20396. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  20397. std::atomic<int> connection_count{0};
  20398. std::vector<std::string> received_last_event_ids;
  20399. std::mutex id_mutex;
  20400. // Endpoint that checks Last-Event-ID header and sends event with ID
  20401. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  20402. int conn = connection_count.fetch_add(1);
  20403. // Capture the Last-Event-ID header from each connection
  20404. {
  20405. std::lock_guard<std::mutex> lock(id_mutex);
  20406. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  20407. }
  20408. res.set_chunked_content_provider(
  20409. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  20410. if (offset == 0) {
  20411. std::string event =
  20412. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  20413. sink.write(event.data(), event.size());
  20414. }
  20415. return false;
  20416. });
  20417. });
  20418. Client client("localhost", get_port());
  20419. sse::SSEClient sse(client, "/reconnect-with-id");
  20420. sse.set_reconnect_interval(100);
  20421. sse.set_max_reconnect_attempts(3);
  20422. sse.start_async();
  20423. // Wait for at least 2 connections
  20424. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20425. sse.stop();
  20426. // Verify behavior
  20427. std::lock_guard<std::mutex> lock(id_mutex);
  20428. EXPECT_GE(received_last_event_ids.size(), 2u);
  20429. // First connection should have no Last-Event-ID
  20430. if (!received_last_event_ids.empty()) {
  20431. EXPECT_EQ(received_last_event_ids[0], "");
  20432. }
  20433. // Second connection should have Last-Event-ID from first connection
  20434. if (received_last_event_ids.size() >= 2) {
  20435. EXPECT_EQ(received_last_event_ids[1], "event-0");
  20436. }
  20437. }
  20438. // Test: set_headers updates headers used on reconnect
  20439. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  20440. std::vector<std::string> received_tokens;
  20441. std::mutex token_mutex;
  20442. // Endpoint that captures Authorization header
  20443. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  20444. {
  20445. std::lock_guard<std::mutex> lock(token_mutex);
  20446. received_tokens.push_back(req.get_header_value("Authorization"));
  20447. }
  20448. res.set_chunked_content_provider(
  20449. "text/event-stream", [](size_t offset, DataSink &sink) {
  20450. if (offset == 0) {
  20451. std::string event = "data: hello\n\n";
  20452. sink.write(event.data(), event.size());
  20453. }
  20454. return false; // Close connection to trigger reconnect
  20455. });
  20456. });
  20457. Client client("localhost", get_port());
  20458. Headers headers = {{"Authorization", "Bearer old-token"}};
  20459. sse::SSEClient sse(client, "/auth-check", headers);
  20460. // Update headers on each successful connection
  20461. sse.on_open(
  20462. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  20463. sse.set_reconnect_interval(100);
  20464. sse.set_max_reconnect_attempts(3);
  20465. sse.start_async();
  20466. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20467. sse.stop();
  20468. std::lock_guard<std::mutex> lock(token_mutex);
  20469. ASSERT_GE(received_tokens.size(), 2u);
  20470. // First connection uses original header
  20471. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  20472. // Second connection uses updated header from set_headers
  20473. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  20474. }
  20475. // Test: 401 allows reconnection (so on_error can refresh headers)
  20476. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  20477. std::atomic<int> connection_count{0};
  20478. // Endpoint: returns 401 on first attempt, 200 on second
  20479. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  20480. int conn = connection_count.fetch_add(1);
  20481. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  20482. res.status = StatusCode::Unauthorized_401;
  20483. res.set_content("Unauthorized", "text/plain");
  20484. return;
  20485. }
  20486. res.set_chunked_content_provider(
  20487. "text/event-stream", [](size_t offset, DataSink &sink) {
  20488. if (offset == 0) {
  20489. std::string event = "data: authenticated\n\n";
  20490. sink.write(event.data(), event.size());
  20491. }
  20492. return false;
  20493. });
  20494. });
  20495. Client client("localhost", get_port());
  20496. Headers headers = {{"Authorization", "Bearer expired"}};
  20497. sse::SSEClient sse(client, "/auth-retry", headers);
  20498. std::atomic<bool> message_received{false};
  20499. // Refresh token on error
  20500. sse.on_error(
  20501. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  20502. sse.on_message([&](const sse::SSEMessage &msg) {
  20503. if (msg.data == "authenticated") { message_received.store(true); }
  20504. });
  20505. sse.set_reconnect_interval(100);
  20506. sse.set_max_reconnect_attempts(3);
  20507. sse.start_async();
  20508. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20509. sse.stop();
  20510. // Should have reconnected after 401 and succeeded with new token
  20511. EXPECT_GE(connection_count.load(), 2);
  20512. EXPECT_TRUE(message_received.load());
  20513. }
  20514. TEST(Issue2318Test, EmptyHostString) {
  20515. {
  20516. httplib::Client cli_empty("", PORT);
  20517. auto res = cli_empty.Get("/");
  20518. ASSERT_FALSE(res);
  20519. EXPECT_EQ(httplib::Error::Connection, res.error());
  20520. }
  20521. {
  20522. httplib::Client cli(" ", PORT);
  20523. auto res = cli.Get("/");
  20524. ASSERT_FALSE(res);
  20525. EXPECT_EQ(httplib::Error::Connection, res.error());
  20526. }
  20527. }
  20528. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20529. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  20530. Server svr;
  20531. // Set a small payload limit (1KB)
  20532. svr.set_payload_max_length(1024);
  20533. svr.Post("/test", [&](const Request &req, Response &res) {
  20534. res.set_content("Body size: " + std::to_string(req.body.size()),
  20535. "text/plain");
  20536. });
  20537. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  20538. auto se = detail::scope_exit([&] {
  20539. svr.stop();
  20540. listen_thread.join();
  20541. });
  20542. svr.wait_until_ready();
  20543. // Create data that compresses well but exceeds limit when decompressed
  20544. // 8KB of repeated null bytes compresses to a very small size
  20545. std::string original_data(8 * 1024, '\0');
  20546. // Compress the data using gzip
  20547. std::string compressed_data;
  20548. detail::gzip_compressor compressor;
  20549. compressor.compress(original_data.data(), original_data.size(), true,
  20550. [&](const char *data, size_t size) {
  20551. compressed_data.append(data, size);
  20552. return true;
  20553. });
  20554. // Verify compression worked (compressed should be much smaller)
  20555. ASSERT_LT(compressed_data.size(), original_data.size());
  20556. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  20557. // Send compressed data with Content-Encoding: gzip
  20558. Client cli(HOST, PORT);
  20559. Headers headers = {{"Content-Encoding", "gzip"}};
  20560. auto res =
  20561. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  20562. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  20563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20564. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  20565. }
  20566. #endif
  20567. // ============================================================================
  20568. // OpenSSL-Specific Tests
  20569. // ============================================================================
  20570. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  20571. X509 *readCertificate(const std::string &strFileName) {
  20572. std::ifstream inStream(strFileName);
  20573. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  20574. std::istreambuf_iterator<char>());
  20575. if (strCertPEM.empty()) return (nullptr);
  20576. BIO *pbCert = BIO_new(BIO_s_mem());
  20577. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  20578. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  20579. BIO_free(pbCert);
  20580. return (pCert);
  20581. }
  20582. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  20583. std::ifstream inStream(strFileName);
  20584. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  20585. std::istreambuf_iterator<char>());
  20586. if (strPrivateKeyPEM.empty()) return (nullptr);
  20587. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  20588. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  20589. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  20590. BIO_free(pbPrivKey);
  20591. return (pPrivateKey);
  20592. }
  20593. TEST(BindServerTest, UpdateCerts) {
  20594. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20595. int port = svr.bind_to_any_port("0.0.0.0");
  20596. ASSERT_TRUE(svr.is_valid());
  20597. ASSERT_TRUE(port > 0);
  20598. X509 *cert = readCertificate(SERVER_CERT_FILE);
  20599. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  20600. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  20601. ASSERT_TRUE(cert != nullptr);
  20602. ASSERT_TRUE(ca_cert != nullptr);
  20603. ASSERT_TRUE(key != nullptr);
  20604. X509_STORE *cert_store = X509_STORE_new();
  20605. X509_STORE_add_cert(cert_store, ca_cert);
  20606. // svr.update_certs(cert, key, cert_store); // deprecated
  20607. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  20608. CLIENT_CA_CERT_FILE);
  20609. ASSERT_TRUE(svr.is_valid());
  20610. svr.stop();
  20611. X509_STORE_free(cert_store);
  20612. X509_free(cert);
  20613. X509_free(ca_cert);
  20614. EVP_PKEY_free(key);
  20615. }
  20616. // Test that update_certs() updates client CA list correctly
  20617. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  20618. // Start with file-based constructor
  20619. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20620. ASSERT_TRUE(svr.is_valid());
  20621. // Initially no client CA list should be set
  20622. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20623. ASSERT_TRUE(ssl_ctx != nullptr);
  20624. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  20625. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  20626. EXPECT_EQ(0, count_before);
  20627. // Now update with client CA (PEM string)
  20628. std::string cert_pem, key_pem, ca_pem;
  20629. read_file(SERVER_CERT_FILE, cert_pem);
  20630. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  20631. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  20632. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  20633. ASSERT_TRUE(svr.is_valid());
  20634. // Now client CA list should be set
  20635. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  20636. ASSERT_TRUE(ca_list_after != nullptr);
  20637. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  20638. }
  20639. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  20640. // Test that the file-path SSLServer constructor properly sets the client CA
  20641. // list that is sent to clients during the TLS handshake (CertificateRequest)
  20642. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20643. ASSERT_TRUE(svr.is_valid());
  20644. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20645. ASSERT_TRUE(ssl_ctx != nullptr);
  20646. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  20647. ASSERT_TRUE(ca_list != nullptr);
  20648. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  20649. }
  20650. #endif
  20651. // ============================================================================
  20652. // MbedTLS-Specific Tests
  20653. // ============================================================================
  20654. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  20655. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  20656. using namespace httplib::tls;
  20657. // Track if callback was invoked
  20658. bool callback_invoked = false;
  20659. // The callback receives void* ctx which is actually MbedTlsContext*
  20660. // We can access the mbedtls_ssl_config via the context
  20661. auto setup_callback = [&callback_invoked](void *ctx) {
  20662. callback_invoked = true;
  20663. // Cast to MbedTlsContext* to access the ssl config
  20664. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  20665. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  20666. // Use static variables to hold certificate data (simplified for test)
  20667. static mbedtls_x509_crt own_cert;
  20668. static mbedtls_pk_context own_key;
  20669. static mbedtls_x509_crt ca_chain;
  20670. static bool initialized = false;
  20671. if (!initialized) {
  20672. mbedtls_x509_crt_init(&own_cert);
  20673. mbedtls_pk_init(&own_key);
  20674. mbedtls_x509_crt_init(&ca_chain);
  20675. // Load server certificate
  20676. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  20677. return false;
  20678. }
  20679. // Load server private key.
  20680. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  20681. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  20682. #if MBEDTLS_VERSION_MAJOR == 3
  20683. ,
  20684. mbedtls_ctr_drbg_random, nullptr
  20685. #endif
  20686. ) != 0) {
  20687. return false;
  20688. }
  20689. // Load CA chain for client verification
  20690. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  20691. return false;
  20692. }
  20693. initialized = true;
  20694. }
  20695. // Configure the SSL config
  20696. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  20697. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  20698. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  20699. // Set minimum TLS version using mbedTLS native API
  20700. #if MBEDTLS_VERSION_MAJOR >= 3
  20701. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  20702. #else
  20703. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  20704. MBEDTLS_SSL_MINOR_VERSION_3);
  20705. #endif
  20706. return true;
  20707. };
  20708. SSLServer svr(setup_callback);
  20709. ASSERT_TRUE(svr.is_valid());
  20710. ASSERT_TRUE(callback_invoked);
  20711. svr.Get("/test", [&](const Request &req, Response &res) {
  20712. res.set_content("test", "text/plain");
  20713. auto cert = req.peer_cert();
  20714. ASSERT_TRUE(static_cast<bool>(cert));
  20715. auto common_name = cert.subject_cn();
  20716. EXPECT_EQ("Common Name", common_name);
  20717. });
  20718. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20719. auto se = detail::scope_exit([&] {
  20720. svr.stop();
  20721. t.join();
  20722. ASSERT_FALSE(svr.is_running());
  20723. });
  20724. svr.wait_until_ready();
  20725. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  20726. cli.enable_server_certificate_verification(false);
  20727. cli.set_connection_timeout(30);
  20728. auto res = cli.Get("/test");
  20729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20730. ASSERT_EQ(StatusCode::OK_200, res->status);
  20731. }
  20732. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  20733. // context (owning mbedtls_ssl_config) before shutting down a still-open
  20734. // keep-alive SSL session, which reads through that config in
  20735. // mbedtls_ssl_close_notify.
  20736. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  20737. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20738. ASSERT_TRUE(svr.is_valid());
  20739. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  20740. res.set_content("test", "text/plain");
  20741. });
  20742. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20743. auto se = detail::scope_exit([&] {
  20744. svr.stop();
  20745. t.join();
  20746. ASSERT_FALSE(svr.is_running());
  20747. });
  20748. svr.wait_until_ready();
  20749. {
  20750. SSLClient cli(HOST, PORT);
  20751. cli.enable_server_certificate_verification(false);
  20752. cli.set_keep_alive(true);
  20753. auto res = cli.Get("/test");
  20754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20755. ASSERT_EQ(StatusCode::OK_200, res->status);
  20756. // cli is destructed here with the keep-alive SSL session still open.
  20757. }
  20758. }
  20759. #endif
  20760. // WebSocket Tests
  20761. TEST(WebSocketTest, RSVBitsMustBeZero) {
  20762. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  20763. // defining the meaning of these bits has been negotiated.
  20764. auto make_frame = [](uint8_t first_byte) {
  20765. std::string frame;
  20766. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  20767. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  20768. frame += "Hello";
  20769. return frame;
  20770. };
  20771. // RSV1 set (0x40)
  20772. {
  20773. detail::BufferStream strm;
  20774. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  20775. ws::Opcode opcode;
  20776. std::string payload;
  20777. bool fin;
  20778. EXPECT_EQ(
  20779. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20780. ws::impl::FrameRead::Fail);
  20781. }
  20782. // RSV2 set (0x20)
  20783. {
  20784. detail::BufferStream strm;
  20785. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  20786. ws::Opcode opcode;
  20787. std::string payload;
  20788. bool fin;
  20789. EXPECT_EQ(
  20790. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20791. ws::impl::FrameRead::Fail);
  20792. }
  20793. // RSV3 set (0x10)
  20794. {
  20795. detail::BufferStream strm;
  20796. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  20797. ws::Opcode opcode;
  20798. std::string payload;
  20799. bool fin;
  20800. EXPECT_EQ(
  20801. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20802. ws::impl::FrameRead::Fail);
  20803. }
  20804. // No RSV bits set - should succeed
  20805. {
  20806. detail::BufferStream strm;
  20807. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  20808. ws::Opcode opcode;
  20809. std::string payload;
  20810. bool fin;
  20811. EXPECT_EQ(
  20812. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20813. ws::impl::FrameRead::Ok);
  20814. EXPECT_EQ(ws::Opcode::Text, opcode);
  20815. EXPECT_EQ("Hello", payload);
  20816. EXPECT_TRUE(fin);
  20817. }
  20818. }
  20819. TEST(WebSocketTest, ControlFrameValidation) {
  20820. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  20821. // payload length <= 125.
  20822. // Ping with FIN=0 - must be rejected
  20823. {
  20824. detail::BufferStream strm;
  20825. std::string frame;
  20826. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  20827. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20828. strm.write(frame.data(), frame.size());
  20829. ws::Opcode opcode;
  20830. std::string payload;
  20831. bool fin;
  20832. EXPECT_EQ(
  20833. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20834. ws::impl::FrameRead::Fail);
  20835. }
  20836. // Close with FIN=0 - must be rejected
  20837. {
  20838. detail::BufferStream strm;
  20839. std::string frame;
  20840. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  20841. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20842. strm.write(frame.data(), frame.size());
  20843. ws::Opcode opcode;
  20844. std::string payload;
  20845. bool fin;
  20846. EXPECT_EQ(
  20847. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20848. ws::impl::FrameRead::Fail);
  20849. }
  20850. // Ping with payload_len=126 (extended length) - must be rejected
  20851. {
  20852. detail::BufferStream strm;
  20853. std::string frame;
  20854. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20855. frame += static_cast<char>(126); // payload_len=126 (>125)
  20856. frame += static_cast<char>(0x00); // extended length high byte
  20857. frame += static_cast<char>(126); // extended length low byte
  20858. frame += std::string(126, 'x');
  20859. strm.write(frame.data(), frame.size());
  20860. ws::Opcode opcode;
  20861. std::string payload;
  20862. bool fin;
  20863. EXPECT_EQ(
  20864. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20865. ws::impl::FrameRead::Fail);
  20866. }
  20867. // Ping with FIN=1 and payload_len=125 - should succeed
  20868. {
  20869. detail::BufferStream strm;
  20870. std::string frame;
  20871. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20872. frame += static_cast<char>(125); // payload_len=125
  20873. frame += std::string(125, 'x');
  20874. strm.write(frame.data(), frame.size());
  20875. ws::Opcode opcode;
  20876. std::string payload;
  20877. bool fin;
  20878. EXPECT_EQ(
  20879. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20880. ws::impl::FrameRead::Ok);
  20881. EXPECT_EQ(ws::Opcode::Ping, opcode);
  20882. EXPECT_EQ(125u, payload.size());
  20883. EXPECT_TRUE(fin);
  20884. }
  20885. }
  20886. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  20887. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  20888. // length MUST be 0.
  20889. // MSB set - must be rejected
  20890. {
  20891. detail::BufferStream strm;
  20892. std::string frame;
  20893. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20894. frame += static_cast<char>(127); // 64-bit extended length
  20895. frame += static_cast<char>(0x80); // MSB set (invalid)
  20896. frame += std::string(7, '\0'); // remaining 7 bytes of length
  20897. strm.write(frame.data(), frame.size());
  20898. ws::Opcode opcode;
  20899. std::string payload;
  20900. bool fin;
  20901. EXPECT_EQ(
  20902. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20903. ws::impl::FrameRead::Fail);
  20904. }
  20905. // MSB clear - should pass length parsing (will be rejected by max_len,
  20906. // but that's a different check; use a small length to verify)
  20907. {
  20908. detail::BufferStream strm;
  20909. std::string frame;
  20910. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20911. frame += static_cast<char>(127); // 64-bit extended length
  20912. frame += std::string(7, '\0'); // high bytes = 0
  20913. frame += static_cast<char>(0x03); // length = 3
  20914. frame += "abc";
  20915. strm.write(frame.data(), frame.size());
  20916. ws::Opcode opcode;
  20917. std::string payload;
  20918. bool fin;
  20919. EXPECT_EQ(
  20920. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20921. ws::impl::FrameRead::Ok);
  20922. EXPECT_EQ(ws::Opcode::Text, opcode);
  20923. EXPECT_EQ("abc", payload);
  20924. }
  20925. }
  20926. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  20927. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  20928. // Valid UTF-8
  20929. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  20930. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  20931. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  20932. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  20933. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  20934. // Invalid UTF-8
  20935. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  20936. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  20937. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  20938. EXPECT_FALSE(
  20939. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  20940. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  20941. }
  20942. TEST(WebSocketTest, ConnectAndDisconnect) {
  20943. Server svr;
  20944. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20945. std::string msg;
  20946. while (ws.read(msg)) {}
  20947. });
  20948. auto port = svr.bind_to_any_port(HOST);
  20949. std::thread t([&]() { svr.listen_after_bind(); });
  20950. svr.wait_until_ready();
  20951. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20952. auto res = client.connect();
  20953. ASSERT_TRUE(res);
  20954. EXPECT_EQ(Error::Success, res.error());
  20955. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  20956. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  20957. EXPECT_TRUE(client.is_open());
  20958. client.close();
  20959. EXPECT_FALSE(client.is_open());
  20960. svr.stop();
  20961. t.join();
  20962. }
  20963. TEST(WebSocketTest, ValidURL) {
  20964. ws::WebSocketClient ws1("ws://localhost:8080/path");
  20965. EXPECT_TRUE(ws1.is_valid());
  20966. ws::WebSocketClient ws2("ws://example.com/path");
  20967. EXPECT_TRUE(ws2.is_valid());
  20968. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  20969. EXPECT_TRUE(ws3.is_valid());
  20970. #ifdef CPPHTTPLIB_SSL_ENABLED
  20971. ws::WebSocketClient wss1("wss://example.com/path");
  20972. EXPECT_TRUE(wss1.is_valid());
  20973. ws::WebSocketClient wss2("wss://example.com:443/path");
  20974. EXPECT_TRUE(wss2.is_valid());
  20975. #endif
  20976. }
  20977. TEST(WebSocketTest, InvalidURL) {
  20978. // No scheme
  20979. ws::WebSocketClient ws1("localhost:8080/path");
  20980. EXPECT_FALSE(ws1.is_valid());
  20981. // No path
  20982. ws::WebSocketClient ws2("ws://localhost:8080");
  20983. EXPECT_FALSE(ws2.is_valid());
  20984. // Empty string
  20985. ws::WebSocketClient ws3("");
  20986. EXPECT_FALSE(ws3.is_valid());
  20987. // Missing host
  20988. ws::WebSocketClient ws4("ws://:8080/path");
  20989. EXPECT_FALSE(ws4.is_valid());
  20990. // Port number overflow — should not crash
  20991. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  20992. EXPECT_FALSE(ws5.is_valid());
  20993. // Port out of range
  20994. ws::WebSocketClient ws6("ws://localhost:99999/path");
  20995. EXPECT_FALSE(ws6.is_valid());
  20996. }
  20997. TEST(WebSocketTest, UnsupportedScheme) {
  20998. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  20999. ws::WebSocketClient ws1("http://localhost:8080/path");
  21000. EXPECT_FALSE(ws1.is_valid());
  21001. ws::WebSocketClient ws2("https://localhost:8080/path");
  21002. EXPECT_FALSE(ws2.is_valid());
  21003. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  21004. EXPECT_FALSE(ws3.is_valid());
  21005. #else
  21006. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  21007. std::invalid_argument);
  21008. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  21009. std::invalid_argument);
  21010. #endif
  21011. }
  21012. TEST(WebSocketTest, ConnectWhenInvalid) {
  21013. ws::WebSocketClient ws("not a valid url");
  21014. EXPECT_FALSE(ws.is_valid());
  21015. auto res = ws.connect();
  21016. EXPECT_FALSE(res);
  21017. EXPECT_EQ(Error::Connection, res.error());
  21018. EXPECT_EQ(-1, res.status());
  21019. }
  21020. TEST(WebSocketTest, ConnectRefusedReportsError) {
  21021. // Grab a port that is free, then close it again so nothing listens there
  21022. Server svr;
  21023. auto port = svr.bind_to_any_port(HOST);
  21024. svr.stop();
  21025. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21026. auto res = client.connect();
  21027. ASSERT_FALSE(res);
  21028. EXPECT_EQ(Error::Connection, res.error());
  21029. EXPECT_EQ(-1, res.status());
  21030. }
  21031. TEST(WebSocketTest, DefaultPort) {
  21032. ws::WebSocketClient ws1("ws://example.com/path");
  21033. EXPECT_TRUE(ws1.is_valid());
  21034. // ws:// defaults to port 80 (verified by successful parse)
  21035. #ifdef CPPHTTPLIB_SSL_ENABLED
  21036. ws::WebSocketClient ws2("wss://example.com/path");
  21037. EXPECT_TRUE(ws2.is_valid());
  21038. // wss:// defaults to port 443 (verified by successful parse)
  21039. #endif
  21040. }
  21041. TEST(WebSocketTest, IPv6LiteralAddress) {
  21042. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  21043. EXPECT_TRUE(ws1.is_valid());
  21044. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  21045. EXPECT_TRUE(ws2.is_valid());
  21046. }
  21047. TEST(WebSocketTest, ComplexPath) {
  21048. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  21049. EXPECT_TRUE(ws1.is_valid());
  21050. ws::WebSocketClient ws2("ws://localhost:8080/");
  21051. EXPECT_TRUE(ws2.is_valid());
  21052. }
  21053. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  21054. Server svr;
  21055. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21056. std::string msg;
  21057. while (ws.read(msg)) {}
  21058. });
  21059. auto port = svr.bind_to_any_port(HOST);
  21060. std::thread t([&]() { svr.listen_after_bind(); });
  21061. svr.wait_until_ready();
  21062. auto another_host = "example.com";
  21063. auto wrong_ip = "192.0.2.1";
  21064. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21065. client.set_hostname_addr_map({{another_host, wrong_ip}});
  21066. ASSERT_TRUE(client.connect());
  21067. EXPECT_TRUE(client.is_open());
  21068. client.close();
  21069. svr.stop();
  21070. t.join();
  21071. }
  21072. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  21073. Server svr;
  21074. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21075. std::string msg;
  21076. while (ws.read(msg)) {}
  21077. });
  21078. auto port = svr.bind_to_any_port(HOST);
  21079. std::thread t([&]() { svr.listen_after_bind(); });
  21080. svr.wait_until_ready();
  21081. auto wrong_ip = "192.0.2.1";
  21082. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21083. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  21084. client.set_connection_timeout(1);
  21085. client.set_read_timeout(1);
  21086. client.set_write_timeout(1);
  21087. EXPECT_FALSE(client.connect());
  21088. EXPECT_FALSE(client.is_open());
  21089. svr.stop();
  21090. t.join();
  21091. }
  21092. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  21093. // A mapped value that is not an IP literal must be resolved. HOST resolves
  21094. // from the hosts file, so this test needs no external DNS. "target.invalid"
  21095. // (RFC 6761) is only a map key and the Host header value.
  21096. auto host = "target.invalid";
  21097. Server svr;
  21098. std::string received_host;
  21099. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21100. received_host = req.get_header_value("Host");
  21101. std::string msg;
  21102. while (ws.read(msg)) {}
  21103. });
  21104. auto port = svr.bind_to_any_port(HOST);
  21105. std::thread t([&]() { svr.listen_after_bind(); });
  21106. // ASSERT_* below returns from the test body, which would leave t joinable
  21107. // and make ~thread call std::terminate.
  21108. auto se = detail::scope_exit([&] {
  21109. svr.stop();
  21110. if (t.joinable()) { t.join(); }
  21111. });
  21112. svr.wait_until_ready();
  21113. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  21114. std::to_string(port) + "/ws");
  21115. client.set_hostname_addr_map({{host, HOST}});
  21116. ASSERT_TRUE(client.connect());
  21117. EXPECT_TRUE(client.is_open());
  21118. client.close();
  21119. svr.stop();
  21120. t.join();
  21121. // The mapping only redirects the connection; the identity stays host_.
  21122. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  21123. }
  21124. class WebSocketIntegrationTest : public ::testing::Test {
  21125. protected:
  21126. void SetUp() override {
  21127. server_ = httplib::detail::make_unique<Server>();
  21128. setup_server();
  21129. start_server();
  21130. }
  21131. void TearDown() override {
  21132. server_->stop();
  21133. if (server_thread_.joinable()) { server_thread_.join(); }
  21134. }
  21135. void setup_server() {
  21136. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21137. std::string msg;
  21138. ws::ReadResult ret;
  21139. while ((ret = ws.read(msg))) {
  21140. if (ret == ws::Binary) {
  21141. ws.send(msg.data(), msg.size());
  21142. } else {
  21143. ws.send(msg);
  21144. }
  21145. }
  21146. });
  21147. server_->WebSocket("/ws-echo-string",
  21148. [](const Request &, ws::WebSocket &ws) {
  21149. std::string msg;
  21150. while (ws.read(msg)) {
  21151. ws.send("echo: " + msg);
  21152. }
  21153. });
  21154. server_->WebSocket(
  21155. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  21156. // Echo back request metadata
  21157. ws.send("path:" + req.path);
  21158. ws.send("header:" + req.get_header_value("X-Test-Header"));
  21159. std::string msg;
  21160. while (ws.read(msg)) {}
  21161. });
  21162. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  21163. std::string msg;
  21164. ws.read(msg); // wait for a message
  21165. ws.close();
  21166. });
  21167. server_->WebSocket("/ws-close-status",
  21168. [](const Request &, ws::WebSocket &ws) {
  21169. std::string msg;
  21170. ws.read(msg); // wait for a message
  21171. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  21172. });
  21173. server_->WebSocket(
  21174. "/ws-subprotocol",
  21175. [](const Request &, ws::WebSocket &ws) {
  21176. std::string msg;
  21177. while (ws.read(msg)) {
  21178. ws.send(msg);
  21179. }
  21180. },
  21181. [](const std::vector<std::string> &protocols) -> std::string {
  21182. for (const auto &p : protocols) {
  21183. if (p == "graphql-ws") { return p; }
  21184. }
  21185. return "";
  21186. });
  21187. server_->WebSocket(
  21188. "/ws-subprotocol-unoffered",
  21189. [](const Request &, ws::WebSocket &ws) {
  21190. std::string msg;
  21191. while (ws.read(msg)) {
  21192. ws.send(msg);
  21193. }
  21194. },
  21195. [](const std::vector<std::string> &) -> std::string {
  21196. return "admin";
  21197. });
  21198. }
  21199. void start_server() {
  21200. port_ = server_->bind_to_any_port(HOST);
  21201. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21202. server_->wait_until_ready();
  21203. }
  21204. std::unique_ptr<Server> server_;
  21205. std::thread server_thread_;
  21206. int port_ = 0;
  21207. };
  21208. TEST_F(WebSocketIntegrationTest, TextEcho) {
  21209. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21210. "/ws-echo");
  21211. ASSERT_TRUE(client.connect());
  21212. ASSERT_TRUE(client.is_open());
  21213. ASSERT_TRUE(client.send("Hello WebSocket"));
  21214. std::string msg;
  21215. EXPECT_EQ(ws::Text, client.read(msg));
  21216. EXPECT_EQ("Hello WebSocket", msg);
  21217. client.close();
  21218. }
  21219. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  21220. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21221. "/ws-echo");
  21222. ASSERT_TRUE(client.connect());
  21223. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  21224. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  21225. std::string msg;
  21226. EXPECT_EQ(ws::Binary, client.read(msg));
  21227. EXPECT_EQ(binary_data, msg);
  21228. client.close();
  21229. }
  21230. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  21231. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21232. "/ws-echo");
  21233. ASSERT_TRUE(client.connect());
  21234. for (int i = 0; i < 10; i++) {
  21235. auto text = "message " + std::to_string(i);
  21236. ASSERT_TRUE(client.send(text));
  21237. std::string msg;
  21238. ASSERT_TRUE(client.read(msg));
  21239. EXPECT_EQ(text, msg);
  21240. }
  21241. client.close();
  21242. }
  21243. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  21244. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21245. "/ws-close");
  21246. ASSERT_TRUE(client.connect());
  21247. // Send a message to trigger the server to close
  21248. ASSERT_TRUE(client.send("trigger close"));
  21249. // The server will close, so read should return false
  21250. std::string msg;
  21251. EXPECT_FALSE(client.read(msg));
  21252. EXPECT_FALSE(client.is_open());
  21253. }
  21254. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  21255. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21256. "/ws-echo");
  21257. ASSERT_TRUE(client.connect());
  21258. // 128KB message
  21259. std::string large_data(128 * 1024, 'X');
  21260. ASSERT_TRUE(client.send(large_data));
  21261. std::string msg;
  21262. ASSERT_TRUE(client.read(msg));
  21263. EXPECT_EQ(large_data, msg);
  21264. client.close();
  21265. }
  21266. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  21267. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21268. "/ws-echo");
  21269. ASSERT_TRUE(client.connect());
  21270. const int num_threads = 4;
  21271. std::vector<std::thread> threads;
  21272. std::atomic<int> send_count{0};
  21273. for (int t = 0; t < num_threads; t++) {
  21274. threads.emplace_back([&client, &send_count, t]() {
  21275. for (int i = 0; i < 5; i++) {
  21276. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  21277. if (client.send(text)) { send_count++; }
  21278. }
  21279. });
  21280. }
  21281. for (auto &th : threads) {
  21282. th.join();
  21283. }
  21284. int received = 0;
  21285. std::string msg;
  21286. while (received < send_count.load()) {
  21287. if (!client.read(msg)) { break; }
  21288. received++;
  21289. }
  21290. EXPECT_EQ(send_count.load(), received);
  21291. client.close();
  21292. }
  21293. TEST_F(WebSocketIntegrationTest, ReadString) {
  21294. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21295. "/ws-echo-string");
  21296. ASSERT_TRUE(client.connect());
  21297. ASSERT_TRUE(client.send("hello"));
  21298. std::string msg;
  21299. ASSERT_TRUE(client.read(msg));
  21300. EXPECT_EQ("echo: hello", msg);
  21301. ASSERT_TRUE(client.send("world"));
  21302. ASSERT_TRUE(client.read(msg));
  21303. EXPECT_EQ("echo: world", msg);
  21304. client.close();
  21305. }
  21306. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  21307. Headers headers = {{"X-Test-Header", "test-value"}};
  21308. ws::WebSocketClient client(
  21309. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  21310. ASSERT_TRUE(client.connect());
  21311. std::string msg;
  21312. ASSERT_TRUE(client.read(msg));
  21313. EXPECT_EQ("path:/ws-request-info", msg);
  21314. ASSERT_TRUE(client.read(msg));
  21315. EXPECT_EQ("header:test-value", msg);
  21316. client.close();
  21317. }
  21318. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  21319. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21320. "/ws-echo");
  21321. client.set_read_timeout(1, 0); // 1 second
  21322. ASSERT_TRUE(client.connect());
  21323. // Don't send anything — server echo handler waits for a message, so read()
  21324. // should time out. The connection survives it: nothing was consumed.
  21325. std::string msg;
  21326. EXPECT_EQ(client.read(msg), ws::Timeout);
  21327. EXPECT_TRUE(client.is_open());
  21328. // And it is still usable afterwards.
  21329. EXPECT_TRUE(client.send("after timeout"));
  21330. EXPECT_EQ(client.read(msg), ws::Text);
  21331. EXPECT_EQ(msg, "after timeout");
  21332. }
  21333. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  21334. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21335. "/ws-echo");
  21336. client.set_read_timeout(1, 0);
  21337. ASSERT_TRUE(client.connect());
  21338. ASSERT_TRUE(client.send("first"));
  21339. std::string msg;
  21340. ASSERT_EQ(client.read(msg), ws::Text);
  21341. ASSERT_EQ(msg, "first");
  21342. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  21343. // not be used with a read timeout: it would reprocess the previous message.
  21344. EXPECT_EQ(client.read(msg), ws::Timeout);
  21345. EXPECT_EQ(msg, "first");
  21346. }
  21347. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  21348. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21349. "/ws-echo");
  21350. ASSERT_TRUE(client.connect());
  21351. // Setting it once the connection is open reaches the live stream, not just
  21352. // the seed for the next connect().
  21353. client.set_read_timeout(1, 0);
  21354. std::string msg;
  21355. EXPECT_EQ(client.read(msg), ws::Timeout);
  21356. EXPECT_TRUE(client.is_open());
  21357. }
  21358. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  21359. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21360. "/ws-echo");
  21361. client.set_read_timeout(5, 0);
  21362. ASSERT_TRUE(client.connect());
  21363. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21364. // The server should reject it and close the connection.
  21365. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  21366. client.send(oversized);
  21367. // The server's read() should have failed due to payload limit,
  21368. // so our read() should return false (connection closed).
  21369. std::string msg;
  21370. EXPECT_FALSE(client.read(msg));
  21371. }
  21372. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  21373. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21374. "/ws-echo");
  21375. client.set_read_timeout(10, 0);
  21376. ASSERT_TRUE(client.connect());
  21377. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21378. // This should succeed.
  21379. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  21380. ASSERT_TRUE(client.send(at_limit));
  21381. std::string msg;
  21382. ASSERT_TRUE(client.read(msg));
  21383. EXPECT_EQ(at_limit.size(), msg.size());
  21384. client.close();
  21385. }
  21386. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  21387. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21388. "/nonexistent");
  21389. auto res = client.connect();
  21390. EXPECT_FALSE(res);
  21391. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21392. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  21393. EXPECT_FALSE(client.is_open());
  21394. }
  21395. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  21396. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21397. "/ws-echo");
  21398. ASSERT_TRUE(client.connect());
  21399. ASSERT_TRUE(client.send(""));
  21400. std::string msg;
  21401. EXPECT_EQ(ws::Text, client.read(msg));
  21402. EXPECT_EQ("", msg);
  21403. client.close();
  21404. }
  21405. TEST_F(WebSocketIntegrationTest, Reconnect) {
  21406. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21407. "/ws-echo");
  21408. // First connection
  21409. ASSERT_TRUE(client.connect());
  21410. ASSERT_TRUE(client.send("first"));
  21411. std::string msg;
  21412. ASSERT_TRUE(client.read(msg));
  21413. EXPECT_EQ("first", msg);
  21414. client.close();
  21415. EXPECT_FALSE(client.is_open());
  21416. // Reconnect using the same client object
  21417. ASSERT_TRUE(client.connect());
  21418. ASSERT_TRUE(client.is_open());
  21419. ASSERT_TRUE(client.send("second"));
  21420. ASSERT_TRUE(client.read(msg));
  21421. EXPECT_EQ("second", msg);
  21422. client.close();
  21423. }
  21424. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  21425. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21426. "/ws-close-status");
  21427. ASSERT_TRUE(client.connect());
  21428. // Trigger the server to close with GoingAway status
  21429. ASSERT_TRUE(client.send("trigger"));
  21430. // read() should return false after receiving the close frame
  21431. std::string msg;
  21432. EXPECT_FALSE(client.read(msg));
  21433. EXPECT_FALSE(client.is_open());
  21434. }
  21435. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  21436. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21437. "/ws-echo");
  21438. ASSERT_TRUE(client.connect());
  21439. client.close(ws::CloseStatus::GoingAway, "client leaving");
  21440. EXPECT_FALSE(client.is_open());
  21441. }
  21442. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  21443. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  21444. ws::WebSocketClient client(
  21445. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21446. ASSERT_TRUE(client.connect());
  21447. // Server should have selected graphql-ws
  21448. EXPECT_EQ("graphql-ws", client.subprotocol());
  21449. client.close();
  21450. }
  21451. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  21452. Headers headers;
  21453. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  21454. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  21455. ws::WebSocketClient client(
  21456. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21457. ASSERT_TRUE(client.connect());
  21458. // The offer on the second field line counts too, so graphql-ws is selected
  21459. EXPECT_EQ("graphql-ws", client.subprotocol());
  21460. client.close();
  21461. }
  21462. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  21463. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  21464. ws::WebSocketClient client(
  21465. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21466. ASSERT_TRUE(client.connect());
  21467. // Server should not have selected any subprotocol
  21468. EXPECT_TRUE(client.subprotocol().empty());
  21469. client.close();
  21470. }
  21471. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  21472. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21473. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21474. "/ws-subprotocol-unoffered",
  21475. headers);
  21476. ASSERT_TRUE(client.connect());
  21477. EXPECT_TRUE(client.subprotocol().empty());
  21478. client.close();
  21479. }
  21480. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  21481. // Connect without requesting any subprotocol
  21482. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21483. "/ws-subprotocol");
  21484. ASSERT_TRUE(client.connect());
  21485. EXPECT_TRUE(client.subprotocol().empty());
  21486. client.close();
  21487. }
  21488. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  21489. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21490. "/ws-echo");
  21491. client.set_tcp_nodelay(true);
  21492. client.set_connection_timeout(3, 0);
  21493. bool socket_options_called = false;
  21494. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  21495. ASSERT_TRUE(client.connect());
  21496. ASSERT_TRUE(client.is_open());
  21497. EXPECT_TRUE(socket_options_called);
  21498. ASSERT_TRUE(client.send("hello"));
  21499. std::string msg;
  21500. auto result = client.read(msg);
  21501. EXPECT_EQ(result, ws::ReadResult::Text);
  21502. EXPECT_EQ(msg, "hello");
  21503. client.close();
  21504. }
  21505. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  21506. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21507. "/ws-echo");
  21508. client.set_connection_timeout(std::chrono::seconds(3));
  21509. client.set_write_timeout(std::chrono::seconds(3));
  21510. // A sub-second remainder exercises the seconds/microseconds split.
  21511. client.set_read_timeout(std::chrono::milliseconds(1500));
  21512. ASSERT_TRUE(client.connect());
  21513. auto start = std::chrono::steady_clock::now();
  21514. std::string msg;
  21515. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  21516. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  21517. std::chrono::steady_clock::now() - start)
  21518. .count();
  21519. // Above 1s so that dropping the microseconds half of the split fails here.
  21520. // Ignoring the setter altogether would not reach this line at all: a client
  21521. // waits forever by default.
  21522. EXPECT_GE(elapsed, 1400);
  21523. EXPECT_LT(elapsed, 30000);
  21524. }
  21525. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  21526. Server svr;
  21527. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  21528. if (!req.has_header("Authorization")) {
  21529. res.status = StatusCode::Unauthorized_401;
  21530. res.set_content("Unauthorized", "text/plain");
  21531. return Server::HandlerResponse::Handled;
  21532. }
  21533. return Server::HandlerResponse::Unhandled;
  21534. });
  21535. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21536. std::string msg;
  21537. while (ws.read(msg)) {
  21538. ws.send(msg);
  21539. }
  21540. });
  21541. auto port = svr.bind_to_any_port("localhost");
  21542. std::thread t([&]() { svr.listen_after_bind(); });
  21543. svr.wait_until_ready();
  21544. // Without Authorization header - should be rejected before upgrade
  21545. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  21546. EXPECT_FALSE(client1.connect());
  21547. // The rejection is framed like any other HTTP response
  21548. {
  21549. Client cli("localhost", port);
  21550. Headers headers = {{"Upgrade", "websocket"},
  21551. {"Connection", "Upgrade"},
  21552. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21553. {"Sec-WebSocket-Version", "13"}};
  21554. auto res = cli.Get("/ws", headers);
  21555. ASSERT_TRUE(res);
  21556. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21557. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21558. EXPECT_EQ("Unauthorized", res->body);
  21559. }
  21560. // With Authorization header - should succeed
  21561. Headers headers = {{"Authorization", "Bearer token123"}};
  21562. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  21563. headers);
  21564. ASSERT_TRUE(client2.connect());
  21565. ASSERT_TRUE(client2.send("hello"));
  21566. std::string msg;
  21567. ASSERT_TRUE(client2.read(msg));
  21568. EXPECT_EQ("hello", msg);
  21569. client2.close();
  21570. svr.stop();
  21571. t.join();
  21572. }
  21573. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  21574. Server svr;
  21575. std::atomic<int> pre_request_calls{0};
  21576. std::atomic<bool> route_matched{false};
  21577. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  21578. pre_request_calls++;
  21579. if (req.matched_route == "/ws/:id") { route_matched = true; }
  21580. if (req.get_header_value("Authorization") != "Bearer token123") {
  21581. res.status = StatusCode::Unauthorized_401;
  21582. res.set_content("Unauthorized", "text/plain");
  21583. return Server::HandlerResponse::Handled;
  21584. }
  21585. return Server::HandlerResponse::Unhandled;
  21586. });
  21587. std::atomic<bool> handler_called{false};
  21588. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  21589. handler_called = true;
  21590. ws.send(req.matched_route + " " + req.path_params.at("id"));
  21591. });
  21592. auto port = svr.bind_to_any_port("localhost");
  21593. std::thread t([&]() { svr.listen_after_bind(); });
  21594. svr.wait_until_ready();
  21595. // Without Authorization header - should be rejected before upgrade
  21596. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  21597. "/ws/1");
  21598. EXPECT_FALSE(client1.connect());
  21599. EXPECT_FALSE(handler_called);
  21600. EXPECT_EQ(1, pre_request_calls);
  21601. EXPECT_TRUE(route_matched);
  21602. // The rejection is an ordinary HTTP response, not a protocol switch
  21603. {
  21604. Client cli("localhost", port);
  21605. Headers headers = {{"Upgrade", "websocket"},
  21606. {"Connection", "Upgrade"},
  21607. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21608. {"Sec-WebSocket-Version", "13"}};
  21609. auto res = cli.Get("/ws/1", headers);
  21610. ASSERT_TRUE(res);
  21611. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21612. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21613. EXPECT_EQ("Unauthorized", res->body);
  21614. }
  21615. EXPECT_FALSE(handler_called);
  21616. // With Authorization header - should succeed
  21617. Headers headers = {{"Authorization", "Bearer token123"}};
  21618. ws::WebSocketClient client2(
  21619. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  21620. ASSERT_TRUE(client2.connect());
  21621. std::string msg;
  21622. ASSERT_TRUE(client2.read(msg));
  21623. EXPECT_EQ("/ws/:id 2", msg);
  21624. EXPECT_TRUE(handler_called);
  21625. client2.close();
  21626. svr.stop();
  21627. t.join();
  21628. }
  21629. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  21630. Server svr;
  21631. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21632. // A read timeout is how a handler gets control back. Without it, a handler
  21633. // parked in read() can never write on the connection it is reading.
  21634. ws.set_read_timeout(std::chrono::milliseconds(100));
  21635. std::string msg;
  21636. while (ws.is_open()) {
  21637. auto r = ws.read(msg);
  21638. if (r == httplib::ws::Timeout) {
  21639. ws.send("tick");
  21640. continue;
  21641. }
  21642. if (r == httplib::ws::Fail) { break; }
  21643. ws.send(msg);
  21644. }
  21645. });
  21646. auto port = svr.bind_to_any_port("localhost");
  21647. std::thread t([&]() { svr.listen_after_bind(); });
  21648. svr.wait_until_ready();
  21649. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21650. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  21651. ASSERT_TRUE(client.connect());
  21652. // The client sends nothing, so anything it receives came out of the
  21653. // handler's timeout path.
  21654. std::string msg;
  21655. ASSERT_EQ(client.read(msg), ws::Text);
  21656. EXPECT_EQ("tick", msg);
  21657. client.close();
  21658. svr.stop();
  21659. t.join();
  21660. }
  21661. // Stream::read may return fewer bytes than asked for. This is that contract at
  21662. // its worst -- one byte per call -- which is what a frame header straddling a
  21663. // read buffer's boundary looks like to the frame parser.
  21664. class WsByteAtATimeStream : public Stream {
  21665. public:
  21666. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  21667. bool is_readable() const override { return true; }
  21668. bool wait_readable() const override { return true; }
  21669. bool wait_writable() const override { return true; }
  21670. ssize_t read(char *ptr, size_t size) override {
  21671. if (size == 0 || pos_ >= data_.size()) { return 0; }
  21672. *ptr = data_[pos_++];
  21673. return 1;
  21674. }
  21675. ssize_t write(const char *, size_t size) override {
  21676. return static_cast<ssize_t>(size);
  21677. }
  21678. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  21679. ip = "127.0.0.1";
  21680. port = 0;
  21681. }
  21682. void get_local_ip_and_port(std::string &ip, int &port) const override {
  21683. ip = "127.0.0.1";
  21684. port = 0;
  21685. }
  21686. socket_t socket() const override { return INVALID_SOCKET; }
  21687. time_t duration() const override { return 0; }
  21688. private:
  21689. std::string data_;
  21690. size_t pos_ = 0;
  21691. };
  21692. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  21693. // The payload uses the 16-bit extended length, so the header, the length
  21694. // and the mask key are all multi-byte fields here. Each used to be read
  21695. // with a single read() call, which fails as soon as one is split. The
  21696. // payload is also a little over one read chunk, so it is read in two.
  21697. std::string body;
  21698. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  21699. body += static_cast<char>(i % 251);
  21700. }
  21701. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  21702. std::string frame;
  21703. frame += static_cast<char>(0x81); // FIN + Text
  21704. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  21705. frame += static_cast<char>(body.size() >> 8);
  21706. frame += static_cast<char>(body.size() & 0xff);
  21707. for (size_t i = 0; i < 4; i++) {
  21708. frame += static_cast<char>(mask[i]);
  21709. }
  21710. for (size_t i = 0; i < body.size(); i++) {
  21711. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  21712. }
  21713. WsByteAtATimeStream strm(frame);
  21714. ws::Opcode opcode;
  21715. std::string payload;
  21716. bool fin = false;
  21717. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  21718. /*expect_masked=*/true, body.size()),
  21719. ws::impl::FrameRead::Ok);
  21720. EXPECT_TRUE(fin);
  21721. EXPECT_EQ(opcode, ws::Opcode::Text);
  21722. EXPECT_EQ(payload, body);
  21723. }
  21724. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  21725. std::string body(2000, 'x');
  21726. std::string frame;
  21727. frame += static_cast<char>(0x82); // FIN + Binary
  21728. frame += static_cast<char>(126); // 16-bit length follows
  21729. frame += static_cast<char>(body.size() >> 8);
  21730. frame += static_cast<char>(body.size() & 0xff);
  21731. frame += body;
  21732. detail::BufferStream strm;
  21733. strm.write(frame.data(), frame.size());
  21734. ws::Opcode opcode;
  21735. std::string payload;
  21736. bool fin;
  21737. EXPECT_EQ(
  21738. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  21739. ws::impl::FrameRead::Ok);
  21740. EXPECT_EQ(body, payload);
  21741. }
  21742. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  21743. // The header announces the largest payload allowed, and only 3 bytes of it
  21744. // ever arrive.
  21745. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  21746. std::string frame;
  21747. frame += static_cast<char>(0x82); // FIN + Binary
  21748. frame += static_cast<char>(127); // 64-bit length follows
  21749. for (int shift = 56; shift >= 0; shift -= 8) {
  21750. frame += static_cast<char>((len >> shift) & 0xff);
  21751. }
  21752. frame += "abc";
  21753. detail::BufferStream strm;
  21754. strm.write(frame.data(), frame.size());
  21755. ws::Opcode opcode;
  21756. std::string payload;
  21757. bool fin;
  21758. EXPECT_EQ(
  21759. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  21760. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  21761. ws::impl::FrameRead::Fail);
  21762. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  21763. }
  21764. TEST(WebSocketTest, QueryStringInHandshake) {
  21765. Server svr;
  21766. std::mutex mtx;
  21767. std::string received_target;
  21768. std::string received_token;
  21769. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21770. {
  21771. std::lock_guard<std::mutex> lock(mtx);
  21772. received_target = req.target;
  21773. if (req.has_param("token")) {
  21774. received_token = req.get_param_value("token");
  21775. }
  21776. }
  21777. std::string msg;
  21778. while (ws.read(msg)) {
  21779. ws.send(msg);
  21780. }
  21781. });
  21782. auto port = svr.bind_to_any_port("localhost");
  21783. std::thread t([&]() { svr.listen_after_bind(); });
  21784. svr.wait_until_ready();
  21785. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  21786. "/ws?token=ABC&session=123");
  21787. ASSERT_TRUE(client.connect());
  21788. // Round-trip ensures the handler has run and captured the request.
  21789. ASSERT_TRUE(client.send("hello"));
  21790. std::string msg;
  21791. ASSERT_TRUE(client.read(msg));
  21792. EXPECT_EQ("hello", msg);
  21793. client.close();
  21794. {
  21795. std::lock_guard<std::mutex> lock(mtx);
  21796. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  21797. EXPECT_EQ("ABC", received_token);
  21798. }
  21799. svr.stop();
  21800. t.join();
  21801. }
  21802. // Run a handshake against a throwaway server and hand the request the server
  21803. // received back to the caller, so tests can assert on the headers the client
  21804. // actually put on the wire.
  21805. static void capture_websocket_handshake_request(
  21806. const Headers &client_headers,
  21807. std::function<void(const Request &, int port)> verify) {
  21808. Server svr;
  21809. std::mutex mtx;
  21810. Request received;
  21811. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21812. {
  21813. std::lock_guard<std::mutex> lock(mtx);
  21814. received = req;
  21815. }
  21816. std::string msg;
  21817. while (ws.read(msg)) {
  21818. ws.send(msg);
  21819. }
  21820. });
  21821. auto port = svr.bind_to_any_port("localhost");
  21822. std::thread t([&]() { svr.listen_after_bind(); });
  21823. auto se = detail::scope_exit([&] {
  21824. svr.stop();
  21825. t.join();
  21826. });
  21827. svr.wait_until_ready();
  21828. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  21829. client_headers);
  21830. ASSERT_TRUE(client.connect());
  21831. ASSERT_TRUE(client.send("hello"));
  21832. std::string msg;
  21833. ASSERT_TRUE(client.read(msg));
  21834. client.close();
  21835. {
  21836. std::lock_guard<std::mutex> lock(mtx);
  21837. verify(received, port);
  21838. }
  21839. }
  21840. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  21841. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  21842. // Non-default port must be present in the Host header. Default ports
  21843. // (80/443) are omitted; that logic is covered by
  21844. // MakeHostAndPortStringTest.
  21845. EXPECT_EQ("localhost:" + std::to_string(port),
  21846. req.get_header_value("Host"));
  21847. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  21848. req.get_header_value("User-Agent"));
  21849. EXPECT_FALSE(req.has_header("Accept"));
  21850. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  21851. EXPECT_FALSE(req.has_header("Content-Length"));
  21852. });
  21853. }
  21854. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  21855. capture_websocket_handshake_request(
  21856. {{"Host", "example.com"},
  21857. {"User-Agent", "custom-agent"},
  21858. {"X-Custom", "value"}},
  21859. [](const Request &req, int) {
  21860. EXPECT_EQ("example.com", req.get_header_value("Host"));
  21861. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  21862. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  21863. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  21864. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  21865. });
  21866. }
  21867. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  21868. capture_websocket_handshake_request(
  21869. {{"Upgrade", "bogus"},
  21870. {"Connection", "close"},
  21871. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  21872. {"Sec-WebSocket-Version", "8"}},
  21873. [](const Request &req, int) {
  21874. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  21875. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  21876. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  21877. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  21878. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  21879. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  21880. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  21881. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  21882. req.get_header_value("Sec-WebSocket-Key"));
  21883. });
  21884. }
  21885. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  21886. // A header the client refuses to send must abort the handshake before any
  21887. // part of it reaches the wire; a lone request line would otherwise sit in
  21888. // the peer's buffer as a truncated request.
  21889. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21890. ASSERT_NE(INVALID_SOCKET, srv);
  21891. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  21892. sockaddr_in addr{};
  21893. addr.sin_family = AF_INET;
  21894. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  21895. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21896. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  21897. ASSERT_EQ(0, ::listen(srv, 1));
  21898. sockaddr_in bound{};
  21899. socklen_t bound_len = sizeof(bound);
  21900. ASSERT_EQ(
  21901. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  21902. auto port = ntohs(bound.sin_port);
  21903. ssize_t received = -1;
  21904. std::thread t([&] {
  21905. // Bound every blocking call so a regression fails the test with a bad
  21906. // value instead of hanging the suite.
  21907. fd_set rfds;
  21908. FD_ZERO(&rfds);
  21909. FD_SET(srv, &rfds);
  21910. timeval tv{5, 0};
  21911. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  21912. 0) {
  21913. return;
  21914. }
  21915. sockaddr_in cli_addr{};
  21916. socklen_t cli_len = sizeof(cli_addr);
  21917. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  21918. if (cli == INVALID_SOCKET) { return; }
  21919. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  21920. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21921. char buf[4096];
  21922. received = ::recv(cli, buf, sizeof(buf), 0);
  21923. });
  21924. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  21925. // connect() has already shut the socket down by the time it returns false,
  21926. // so the peer sees EOF without waiting for the client to be destroyed.
  21927. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  21928. {{"X-Bad", "a\r\nInjected: 1"}});
  21929. EXPECT_FALSE(client.connect());
  21930. t.join();
  21931. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  21932. EXPECT_EQ(0, received);
  21933. }
  21934. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  21935. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  21936. // contains "upgrade" as a substring is a different token and must not
  21937. // start a WebSocket handshake.
  21938. auto make_request = [](const std::vector<std::string> &connection_values) {
  21939. Request req;
  21940. req.method = "GET";
  21941. req.headers.emplace("Upgrade", "websocket");
  21942. for (const auto &value : connection_values) {
  21943. req.headers.emplace("Connection", value);
  21944. }
  21945. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21946. req.headers.emplace("Sec-WebSocket-Version", "13");
  21947. return req;
  21948. };
  21949. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  21950. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  21951. EXPECT_TRUE(
  21952. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  21953. EXPECT_TRUE(
  21954. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  21955. EXPECT_TRUE(
  21956. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  21957. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  21958. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  21959. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  21960. EXPECT_FALSE(
  21961. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  21962. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  21963. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21964. }
  21965. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  21966. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  21967. // asks recipients to match each protocol-name case-insensitively, and RFC
  21968. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  21969. // client naming websocket alongside another protocol, or on a second field
  21970. // line, is offering websocket; a value that merely contains "websocket" as a
  21971. // substring is a different protocol name and is not.
  21972. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  21973. Request req;
  21974. req.method = "GET";
  21975. for (const auto &value : upgrade_values) {
  21976. req.headers.emplace("Upgrade", value);
  21977. }
  21978. req.headers.emplace("Connection", "Upgrade");
  21979. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21980. req.headers.emplace("Sec-WebSocket-Version", "13");
  21981. return req;
  21982. };
  21983. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  21984. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  21985. EXPECT_TRUE(
  21986. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  21987. EXPECT_TRUE(
  21988. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  21989. EXPECT_TRUE(
  21990. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  21991. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  21992. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  21993. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  21994. EXPECT_FALSE(
  21995. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  21996. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  21997. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21998. }
  21999. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  22000. Server svr;
  22001. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  22002. auto port = svr.bind_to_any_port("localhost");
  22003. std::thread t([&]() { svr.listen_after_bind(); });
  22004. auto se = detail::scope_exit([&] {
  22005. svr.stop();
  22006. t.join();
  22007. });
  22008. svr.wait_until_ready();
  22009. Headers headers = {{"Upgrade", "websocket"},
  22010. {"Connection", "notupgrade"},
  22011. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22012. {"Sec-WebSocket-Version", "13"}};
  22013. Client cli("localhost", port);
  22014. auto res = cli.Get("/ws", headers);
  22015. // The route exists only as a WebSocket route, so a request that fails the
  22016. // handshake check falls through to ordinary routing.
  22017. ASSERT_TRUE(res);
  22018. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  22019. }
  22020. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  22021. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  22022. // Connection value is the only thing left for the client to reject.
  22023. Server svr;
  22024. svr.Get("/ws", [](const Request &req, Response &res) {
  22025. res.status = StatusCode::SwitchingProtocol_101;
  22026. res.set_header("Upgrade", "websocket");
  22027. res.set_header("Connection", "notupgrade");
  22028. res.set_header("Sec-WebSocket-Accept",
  22029. detail::websocket_accept_key(
  22030. req.get_header_value("Sec-WebSocket-Key")));
  22031. });
  22032. auto port = svr.bind_to_any_port("localhost");
  22033. std::thread t([&]() { svr.listen_after_bind(); });
  22034. auto se = detail::scope_exit([&] {
  22035. svr.stop();
  22036. t.join();
  22037. });
  22038. svr.wait_until_ready();
  22039. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22040. auto res = client.connect();
  22041. EXPECT_FALSE(res);
  22042. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22043. EXPECT_FALSE(client.is_open());
  22044. }
  22045. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  22046. Server svr;
  22047. svr.Get("/ws", [](const Request &req, Response &res) {
  22048. res.status = StatusCode::SwitchingProtocol_101;
  22049. res.set_header("Upgrade", "websocket");
  22050. res.set_header("Connection", "Upgrade");
  22051. res.set_header("Sec-WebSocket-Accept",
  22052. detail::websocket_accept_key(
  22053. req.get_header_value("Sec-WebSocket-Key")));
  22054. res.set_header("Sec-WebSocket-Protocol", "admin");
  22055. });
  22056. auto port = svr.bind_to_any_port("localhost");
  22057. std::thread t([&]() { svr.listen_after_bind(); });
  22058. auto se = detail::scope_exit([&] {
  22059. svr.stop();
  22060. t.join();
  22061. });
  22062. svr.wait_until_ready();
  22063. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  22064. // Server selects a subprotocol the client never offered
  22065. {
  22066. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22067. ws::WebSocketClient client(url, headers);
  22068. auto res = client.connect();
  22069. EXPECT_FALSE(res);
  22070. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22071. EXPECT_FALSE(client.is_open());
  22072. EXPECT_TRUE(client.subprotocol().empty());
  22073. }
  22074. // Client offered none but the server named one anyway
  22075. {
  22076. ws::WebSocketClient client(url);
  22077. auto res = client.connect();
  22078. EXPECT_FALSE(res);
  22079. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22080. EXPECT_FALSE(client.is_open());
  22081. EXPECT_TRUE(client.subprotocol().empty());
  22082. }
  22083. }
  22084. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  22085. // The socket path doubles as the URL host, so it must not contain '/'.
  22086. const char *shard = getenv("GTEST_SHARD_INDEX");
  22087. const std::string sock_path =
  22088. shard ? std::string("httplib-ws-") + shard + ".sock"
  22089. : std::string("httplib-ws.sock");
  22090. std::remove(sock_path.c_str());
  22091. Server svr;
  22092. std::mutex mtx;
  22093. std::string received_host;
  22094. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22095. {
  22096. std::lock_guard<std::mutex> lock(mtx);
  22097. received_host = req.get_header_value("Host");
  22098. }
  22099. std::string msg;
  22100. while (ws.read(msg)) {
  22101. ws.send(msg);
  22102. }
  22103. });
  22104. svr.set_address_family(AF_UNIX);
  22105. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  22106. auto se = detail::scope_exit([&] {
  22107. svr.stop();
  22108. t.join();
  22109. std::remove(sock_path.c_str());
  22110. });
  22111. svr.wait_until_ready();
  22112. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  22113. client.set_address_family(AF_UNIX);
  22114. ASSERT_TRUE(client.connect());
  22115. ASSERT_TRUE(client.send("hello"));
  22116. std::string msg;
  22117. ASSERT_TRUE(client.read(msg));
  22118. client.close();
  22119. {
  22120. std::lock_guard<std::mutex> lock(mtx);
  22121. // There is no host:port for a Unix socket, so the same "localhost"
  22122. // placeholder the HTTP client uses is expected.
  22123. EXPECT_EQ("localhost", received_host);
  22124. }
  22125. }
  22126. // Two threads must never parse WebSocket frames from the same stream.
  22127. // close() used to read the peer's Close reply with its own frame read, so it
  22128. // raced a reader thread that was in the middle of a payload: the payload loop
  22129. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  22130. // so bytes taken by close() were replaced with bytes from further along the
  22131. // stream. The message kept its length and silently changed content.
  22132. //
  22133. // The raw peer below sends a frame header plus part of the payload, waits for
  22134. // the handler to call close(), and only then sends the rest. Whichever thread
  22135. // would win the race for those bytes, the message must arrive intact, because
  22136. // close() must not touch the stream while read() owns it.
  22137. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  22138. #ifndef _WIN32
  22139. signal(SIGPIPE, SIG_IGN);
  22140. #endif
  22141. const size_t payload_len = 120; // fits the 7-bit length field
  22142. const size_t prefix_len = 8;
  22143. const int attempts = 8;
  22144. std::string expected(payload_len, '\0');
  22145. for (size_t i = 0; i < payload_len; i++) {
  22146. expected[i] = static_cast<char>('a' + i % 26);
  22147. }
  22148. std::atomic<bool> peer_stalled{false};
  22149. std::atomic<bool> handler_done{false};
  22150. std::mutex received_mutex;
  22151. std::vector<std::string> received;
  22152. // Bound every wait, so a regression fails the test instead of hanging the
  22153. // suite.
  22154. auto wait_for = [](const std::atomic<bool> &flag) {
  22155. for (int i = 0; i < 500 && !flag; i++) {
  22156. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22157. }
  22158. };
  22159. Server svr;
  22160. svr.set_websocket_ping_interval(0);
  22161. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22162. std::thread reader([&]() {
  22163. std::string msg;
  22164. while (ws.read(msg)) {
  22165. std::lock_guard<std::mutex> guard(received_mutex);
  22166. received.push_back(msg);
  22167. }
  22168. });
  22169. // Wait until the peer stalls mid-payload, so the reader thread is parked
  22170. // inside read_websocket_frame() when close() runs.
  22171. wait_for(peer_stalled);
  22172. ws.close();
  22173. reader.join();
  22174. handler_done = true;
  22175. });
  22176. auto port = svr.bind_to_any_port("127.0.0.1");
  22177. std::thread t([&]() { svr.listen_after_bind(); });
  22178. auto se = detail::scope_exit([&] {
  22179. svr.stop();
  22180. t.join();
  22181. });
  22182. svr.wait_until_ready();
  22183. auto send_bytes = [](socket_t s, const std::string &data) {
  22184. #ifdef _WIN32
  22185. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  22186. #else
  22187. auto n = ::send(s, data.data(), data.size(), 0);
  22188. #endif
  22189. return n == static_cast<decltype(n)>(data.size());
  22190. };
  22191. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  22192. // Every length used here fits the 7-bit length field.
  22193. auto masked_header = [](uint8_t first_byte, size_t len) {
  22194. std::string h;
  22195. h += static_cast<char>(first_byte);
  22196. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  22197. h.append(4, '\0'); // mask key
  22198. return h;
  22199. };
  22200. for (int attempt = 0; attempt < attempts; attempt++) {
  22201. peer_stalled = false;
  22202. handler_done = false;
  22203. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22204. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  22205. auto se_sock = detail::scope_exit([&] {
  22206. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  22207. });
  22208. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22209. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  22210. sockaddr_in addr{};
  22211. addr.sin_family = AF_INET;
  22212. addr.sin_port = htons(static_cast<uint16_t>(port));
  22213. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22214. ASSERT_EQ(
  22215. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  22216. << "attempt " << attempt;
  22217. ASSERT_TRUE(send_bytes(sock,
  22218. "GET /ws HTTP/1.1\r\n"
  22219. "Host: 127.0.0.1\r\n"
  22220. "Upgrade: websocket\r\n"
  22221. "Connection: Upgrade\r\n"
  22222. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22223. "Sec-WebSocket-Version: 13\r\n"
  22224. "\r\n"))
  22225. << "attempt " << attempt;
  22226. std::string response;
  22227. while (response.find("\r\n\r\n") == std::string::npos) {
  22228. char buf[512];
  22229. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  22230. if (n <= 0) { break; }
  22231. response.append(buf, static_cast<size_t>(n));
  22232. }
  22233. ASSERT_NE(std::string::npos, response.find(" 101 "))
  22234. << "attempt " << attempt;
  22235. // Send the header of a Binary message but only the first prefix_len bytes
  22236. // of its payload, leaving the reader thread stalled inside the payload.
  22237. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  22238. expected.substr(0, prefix_len)))
  22239. << "attempt " << attempt;
  22240. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22241. peer_stalled = true;
  22242. // Let close() send its Close frame and park in its own read before the
  22243. // rest of the payload arrives, so both threads are waiting for it.
  22244. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22245. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  22246. close_frame += static_cast<char>(0x03); // status 1000
  22247. close_frame += static_cast<char>(0xE8);
  22248. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  22249. << "attempt " << attempt;
  22250. // Closing the peer releases the reader thread even on the buggy path,
  22251. // where it waits for bytes another thread already consumed.
  22252. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22253. detail::close_socket(sock);
  22254. sock = INVALID_SOCKET;
  22255. wait_for(handler_done);
  22256. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  22257. }
  22258. std::lock_guard<std::mutex> guard(received_mutex);
  22259. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  22260. << "a message in flight when close() ran was dropped";
  22261. for (size_t i = 0; i < received.size(); i++) {
  22262. EXPECT_EQ(expected, received[i]) << "message " << i;
  22263. }
  22264. }
  22265. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  22266. std::atomic<bool> done{false};
  22267. std::string received;
  22268. Server svr;
  22269. svr.set_websocket_ping_interval(0);
  22270. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22271. std::string msg;
  22272. if (ws.read(msg) == ws::Binary) { received = msg; }
  22273. done = true;
  22274. });
  22275. auto port = svr.bind_to_any_port("127.0.0.1");
  22276. std::thread t([&]() { svr.listen_after_bind(); });
  22277. auto se = detail::scope_exit([&] {
  22278. svr.stop();
  22279. t.join();
  22280. });
  22281. svr.wait_until_ready();
  22282. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22283. ASSERT_NE(INVALID_SOCKET, sock);
  22284. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  22285. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22286. sockaddr_in addr{};
  22287. addr.sin_family = AF_INET;
  22288. addr.sin_port = htons(static_cast<uint16_t>(port));
  22289. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22290. ASSERT_EQ(0,
  22291. ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  22292. // Frames with an all-zero mask key, so the payload goes out verbatim.
  22293. auto frame = [](uint8_t first_byte, const std::string &payload) {
  22294. std::string f;
  22295. f += static_cast<char>(first_byte);
  22296. f += static_cast<char>(0x80 | payload.size());
  22297. f.append(4, '\0');
  22298. return f + payload;
  22299. };
  22300. std::string data = "GET /ws HTTP/1.1\r\n"
  22301. "Host: 127.0.0.1\r\n"
  22302. "Upgrade: websocket\r\n"
  22303. "Connection: Upgrade\r\n"
  22304. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22305. "Sec-WebSocket-Version: 13\r\n"
  22306. "\r\n";
  22307. data += frame(0x02, "Hel"); // Binary, more to come
  22308. data += frame(0x89, "p"); // FIN + Ping
  22309. data += frame(0x80, "lo"); // FIN + Continuation
  22310. #ifdef _WIN32
  22311. ::send(sock, data.data(), static_cast<int>(data.size()), 0);
  22312. #else
  22313. ::send(sock, data.data(), data.size(), 0);
  22314. #endif
  22315. for (int i = 0; i < 500 && !done; i++) {
  22316. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22317. }
  22318. ASSERT_TRUE(done);
  22319. EXPECT_EQ("Hello", received);
  22320. }
  22321. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22322. class WebSocketSSLIntegrationTest : public ::testing::Test {
  22323. protected:
  22324. void SetUp() override {
  22325. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  22326. SERVER_PRIVATE_KEY_FILE);
  22327. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22328. std::string msg;
  22329. ws::ReadResult ret;
  22330. while ((ret = ws.read(msg))) {
  22331. if (ret == ws::Binary) {
  22332. ws.send(msg.data(), msg.size());
  22333. } else {
  22334. ws.send(msg);
  22335. }
  22336. }
  22337. });
  22338. port_ = server_->bind_to_any_port(HOST);
  22339. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22340. server_->wait_until_ready();
  22341. }
  22342. void TearDown() override {
  22343. server_->stop();
  22344. if (server_thread_.joinable()) { server_thread_.join(); }
  22345. }
  22346. std::unique_ptr<SSLServer> server_;
  22347. std::thread server_thread_;
  22348. int port_ = 0;
  22349. };
  22350. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  22351. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22352. "/ws-echo");
  22353. client.enable_server_certificate_verification(false);
  22354. ASSERT_TRUE(client.connect());
  22355. ASSERT_TRUE(client.is_open());
  22356. ASSERT_TRUE(client.send("Hello WSS"));
  22357. std::string msg;
  22358. EXPECT_EQ(ws::Text, client.read(msg));
  22359. EXPECT_EQ("Hello WSS", msg);
  22360. client.close();
  22361. }
  22362. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  22363. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  22364. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  22365. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  22366. // client (without calling close() first) is the only path that runs
  22367. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  22368. // bug exactly.
  22369. //
  22370. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  22371. // when linked against an instrumented libssl; run under Valgrind to catch it
  22372. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  22373. // suite (the freed session otherwise stalls on the close handshake) — this test
  22374. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  22375. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  22376. {
  22377. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22378. "/ws-echo");
  22379. client.enable_server_certificate_verification(false);
  22380. client.set_read_timeout(2, 0);
  22381. client.set_write_timeout(2, 0);
  22382. ASSERT_TRUE(client.connect());
  22383. ASSERT_TRUE(client.is_open());
  22384. ASSERT_TRUE(client.send("still open"));
  22385. // Intentionally do NOT call client.close(): leaving scope runs
  22386. // shutdown_and_close() with the WebSocket still open, which must send the
  22387. // close frame while the TLS session is still alive.
  22388. }
  22389. }
  22390. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  22391. // shutdown_and_close() at the start of connect(), reproducing the same
  22392. // use-after-free within the test body rather than at scope exit. The second
  22393. // connect must succeed and echo, proving the close handshake ran over a live
  22394. // session. See the note above about memory-tool requirements.
  22395. TEST_F(WebSocketSSLIntegrationTest,
  22396. ReconnectWhileOpenSendsCloseOverLiveSession) {
  22397. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22398. "/ws-echo");
  22399. client.enable_server_certificate_verification(false);
  22400. client.set_read_timeout(2, 0);
  22401. client.set_write_timeout(2, 0);
  22402. ASSERT_TRUE(client.connect());
  22403. ASSERT_TRUE(client.is_open());
  22404. ASSERT_TRUE(client.send("still open"));
  22405. // Reconnect without closing first: connect() calls shutdown_and_close() on
  22406. // the still-open connection, which must not touch a freed TLS session.
  22407. ASSERT_TRUE(client.connect());
  22408. ASSERT_TRUE(client.is_open());
  22409. ASSERT_TRUE(client.send("after reconnect"));
  22410. std::string msg;
  22411. EXPECT_EQ(ws::Text, client.read(msg));
  22412. EXPECT_EQ("after reconnect", msg);
  22413. client.close();
  22414. }
  22415. #endif
  22416. #ifdef CPPHTTPLIB_SSL_ENABLED
  22417. class WebSocketSSLCATest : public ::testing::Test {
  22418. protected:
  22419. void SetUp() override {
  22420. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  22421. SERVER_PRIVATE_KEY_FILE);
  22422. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22423. std::string msg;
  22424. while (ws.read(msg)) {
  22425. ws.send(msg);
  22426. }
  22427. });
  22428. port_ = server_->bind_to_any_port("127.0.0.1");
  22429. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22430. server_->wait_until_ready();
  22431. }
  22432. void TearDown() override {
  22433. server_->stop();
  22434. if (server_thread_.joinable()) { server_thread_.join(); }
  22435. }
  22436. std::string url() const {
  22437. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  22438. }
  22439. std::unique_ptr<SSLServer> server_;
  22440. std::thread server_thread_;
  22441. int port_ = 0;
  22442. };
  22443. // A custom CA loaded as PEM verifies the server with full certificate
  22444. // verification enabled
  22445. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  22446. ws::WebSocketClient client(url());
  22447. std::string cert;
  22448. read_file(SERVER_CERT2_FILE, cert);
  22449. client.load_ca_cert_store(cert.c_str(), cert.size());
  22450. ASSERT_TRUE(client.connect());
  22451. ASSERT_TRUE(client.send("hello"));
  22452. std::string msg;
  22453. EXPECT_EQ(ws::Text, client.read(msg));
  22454. EXPECT_EQ("hello", msg);
  22455. client.close();
  22456. }
  22457. // A custom CA that does not cover the server must fail verification (the
  22458. // custom CA is exclusive; system certs are not loaded alongside it)
  22459. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  22460. ws::WebSocketClient client(url());
  22461. std::string cert;
  22462. read_file(CLIENT_CA_CERT_FILE, cert);
  22463. client.load_ca_cert_store(cert.c_str(), cert.size());
  22464. auto res = client.connect();
  22465. ASSERT_FALSE(res);
  22466. EXPECT_EQ(Error::SSLServerVerification, res.error());
  22467. EXPECT_EQ(-1, res.status());
  22468. EXPECT_NE(0u, res.ssl_backend_error());
  22469. }
  22470. // The same CA as a file path rather than PEM in memory
  22471. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  22472. ws::WebSocketClient client(url());
  22473. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22474. ASSERT_TRUE(client.connect());
  22475. ASSERT_TRUE(client.send("hello"));
  22476. std::string msg;
  22477. EXPECT_EQ(ws::Text, client.read(msg));
  22478. EXPECT_EQ("hello", msg);
  22479. client.close();
  22480. }
  22481. // ...and a CA file that does not cover the server still fails, so it is the
  22482. // path above that decides the outcome
  22483. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  22484. ws::WebSocketClient client(url());
  22485. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22486. ASSERT_FALSE(client.connect());
  22487. }
  22488. // Regression test: reconnecting with a native custom CA store used to reuse
  22489. // a store handle the previous TLS context had already freed (use-after-free
  22490. // under the OpenSSL backend). The context now lives as long as the client.
  22491. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  22492. ws::WebSocketClient client(url());
  22493. std::string cert;
  22494. read_file(SERVER_CERT2_FILE, cert);
  22495. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  22496. ASSERT_TRUE(client.connect());
  22497. client.close();
  22498. ASSERT_TRUE(client.connect());
  22499. ASSERT_TRUE(client.send("again"));
  22500. std::string msg;
  22501. EXPECT_EQ(ws::Text, client.read(msg));
  22502. EXPECT_EQ("again", msg);
  22503. client.close();
  22504. }
  22505. // Regression test: a certificate with a trusted chain but no identity match
  22506. // for the server IP must be rejected. The Mbed TLS backend used to skip
  22507. // verification entirely for IP hosts, so this connection succeeded there.
  22508. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  22509. // chain verification while the identity check must still fail.
  22510. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  22511. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22512. ASSERT_TRUE(svr.is_valid());
  22513. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22514. std::string msg;
  22515. while (ws.read(msg)) {
  22516. ws.send(msg);
  22517. }
  22518. });
  22519. auto port = svr.bind_to_any_port("127.0.0.1");
  22520. auto t = std::thread([&]() { svr.listen_after_bind(); });
  22521. auto se = detail::scope_exit([&] {
  22522. svr.stop();
  22523. t.join();
  22524. });
  22525. svr.wait_until_ready();
  22526. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  22527. "/echo");
  22528. std::string cert;
  22529. read_file(SERVER_CERT_FILE, cert);
  22530. client.load_ca_cert_store(cert.c_str(), cert.size());
  22531. ASSERT_FALSE(client.connect());
  22532. }
  22533. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  22534. // SNI, so nothing binds the host name to the TLS session. These bind the
  22535. // server to "localhost" instead, the only shape that exercises the SNI and
  22536. // hostname-verification path with certificate verification left enabled.
  22537. class WebSocketSSLDnsHostTest : public ::testing::Test {
  22538. protected:
  22539. void Start(const char *cert_file) {
  22540. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  22541. SERVER_PRIVATE_KEY_FILE);
  22542. ASSERT_TRUE(server_->is_valid());
  22543. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22544. std::string msg;
  22545. while (ws.read(msg)) {
  22546. ws.send(msg);
  22547. }
  22548. });
  22549. port_ = server_->bind_to_any_port("localhost");
  22550. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22551. server_->wait_until_ready();
  22552. }
  22553. void TearDown() override {
  22554. if (server_) { server_->stop(); }
  22555. if (server_thread_.joinable()) { server_thread_.join(); }
  22556. }
  22557. std::string url() const {
  22558. return "wss://localhost:" + std::to_string(port_) + "/echo";
  22559. }
  22560. std::unique_ptr<SSLServer> server_;
  22561. std::thread server_thread_;
  22562. int port_ = 0;
  22563. };
  22564. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  22565. // out and the connection is usable
  22566. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  22567. Start(SERVER_CERT2_FILE);
  22568. ws::WebSocketClient client(url());
  22569. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22570. ASSERT_TRUE(client.connect());
  22571. ASSERT_TRUE(client.send("hello"));
  22572. std::string msg;
  22573. EXPECT_EQ(ws::Text, client.read(msg));
  22574. EXPECT_EQ("hello", msg);
  22575. client.close();
  22576. }
  22577. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  22578. // while the identity check must still reject "localhost"
  22579. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  22580. Start(SERVER_CERT_FILE);
  22581. ws::WebSocketClient client(url());
  22582. client.set_ca_cert_path(SERVER_CERT_FILE);
  22583. auto res = client.connect();
  22584. ASSERT_FALSE(res);
  22585. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  22586. EXPECT_EQ(-1, res.status());
  22587. }
  22588. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  22589. // disabled: the chain is still checked, only the identity check is skipped
  22590. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  22591. Start(SERVER_CERT_FILE);
  22592. ws::WebSocketClient client(url());
  22593. client.set_ca_cert_path(SERVER_CERT_FILE);
  22594. client.enable_server_hostname_verification(false);
  22595. ASSERT_TRUE(client.connect());
  22596. ASSERT_TRUE(client.send("hello"));
  22597. std::string msg;
  22598. EXPECT_EQ(ws::Text, client.read(msg));
  22599. EXPECT_EQ("hello", msg);
  22600. client.close();
  22601. }
  22602. // A CA that did not sign the server certificate fails the chain, even though
  22603. // the name would match
  22604. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  22605. Start(SERVER_CERT2_FILE);
  22606. ws::WebSocketClient client(url());
  22607. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22608. ASSERT_FALSE(client.connect());
  22609. }
  22610. // With verification disabled, neither the chain nor the name is checked
  22611. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  22612. Start(SERVER_CERT_FILE);
  22613. ws::WebSocketClient client(url());
  22614. client.enable_server_certificate_verification(false);
  22615. ASSERT_TRUE(client.connect());
  22616. ASSERT_TRUE(client.send("hello"));
  22617. std::string msg;
  22618. EXPECT_EQ(ws::Text, client.read(msg));
  22619. EXPECT_EQ("hello", msg);
  22620. client.close();
  22621. }
  22622. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  22623. protected:
  22624. void SetUp() override {
  22625. server_ = httplib::detail::make_unique<SSLServer>(
  22626. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22627. ASSERT_TRUE(server_->is_valid());
  22628. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22629. std::string msg;
  22630. while (ws.read(msg)) {
  22631. ws.send(msg);
  22632. }
  22633. });
  22634. port_ = server_->bind_to_any_port("localhost");
  22635. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22636. server_->wait_until_ready();
  22637. }
  22638. void TearDown() override {
  22639. server_->stop();
  22640. if (server_thread_.joinable()) { server_thread_.join(); }
  22641. }
  22642. std::string url() const {
  22643. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  22644. }
  22645. void ConnectWithClientCert(const std::string &client_cert_file,
  22646. const std::string &client_private_key_file,
  22647. const char *private_key_password) {
  22648. std::string cert_pem, key_pem;
  22649. read_file(client_cert_file, cert_pem);
  22650. read_file(client_private_key_file, key_pem);
  22651. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  22652. key_pem.c_str(), key_pem.size(),
  22653. private_key_password};
  22654. ws::WebSocketClient client(url(), pem);
  22655. ASSERT_TRUE(client.is_valid());
  22656. client.enable_server_certificate_verification(false);
  22657. ASSERT_TRUE(client.connect());
  22658. ASSERT_TRUE(client.send("hello"));
  22659. std::string msg;
  22660. EXPECT_EQ(ws::Text, client.read(msg));
  22661. EXPECT_EQ("hello", msg);
  22662. client.close();
  22663. }
  22664. std::unique_ptr<SSLServer> server_;
  22665. std::thread server_thread_;
  22666. int port_ = 0;
  22667. };
  22668. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  22669. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  22670. }
  22671. // Control for the tests above: the fixture's server really does require a
  22672. // client certificate, so it is the PEM the constructor installed that decides
  22673. // the outcome.
  22674. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  22675. ws::WebSocketClient client(url());
  22676. ASSERT_TRUE(client.is_valid());
  22677. client.enable_server_certificate_verification(false);
  22678. EXPECT_FALSE(client.connect());
  22679. }
  22680. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  22681. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  22682. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  22683. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  22684. }
  22685. #endif
  22686. #if !defined(_WIN32)
  22687. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  22688. auto secret_dir = std::string("./symlink_test_secret");
  22689. auto served_dir = std::string("./symlink_test_served");
  22690. auto secret_file = secret_dir + "/secret.txt";
  22691. auto symlink_path = served_dir + "/escape";
  22692. // Setup: create directories and files
  22693. mkdir(secret_dir.c_str(), 0755);
  22694. mkdir(served_dir.c_str(), 0755);
  22695. {
  22696. std::ofstream ofs(secret_file);
  22697. ofs << "SECRET_DATA";
  22698. }
  22699. // Create symlink using absolute path so it resolves correctly
  22700. #ifdef PATH_MAX
  22701. char abs_secret[PATH_MAX];
  22702. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  22703. #else
  22704. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  22705. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  22706. ASSERT_NE(nullptr, abs_secret);
  22707. #endif
  22708. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  22709. auto se = detail::scope_exit([&] {
  22710. unlink(symlink_path.c_str());
  22711. unlink(secret_file.c_str());
  22712. rmdir(served_dir.c_str());
  22713. rmdir(secret_dir.c_str());
  22714. });
  22715. Server svr;
  22716. svr.set_mount_point("/", served_dir);
  22717. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  22718. auto se2 = detail::scope_exit([&] {
  22719. svr.stop();
  22720. listen_thread.join();
  22721. });
  22722. svr.wait_until_ready();
  22723. Client cli("localhost", PORT);
  22724. // Symlink pointing outside base dir should be blocked
  22725. auto res = cli.Get("/escape/secret.txt");
  22726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22727. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  22728. }
  22729. #endif
  22730. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  22731. // "GET /smuggled" request), reads the first response, and only then sends the
  22732. // embedded request as the body. Returns how many times /smuggled ran.
  22733. //
  22734. // The body is sent AFTER receiving the first response (as in the original
  22735. // PoC) so that the stream_line_reader cannot buffer it together with the
  22736. // headers of the first request.
  22737. static int count_smuggled_requests(const std::string &outer_head,
  22738. std::string &first_response) {
  22739. Server svr;
  22740. svr.set_mount_point("/", "./www");
  22741. std::atomic<int> smuggled_count(0);
  22742. svr.Get("/smuggled", [&](const Request &, Response &res) {
  22743. smuggled_count++;
  22744. res.set_content("oops", "text/plain");
  22745. });
  22746. svr.Post("/post", [&](const Request &req, Response &res) {
  22747. res.set_content(req.body, "text/plain");
  22748. });
  22749. auto port = svr.bind_to_any_port("localhost");
  22750. thread t = thread([&] { svr.listen_after_bind(); });
  22751. auto se = detail::scope_exit([&] {
  22752. svr.stop();
  22753. t.join();
  22754. });
  22755. svr.wait_until_ready();
  22756. auto error = Error::Success;
  22757. auto sock = detail::create_client_socket(
  22758. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  22759. /*connection_timeout_sec=*/2, 0,
  22760. /*read_timeout_sec=*/2, 0,
  22761. /*write_timeout_sec=*/2, 0, std::string(), error);
  22762. EXPECT_NE(INVALID_SOCKET, sock);
  22763. if (sock == INVALID_SOCKET) { return -1; }
  22764. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22765. // The "smuggled" request will be sent as the body of the outer request
  22766. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  22767. "Host: localhost\r\n"
  22768. "Connection: close\r\n"
  22769. "\r\n";
  22770. auto head = outer_head;
  22771. auto len = std::to_string(smuggled.size());
  22772. for (auto pos = head.find("{len}"); pos != std::string::npos;
  22773. pos = head.find("{len}", pos + len.size())) {
  22774. head.replace(pos, 5, len);
  22775. }
  22776. // Step 1: Send only the outer request headers (no body yet)
  22777. auto sent = send(sock, head.data(), head.size(), 0);
  22778. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  22779. // Step 2: Read the first response
  22780. char buf[4096];
  22781. for (;;) {
  22782. auto n = recv(sock, buf, sizeof(buf), 0);
  22783. if (n <= 0) break;
  22784. first_response.append(buf, static_cast<size_t>(n));
  22785. // Stop once we have a complete response (headers + body)
  22786. auto hdr_end = first_response.find("\r\n\r\n");
  22787. if (hdr_end != std::string::npos) {
  22788. // Check for Content-Length to know when the body is complete
  22789. auto cl_pos = first_response.find("Content-Length:");
  22790. if (cl_pos != std::string::npos) {
  22791. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  22792. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  22793. auto cl = std::stoul(
  22794. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  22795. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  22796. } else {
  22797. break; // No Content-Length, assume headers-only response
  22798. }
  22799. }
  22800. }
  22801. // Step 3: Now send the body, which looks like a new HTTP request. On a
  22802. // vulnerable server the keep-alive loop reads this as a second request. The
  22803. // server may already have closed the connection, so the result is ignored.
  22804. send(sock, smuggled.data(), smuggled.size(), 0);
  22805. // Half-close so that a server which drained the body sees EOF and closes,
  22806. // instead of the read below waiting for the read timeout.
  22807. #ifdef _WIN32
  22808. ::shutdown(sock, SD_SEND);
  22809. #else
  22810. ::shutdown(sock, SHUT_WR);
  22811. #endif
  22812. // Step 4: Read until the server closes the connection
  22813. for (;;) {
  22814. auto n = recv(sock, buf, sizeof(buf), 0);
  22815. if (n <= 0) break;
  22816. }
  22817. return smuggled_count.load();
  22818. }
  22819. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  22820. // A GET request with Content-Length to a static file handler must have its
  22821. // body drained before the keep-alive connection is reused. Otherwise the
  22822. // unread body bytes are interpreted as the next HTTP request.
  22823. std::string first_response;
  22824. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22825. "Host: localhost\r\n"
  22826. "Content-Length: {len}\r\n"
  22827. "\r\n",
  22828. first_response));
  22829. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  22830. }
  22831. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  22832. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  22833. // be answered with 400 and the connection closed. Treating it as "no body"
  22834. // leaves the body to be parsed as the next request.
  22835. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  22836. const char *targets[] = {
  22837. "GET /file", // handler that never reads the body
  22838. "GET /not-found", // no handler matches (404)
  22839. "POST /post", // handler that reads the body
  22840. };
  22841. for (auto target : targets) {
  22842. for (auto value : values) {
  22843. std::string first_response;
  22844. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  22845. " HTTP/1.1\r\n"
  22846. "Host: localhost\r\n"
  22847. "Content-Length: " +
  22848. value + "\r\n\r\n",
  22849. first_response))
  22850. << target << " with Content-Length: " << value;
  22851. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  22852. << target << " with Content-Length: " << value;
  22853. }
  22854. }
  22855. }
  22856. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  22857. // A 400 for an unparseable request line leaves the rest of the message
  22858. // unread, so the connection must be closed rather than reused.
  22859. std::string first_response;
  22860. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  22861. "Host: localhost\r\n"
  22862. "Content-Length: {len}\r\n"
  22863. "\r\n",
  22864. first_response));
  22865. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22866. }
  22867. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  22868. // Same as above for a header block that fails to parse.
  22869. std::string first_response;
  22870. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22871. "Host: localhost\r\n"
  22872. "Bad Header\r\n"
  22873. "Content-Length: {len}\r\n"
  22874. "\r\n",
  22875. first_response));
  22876. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22877. }
  22878. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  22879. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  22880. // server must not read another request on that connection, even when the
  22881. // request had no body to drain.
  22882. std::string first_response;
  22883. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  22884. "Host: localhost\r\n"
  22885. "\r\n",
  22886. first_response));
  22887. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  22888. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  22889. }
  22890. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  22891. // A content reader that stops early leaves the stream inside the body.
  22892. // Draining the whole Content-Length from there, or reading the body again,
  22893. // reads into the next request, and whatever follows is parsed as a request
  22894. // of its own.
  22895. Server svr;
  22896. std::atomic<int> smuggled_count(0);
  22897. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  22898. svr.Post("/upload", [](const Request &req, Response &res,
  22899. const ContentReader &content_reader) {
  22900. // Stop at the last chunk, so the whole body has been read however it
  22901. // arrives.
  22902. auto length = req.get_header_value_u64("Content-Length");
  22903. size_t total = 0;
  22904. auto consumed = content_reader([&](const char *, size_t n) {
  22905. total += n;
  22906. return total < length;
  22907. });
  22908. EXPECT_FALSE(consumed);
  22909. if (req.has_param("retry")) {
  22910. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  22911. }
  22912. // Replace the 400 the aborted read set, which would close the connection.
  22913. res.set_redirect("/done");
  22914. });
  22915. auto port = svr.bind_to_any_port(HOST);
  22916. thread t = thread([&] { svr.listen_after_bind(); });
  22917. auto se = detail::scope_exit([&] {
  22918. svr.stop();
  22919. t.join();
  22920. });
  22921. svr.wait_until_ready();
  22922. // A front end sees the second request as a POST whose body is the GET. The
  22923. // first body is as long as the POST's headers, so draining it again reads
  22924. // exactly those and leaves the GET to be parsed next.
  22925. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  22926. "Host: localhost\r\n"
  22927. "\r\n";
  22928. std::string second_head = "POST /post HTTP/1.1\r\n"
  22929. "Host: localhost\r\n"
  22930. "Content-Length: " +
  22931. std::to_string(inner.size()) +
  22932. "\r\n"
  22933. "\r\n";
  22934. for (auto target : {"/upload", "/upload?retry"}) {
  22935. smuggled_count = 0;
  22936. std::string request = "POST " + std::string(target) +
  22937. " HTTP/1.1\r\n"
  22938. "Host: localhost\r\n"
  22939. "Content-Length: " +
  22940. std::to_string(second_head.size()) +
  22941. "\r\n"
  22942. "\r\n" +
  22943. std::string(second_head.size(), 'A') + second_head +
  22944. inner;
  22945. std::string response;
  22946. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  22947. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  22948. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  22949. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  22950. EXPECT_EQ(0, smuggled_count.load()) << target;
  22951. }
  22952. }
  22953. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  22954. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  22955. // must be rejected with 400 Bad Request.
  22956. Server svr;
  22957. svr.Post("/test", [&](const Request &, Response &res) {
  22958. res.set_content("ok", "text/plain");
  22959. });
  22960. thread t = thread([&] { svr.listen(HOST, PORT); });
  22961. auto se = detail::scope_exit([&] {
  22962. svr.stop();
  22963. t.join();
  22964. ASSERT_FALSE(svr.is_running());
  22965. });
  22966. svr.wait_until_ready();
  22967. // Exact "chunked"
  22968. {
  22969. auto req = "POST /test HTTP/1.1\r\n"
  22970. "Host: localhost\r\n"
  22971. "Content-Length: 5\r\n"
  22972. "Transfer-Encoding: chunked\r\n"
  22973. "Connection: close\r\n"
  22974. "\r\n"
  22975. "hello";
  22976. std::string response;
  22977. ASSERT_TRUE(send_request(1, req, &response));
  22978. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22979. response.substr(0, response.find("\r\n")));
  22980. }
  22981. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  22982. {
  22983. auto req = "POST /test HTTP/1.1\r\n"
  22984. "Host: localhost\r\n"
  22985. "Content-Length: 5\r\n"
  22986. "Transfer-Encoding: gzip, chunked\r\n"
  22987. "Connection: close\r\n"
  22988. "\r\n"
  22989. "hello";
  22990. std::string response;
  22991. ASSERT_TRUE(send_request(1, req, &response));
  22992. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22993. response.substr(0, response.find("\r\n")));
  22994. }
  22995. }
  22996. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  22997. Server svr;
  22998. svr.Post("/test", [&](const Request &, Response &res) {
  22999. res.set_content("ok", "text/plain");
  23000. });
  23001. thread t = thread([&] { svr.listen(HOST, PORT); });
  23002. auto se = detail::scope_exit([&] {
  23003. svr.stop();
  23004. t.join();
  23005. ASSERT_FALSE(svr.is_running());
  23006. });
  23007. svr.wait_until_ready();
  23008. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  23009. // length cannot be determined, so the server must answer 400 and close
  23010. // rather than treat the request as bodyless and leave the body in the
  23011. // socket for the next request to pick up.
  23012. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  23013. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  23014. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  23015. std::string response;
  23016. ASSERT_TRUE(send_request(1, req, &response));
  23017. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23018. response.substr(0, response.find("\r\n")))
  23019. << transfer_encoding;
  23020. }
  23021. // RFC 9110 5.3: the codings may also be split across several
  23022. // Transfer-Encoding lines, which combine in the order they were received.
  23023. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  23024. // just like the single-line "chunked, gzip" above.
  23025. {
  23026. auto req = "POST /test HTTP/1.1\r\n"
  23027. "Host: localhost\r\n"
  23028. "Transfer-Encoding: chunked\r\n"
  23029. "Transfer-Encoding: gzip\r\n"
  23030. "\r\n"
  23031. "0\r\n\r\n";
  23032. std::string response;
  23033. ASSERT_TRUE(send_request(1, req, &response));
  23034. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23035. response.substr(0, response.find("\r\n")));
  23036. }
  23037. // A sequence ending in chunked stays valid.
  23038. auto req = "POST /test HTTP/1.1\r\n"
  23039. "Host: localhost\r\n"
  23040. "Transfer-Encoding: gzip, chunked\r\n"
  23041. "Connection: close\r\n"
  23042. "\r\n"
  23043. "0\r\n\r\n";
  23044. std::string response;
  23045. ASSERT_TRUE(send_request(1, req, &response));
  23046. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  23047. // ...including when it is spread over several lines.
  23048. auto split_req = "POST /test HTTP/1.1\r\n"
  23049. "Host: localhost\r\n"
  23050. "Transfer-Encoding: gzip\r\n"
  23051. "Transfer-Encoding: chunked\r\n"
  23052. "Connection: close\r\n"
  23053. "\r\n"
  23054. "0\r\n\r\n";
  23055. std::string split_response;
  23056. ASSERT_TRUE(send_request(1, split_req, &split_response));
  23057. EXPECT_EQ("HTTP/1.1 200 OK",
  23058. split_response.substr(0, split_response.find("\r\n")));
  23059. }
  23060. // Regression for issue #2450: a DELETE without Content-Length on a
  23061. // keep-alive connection must not let the post-response drain consume the
  23062. // next request's bytes.
  23063. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  23064. Server svr;
  23065. std::atomic<int> delete_count(0);
  23066. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  23067. delete_count++;
  23068. res.status = StatusCode::NoContent_204;
  23069. });
  23070. auto port = svr.bind_to_any_port(HOST);
  23071. thread t = thread([&] { svr.listen_after_bind(); });
  23072. auto se = detail::scope_exit([&] {
  23073. svr.stop();
  23074. t.join();
  23075. });
  23076. svr.wait_until_ready();
  23077. auto error = Error::Success;
  23078. auto sock = detail::create_client_socket(
  23079. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23080. /*connection_timeout_sec=*/2, 0,
  23081. /*read_timeout_sec=*/2, 0,
  23082. /*write_timeout_sec=*/2, 0, std::string(), error);
  23083. ASSERT_NE(INVALID_SOCKET, sock);
  23084. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23085. auto send_request_and_read_response = [&](const std::string &req,
  23086. std::string &out) -> bool {
  23087. auto sent = send(sock, req.data(), req.size(), 0);
  23088. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  23089. char buf[4096];
  23090. for (;;) {
  23091. auto n = recv(sock, buf, sizeof(buf), 0);
  23092. if (n <= 0) { return !out.empty(); }
  23093. out.append(buf, static_cast<size_t>(n));
  23094. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  23095. }
  23096. };
  23097. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  23098. "Host: localhost\r\n"
  23099. "\r\n";
  23100. std::string resp1;
  23101. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  23102. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  23103. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  23104. "Host: localhost\r\n"
  23105. "Connection: close\r\n"
  23106. "\r\n";
  23107. std::string resp2;
  23108. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  23109. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  23110. EXPECT_EQ(2, delete_count.load());
  23111. }
  23112. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  23113. Server svr;
  23114. svr.Post("/ingest", [&](const Request &, Response &res,
  23115. const ContentReader &content_reader) {
  23116. auto consumed = content_reader([](const char *, size_t) { return false; });
  23117. EXPECT_FALSE(consumed);
  23118. res.status = StatusCode::Conflict_409;
  23119. res.set_header("Connection", "close");
  23120. });
  23121. auto port = svr.bind_to_any_port(HOST);
  23122. thread t = thread([&] { svr.listen_after_bind(); });
  23123. auto se = detail::scope_exit([&] {
  23124. svr.stop();
  23125. t.join();
  23126. });
  23127. svr.wait_until_ready();
  23128. auto error = Error::Success;
  23129. auto sock = detail::create_client_socket(
  23130. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23131. /*connection_timeout_sec=*/2, 0,
  23132. /*read_timeout_sec=*/1, 0,
  23133. /*write_timeout_sec=*/2, 0, std::string(), error);
  23134. ASSERT_NE(INVALID_SOCKET, sock);
  23135. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23136. std::string request = "POST /ingest HTTP/1.1\r\n"
  23137. "Host: localhost\r\n"
  23138. "Transfer-Encoding: chunked\r\n"
  23139. "\r\n"
  23140. "4\r\n"
  23141. "data\r\n";
  23142. auto sent = send(sock, request.data(), request.size(), 0);
  23143. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  23144. std::string response;
  23145. ssize_t received = 0;
  23146. do {
  23147. char buf[4096];
  23148. received = recv(sock, buf, sizeof(buf), 0);
  23149. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  23150. } while (received > 0);
  23151. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  23152. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  23153. EXPECT_EQ(0, received);
  23154. }
  23155. namespace no_proxy_test {
  23156. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  23157. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  23158. // calling listen().
  23159. class ScopedServer {
  23160. public:
  23161. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  23162. ~ScopedServer() {
  23163. svr_.stop();
  23164. if (th_.joinable()) { th_.join(); }
  23165. }
  23166. Server &svr() { return svr_; }
  23167. int port() const { return port_; }
  23168. void listen() {
  23169. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23170. svr_.wait_until_ready();
  23171. }
  23172. private:
  23173. Server svr_;
  23174. std::thread th_;
  23175. int port_ = 0;
  23176. };
  23177. class ProxyAndTargetServers {
  23178. public:
  23179. ProxyAndTargetServers() {
  23180. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  23181. proxy_hits_++;
  23182. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23183. res.set_content("via-proxy", "text/plain");
  23184. });
  23185. target_.Get(".*", [this](const Request &req, Response &res) {
  23186. target_hits_++;
  23187. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23188. res.set_content("direct", "text/plain");
  23189. });
  23190. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  23191. target_port_ = target_.bind_to_any_port("127.0.0.1");
  23192. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  23193. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  23194. proxy_mock_.wait_until_ready();
  23195. target_.wait_until_ready();
  23196. }
  23197. ~ProxyAndTargetServers() {
  23198. proxy_mock_.stop();
  23199. target_.stop();
  23200. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  23201. if (target_thread_.joinable()) { target_thread_.join(); }
  23202. }
  23203. Server &proxy_mock() { return proxy_mock_; }
  23204. Server &target() { return target_; }
  23205. int proxy_port() const { return proxy_port_; }
  23206. int target_port() const { return target_port_; }
  23207. int proxy_hits() const { return proxy_hits_.load(); }
  23208. int target_hits() const { return target_hits_.load(); }
  23209. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  23210. void reset_counters() {
  23211. proxy_hits_ = 0;
  23212. target_hits_ = 0;
  23213. last_had_proxy_authz_ = false;
  23214. }
  23215. private:
  23216. Server proxy_mock_;
  23217. Server target_;
  23218. std::thread proxy_thread_;
  23219. std::thread target_thread_;
  23220. int proxy_port_ = 0;
  23221. int target_port_ = 0;
  23222. std::atomic<int> proxy_hits_{0};
  23223. std::atomic<int> target_hits_{0};
  23224. std::atomic<bool> last_had_proxy_authz_{false};
  23225. };
  23226. inline std::unique_ptr<Client> make_client(const std::string &host,
  23227. ProxyAndTargetServers &s) {
  23228. auto cli = detail::make_unique<Client>(host, s.target_port());
  23229. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  23230. cli->set_proxy("127.0.0.1", s.proxy_port());
  23231. return cli;
  23232. }
  23233. } // namespace no_proxy_test
  23234. using no_proxy_test::make_client;
  23235. using no_proxy_test::ProxyAndTargetServers;
  23236. TEST(NoProxyTest, ExactHostnameBypasses) {
  23237. ProxyAndTargetServers s;
  23238. auto cli = make_client("example.com", s);
  23239. cli->set_no_proxy({"example.com"});
  23240. auto res = cli->Get("/");
  23241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23242. EXPECT_EQ(0, s.proxy_hits());
  23243. EXPECT_EQ(1, s.target_hits());
  23244. }
  23245. TEST(NoProxyTest, SubdomainBypasses) {
  23246. ProxyAndTargetServers s;
  23247. auto cli = make_client("foo.example.com", s);
  23248. cli->set_no_proxy({"example.com"});
  23249. auto res = cli->Get("/");
  23250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23251. EXPECT_EQ(0, s.proxy_hits());
  23252. EXPECT_EQ(1, s.target_hits());
  23253. }
  23254. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  23255. // Regression guard: "evilexample.com" must not be considered a subdomain
  23256. // of "example.com". Without the dot-boundary rule, a naive endsWith
  23257. // check would let traffic bypass the proxy and leak credentials direct
  23258. // to the attacker host.
  23259. ProxyAndTargetServers s;
  23260. auto cli = make_client("evilexample.com", s);
  23261. cli->set_no_proxy({"example.com"});
  23262. auto res = cli->Get("/");
  23263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23264. EXPECT_GE(s.proxy_hits(), 1);
  23265. EXPECT_EQ(0, s.target_hits());
  23266. }
  23267. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  23268. ProxyAndTargetServers s;
  23269. auto cli = make_client("example.com.evil.com", s);
  23270. cli->set_no_proxy({"example.com"});
  23271. auto res = cli->Get("/");
  23272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23273. EXPECT_GE(s.proxy_hits(), 1);
  23274. EXPECT_EQ(0, s.target_hits());
  23275. }
  23276. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  23277. ProxyAndTargetServers s;
  23278. auto cli = make_client("example.com", s);
  23279. cli->set_no_proxy({".example.com"});
  23280. auto res = cli->Get("/");
  23281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23282. EXPECT_EQ(0, s.proxy_hits());
  23283. EXPECT_EQ(1, s.target_hits());
  23284. }
  23285. TEST(NoProxyTest, CaseInsensitiveHostname) {
  23286. ProxyAndTargetServers s;
  23287. auto cli = make_client("Example.COM", s);
  23288. cli->set_no_proxy({"EXAMPLE.com"});
  23289. auto res = cli->Get("/");
  23290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23291. EXPECT_EQ(0, s.proxy_hits());
  23292. EXPECT_EQ(1, s.target_hits());
  23293. }
  23294. TEST(NoProxyTest, TrailingDotIsNormalized) {
  23295. ProxyAndTargetServers s;
  23296. auto cli = make_client("example.com.", s);
  23297. cli->set_no_proxy({"example.com"});
  23298. auto res = cli->Get("/");
  23299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23300. EXPECT_EQ(0, s.proxy_hits());
  23301. EXPECT_EQ(1, s.target_hits());
  23302. }
  23303. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  23304. // Trailing dots must be normalized on BOTH sides — host and entry.
  23305. // An implementation that only strips the host-side trailing dot would
  23306. // fail to match host "example.com" against entry "example.com." because
  23307. // a literal substring search would compare 11 chars against 12.
  23308. ProxyAndTargetServers s;
  23309. auto cli = make_client("example.com", s);
  23310. cli->set_no_proxy({"example.com."});
  23311. auto res = cli->Get("/");
  23312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23313. EXPECT_EQ(0, s.proxy_hits());
  23314. EXPECT_EQ(1, s.target_hits());
  23315. }
  23316. TEST(NoProxyTest, WildcardBypassesEverything) {
  23317. ProxyAndTargetServers s;
  23318. auto cli = make_client("anything.invalid.test", s);
  23319. cli->set_no_proxy({"*"});
  23320. auto res = cli->Get("/");
  23321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23322. EXPECT_EQ(0, s.proxy_hits());
  23323. EXPECT_EQ(1, s.target_hits());
  23324. }
  23325. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  23326. ProxyAndTargetServers s;
  23327. Client cli("127.0.0.1", s.target_port());
  23328. cli.set_proxy("127.0.0.1", s.proxy_port());
  23329. cli.set_no_proxy({"127.0.0.1"});
  23330. auto res = cli.Get("/");
  23331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23332. EXPECT_EQ(0, s.proxy_hits());
  23333. EXPECT_EQ(1, s.target_hits());
  23334. }
  23335. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  23336. ProxyAndTargetServers s;
  23337. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  23338. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  23339. cli.set_proxy("127.0.0.1", s.proxy_port());
  23340. cli.set_no_proxy({"::1"});
  23341. auto res = cli.Get("/");
  23342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23343. EXPECT_EQ(0, s.proxy_hits());
  23344. EXPECT_EQ(1, s.target_hits());
  23345. }
  23346. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  23347. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  23348. // must still be recognized as IPv6 for CIDR matching. Implementations
  23349. // that detect IPv6 only when the host begins with '[' would parse the
  23350. // host as a hostname and miss the match.
  23351. ProxyAndTargetServers s;
  23352. Client cli("fe80::1", s.target_port());
  23353. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23354. cli.set_proxy("127.0.0.1", s.proxy_port());
  23355. cli.set_no_proxy({"fe80::/10"});
  23356. auto res = cli.Get("/");
  23357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23358. EXPECT_EQ(0, s.proxy_hits());
  23359. EXPECT_EQ(1, s.target_hits());
  23360. }
  23361. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  23362. ProxyAndTargetServers s;
  23363. Client cli("::1", s.target_port());
  23364. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  23365. cli.set_proxy("127.0.0.1", s.proxy_port());
  23366. cli.set_no_proxy({"[::1]"});
  23367. auto res = cli.Get("/");
  23368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23369. EXPECT_EQ(0, s.proxy_hits());
  23370. EXPECT_EQ(1, s.target_hits());
  23371. }
  23372. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  23373. ProxyAndTargetServers s;
  23374. Client cli("fe80::1", s.target_port());
  23375. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23376. cli.set_proxy("127.0.0.1", s.proxy_port());
  23377. cli.set_no_proxy({"[fe80::]/10"});
  23378. auto res = cli.Get("/");
  23379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23380. EXPECT_EQ(0, s.proxy_hits());
  23381. EXPECT_EQ(1, s.target_hits());
  23382. }
  23383. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  23384. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  23385. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  23386. // tricks via address-family conversion.
  23387. ProxyAndTargetServers s;
  23388. Client cli("::ffff:127.0.0.1", s.target_port());
  23389. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  23390. cli.set_proxy("127.0.0.1", s.proxy_port());
  23391. cli.set_no_proxy({"127.0.0.1"});
  23392. auto res = cli.Get("/");
  23393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23394. EXPECT_GE(s.proxy_hits(), 1);
  23395. EXPECT_EQ(0, s.target_hits());
  23396. }
  23397. TEST(NoProxyTest, IPv4CidrMatch) {
  23398. ProxyAndTargetServers s;
  23399. Client cli("127.0.0.1", s.target_port());
  23400. cli.set_proxy("127.0.0.1", s.proxy_port());
  23401. cli.set_no_proxy({"127.0.0.0/8"});
  23402. auto res = cli.Get("/");
  23403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23404. EXPECT_EQ(0, s.proxy_hits());
  23405. EXPECT_EQ(1, s.target_hits());
  23406. }
  23407. TEST(NoProxyTest, IPv4CidrNonMatch) {
  23408. ProxyAndTargetServers s;
  23409. Client cli("127.0.0.1", s.target_port());
  23410. cli.set_proxy("127.0.0.1", s.proxy_port());
  23411. cli.set_no_proxy({"10.0.0.0/8"});
  23412. auto res = cli.Get("/");
  23413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23414. EXPECT_GE(s.proxy_hits(), 1);
  23415. EXPECT_EQ(0, s.target_hits());
  23416. }
  23417. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  23418. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  23419. // IPv4 target matches.
  23420. ProxyAndTargetServers s;
  23421. Client cli("127.0.0.1", s.target_port());
  23422. cli.set_proxy("127.0.0.1", s.proxy_port());
  23423. cli.set_no_proxy({"0.0.0.0/0"});
  23424. auto res = cli.Get("/");
  23425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23426. EXPECT_EQ(0, s.proxy_hits());
  23427. EXPECT_EQ(1, s.target_hits());
  23428. }
  23429. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  23430. ProxyAndTargetServers s;
  23431. Client cli("127.0.0.1", s.target_port());
  23432. cli.set_proxy("127.0.0.1", s.proxy_port());
  23433. cli.set_no_proxy({"127.0.0.1"});
  23434. auto res = cli.Get("/");
  23435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23436. EXPECT_EQ(0, s.proxy_hits());
  23437. EXPECT_EQ(1, s.target_hits());
  23438. }
  23439. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  23440. ProxyAndTargetServers s;
  23441. Client cli("127.0.0.1", s.target_port());
  23442. cli.set_proxy("127.0.0.1", s.proxy_port());
  23443. cli.set_no_proxy({"127.0.0.0/33"});
  23444. auto res = cli.Get("/");
  23445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23446. EXPECT_GE(s.proxy_hits(), 1);
  23447. EXPECT_EQ(0, s.target_hits());
  23448. }
  23449. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  23450. // Empty prefix after the slash must be rejected, not silently treated as /32.
  23451. ProxyAndTargetServers s;
  23452. Client cli("127.0.0.1", s.target_port());
  23453. cli.set_proxy("127.0.0.1", s.proxy_port());
  23454. cli.set_no_proxy({"127.0.0.1/"});
  23455. auto res = cli.Get("/");
  23456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23457. EXPECT_GE(s.proxy_hits(), 1);
  23458. EXPECT_EQ(0, s.target_hits());
  23459. }
  23460. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  23461. ProxyAndTargetServers s;
  23462. auto cli = make_client("internal.corp", s);
  23463. cli->set_proxy_basic_auth("u", "p");
  23464. cli->set_no_proxy({"internal.corp"});
  23465. auto res = cli->Get("/");
  23466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23467. EXPECT_EQ(1, s.target_hits());
  23468. EXPECT_EQ(0, s.proxy_hits());
  23469. EXPECT_FALSE(s.last_had_proxy_authz())
  23470. << "Proxy-Authorization must not be sent direct to the target";
  23471. }
  23472. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  23473. ProxyAndTargetServers s;
  23474. auto cli = make_client("public.example", s);
  23475. cli->set_proxy_basic_auth("u", "p");
  23476. cli->set_no_proxy({"internal.corp"}); // does not match
  23477. auto res = cli->Get("/");
  23478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23479. EXPECT_GE(s.proxy_hits(), 1);
  23480. EXPECT_TRUE(s.last_had_proxy_authz());
  23481. }
  23482. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  23483. std::atomic<int> hits{0};
  23484. std::atomic<int> hits_with_authz{0};
  23485. no_proxy_test::ScopedServer proxy_mock;
  23486. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23487. hits++;
  23488. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  23489. if (req.target.find("/redir") != std::string::npos) {
  23490. res.set_redirect("http://other.example/landed");
  23491. } else {
  23492. res.set_content("via-proxy", "text/plain");
  23493. }
  23494. });
  23495. proxy_mock.listen();
  23496. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  23497. hits = 0;
  23498. hits_with_authz = 0;
  23499. Client cli("public.example", 80);
  23500. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23501. cli.set_proxy_basic_auth(c.first, c.second);
  23502. cli.set_follow_location(true);
  23503. // The redirect to another host goes through the proxy as well
  23504. auto res = cli.Get("/redir");
  23505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23506. EXPECT_EQ(2, hits.load());
  23507. EXPECT_EQ(2, hits_with_authz.load());
  23508. }
  23509. }
  23510. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  23511. ProxyAndTargetServers s;
  23512. auto cli = make_client("anything.test", s);
  23513. auto res = cli->Get("/");
  23514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23515. EXPECT_GE(s.proxy_hits(), 1);
  23516. EXPECT_EQ(0, s.target_hits());
  23517. }
  23518. TEST(NoProxyTest, PortSpecificEntryRejected) {
  23519. ProxyAndTargetServers s;
  23520. auto cli = make_client("example.com", s);
  23521. cli->set_no_proxy({"example.com:8080"});
  23522. auto res = cli->Get("/");
  23523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23524. EXPECT_GE(s.proxy_hits(), 1);
  23525. EXPECT_EQ(0, s.target_hits());
  23526. }
  23527. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  23528. ProxyAndTargetServers s;
  23529. auto cli = make_client("anything.test", s);
  23530. cli->set_no_proxy({"", " ", "\t"});
  23531. auto res = cli->Get("/");
  23532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23533. EXPECT_GE(s.proxy_hits(), 1);
  23534. EXPECT_EQ(0, s.target_hits());
  23535. }
  23536. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  23537. // An entry with leading/trailing whitespace must still match — env-style
  23538. // values are commonly pasted with stray spaces and an implementation
  23539. // that feeds the raw token directly to inet_pton would fail to match
  23540. // valid CIDRs because of the spaces.
  23541. ProxyAndTargetServers s;
  23542. Client cli("127.0.0.1", s.target_port());
  23543. cli.set_proxy("127.0.0.1", s.proxy_port());
  23544. cli.set_no_proxy({" 127.0.0.0/8 "});
  23545. auto res = cli.Get("/");
  23546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23547. EXPECT_EQ(0, s.proxy_hits());
  23548. EXPECT_EQ(1, s.target_hits());
  23549. }
  23550. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  23551. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  23552. // go direct and must NOT carry Proxy-Authorization.
  23553. std::atomic<int> proxy_hits{0};
  23554. std::atomic<int> target_hits{0};
  23555. std::atomic<bool> target_saw_authz{false};
  23556. no_proxy_test::ScopedServer proxy_mock, target;
  23557. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23558. proxy_hits++;
  23559. res.status = 302;
  23560. res.set_header("Location", "http://127.0.0.1:" +
  23561. std::to_string(target.port()) + "/landed");
  23562. });
  23563. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23564. target_hits++;
  23565. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  23566. res.set_content("direct", "text/plain");
  23567. });
  23568. proxy_mock.listen();
  23569. target.listen();
  23570. Client cli("public.example", target.port());
  23571. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23572. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23573. cli.set_proxy_basic_auth("u", "p");
  23574. cli.set_no_proxy({"127.0.0.1"});
  23575. cli.set_follow_location(true);
  23576. auto res = cli.Get("/redir");
  23577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23578. EXPECT_GE(proxy_hits.load(), 1);
  23579. EXPECT_GE(target_hits.load(), 1);
  23580. EXPECT_FALSE(target_saw_authz.load());
  23581. }
  23582. #ifdef CPPHTTPLIB_SSL_ENABLED
  23583. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  23584. // Direct origin replying 407 must not trigger the digest retry; otherwise
  23585. // proxy creds would be sent to the (possibly hostile) origin.
  23586. std::atomic<int> target_hits{0};
  23587. std::atomic<bool> target_saw_proxy_authz{false};
  23588. no_proxy_test::ScopedServer target;
  23589. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23590. target_hits++;
  23591. if (req.has_header("Proxy-Authorization")) {
  23592. target_saw_proxy_authz = true;
  23593. }
  23594. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23595. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  23596. "nonce=\"abc\", algorithm=MD5");
  23597. });
  23598. target.listen();
  23599. // The proxy address is set to the target's port: the bypass MUST kick in;
  23600. // if it doesn't, the test still routes "via proxy" to the same server and
  23601. // the Proxy-Authorization assertion below catches the leak.
  23602. Client cli("evil.example", target.port());
  23603. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  23604. cli.set_proxy("127.0.0.1", target.port());
  23605. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23606. cli.set_no_proxy({"evil.example"});
  23607. auto res = cli.Get("/x");
  23608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23609. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23610. EXPECT_EQ(1, target_hits.load());
  23611. EXPECT_FALSE(target_saw_proxy_authz.load());
  23612. }
  23613. #endif
  23614. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  23615. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  23616. std::atomic<int> proxy_hits{0};
  23617. std::atomic<int> bypass_hits{0};
  23618. std::atomic<bool> proxy_saw_c_url{false};
  23619. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  23620. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23621. proxy_hits++;
  23622. if (req.path.find("/start") != std::string::npos) {
  23623. res.status = 302;
  23624. res.set_header("Location", "http://127.0.0.1:" +
  23625. std::to_string(bypass_server.port()) +
  23626. "/middle");
  23627. return;
  23628. }
  23629. if (req.path.find("/end") != std::string::npos) {
  23630. proxy_saw_c_url = true;
  23631. res.set_content("c-via-proxy", "text/plain");
  23632. return;
  23633. }
  23634. res.set_content("unexpected", "text/plain");
  23635. });
  23636. // public.example's "advertised" port is arbitrary (the request never lands
  23637. // there — it goes through the proxy), but use a dynamic value to stay
  23638. // friendly with sharded parallel runs.
  23639. int public_port = bypass_server.port();
  23640. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  23641. bypass_hits++;
  23642. res.status = 302;
  23643. res.set_header("Location", "http://public.example:" +
  23644. std::to_string(public_port) + "/end");
  23645. });
  23646. proxy_mock.listen();
  23647. bypass_server.listen();
  23648. Client cli("public.example", public_port);
  23649. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23650. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23651. cli.set_no_proxy({"127.0.0.1"});
  23652. cli.set_follow_location(true);
  23653. auto res = cli.Get("/start");
  23654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23655. EXPECT_EQ(StatusCode::OK_200, res->status);
  23656. EXPECT_EQ("c-via-proxy", res->body);
  23657. EXPECT_GE(proxy_hits.load(), 2);
  23658. EXPECT_GE(bypass_hits.load(), 1);
  23659. EXPECT_TRUE(proxy_saw_c_url.load());
  23660. }
  23661. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  23662. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  23663. // request reconnects to the correct endpoint.
  23664. std::atomic<int> proxy_hits{0};
  23665. std::atomic<int> target_hits{0};
  23666. no_proxy_test::ScopedServer proxy_mock, target;
  23667. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23668. proxy_hits++;
  23669. res.set_content("via-proxy", "text/plain");
  23670. });
  23671. target.svr().Get(".*", [&](const Request &, Response &res) {
  23672. target_hits++;
  23673. res.set_content("direct", "text/plain");
  23674. });
  23675. proxy_mock.listen();
  23676. target.listen();
  23677. Client cli("public.example", target.port());
  23678. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23679. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23680. cli.set_keep_alive(true);
  23681. auto res1 = cli.Get("/a");
  23682. ASSERT_TRUE(res1);
  23683. EXPECT_EQ("via-proxy", res1->body);
  23684. EXPECT_EQ(1, proxy_hits.load());
  23685. EXPECT_EQ(0, target_hits.load());
  23686. cli.set_no_proxy({"public.example"});
  23687. auto res2 = cli.Get("/b");
  23688. ASSERT_TRUE(res2);
  23689. EXPECT_EQ("direct", res2->body);
  23690. EXPECT_EQ(1, proxy_hits.load());
  23691. EXPECT_EQ(1, target_hits.load());
  23692. }
  23693. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  23694. namespace proxy_tunnel_test {
  23695. // SSLServer counterpart to no_proxy_test::ScopedServer.
  23696. class ScopedSSLServer {
  23697. public:
  23698. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  23699. port_ = svr_.bind_to_any_port("127.0.0.1");
  23700. }
  23701. ~ScopedSSLServer() {
  23702. svr_.stop();
  23703. if (th_.joinable()) { th_.join(); }
  23704. }
  23705. SSLServer &svr() { return svr_; }
  23706. int port() const { return port_; }
  23707. void listen() {
  23708. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23709. svr_.wait_until_ready();
  23710. }
  23711. private:
  23712. SSLServer svr_;
  23713. std::thread th_;
  23714. int port_ = 0;
  23715. };
  23716. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  23717. class ScopedConnectProxy {
  23718. public:
  23719. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  23720. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  23721. if (listen_fd_ < 0) { return; }
  23722. int yes = 1;
  23723. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  23724. sockaddr_in a{};
  23725. a.sin_family = AF_INET;
  23726. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23727. a.sin_port = 0;
  23728. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  23729. return;
  23730. }
  23731. socklen_t alen = sizeof(a);
  23732. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  23733. 0) {
  23734. return;
  23735. }
  23736. port_ = ntohs(a.sin_port);
  23737. if (::listen(listen_fd_, 1) != 0) { return; }
  23738. th_ = std::thread([this] { run(); });
  23739. }
  23740. ~ScopedConnectProxy() {
  23741. stop_ = true;
  23742. if (listen_fd_ >= 0) {
  23743. ::shutdown(listen_fd_, SHUT_RDWR);
  23744. ::close(listen_fd_);
  23745. }
  23746. if (th_.joinable()) { th_.join(); }
  23747. }
  23748. int port() const { return port_; }
  23749. int connect_hits() const { return connect_hits_.load(); }
  23750. // Head of the last CONNECT request, as the proxy saw it on the wire.
  23751. std::string connect_request() const {
  23752. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23753. return connect_request_;
  23754. }
  23755. private:
  23756. void run() {
  23757. while (!stop_.load()) {
  23758. fd_set rfds;
  23759. FD_ZERO(&rfds);
  23760. FD_SET(listen_fd_, &rfds);
  23761. timeval tv{0, 100 * 1000};
  23762. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  23763. if (sel <= 0) { continue; }
  23764. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  23765. if (client_fd < 0) { continue; }
  23766. std::string req;
  23767. char buf[2048];
  23768. while (req.find("\r\n\r\n") == std::string::npos) {
  23769. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  23770. if (n <= 0) { break; }
  23771. req.append(buf, static_cast<size_t>(n));
  23772. }
  23773. if (req.compare(0, 7, "CONNECT") != 0) {
  23774. ::close(client_fd);
  23775. continue;
  23776. }
  23777. connect_hits_++;
  23778. {
  23779. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23780. connect_request_ = req;
  23781. }
  23782. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  23783. ::send(client_fd, ok, std::strlen(ok), 0);
  23784. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  23785. sockaddr_in o{};
  23786. o.sin_family = AF_INET;
  23787. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23788. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  23789. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  23790. 0) {
  23791. ::close(client_fd);
  23792. ::close(origin_fd);
  23793. continue;
  23794. }
  23795. auto forward = [](int from, int to) {
  23796. char b[8192];
  23797. for (;;) {
  23798. ssize_t n = ::recv(from, b, sizeof(b), 0);
  23799. if (n <= 0) { break; }
  23800. ssize_t off = 0;
  23801. while (off < n) {
  23802. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  23803. if (s <= 0) {
  23804. off = n;
  23805. break;
  23806. }
  23807. off += s;
  23808. }
  23809. }
  23810. ::shutdown(to, SHUT_WR);
  23811. };
  23812. std::thread t1([&] { forward(client_fd, origin_fd); });
  23813. std::thread t2([&] { forward(origin_fd, client_fd); });
  23814. t1.join();
  23815. t2.join();
  23816. ::close(client_fd);
  23817. ::close(origin_fd);
  23818. }
  23819. }
  23820. int forward_port_ = -1;
  23821. int listen_fd_ = -1;
  23822. int port_ = 0;
  23823. std::thread th_;
  23824. std::atomic<bool> stop_{false};
  23825. std::atomic<int> connect_hits_{0};
  23826. mutable std::mutex connect_request_mutex_;
  23827. std::string connect_request_;
  23828. };
  23829. // Sends one request through the CONNECT proxy to the TLS origin with a
  23830. // credential configured for each hop, and checks that each credential reaches
  23831. // only the hop it was configured for: the proxy's on the CONNECT request, the
  23832. // origin's (every header in origin_headers) on the tunnelled request.
  23833. void CredentialsStayWithTheirHop(
  23834. const std::function<void(SSLClient &)> &set_credentials,
  23835. const std::string &scheme,
  23836. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  23837. std::atomic<int> origin_hits{0};
  23838. std::atomic<bool> origin_saw_proxy_authz{false};
  23839. std::atomic<bool> origin_saw_headers{false};
  23840. ScopedSSLServer origin;
  23841. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23842. origin_hits++;
  23843. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  23844. origin_saw_headers =
  23845. std::all_of(origin_headers.begin(), origin_headers.end(),
  23846. [&](const std::string &h) { return req.has_header(h); });
  23847. res.set_content("ok", "text/plain");
  23848. });
  23849. origin.listen();
  23850. ScopedConnectProxy proxy(origin.port());
  23851. ASSERT_NE(0, proxy.port());
  23852. // Pinned to 127.0.0.1 for the same reason as the test below.
  23853. SSLClient cli("127.0.0.1", origin.port());
  23854. cli.enable_server_certificate_verification(false);
  23855. cli.set_proxy("127.0.0.1", proxy.port());
  23856. set_credentials(cli);
  23857. auto res = cli.Get("/x");
  23858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23859. EXPECT_EQ(StatusCode::OK_200, res->status);
  23860. EXPECT_EQ(1, origin_hits.load());
  23861. EXPECT_EQ(1, proxy.connect_hits());
  23862. EXPECT_TRUE(origin_saw_headers.load());
  23863. EXPECT_FALSE(origin_saw_proxy_authz.load())
  23864. << "Proxy-Authorization must not be sent inside the tunnel";
  23865. auto connect_req = proxy.connect_request();
  23866. EXPECT_NE(std::string::npos,
  23867. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  23868. for (const auto &h : origin_headers) {
  23869. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  23870. << h << " must not be sent to the proxy on CONNECT";
  23871. }
  23872. }
  23873. } // namespace proxy_tunnel_test
  23874. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  23875. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23876. [](SSLClient &cli) {
  23877. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  23878. cli.set_basic_auth("origin-user", "origin-pass");
  23879. },
  23880. "Basic");
  23881. }
  23882. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  23883. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23884. [](SSLClient &cli) {
  23885. cli.set_proxy_bearer_token_auth("proxy-token");
  23886. cli.set_bearer_token_auth("origin-token");
  23887. },
  23888. "Bearer");
  23889. }
  23890. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  23891. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23892. [](SSLClient &cli) {
  23893. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  23894. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  23895. {"Cookie", "sid=origin-session"},
  23896. {"X-Api-Key", "origin-key"}});
  23897. },
  23898. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  23899. }
  23900. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  23901. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  23902. // retry; otherwise proxy creds would be sent to the origin.
  23903. std::atomic<int> origin_hits{0};
  23904. std::atomic<bool> origin_saw_proxy_authz{false};
  23905. proxy_tunnel_test::ScopedSSLServer origin;
  23906. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23907. origin_hits++;
  23908. if (req.has_header("Proxy-Authorization")) {
  23909. origin_saw_proxy_authz = true;
  23910. }
  23911. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23912. res.set_header("Proxy-Authenticate",
  23913. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  23914. "algorithm=MD5");
  23915. });
  23916. origin.listen();
  23917. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  23918. ASSERT_NE(0, proxy.port());
  23919. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  23920. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  23921. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  23922. // and answer with its own status, making this test flaky.
  23923. SSLClient cli("127.0.0.1", origin.port());
  23924. cli.enable_server_certificate_verification(false);
  23925. cli.set_proxy("127.0.0.1", proxy.port());
  23926. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23927. auto res = cli.Get("/x");
  23928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23929. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23930. EXPECT_EQ(1, origin_hits.load());
  23931. EXPECT_FALSE(origin_saw_proxy_authz.load());
  23932. EXPECT_EQ(1, proxy.connect_hits());
  23933. }
  23934. #endif