test.cc 873 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966
  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_PRIVATE_KEY_FILE "./key.pem"
  42. #define CA_CERT_FILE "./ca-bundle.crt"
  43. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  44. #define CLIENT_CA_CERT_DIR "."
  45. #define CLIENT_CERT_FILE "./client.cert.pem"
  46. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  47. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  48. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  49. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  50. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  51. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  52. #else
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  54. #endif
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  56. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  57. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  58. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  59. #ifdef CPPHTTPLIB_SSL_ENABLED
  60. namespace httplib {
  61. namespace tls {
  62. // Declared here for the split build, where the TLS abstraction declarations
  63. // live below the split border; the definition is linked from httplib.cc.
  64. ca_store_t create_ca_store(const char *pem, size_t len);
  65. } // namespace tls
  66. } // namespace httplib
  67. #endif
  68. using namespace std;
  69. using namespace httplib;
  70. const char *HOST = "localhost";
  71. static int get_base_port() {
  72. const char *shard = getenv("GTEST_SHARD_INDEX");
  73. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  74. }
  75. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  76. // New standalone tests MUST use svr.bind_to_any_port() instead.
  77. const int PORT = get_base_port();
  78. const string LONG_QUERY_VALUE = string(25000, '@');
  79. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  80. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  81. const string TOO_LONG_QUERY_URL =
  82. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  83. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  84. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  85. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  86. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  87. return file.name == key;
  88. });
  89. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  90. return *it;
  91. #else
  92. if (it != items.end()) { return *it; }
  93. throw std::runtime_error("invalid multipart form data name error");
  94. #endif
  95. }
  96. static void read_file(const std::string &path, std::string &out) {
  97. std::ifstream fs(path, std::ios_base::binary);
  98. if (!fs) {
  99. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  100. return;
  101. #else
  102. throw std::runtime_error("File not found: " + path);
  103. #endif
  104. }
  105. fs.seekg(0, std::ios_base::end);
  106. auto size = fs.tellg();
  107. fs.seekg(0);
  108. out.resize(static_cast<size_t>(size));
  109. fs.read(&out[0], static_cast<std::streamsize>(size));
  110. }
  111. class UnixSocketTest : public ::testing::Test {
  112. protected:
  113. void TearDown() override { std::remove(pathname_.c_str()); }
  114. void client_GET(const std::string &addr) {
  115. httplib::Client cli{addr};
  116. cli.set_address_family(AF_UNIX);
  117. ASSERT_TRUE(cli.is_valid());
  118. const auto &result = cli.Get(pattern_);
  119. ASSERT_TRUE(result) << "error: " << result.error();
  120. const auto &resp = result.value();
  121. EXPECT_EQ(resp.status, StatusCode::OK_200);
  122. EXPECT_EQ(resp.body, content_);
  123. }
  124. static std::string make_sock_path() {
  125. const char *shard = getenv("GTEST_SHARD_INDEX");
  126. return shard ? std::string("./httplib-server-") + shard + ".sock"
  127. : "./httplib-server.sock";
  128. }
  129. const std::string pathname_{make_sock_path()};
  130. const std::string pattern_{"/hi"};
  131. const std::string content_{"Hello World!"};
  132. };
  133. TEST_F(UnixSocketTest, pathname) {
  134. httplib::Server svr;
  135. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  136. res.set_content(content_, "text/plain");
  137. });
  138. std::thread t{[&] {
  139. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  140. }};
  141. auto se = detail::scope_exit([&] {
  142. svr.stop();
  143. t.join();
  144. ASSERT_FALSE(svr.is_running());
  145. });
  146. svr.wait_until_ready();
  147. ASSERT_TRUE(svr.is_running());
  148. client_GET(pathname_);
  149. }
  150. #if defined(__linux__) || \
  151. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  152. TEST_F(UnixSocketTest, PeerPid) {
  153. httplib::Server svr;
  154. std::string remote_port_val;
  155. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  156. res.set_content(content_, "text/plain");
  157. remote_port_val = std::to_string(req.remote_port);
  158. });
  159. std::thread t{[&] {
  160. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  161. }};
  162. auto se = detail::scope_exit([&] {
  163. svr.stop();
  164. t.join();
  165. ASSERT_FALSE(svr.is_running());
  166. });
  167. svr.wait_until_ready();
  168. ASSERT_TRUE(svr.is_running());
  169. client_GET(pathname_);
  170. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  171. }
  172. #endif
  173. #ifdef __linux__
  174. TEST_F(UnixSocketTest, abstract) {
  175. constexpr char svr_path[]{"\x00httplib-server.sock"};
  176. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  177. httplib::Server svr;
  178. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  179. res.set_content(content_, "text/plain");
  180. });
  181. std::thread t{[&] {
  182. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  183. }};
  184. auto se = detail::scope_exit([&] {
  185. svr.stop();
  186. t.join();
  187. ASSERT_FALSE(svr.is_running());
  188. });
  189. svr.wait_until_ready();
  190. ASSERT_TRUE(svr.is_running());
  191. client_GET(abstract_addr);
  192. }
  193. #endif
  194. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  195. httplib::Server svr;
  196. std::string received_host_header;
  197. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  198. // Capture the Host header sent by the client
  199. auto host_iter = req.headers.find("Host");
  200. if (host_iter != req.headers.end()) {
  201. received_host_header = host_iter->second;
  202. }
  203. res.set_content(content_, "text/plain");
  204. });
  205. std::thread t{[&] {
  206. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  207. }};
  208. auto se = detail::scope_exit([&] {
  209. svr.stop();
  210. t.join();
  211. ASSERT_FALSE(svr.is_running());
  212. });
  213. svr.wait_until_ready();
  214. ASSERT_TRUE(svr.is_running());
  215. // Test that Host header is automatically set to "localhost" for Unix socket
  216. // connections
  217. httplib::Client cli{pathname_};
  218. cli.set_address_family(AF_UNIX);
  219. ASSERT_TRUE(cli.is_valid());
  220. const auto &result = cli.Get(pattern_);
  221. ASSERT_TRUE(result) << "error: " << result.error();
  222. const auto &resp = result.value();
  223. EXPECT_EQ(resp.status, StatusCode::OK_200);
  224. EXPECT_EQ(resp.body, content_);
  225. // Verify that Host header was automatically set to "localhost"
  226. EXPECT_EQ(received_host_header, "localhost");
  227. }
  228. #ifndef _WIN32
  229. TEST(SocketStream, wait_writable_UNIX) {
  230. int fds[2];
  231. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  232. const auto asSocketStream = [&](socket_t fd,
  233. std::function<bool(Stream &)> func) {
  234. return detail::process_client_socket(
  235. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  236. };
  237. asSocketStream(fds[0], [&](Stream &s0) {
  238. EXPECT_EQ(s0.socket(), fds[0]);
  239. EXPECT_TRUE(s0.wait_writable());
  240. EXPECT_TRUE(s0.is_peer_alive());
  241. EXPECT_EQ(0, close(fds[1]));
  242. EXPECT_FALSE(s0.is_peer_alive());
  243. return true;
  244. });
  245. EXPECT_EQ(0, close(fds[0]));
  246. }
  247. TEST(SocketStream, wait_writable_INET) {
  248. sockaddr_in addr;
  249. memset(&addr, 0, sizeof(addr));
  250. addr.sin_family = AF_INET;
  251. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  252. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  253. int disconnected_svr_sock = -1;
  254. std::thread svr{[&] {
  255. const int s = socket(AF_INET, SOCK_STREAM, 0);
  256. ASSERT_LE(0, s);
  257. // PORT + 1 is shared with the SSL redirect tests and with
  258. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  259. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  260. // because that happens on a worker thread the ASSERT does not stop the
  261. // test: it runs on and fails at the disconnected_svr_sock check instead.
  262. default_socket_options(s);
  263. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  264. ASSERT_EQ(0, listen(s, 1));
  265. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  266. ASSERT_EQ(0, close(s));
  267. }};
  268. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  269. std::thread cli{[&] {
  270. const int s = socket(AF_INET, SOCK_STREAM, 0);
  271. ASSERT_LE(0, s);
  272. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  273. ASSERT_EQ(0, close(s));
  274. }};
  275. cli.join();
  276. svr.join();
  277. ASSERT_NE(disconnected_svr_sock, -1);
  278. const auto asSocketStream = [&](socket_t fd,
  279. std::function<bool(Stream &)> func) {
  280. return detail::process_client_socket(
  281. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  282. };
  283. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  284. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  285. // wait_writable() returns true because select_write() only checks if the
  286. // send buffer has space. Peer disconnection is detected later by send().
  287. EXPECT_TRUE(ss.wait_writable());
  288. return true;
  289. });
  290. ASSERT_EQ(0, close(disconnected_svr_sock));
  291. }
  292. #endif // #ifndef _WIN32
  293. TEST(SetSocketOptTest, TcpNoDelay) {
  294. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  295. ASSERT_NE(sock, INVALID_SOCKET);
  296. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  297. int val = 0;
  298. socklen_t len = sizeof(val);
  299. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  300. reinterpret_cast<char *>(&val), &len));
  301. EXPECT_NE(val, 0);
  302. detail::close_socket(sock);
  303. }
  304. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  305. // accept() reports failures through WSAGetLastError() on Windows and through
  306. // errno everywhere else. Asking the wrong one is what made the accept loop
  307. // treat every recoverable failure as fatal on Windows.
  308. struct Classification {
  309. bool resource;
  310. bool transient;
  311. };
  312. auto classify = [](int err) {
  313. #ifdef _WIN32
  314. WSASetLastError(err);
  315. #else
  316. errno = err;
  317. #endif
  318. // Read both before asserting: an assertion may clobber the error slot.
  319. Classification c;
  320. c.resource = detail::is_accept_resource_error();
  321. c.transient = detail::is_accept_transient_error();
  322. return c;
  323. };
  324. #ifdef _WIN32
  325. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  326. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  327. WSAECONNRESET, WSAECONNABORTED};
  328. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  329. #else
  330. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  331. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  332. ECONNABORTED};
  333. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  334. #endif
  335. for (auto err : resource_errors) {
  336. const auto c = classify(err);
  337. EXPECT_TRUE(c.resource) << "error " << err;
  338. EXPECT_FALSE(c.transient) << "error " << err;
  339. }
  340. for (auto err : transient_errors) {
  341. const auto c = classify(err);
  342. EXPECT_TRUE(c.transient) << "error " << err;
  343. EXPECT_FALSE(c.resource) << "error " << err;
  344. }
  345. for (auto err : fatal_errors) {
  346. const auto c = classify(err);
  347. EXPECT_FALSE(c.resource) << "error " << err;
  348. EXPECT_FALSE(c.transient) << "error " << err;
  349. }
  350. #ifdef _WIN32
  351. WSASetLastError(0);
  352. #else
  353. errno = 0;
  354. #endif
  355. }
  356. TEST(ClientTest, MoveConstructible) {
  357. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  358. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  359. }
  360. TEST(ClientTest, MoveAssignable) {
  361. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  362. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  363. }
  364. #ifdef _WIN32
  365. TEST(StartupTest, WSAStartup) {
  366. WSADATA wsaData;
  367. int ret = WSAStartup(0x0002, &wsaData);
  368. ASSERT_EQ(0, ret);
  369. }
  370. #endif
  371. TEST(DecodePathTest, PercentCharacter) {
  372. EXPECT_EQ(
  373. decode_path_component(
  374. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  375. U8("descrip=Gastos áéíóúñÑ 6"));
  376. }
  377. TEST(DecodePathTest, PercentCharacterNUL) {
  378. string expected;
  379. expected.push_back('x');
  380. expected.push_back('\0');
  381. expected.push_back('x');
  382. EXPECT_EQ(decode_path_component("x%00x"), expected);
  383. }
  384. TEST(DecodePathTest, UnicodeEncoding) {
  385. // %u0041 = 'A' (1-byte UTF-8)
  386. EXPECT_EQ("A", decode_path_component("%u0041"));
  387. // %u00E9 = 'é' (2-byte UTF-8)
  388. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  389. // %u3042 = 'あ' (3-byte UTF-8)
  390. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  391. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  392. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  393. // %uD800 = surrogate (invalid, silently dropped)
  394. EXPECT_EQ("", decode_path_component("%uD800"));
  395. }
  396. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  397. // A sign or whitespace inside the two-character escape window must not be
  398. // accepted as a valid percent-encoding; the sequence is passed through
  399. // literally, matching decode_uri_component / decode_path_component.
  400. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  401. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  402. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  403. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  404. // Well-formed escapes still decode.
  405. EXPECT_EQ("-", decode_query_component("%2D", false));
  406. EXPECT_EQ("A", decode_query_component("%41", false));
  407. }
  408. TEST(SanitizeFilenameTest, VariousPatterns) {
  409. // Path traversal
  410. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  411. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  412. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  413. // Normal and edge cases
  414. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  415. EXPECT_EQ("filename.txt",
  416. httplib::sanitize_filename("/path/to/filename.txt"));
  417. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  418. EXPECT_EQ("", httplib::sanitize_filename(".."));
  419. EXPECT_EQ("", httplib::sanitize_filename(""));
  420. // Null bytes stripped
  421. EXPECT_EQ("safe.txt",
  422. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  423. // Whitespace-only rejected
  424. EXPECT_EQ("", httplib::sanitize_filename(" "));
  425. }
  426. // Forward declaration (see the base64_encode note below): split builds move the
  427. // definition into httplib.cc, so re-declaring it here lets the test link.
  428. namespace httplib {
  429. namespace detail {
  430. bool is_chunked_transfer_encoding(const Headers &headers);
  431. } // namespace detail
  432. } // namespace httplib
  433. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  434. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  435. auto make = [](std::initializer_list<const char *> lines) {
  436. Headers h;
  437. for (auto te : lines) {
  438. if (te) { h.emplace("Transfer-Encoding", te); }
  439. }
  440. return h;
  441. };
  442. // Sole coding, matched case-insensitively.
  443. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  444. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  445. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  446. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  448. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  450. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  451. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  452. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  453. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  454. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  455. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  456. // were received, into one list. Headers preserves that order, so the answer
  457. // is decided by the last coding of the last line and the order the lines
  458. // arrived in is significant.
  459. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  460. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  461. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  462. // The split can fall anywhere in the list.
  463. EXPECT_TRUE(
  464. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  465. EXPECT_FALSE(
  466. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  467. // A trailing line naming no coding leaves the list ending in nothing, so it
  468. // must not inherit the chunked from the line before it.
  469. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  470. }
  471. // Forward declaration: in split builds split.py strips `inline` and moves the
  472. // definition into httplib.cc, so detail::base64_encode is not visible from the
  473. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  474. // in both header-only and split builds.
  475. namespace httplib {
  476. namespace detail {
  477. std::string base64_encode(const std::string &in);
  478. } // namespace detail
  479. } // namespace httplib
  480. TEST(Base64EncodeTest, KnownAnswers) {
  481. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  482. // where the accumulator's top bit is already set before the next shift.
  483. EXPECT_EQ("", detail::base64_encode(""));
  484. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  485. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  486. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  487. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  488. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  489. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  490. // High bytes keep the top bit set across several rounds.
  491. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  492. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  493. }
  494. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  495. string unescapedCharacters = "-_.!~*'()";
  496. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  497. }
  498. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  499. string reservedCharacters = ";,/?:@&=+$";
  500. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  501. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  502. }
  503. TEST(ClientQueryOrder, PreserveOrder) {
  504. // This test reproduces Issue #2259: client may reorder query parameters
  505. // when sending a GET request. The expected behavior is that the client
  506. // preserves the original query string order when the caller supplied it
  507. // as part of the path.
  508. Server svr;
  509. svr.Get("/", [&](const Request &req, Response &res) {
  510. // Echo back the raw target so the test can assert ordering
  511. res.set_content(req.target, "text/plain");
  512. });
  513. std::thread t{[&] { svr.listen(HOST, PORT); }};
  514. auto se = detail::scope_exit([&] {
  515. svr.stop();
  516. t.join();
  517. ASSERT_FALSE(svr.is_running());
  518. });
  519. svr.wait_until_ready();
  520. Client cli(HOST, PORT);
  521. ASSERT_TRUE(cli.is_valid());
  522. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  523. auto res = cli.Get(original);
  524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  525. // Expect the echoed target to exactly match the original path (order
  526. // preserved)
  527. EXPECT_EQ(res->body, original);
  528. }
  529. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  530. string chineseCharacters = U8("中国語");
  531. string russianCharacters = U8("дом");
  532. string brazilianCharacters = U8("óculos");
  533. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  534. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  535. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  536. "%D0%B4%D0%BE%D0%BC");
  537. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  538. }
  539. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  540. string unescapedCharacters = "-_.!~*'()";
  541. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  542. }
  543. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  544. string reservedCharacters = ";,/?:@&=+$";
  545. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  546. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  547. }
  548. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  549. string chineseCharacters = U8("中国語");
  550. string russianCharacters = U8("дом");
  551. string brazilianCharacters = U8("óculos");
  552. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  553. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  554. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  555. "%D0%B4%D0%BE%D0%BC");
  556. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  557. }
  558. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  559. // Issue #2082 use case: encoding path component with ampersand
  560. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  561. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  562. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  563. }
  564. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  565. string unescapedCharacters = "-_.!~*'()";
  566. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  567. }
  568. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  569. string reservedCharacters = ";,/?:@&=+$#";
  570. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  571. }
  572. TEST(EncodeUriTest, TestUTF8Characters) {
  573. string chineseCharacters = U8("中国語");
  574. string russianCharacters = U8("дом");
  575. string brazilianCharacters = U8("óculos");
  576. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  577. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  578. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  579. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  580. }
  581. TEST(EncodeUriTest, TestCompleteUri) {
  582. string uri =
  583. "https://example.com/path/to/resource?query=value&param=test#fragment";
  584. EXPECT_EQ(
  585. httplib::encode_uri(uri),
  586. "https://example.com/path/to/resource?query=value&param=test#fragment");
  587. }
  588. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  589. string uri =
  590. "https://example.com/path with spaces/file name.html?q=hello world";
  591. EXPECT_EQ(httplib::encode_uri(uri),
  592. "https://example.com/path%20with%20spaces/"
  593. "file%20name.html?q=hello%20world");
  594. }
  595. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  596. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  597. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  598. }
  599. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  600. string unescapedCharacters = "-_.!~*'()";
  601. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  602. }
  603. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  604. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  605. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  606. string encodedBrazilian = "%C3%B3culos";
  607. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  608. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  609. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  610. }
  611. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  612. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  613. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  614. "Piri Tommy Villiers - on & on");
  615. }
  616. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  617. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  618. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  619. }
  620. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  621. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  622. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  623. }
  624. TEST(DecodeUriTest, TestUTF8Characters) {
  625. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  626. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  627. string encodedBrazilian = "%C3%B3culos";
  628. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  629. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  630. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  631. }
  632. TEST(DecodeUriTest, TestCompleteUri) {
  633. string encodedUri = "https://example.com/path%20with%20spaces/"
  634. "file%20name.html?q=hello%20world";
  635. EXPECT_EQ(
  636. httplib::decode_uri(encodedUri),
  637. "https://example.com/path with spaces/file name.html?q=hello world");
  638. }
  639. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  640. string original =
  641. "https://example.com/path with spaces/file name.html?q=hello world";
  642. string encoded = httplib::encode_uri(original);
  643. string decoded = httplib::decode_uri(encoded);
  644. EXPECT_EQ(decoded, original);
  645. }
  646. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  647. // decode_uri is the inverse of encode_uri: an escaped reserved character
  648. // stays encoded so it is not promoted into a real delimiter, while
  649. // non-reserved escapes still decode (like JS decodeURI).
  650. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  651. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  652. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  653. "%3F%3A%40%26%3D%2B%24%2C%3B");
  654. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  655. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  656. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  657. "http://example.com/a%2Fb");
  658. // decode_uri_component still decodes the reserved character.
  659. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  660. }
  661. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  662. string original = "Piri Tommy Villiers - on & on";
  663. string encoded = httplib::encode_uri_component(original);
  664. string decoded = httplib::decode_uri_component(encoded);
  665. EXPECT_EQ(decoded, original);
  666. }
  667. TEST(TrimTests, TrimStringTests) {
  668. EXPECT_EQ("abc", detail::trim_copy("abc"));
  669. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  670. EXPECT_TRUE(detail::trim_copy("").empty());
  671. }
  672. TEST(AsciiTest, LocaleIndependentClassification) {
  673. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  674. // which consult the global C locale: std::isalnum(0xC5) can return true
  675. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  676. // helpers must classify every byte by the ASCII grammar alone.
  677. for (int i = 0; i < 256; i++) {
  678. auto c = static_cast<char>(i);
  679. auto is_digit = i >= '0' && i <= '9';
  680. auto is_upper = i >= 'A' && i <= 'Z';
  681. auto is_lower = i >= 'a' && i <= 'z';
  682. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  683. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  684. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  685. << "byte " << i;
  686. }
  687. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  688. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  689. // Non-ASCII bytes must be percent-encoded, never passed through as
  690. // alphanumeric.
  691. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  692. }
  693. TEST(FromCharsTest, Double) {
  694. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  695. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  696. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  697. auto parse = [](const std::string &s, double &v) {
  698. return detail::from_chars(s.data(), s.data() + s.size(), v);
  699. };
  700. double v = -1.0;
  701. // Representative quality values.
  702. EXPECT_EQ(parse("0", v).ec, std::errc{});
  703. EXPECT_DOUBLE_EQ(v, 0.0);
  704. EXPECT_EQ(parse("1", v).ec, std::errc{});
  705. EXPECT_DOUBLE_EQ(v, 1.0);
  706. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  707. EXPECT_DOUBLE_EQ(v, 0.8);
  708. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  709. EXPECT_DOUBLE_EQ(v, 0.001);
  710. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  711. EXPECT_DOUBLE_EQ(v, 1.0);
  712. // A missing integer or fractional part is tolerated.
  713. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  714. EXPECT_DOUBLE_EQ(v, 0.5);
  715. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  716. EXPECT_DOUBLE_EQ(v, 5.0);
  717. // Values outside [0, 1] still parse; the caller range-checks them.
  718. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  719. EXPECT_DOUBLE_EQ(v, 123.456);
  720. // Stops at the first byte that is not part of the number and reports where.
  721. std::string trailing = "0.9, text/html";
  722. auto r = parse(trailing, v);
  723. EXPECT_EQ(r.ec, std::errc{});
  724. EXPECT_DOUBLE_EQ(v, 0.9);
  725. EXPECT_EQ(*r.ptr, ',');
  726. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  727. // outright, and an 'e'/'E' simply ends the number.
  728. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  729. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  730. std::string exp_input = "1.5e3";
  731. r = parse(exp_input, v);
  732. EXPECT_EQ(r.ec, std::errc{});
  733. EXPECT_DOUBLE_EQ(v, 1.5);
  734. EXPECT_EQ(*r.ptr, 'e');
  735. // Invalid inputs.
  736. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  737. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  738. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  739. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  740. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  741. // Pathological but well-formed inputs must stay bounded (no overflow, no
  742. // out-of-bounds table access) and stay within [0, 1] for the caller.
  743. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  744. std::errc{});
  745. EXPECT_DOUBLE_EQ(v, 0.0);
  746. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  747. std::errc{});
  748. EXPECT_GE(v, 0.0);
  749. EXPECT_LE(v, 1.0);
  750. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  751. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  752. }
  753. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  754. // Simple case without quality values
  755. std::vector<std::string> result1;
  756. EXPECT_TRUE(detail::parse_accept_header(
  757. "text/html,application/json,text/plain", result1));
  758. EXPECT_EQ(result1.size(), 3U);
  759. EXPECT_EQ(result1[0], "text/html");
  760. EXPECT_EQ(result1[1], "application/json");
  761. EXPECT_EQ(result1[2], "text/plain");
  762. // With quality values
  763. std::vector<std::string> result2;
  764. EXPECT_TRUE(detail::parse_accept_header(
  765. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  766. EXPECT_EQ(result2.size(), 3U);
  767. EXPECT_EQ(result2[0], "application/json"); // highest q value
  768. EXPECT_EQ(result2[1], "text/html");
  769. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  770. }
  771. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  772. // Mixed with and without quality values
  773. std::vector<std::string> result;
  774. EXPECT_TRUE(detail::parse_accept_header(
  775. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  776. EXPECT_EQ(result.size(), 3U);
  777. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  778. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  779. EXPECT_EQ(result[2], "application/json"); // q=0.5
  780. }
  781. TEST(ParseAcceptHeaderTest, EdgeCases) {
  782. // Empty header
  783. std::vector<std::string> empty_result;
  784. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  785. EXPECT_TRUE(empty_result.empty());
  786. // Single type
  787. std::vector<std::string> single_result;
  788. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  789. EXPECT_EQ(single_result.size(), 1U);
  790. EXPECT_EQ(single_result[0], "application/json");
  791. // Wildcard types
  792. std::vector<std::string> wildcard_result;
  793. EXPECT_TRUE(detail::parse_accept_header(
  794. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  795. EXPECT_EQ(wildcard_result.size(), 3U);
  796. EXPECT_EQ(wildcard_result[0], "application/json");
  797. EXPECT_EQ(wildcard_result[1], "text/*");
  798. EXPECT_EQ(wildcard_result[2], "*/*");
  799. }
  800. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  801. // Common browser Accept header
  802. std::vector<std::string> browser_result;
  803. EXPECT_TRUE(
  804. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  805. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  806. browser_result));
  807. EXPECT_EQ(browser_result.size(), 6U);
  808. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  809. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  810. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  811. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  812. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  813. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  814. // API client header
  815. std::vector<std::string> api_result;
  816. EXPECT_TRUE(detail::parse_accept_header(
  817. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  818. api_result));
  819. EXPECT_EQ(api_result.size(), 3U);
  820. EXPECT_EQ(api_result[0], "application/json");
  821. EXPECT_EQ(api_result[1], "application/xml");
  822. EXPECT_EQ(api_result[2], "text/plain");
  823. }
  824. TEST(ParseAcceptHeaderTest, SpecialCases) {
  825. // Quality value with 3 decimal places
  826. std::vector<std::string> decimal_result;
  827. EXPECT_TRUE(detail::parse_accept_header(
  828. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  829. EXPECT_EQ(decimal_result.size(), 2U);
  830. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  831. EXPECT_EQ(decimal_result[1], "text/html");
  832. // Zero quality (should still be included but with lowest priority)
  833. std::vector<std::string> zero_q_result;
  834. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  835. zero_q_result));
  836. EXPECT_EQ(zero_q_result.size(), 2U);
  837. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  838. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  839. // No spaces around commas
  840. std::vector<std::string> no_space_result;
  841. EXPECT_TRUE(detail::parse_accept_header(
  842. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  843. no_space_result));
  844. EXPECT_EQ(no_space_result.size(), 3U);
  845. EXPECT_EQ(no_space_result[0], "text/html");
  846. EXPECT_EQ(no_space_result[1], "application/json");
  847. EXPECT_EQ(no_space_result[2], "text/plain");
  848. }
  849. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  850. // Quality values always use '.' as the decimal separator, so parsing must
  851. // not depend on the process locale. An embedding application may have
  852. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  853. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  854. std::string saved = cur ? cur : "C";
  855. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  856. "fr_FR.UTF-8"};
  857. bool switched = false;
  858. for (const auto loc : comma_locales) {
  859. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  860. std::localeconv()->decimal_point[0] == ',') {
  861. switched = true;
  862. break;
  863. }
  864. }
  865. if (!switched) {
  866. std::setlocale(LC_NUMERIC, saved.c_str());
  867. GTEST_SKIP() << "no comma-decimal locale available on this host";
  868. }
  869. // The higher-weighted type appears later in the list, so a correct parse
  870. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  871. // sensitive parse reads both weights as 0 and leaves the original order.
  872. std::vector<std::string> result;
  873. EXPECT_TRUE(detail::parse_accept_header(
  874. "application/json;q=0.1,text/html;q=0.9", result));
  875. ASSERT_EQ(result.size(), 2U);
  876. EXPECT_EQ(result[0], "text/html");
  877. EXPECT_EQ(result[1], "application/json");
  878. std::setlocale(LC_NUMERIC, saved.c_str());
  879. }
  880. TEST(ParseAcceptHeaderTest, InvalidCases) {
  881. std::vector<std::string> result;
  882. // Invalid quality value (> 1.0)
  883. EXPECT_FALSE(
  884. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  885. // Invalid quality value (< 0.0)
  886. EXPECT_FALSE(
  887. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  888. // Invalid quality value (not a number)
  889. EXPECT_FALSE(detail::parse_accept_header(
  890. "text/html;q=invalid,application/json", result));
  891. // A valid numeric prefix does not make the entire quality value valid.
  892. EXPECT_FALSE(detail::parse_accept_header(
  893. "text/html;q=0.5junk,application/json", result));
  894. // Empty quality value
  895. EXPECT_FALSE(
  896. detail::parse_accept_header("text/html;q=,application/json", result));
  897. // Invalid media type format (no slash and not wildcard)
  898. EXPECT_FALSE(
  899. detail::parse_accept_header("invalidtype,application/json", result));
  900. // Valid cases should still work
  901. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  902. EXPECT_EQ(result.size(), 1U);
  903. EXPECT_EQ(result[0], "*/*");
  904. EXPECT_TRUE(detail::parse_accept_header("*", result));
  905. EXPECT_EQ(result.size(), 1U);
  906. EXPECT_EQ(result[0], "*");
  907. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  908. EXPECT_EQ(result.size(), 1U);
  909. EXPECT_EQ(result[0], "text/*");
  910. }
  911. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  912. // elements, so a leading, trailing or doubled comma is a legal Accept value
  913. // and must not be answered with 400 Bad Request.
  914. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  915. struct {
  916. const char *value;
  917. std::vector<std::string> expected;
  918. } cases[] = {
  919. {",application/json", {"application/json"}},
  920. {"text/html,", {"text/html"}},
  921. {"text/html,,*/*", {"text/html", "*/*"}},
  922. // An empty element may be spelled with whitespace in it
  923. {"text/html, , application/json", {"text/html", "application/json"}},
  924. // Nothing but empty elements is an empty list, which means the same
  925. // thing as no Accept header at all
  926. {",,,", {}},
  927. // Quality values still apply across ignored empty elements
  928. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  929. };
  930. for (const auto &c : cases) {
  931. std::vector<std::string> result;
  932. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  933. << "value: " << c.value;
  934. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  935. }
  936. // An invalid entry is still rejected when empty elements surround it
  937. std::vector<std::string> result;
  938. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  939. }
  940. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  941. Server svr;
  942. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  943. EXPECT_EQ(req.accept_content_types.size(), 3U);
  944. EXPECT_EQ(req.accept_content_types[0], "application/json");
  945. EXPECT_EQ(req.accept_content_types[1], "text/html");
  946. EXPECT_EQ(req.accept_content_types[2], "*/*");
  947. res.set_content("ok", "text/plain");
  948. });
  949. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  950. EXPECT_TRUE(false);
  951. res.set_content("bad request", "text/plain");
  952. });
  953. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  954. auto se = detail::scope_exit([&] {
  955. svr.stop();
  956. listen_thread.join();
  957. ASSERT_FALSE(svr.is_running());
  958. });
  959. svr.wait_until_ready();
  960. Client cli("localhost", PORT);
  961. {
  962. auto res = cli.Get(
  963. "/accept_ok",
  964. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  966. EXPECT_EQ(StatusCode::OK_200, res->status);
  967. }
  968. {
  969. auto res = cli.Get("/accept_bad_request",
  970. Headers{{"Accept", "text/html;q=abc,application/json"}});
  971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  972. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  973. }
  974. }
  975. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  976. Server svr;
  977. svr.Get("/", [](const Request & /*req*/, Response &res) {
  978. res.set_content("ok", "text/plain");
  979. });
  980. std::atomic<int> start_count{0};
  981. std::atomic<bool> running_when_called{false};
  982. svr.set_start_handler([&]() {
  983. running_when_called = svr.is_running();
  984. start_count++;
  985. });
  986. auto port = svr.bind_to_any_port(HOST);
  987. std::thread t([&]() { svr.listen_after_bind(); });
  988. auto se = detail::scope_exit([&] {
  989. svr.stop();
  990. t.join();
  991. ASSERT_FALSE(svr.is_running());
  992. });
  993. svr.wait_until_ready();
  994. // A successful request proves the accept loop is running, which the start
  995. // handler precedes; so by now the handler must have run exactly once.
  996. Client cli(HOST, port);
  997. cli.set_connection_timeout(std::chrono::seconds(5));
  998. auto res = cli.Get("/");
  999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1000. EXPECT_EQ(StatusCode::OK_200, res->status);
  1001. EXPECT_EQ(1, start_count.load());
  1002. EXPECT_TRUE(running_when_called.load());
  1003. }
  1004. TEST(DivideTest, DivideStringTests) {
  1005. auto divide = [](const std::string &str, char d) {
  1006. std::string lhs;
  1007. std::string rhs;
  1008. detail::divide(str, d,
  1009. [&](const char *lhs_data, std::size_t lhs_size,
  1010. const char *rhs_data, std::size_t rhs_size) {
  1011. lhs.assign(lhs_data, lhs_size);
  1012. rhs.assign(rhs_data, rhs_size);
  1013. });
  1014. return std::make_pair(std::move(lhs), std::move(rhs));
  1015. };
  1016. {
  1017. const auto res = divide("", '=');
  1018. EXPECT_EQ(res.first, "");
  1019. EXPECT_EQ(res.second, "");
  1020. }
  1021. {
  1022. const auto res = divide("=", '=');
  1023. EXPECT_EQ(res.first, "");
  1024. EXPECT_EQ(res.second, "");
  1025. }
  1026. {
  1027. const auto res = divide(" ", '=');
  1028. EXPECT_EQ(res.first, " ");
  1029. EXPECT_EQ(res.second, "");
  1030. }
  1031. {
  1032. const auto res = divide("a", '=');
  1033. EXPECT_EQ(res.first, "a");
  1034. EXPECT_EQ(res.second, "");
  1035. }
  1036. {
  1037. const auto res = divide("a=", '=');
  1038. EXPECT_EQ(res.first, "a");
  1039. EXPECT_EQ(res.second, "");
  1040. }
  1041. {
  1042. const auto res = divide("=b", '=');
  1043. EXPECT_EQ(res.first, "");
  1044. EXPECT_EQ(res.second, "b");
  1045. }
  1046. {
  1047. const auto res = divide("a=b", '=');
  1048. EXPECT_EQ(res.first, "a");
  1049. EXPECT_EQ(res.second, "b");
  1050. }
  1051. {
  1052. const auto res = divide("a=b=", '=');
  1053. EXPECT_EQ(res.first, "a");
  1054. EXPECT_EQ(res.second, "b=");
  1055. }
  1056. {
  1057. const auto res = divide("a=b=c", '=');
  1058. EXPECT_EQ(res.first, "a");
  1059. EXPECT_EQ(res.second, "b=c");
  1060. }
  1061. }
  1062. TEST(SplitTest, ParseQueryString) {
  1063. string s = "key1=val1&key2=val2&key3=val3";
  1064. Params dic;
  1065. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1066. [&](const char *b, const char *e) {
  1067. string key, val;
  1068. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1069. if (key.empty()) {
  1070. key.assign(b2, e2);
  1071. } else {
  1072. val.assign(b2, e2);
  1073. }
  1074. });
  1075. dic.emplace(key, val);
  1076. });
  1077. EXPECT_EQ("val1", dic.find("key1")->second);
  1078. EXPECT_EQ("val2", dic.find("key2")->second);
  1079. EXPECT_EQ("val3", dic.find("key3")->second);
  1080. }
  1081. TEST(SplitTest, ParseInvalidQueryTests) {
  1082. {
  1083. string s = " ";
  1084. Params dict;
  1085. detail::parse_query_text(s, dict);
  1086. EXPECT_TRUE(dict.empty());
  1087. }
  1088. {
  1089. string s = " = =";
  1090. Params dict;
  1091. detail::parse_query_text(s, dict);
  1092. EXPECT_TRUE(dict.empty());
  1093. }
  1094. }
  1095. TEST(ParseQueryTest, ParseQueryString) {
  1096. {
  1097. std::string s = "key1=val1&key2=val2&key3=val3";
  1098. Params dic;
  1099. detail::parse_query_text(s, dic);
  1100. EXPECT_EQ("val1", dic.find("key1")->second);
  1101. EXPECT_EQ("val2", dic.find("key2")->second);
  1102. EXPECT_EQ("val3", dic.find("key3")->second);
  1103. }
  1104. {
  1105. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1106. Params dic;
  1107. detail::parse_query_text(s, dic);
  1108. EXPECT_EQ("", dic.find("key1")->second);
  1109. EXPECT_EQ("val1", dic.find("key2")->second);
  1110. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1111. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1112. }
  1113. }
  1114. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1115. Params dic;
  1116. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1117. dic.emplace("key1", "val1");
  1118. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1119. dic.emplace("key2", "val2");
  1120. dic.emplace("key3", "val3");
  1121. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1122. }
  1123. // Joins every entry of a Headers or Params into "key=value " so a whole
  1124. // traversal can be compared in one assertion. Both are instantiations of the
  1125. // same insertion-ordered container, so one helper serves both.
  1126. template <typename Map> static std::string entries_to_string(const Map &m) {
  1127. std::string s;
  1128. for (const auto &entry : m) {
  1129. s += entry.first + "=" + entry.second + " ";
  1130. }
  1131. return s;
  1132. }
  1133. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1134. // Params used to be a std::multimap, which sorted by name and handed the
  1135. // caller's query back alphabetised. A client signing its query string could
  1136. // not reproduce the order it asked for.
  1137. Params dic;
  1138. dic.emplace("zulu", "1");
  1139. dic.emplace("alpha", "2");
  1140. dic.emplace("mike", "3");
  1141. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1142. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1143. }
  1144. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1145. Params dic;
  1146. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1147. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1148. }
  1149. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1150. Request req;
  1151. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1152. req.params);
  1153. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1154. EXPECT_EQ("first", req.get_param_value("tag"));
  1155. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1156. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1157. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1158. EXPECT_EQ("", req.get_param_value("tag", 3));
  1159. }
  1160. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1161. // Params shares its container with Headers, which matches field names
  1162. // case-insensitively. Parameter names must not pick that up.
  1163. Params dic;
  1164. dic.emplace("Key", "upper");
  1165. dic.emplace("key", "lower");
  1166. EXPECT_EQ(2U, dic.size());
  1167. EXPECT_EQ(1U, dic.count("Key"));
  1168. EXPECT_EQ(1U, dic.count("key"));
  1169. EXPECT_EQ("upper", dic.find("Key")->second);
  1170. EXPECT_EQ("lower", dic.find("key")->second);
  1171. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1172. }
  1173. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1174. Server svr;
  1175. std::string order;
  1176. svr.Get("/order", [&](const Request &req, Response &res) {
  1177. order = entries_to_string(req.params);
  1178. res.set_content("ok", "text/plain");
  1179. });
  1180. auto port = svr.bind_to_any_port(HOST);
  1181. thread t = thread([&] { svr.listen_after_bind(); });
  1182. auto se = detail::scope_exit([&] {
  1183. svr.stop();
  1184. t.join();
  1185. ASSERT_FALSE(svr.is_running());
  1186. });
  1187. svr.wait_until_ready();
  1188. Client cli(HOST, port);
  1189. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1190. ASSERT_TRUE(res);
  1191. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1192. }
  1193. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1194. Server svr;
  1195. std::string field_order, file_order;
  1196. svr.Post("/order", [&](const Request &req, Response &res) {
  1197. for (const auto &field : req.form.fields) {
  1198. field_order += field.first + "=" + field.second.content + " ";
  1199. }
  1200. for (const auto &file : req.form.files) {
  1201. file_order += file.first + "=" + file.second.filename + " ";
  1202. }
  1203. res.set_content("ok", "text/plain");
  1204. });
  1205. auto port = svr.bind_to_any_port(HOST);
  1206. thread t = thread([&] { svr.listen_after_bind(); });
  1207. auto se = detail::scope_exit([&] {
  1208. svr.stop();
  1209. t.join();
  1210. ASSERT_FALSE(svr.is_running());
  1211. });
  1212. svr.wait_until_ready();
  1213. UploadFormDataItems items = {
  1214. {"zulu", "1", "", ""},
  1215. {"alpha", "2", "", ""},
  1216. {"mike", "3", "", ""},
  1217. {"zebra", "z", "z.txt", "text/plain"},
  1218. {"apple", "a", "a.txt", "text/plain"},
  1219. };
  1220. Client cli(HOST, port);
  1221. auto res = cli.Post("/order", items);
  1222. ASSERT_TRUE(res);
  1223. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1224. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1225. }
  1226. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1227. Server svr;
  1228. std::vector<std::string> values;
  1229. std::string first, second, out_of_range, order;
  1230. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1231. values = req.form.get_fields("tag");
  1232. first = req.form.get_field("tag", 0);
  1233. second = req.form.get_field("tag", 1);
  1234. out_of_range = req.form.get_field("tag", 2);
  1235. for (const auto &field : req.form.fields) {
  1236. order += field.first + "=" + field.second.content + " ";
  1237. }
  1238. res.set_content("ok", "text/plain");
  1239. });
  1240. auto port = svr.bind_to_any_port(HOST);
  1241. thread t = thread([&] { svr.listen_after_bind(); });
  1242. auto se = detail::scope_exit([&] {
  1243. svr.stop();
  1244. t.join();
  1245. ASSERT_FALSE(svr.is_running());
  1246. });
  1247. svr.wait_until_ready();
  1248. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1249. // not adjacent in the container.
  1250. UploadFormDataItems items = {
  1251. {"tag", "first", "", ""},
  1252. {"other", "x", "", ""},
  1253. {"tag", "second", "", ""},
  1254. };
  1255. Client cli(HOST, port);
  1256. auto res = cli.Post("/repeated", items);
  1257. ASSERT_TRUE(res);
  1258. ASSERT_EQ(2U, values.size());
  1259. EXPECT_EQ("first", values[0]);
  1260. EXPECT_EQ("second", values[1]);
  1261. EXPECT_EQ("first", first);
  1262. EXPECT_EQ("second", second);
  1263. // std::multimap already kept entries sharing a name in insertion order, so
  1264. // everything above passes without this change too. The whole traversal is
  1265. // what tells the two apart: sorting by name would hoist "other" to the front
  1266. // and the two "tag" parts would end up adjacent.
  1267. EXPECT_EQ("tag=first other=x tag=second ", order);
  1268. // Advancing past the last entry of a name used to run off the container;
  1269. // the container's saturating increment makes it return the default instead.
  1270. EXPECT_EQ("", out_of_range);
  1271. }
  1272. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1273. // Server::read_content() keeps a FormFields::iterator alive across the
  1274. // content callbacks that fill the part it points at. The container is
  1275. // vector-backed, so a later emplace can reallocate and invalidate an older
  1276. // iterator; 64 parts grow the vector through seven reallocations, which
  1277. // checks that every part's content still lands in its own entry.
  1278. const size_t part_count = 64;
  1279. // One formula for both the parts sent and the values expected back, so the
  1280. // two cannot drift apart.
  1281. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1282. auto content_of = [](size_t i) {
  1283. return std::string(64, static_cast<char>('a' + (i % 26)));
  1284. };
  1285. Server svr;
  1286. std::vector<std::pair<std::string, std::string>> received;
  1287. svr.Post("/many", [&](const Request &req, Response &res) {
  1288. for (const auto &field : req.form.fields) {
  1289. received.emplace_back(field.first, field.second.content);
  1290. }
  1291. res.set_content("ok", "text/plain");
  1292. });
  1293. auto port = svr.bind_to_any_port(HOST);
  1294. thread t = thread([&] { svr.listen_after_bind(); });
  1295. auto se = detail::scope_exit([&] {
  1296. svr.stop();
  1297. t.join();
  1298. ASSERT_FALSE(svr.is_running());
  1299. });
  1300. svr.wait_until_ready();
  1301. UploadFormDataItems items;
  1302. for (size_t i = 0; i < part_count; i++) {
  1303. items.push_back({name_of(i), content_of(i), "", ""});
  1304. }
  1305. Client cli(HOST, port);
  1306. auto res = cli.Post("/many", items);
  1307. ASSERT_TRUE(res);
  1308. ASSERT_EQ(part_count, received.size());
  1309. for (size_t i = 0; i < part_count; i++) {
  1310. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1311. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1312. }
  1313. }
  1314. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1315. string content_type = "multipart/form-data; boundary=something";
  1316. string boundary;
  1317. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1318. EXPECT_TRUE(ret);
  1319. EXPECT_EQ(boundary, "something");
  1320. }
  1321. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1322. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1323. string boundary;
  1324. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1325. EXPECT_TRUE(ret);
  1326. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1327. }
  1328. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1329. string content_type =
  1330. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1331. string boundary;
  1332. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1333. EXPECT_TRUE(ret);
  1334. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1335. }
  1336. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1337. string content_type =
  1338. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1339. string boundary;
  1340. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1341. EXPECT_TRUE(ret);
  1342. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1343. }
  1344. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1345. const string boundary(70, 'a');
  1346. string content_type = "multipart/form-data; boundary=" + boundary;
  1347. string parsed;
  1348. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1349. EXPECT_TRUE(ret);
  1350. EXPECT_EQ(parsed, boundary);
  1351. }
  1352. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1353. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1354. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1355. string parsed;
  1356. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1357. EXPECT_FALSE(ret);
  1358. }
  1359. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1360. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1361. // is 72 characters on the wire and still valid.
  1362. const string boundary(70, 'a');
  1363. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1364. string parsed;
  1365. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1366. EXPECT_EQ(parsed, boundary);
  1367. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1368. parsed.clear();
  1369. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1370. }
  1371. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1372. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1373. // The parameter parser must not treat that '=' as the key/value separator.
  1374. string content_type =
  1375. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1376. "charset=UTF-8";
  1377. string parsed;
  1378. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1379. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1380. }
  1381. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1382. // A ';' inside the quoted-string is part of the value, not a parameter
  1383. // separator, so it must not truncate the boundary.
  1384. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1385. string parsed;
  1386. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1387. EXPECT_EQ(parsed, "a;b");
  1388. }
  1389. TEST(ParseDispositionParamsTest, QuotedValues) {
  1390. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1391. // ';' and '=' are ordinary characters inside one.
  1392. struct {
  1393. const char *value;
  1394. std::vector<std::pair<const char *, const char *>> expected;
  1395. } cases[] = {
  1396. {"name=\"file1\"; filename=\"a.txt\"",
  1397. {{"name", "file1"}, {"filename", "a.txt"}}},
  1398. // Whitespace around '=' and ';' is still trimmed
  1399. {"name=\"file2\" ;filename = \"a.html\"",
  1400. {{"name", "file2"}, {"filename", "a.html"}}},
  1401. // '=' inside the value used to leave only the text after the last one
  1402. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1403. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1404. {"name=\"x=y\"", {{"name", "x=y"}}},
  1405. // ';' inside the value used to truncate the pair and leave a bogus one
  1406. {"name=\"file3\"; filename=\"a;b.txt\"",
  1407. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1408. // An unquoted value keeps working, and so does filename*
  1409. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1410. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1411. // A parameter with no key is dropped rather than turned into one whose
  1412. // key is the value
  1413. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1414. };
  1415. for (const auto &c : cases) {
  1416. Params params;
  1417. detail::parse_disposition_params(c.value, params);
  1418. for (const auto &kv : c.expected) {
  1419. auto it = params.find(kv.first);
  1420. ASSERT_NE(it, params.end())
  1421. << "value: " << c.value << ", key: " << kv.first;
  1422. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1423. }
  1424. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1425. }
  1426. }
  1427. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1428. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1429. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1430. Server svr;
  1431. std::string field_value, file_name, file_filename;
  1432. bool has_field = false, has_file = false;
  1433. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1434. has_field = req.form.has_field("x=y");
  1435. field_value = req.form.get_field("x=y");
  1436. has_file = req.form.has_file("file1");
  1437. const auto &file = req.form.get_file("file1");
  1438. file_name = file.name;
  1439. file_filename = file.filename;
  1440. res.set_content("ok", "text/plain");
  1441. });
  1442. auto port = svr.bind_to_any_port(HOST);
  1443. thread t = thread([&] { svr.listen_after_bind(); });
  1444. auto se = detail::scope_exit([&] {
  1445. svr.stop();
  1446. t.join();
  1447. ASSERT_FALSE(svr.is_running());
  1448. });
  1449. svr.wait_until_ready();
  1450. UploadFormDataItems items = {
  1451. {"x=y", "field-value", "", ""},
  1452. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1453. };
  1454. Client cli(HOST, port);
  1455. auto res = cli.Post("/quoted", items);
  1456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1457. ASSERT_EQ(StatusCode::OK_200, res->status);
  1458. EXPECT_TRUE(has_field);
  1459. EXPECT_EQ("field-value", field_value);
  1460. EXPECT_TRUE(has_file);
  1461. EXPECT_EQ("file1", file_name);
  1462. EXPECT_EQ("a;b=report.pdf", file_filename);
  1463. }
  1464. TEST(GetHeaderValueTest, DefaultValue) {
  1465. Headers headers = {{"Dummy", "Dummy"}};
  1466. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1467. EXPECT_STREQ("text/plain", val);
  1468. }
  1469. TEST(GetHeaderValueTest, DefaultValueInt) {
  1470. Headers headers = {{"Dummy", "Dummy"}};
  1471. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1472. EXPECT_EQ(100ull, val);
  1473. }
  1474. TEST(GetHeaderValueTest, RegularValue) {
  1475. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1476. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1477. EXPECT_STREQ("text/html", val);
  1478. }
  1479. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1480. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1481. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1482. EXPECT_STREQ("text/html", val);
  1483. }
  1484. TEST(GetHeaderValueTest, SetContent) {
  1485. Response res;
  1486. res.set_content("html", "text/html");
  1487. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1488. res.set_content("text", "text/plain");
  1489. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1490. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1491. }
  1492. TEST(GetHeaderValueTest, RegularValueInt) {
  1493. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1494. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1495. EXPECT_EQ(100ull, val);
  1496. }
  1497. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1498. Headers headers = {{"Content-Length", "x"}};
  1499. auto is_invalid_value = false;
  1500. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1501. is_invalid_value);
  1502. EXPECT_EQ(0ull, val);
  1503. EXPECT_TRUE(is_invalid_value);
  1504. }
  1505. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1506. // An all-digit value that overflows size_t must be reported as invalid, not
  1507. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1508. // a large length to a small one on 32-bit builds, leaving the framing length
  1509. // wrong while is_invalid_value stayed false.
  1510. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1511. auto is_invalid_value = false;
  1512. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1513. is_invalid_value);
  1514. EXPECT_TRUE(is_invalid_value);
  1515. // A well-formed length is unaffected.
  1516. Headers ok = {{"Content-Length", "1234"}};
  1517. is_invalid_value = false;
  1518. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1519. is_invalid_value);
  1520. EXPECT_EQ(1234ull, val);
  1521. EXPECT_FALSE(is_invalid_value);
  1522. }
  1523. TEST(GetHeaderValueTest, Range) {
  1524. {
  1525. Headers headers = {make_range_header({{1, -1}})};
  1526. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1527. EXPECT_STREQ("bytes=1-", val);
  1528. }
  1529. {
  1530. Headers headers = {make_range_header({{-1, 1}})};
  1531. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1532. EXPECT_STREQ("bytes=-1", val);
  1533. }
  1534. {
  1535. Headers headers = {make_range_header({{1, 10}})};
  1536. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1537. EXPECT_STREQ("bytes=1-10", val);
  1538. }
  1539. {
  1540. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1541. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1542. EXPECT_STREQ("bytes=1-10, 100-", val);
  1543. }
  1544. {
  1545. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1546. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1547. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1548. }
  1549. {
  1550. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1551. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1552. EXPECT_STREQ("bytes=0-0, -1", val);
  1553. }
  1554. }
  1555. TEST(BearerTokenAuthTest, SchemeValidation) {
  1556. // A value shorter than "Bearer " must not throw from the fixed-length
  1557. // substr, and a non-Bearer scheme must not be reported as a token.
  1558. struct {
  1559. const char *value;
  1560. const char *expected;
  1561. } cases[] = {
  1562. {"x", ""},
  1563. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1564. {"Bearer abc123", "abc123"},
  1565. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1566. };
  1567. for (const auto &c : cases) {
  1568. Request req;
  1569. req.set_header("Authorization", c.value);
  1570. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1571. }
  1572. }
  1573. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1574. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1575. // to depend on the standard library (libstdc++ handed back duplicates in
  1576. // reverse insertion order, libc++ in insertion order).
  1577. Request req;
  1578. req.set_header("Accept-Encoding", "gzip");
  1579. req.set_header("Accept-Encoding", "deflate");
  1580. req.set_header("Accept-Encoding", "br");
  1581. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1582. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1583. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1584. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1585. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1586. }
  1587. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1588. Request req;
  1589. req.set_header("X-Test", "only");
  1590. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1591. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1592. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1593. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1594. }
  1595. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1596. Headers headers;
  1597. headers.emplace("Host", "example.com");
  1598. headers.emplace("Accept-Encoding", "gzip");
  1599. headers.emplace("User-Agent", "test");
  1600. headers.emplace("Accept-Encoding", "deflate");
  1601. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1602. "Accept-Encoding=deflate ",
  1603. entries_to_string(headers));
  1604. }
  1605. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1606. Headers headers = {{"Content-Type", "text/html"},
  1607. {"CONTENT-TYPE", "text/xml"}};
  1608. EXPECT_EQ(2U, headers.count("content-type"));
  1609. auto it = headers.find("content-type");
  1610. ASSERT_TRUE(it != headers.end());
  1611. EXPECT_EQ("text/html", it->second);
  1612. }
  1613. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1614. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1615. // drop only those fields and leave everything positioned between them.
  1616. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1617. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1618. auto rng = headers.equal_range("a");
  1619. headers.erase(rng.first, rng.second);
  1620. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1621. }
  1622. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1623. Headers headers = {
  1624. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1625. EXPECT_EQ(3U, headers.erase("A"));
  1626. EXPECT_EQ(0U, headers.count("A"));
  1627. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1628. }
  1629. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1630. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1631. headers.emplace_front("Host", "example.com");
  1632. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1633. entries_to_string(headers));
  1634. }
  1635. TEST(ParseHeaderValueTest, Range) {
  1636. {
  1637. Ranges ranges;
  1638. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1639. EXPECT_TRUE(ret);
  1640. EXPECT_EQ(1u, ranges.size());
  1641. EXPECT_EQ(1u, ranges[0].first);
  1642. EXPECT_EQ(-1, ranges[0].second);
  1643. }
  1644. {
  1645. Ranges ranges;
  1646. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1647. EXPECT_TRUE(ret);
  1648. EXPECT_EQ(1u, ranges.size());
  1649. EXPECT_EQ(-1, ranges[0].first);
  1650. EXPECT_EQ(1u, ranges[0].second);
  1651. }
  1652. {
  1653. Ranges ranges;
  1654. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1655. EXPECT_TRUE(ret);
  1656. EXPECT_EQ(1u, ranges.size());
  1657. EXPECT_EQ(1u, ranges[0].first);
  1658. EXPECT_EQ(10u, ranges[0].second);
  1659. }
  1660. {
  1661. Ranges ranges;
  1662. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1663. EXPECT_FALSE(ret);
  1664. }
  1665. {
  1666. Ranges ranges;
  1667. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1668. EXPECT_TRUE(ret);
  1669. EXPECT_EQ(2u, ranges.size());
  1670. EXPECT_EQ(1u, ranges[0].first);
  1671. EXPECT_EQ(10u, ranges[0].second);
  1672. EXPECT_EQ(100u, ranges[1].first);
  1673. EXPECT_EQ(-1, ranges[1].second);
  1674. }
  1675. {
  1676. Ranges ranges;
  1677. auto ret =
  1678. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1679. EXPECT_TRUE(ret);
  1680. EXPECT_EQ(3u, ranges.size());
  1681. EXPECT_EQ(1u, ranges[0].first);
  1682. EXPECT_EQ(10u, ranges[0].second);
  1683. EXPECT_EQ(100u, ranges[1].first);
  1684. EXPECT_EQ(200u, ranges[1].second);
  1685. EXPECT_EQ(300u, ranges[2].first);
  1686. EXPECT_EQ(400u, ranges[2].second);
  1687. }
  1688. {
  1689. Ranges ranges;
  1690. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1691. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1692. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1693. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1694. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1695. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1696. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1697. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1698. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1699. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1700. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1701. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1702. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1703. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1704. EXPECT_FALSE(
  1705. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1706. EXPECT_TRUE(ranges.empty());
  1707. }
  1708. {
  1709. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1710. // remainder of the representation, so it stays accepted.
  1711. Ranges ranges;
  1712. auto ret =
  1713. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1714. EXPECT_TRUE(ret);
  1715. ASSERT_EQ(1u, ranges.size());
  1716. EXPECT_EQ(0, ranges[0].first);
  1717. EXPECT_EQ(-1, ranges[0].second);
  1718. }
  1719. }
  1720. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1721. Request req;
  1722. req.set_header("Accept-Encoding", "gzip");
  1723. Response res;
  1724. res.set_header("Content-Type", "text/plain");
  1725. auto ret = detail::encoding_type(req, res);
  1726. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1727. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1728. #else
  1729. EXPECT_TRUE(ret == detail::EncodingType::None);
  1730. #endif
  1731. }
  1732. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1733. Request req;
  1734. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1735. Response res;
  1736. res.set_header("Content-Type", "text/plain");
  1737. auto ret = detail::encoding_type(req, res);
  1738. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1739. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1740. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1741. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1742. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1743. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1744. #else
  1745. EXPECT_TRUE(ret == detail::EncodingType::None);
  1746. #endif
  1747. }
  1748. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1749. Request req;
  1750. req.set_header("Accept-Encoding",
  1751. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1752. Response res;
  1753. res.set_header("Content-Type", "text/plain");
  1754. auto ret = detail::encoding_type(req, res);
  1755. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1756. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1757. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1758. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1759. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1760. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1761. #else
  1762. EXPECT_TRUE(ret == detail::EncodingType::None);
  1763. #endif
  1764. }
  1765. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1766. // All supported encodings rejected with q=0 should return None
  1767. Request req;
  1768. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1769. Response res;
  1770. res.set_header("Content-Type", "text/plain");
  1771. auto ret = detail::encoding_type(req, res);
  1772. EXPECT_TRUE(ret == detail::EncodingType::None);
  1773. }
  1774. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1775. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1776. Request req;
  1777. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1778. Response res;
  1779. res.set_header("Content-Type", "text/plain");
  1780. auto ret = detail::encoding_type(req, res);
  1781. EXPECT_TRUE(ret == detail::EncodingType::None);
  1782. }
  1783. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  1784. Request req;
  1785. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  1786. Response res;
  1787. res.set_header("Content-Type", "text/plain");
  1788. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  1789. }
  1790. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1791. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1792. Request req;
  1793. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1794. Response res;
  1795. res.set_header("Content-Type", "text/plain");
  1796. auto ret = detail::encoding_type(req, res);
  1797. EXPECT_TRUE(ret == detail::EncodingType::None);
  1798. }
  1799. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1800. // RFC 7231: Accept-Encoding values are case-insensitive
  1801. Request req;
  1802. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1803. Response res;
  1804. res.set_header("Content-Type", "text/plain");
  1805. auto ret = detail::encoding_type(req, res);
  1806. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1807. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1808. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1809. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1810. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1811. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1812. #else
  1813. EXPECT_TRUE(ret == detail::EncodingType::None);
  1814. #endif
  1815. }
  1816. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1817. // q value should determine priority, not hardcoded order
  1818. Request req;
  1819. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1820. Response res;
  1821. res.set_header("Content-Type", "text/plain");
  1822. auto ret = detail::encoding_type(req, res);
  1823. // gzip has highest q=1.0, so it should be selected even though
  1824. // br and zstd are also supported
  1825. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1826. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1827. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1828. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1829. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1830. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1831. #else
  1832. EXPECT_TRUE(ret == detail::EncodingType::None);
  1833. #endif
  1834. }
  1835. TEST(BufferStreamTest, read) {
  1836. detail::BufferStream strm1;
  1837. Stream &strm = strm1;
  1838. EXPECT_EQ(5, strm.write("hello"));
  1839. char buf[512];
  1840. EXPECT_EQ(2, strm.read(buf, 2));
  1841. EXPECT_EQ('h', buf[0]);
  1842. EXPECT_EQ('e', buf[1]);
  1843. EXPECT_EQ(2, strm.read(buf, 2));
  1844. EXPECT_EQ('l', buf[0]);
  1845. EXPECT_EQ('l', buf[1]);
  1846. EXPECT_EQ(1, strm.read(buf, 1));
  1847. EXPECT_EQ('o', buf[0]);
  1848. EXPECT_EQ(0, strm.read(buf, 1));
  1849. }
  1850. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1851. auto host = "www.httpwatch.com";
  1852. auto ip = hosted_at(host);
  1853. EXPECT_EQ("23.96.13.243", ip);
  1854. std::vector<std::string> addrs;
  1855. hosted_at(host, addrs);
  1856. EXPECT_EQ(1u, addrs.size());
  1857. }
  1858. #if 0 // It depends on each test environment...
  1859. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1860. auto host = "www.youtube.com";
  1861. std::vector<std::string> addrs;
  1862. hosted_at(host, addrs);
  1863. EXPECT_EQ(20u, addrs.size());
  1864. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1865. EXPECT_TRUE(it != addrs.end());
  1866. }
  1867. #endif
  1868. class ChunkedEncodingTest : public ::testing::Test {
  1869. protected:
  1870. ChunkedEncodingTest()
  1871. : cli_(HOST, PORT)
  1872. #ifdef CPPHTTPLIB_SSL_ENABLED
  1873. ,
  1874. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1875. #endif
  1876. {
  1877. cli_.set_connection_timeout(2);
  1878. #ifdef CPPHTTPLIB_SSL_ENABLED
  1879. cli_.enable_server_certificate_verification(false);
  1880. #endif
  1881. }
  1882. virtual void SetUp() {
  1883. read_file("./image.jpg", image_data_);
  1884. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1885. res.set_content("Hello World!", "text/plain");
  1886. });
  1887. svr_.Get(
  1888. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1889. res.set_chunked_content_provider(
  1890. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1891. size_t remaining = image_data_.size() - offset;
  1892. if (remaining == 0) {
  1893. sink.done();
  1894. } else {
  1895. constexpr size_t CHUNK_SIZE = 1024;
  1896. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1897. sink.write(&image_data_[offset], send_size);
  1898. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1899. }
  1900. return true;
  1901. });
  1902. });
  1903. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1904. svr_.wait_until_ready();
  1905. }
  1906. virtual void TearDown() {
  1907. svr_.stop();
  1908. if (!request_threads_.empty()) {
  1909. std::this_thread::sleep_for(std::chrono::seconds(1));
  1910. for (auto &t : request_threads_) {
  1911. t.join();
  1912. }
  1913. }
  1914. t_.join();
  1915. }
  1916. #ifdef CPPHTTPLIB_SSL_ENABLED
  1917. SSLClient cli_;
  1918. SSLServer svr_;
  1919. #else
  1920. Client cli_;
  1921. Server svr_;
  1922. #endif
  1923. thread t_;
  1924. std::vector<thread> request_threads_;
  1925. std::string image_data_;
  1926. };
  1927. TEST_F(ChunkedEncodingTest, NormalGet) {
  1928. auto res = cli_.Get("/chunked");
  1929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1930. std::string out;
  1931. read_file("./image.jpg", out);
  1932. EXPECT_EQ(StatusCode::OK_200, res->status);
  1933. EXPECT_EQ(out, res->body);
  1934. }
  1935. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1936. std::string body;
  1937. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1938. body.append(data, data_length);
  1939. return true;
  1940. });
  1941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1942. std::string out;
  1943. read_file("./image.jpg", out);
  1944. EXPECT_EQ(StatusCode::OK_200, res->status);
  1945. EXPECT_EQ(out, body);
  1946. }
  1947. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1948. std::string body;
  1949. auto res = cli_.Get(
  1950. "/chunked",
  1951. [&](const Response &response) {
  1952. EXPECT_EQ(StatusCode::OK_200, response.status);
  1953. return true;
  1954. },
  1955. [&](const char *data, size_t data_length) {
  1956. body.append(data, data_length);
  1957. return true;
  1958. });
  1959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1960. std::string out;
  1961. read_file("./image.jpg", out);
  1962. EXPECT_EQ(StatusCode::OK_200, res->status);
  1963. EXPECT_EQ(out, body);
  1964. }
  1965. TEST(RangeTest, FromHTTPBin_Online) {
  1966. auto host = "httpbingo.org";
  1967. auto path = std::string{"/range/32"};
  1968. #ifdef CPPHTTPLIB_SSL_ENABLED
  1969. auto port = 443;
  1970. SSLClient cli(host, port);
  1971. #else
  1972. auto port = 80;
  1973. Client cli(host, port);
  1974. #endif
  1975. cli.set_connection_timeout(5);
  1976. {
  1977. auto res = cli.Get(path);
  1978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1979. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1980. EXPECT_EQ(StatusCode::OK_200, res->status);
  1981. }
  1982. {
  1983. Headers headers = {make_range_header({{1, -1}})};
  1984. auto res = cli.Get(path, headers);
  1985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1986. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1987. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1988. }
  1989. {
  1990. Headers headers = {make_range_header({{1, 10}})};
  1991. auto res = cli.Get(path, headers);
  1992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1993. EXPECT_EQ("bcdefghijk", res->body);
  1994. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1995. }
  1996. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1997. // entire resource, while the original httpbin returned 200. Both are
  1998. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1999. {
  2000. Headers headers = {make_range_header({{0, 31}})};
  2001. auto res = cli.Get(path, headers);
  2002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2003. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2004. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2005. res->status == StatusCode::PartialContent_206);
  2006. }
  2007. {
  2008. Headers headers = {make_range_header({{0, -1}})};
  2009. auto res = cli.Get(path, headers);
  2010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2011. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2012. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2013. res->status == StatusCode::PartialContent_206);
  2014. }
  2015. // go-httpbin returns 206 with clamped range for over-range requests,
  2016. // while the original httpbin returned 416. Both behaviors are observed
  2017. // in real servers, so we only verify the request succeeds.
  2018. {
  2019. Headers headers = {make_range_header({{0, 32}})};
  2020. auto res = cli.Get(path, headers);
  2021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2022. }
  2023. }
  2024. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2025. auto host = "unresolvableaddress.local";
  2026. auto path = std::string{"/"};
  2027. #ifdef CPPHTTPLIB_SSL_ENABLED
  2028. auto port = 443;
  2029. SSLClient cli(host, port);
  2030. #else
  2031. auto port = 80;
  2032. Client cli(host, port);
  2033. #endif
  2034. cli.set_connection_timeout(1);
  2035. {
  2036. auto res = cli.Get(path);
  2037. ASSERT_FALSE(res);
  2038. }
  2039. std::this_thread::sleep_for(std::chrono::seconds(8));
  2040. }
  2041. #if defined(__linux__) && defined(__GLIBC__) && \
  2042. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2043. // Forward declaration: in split builds split.py strips `inline` and moves the
  2044. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2045. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2046. // against the symbol in both header-only and split builds.
  2047. namespace httplib {
  2048. namespace detail {
  2049. int getaddrinfo_with_timeout(const char *node, const char *service,
  2050. const struct addrinfo *hints,
  2051. struct addrinfo **res, time_t timeout_sec);
  2052. } // namespace detail
  2053. } // namespace httplib
  2054. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2055. //
  2056. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2057. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2058. // gai_suspend() call hits the connection timeout the function calls
  2059. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2060. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2061. // still alive and still references the now-destroyed stack frame.
  2062. //
  2063. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2064. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2065. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2066. // and runs them in a container.
  2067. namespace {
  2068. bool should_run_issue_2431_tests() {
  2069. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2070. return v && *v && std::string(v) != "0";
  2071. }
  2072. std::string unique_unresolvable_host(int n) {
  2073. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2074. // glibc still asks the configured nameserver — which is exactly the path
  2075. // we want to exercise. A unique label per call avoids the resolver cache.
  2076. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2077. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2078. std::to_string(n) + ".invalid";
  2079. }
  2080. } // namespace
  2081. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2082. if (!should_run_issue_2431_tests()) {
  2083. GTEST_SKIP()
  2084. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2085. }
  2086. for (int i = 0; i < 8; ++i) {
  2087. struct addrinfo hints;
  2088. memset(&hints, 0, sizeof(hints));
  2089. hints.ai_family = AF_UNSPEC;
  2090. hints.ai_socktype = SOCK_STREAM;
  2091. auto host = unique_unresolvable_host(i);
  2092. struct addrinfo *result = nullptr;
  2093. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2094. &result, /*timeout_sec=*/1);
  2095. if (rc == 0 && result) { freeaddrinfo(result); }
  2096. }
  2097. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2098. // stack region they still believe holds their gaicb.
  2099. std::this_thread::sleep_for(std::chrono::seconds(3));
  2100. }
  2101. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2102. if (!should_run_issue_2431_tests()) {
  2103. GTEST_SKIP()
  2104. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2105. }
  2106. std::atomic<bool> stop{false};
  2107. std::vector<std::thread> threads;
  2108. for (int t = 0; t < 8; ++t) {
  2109. threads.emplace_back([t, &stop] {
  2110. int i = 0;
  2111. while (!stop.load(std::memory_order_relaxed)) {
  2112. struct addrinfo hints;
  2113. memset(&hints, 0, sizeof(hints));
  2114. hints.ai_family = AF_UNSPEC;
  2115. hints.ai_socktype = SOCK_STREAM;
  2116. auto host = unique_unresolvable_host(t * 100000 + i++);
  2117. struct addrinfo *result = nullptr;
  2118. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2119. &result, /*timeout_sec=*/1);
  2120. if (rc == 0 && result) { freeaddrinfo(result); }
  2121. }
  2122. });
  2123. }
  2124. std::this_thread::sleep_for(std::chrono::seconds(8));
  2125. stop.store(true, std::memory_order_relaxed);
  2126. for (auto &th : threads) {
  2127. th.join();
  2128. }
  2129. std::this_thread::sleep_for(std::chrono::seconds(3));
  2130. }
  2131. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2132. if (!should_run_issue_2431_tests()) {
  2133. GTEST_SKIP()
  2134. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2135. }
  2136. std::atomic<bool> stop{false};
  2137. std::vector<std::thread> threads;
  2138. for (int t = 0; t < 8; ++t) {
  2139. threads.emplace_back([t, &stop] {
  2140. int i = 0;
  2141. while (!stop.load(std::memory_order_relaxed)) {
  2142. auto host = unique_unresolvable_host(t * 100000 + i++);
  2143. Client cli(host, 80);
  2144. cli.set_connection_timeout(1, 0);
  2145. cli.set_read_timeout(1, 0);
  2146. cli.set_write_timeout(1, 0);
  2147. (void)cli.Get("/");
  2148. }
  2149. });
  2150. }
  2151. std::this_thread::sleep_for(std::chrono::seconds(8));
  2152. stop.store(true, std::memory_order_relaxed);
  2153. for (auto &th : threads) {
  2154. th.join();
  2155. }
  2156. std::this_thread::sleep_for(std::chrono::seconds(3));
  2157. }
  2158. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2159. TEST(ConnectionErrorTest, InvalidHost) {
  2160. auto host = "-abcde.com";
  2161. #ifdef CPPHTTPLIB_SSL_ENABLED
  2162. auto port = 443;
  2163. SSLClient cli(host, port);
  2164. #else
  2165. auto port = 80;
  2166. Client cli(host, port);
  2167. #endif
  2168. cli.set_connection_timeout(std::chrono::seconds(2));
  2169. auto res = cli.Get("/");
  2170. ASSERT_TRUE(!res);
  2171. EXPECT_EQ(Error::Connection, res.error());
  2172. }
  2173. TEST(ConnectionErrorTest, InvalidHost2) {
  2174. auto host = "httpcan.org/";
  2175. #ifdef CPPHTTPLIB_SSL_ENABLED
  2176. SSLClient cli(host);
  2177. #else
  2178. Client cli(host);
  2179. #endif
  2180. cli.set_connection_timeout(std::chrono::seconds(2));
  2181. auto res = cli.Get("/");
  2182. ASSERT_TRUE(!res);
  2183. EXPECT_EQ(Error::Connection, res.error());
  2184. }
  2185. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2186. auto host = "httpcan.org/";
  2187. #ifdef CPPHTTPLIB_SSL_ENABLED
  2188. SSLClient cli(host);
  2189. #else
  2190. Client cli(host);
  2191. #endif
  2192. cli.set_connection_timeout(std::chrono::seconds(2));
  2193. auto res = cli.Get("/");
  2194. ASSERT_TRUE(!res);
  2195. stringstream s;
  2196. s << "error code: " << res.error();
  2197. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2198. }
  2199. TEST(ConnectionErrorTest, InvalidPort) {
  2200. auto host = "localhost";
  2201. auto port = 44380;
  2202. #ifdef CPPHTTPLIB_SSL_ENABLED
  2203. SSLClient cli(host, port);
  2204. #else
  2205. Client cli(host, port);
  2206. #endif
  2207. cli.set_connection_timeout(std::chrono::seconds(2));
  2208. auto res = cli.Get("/");
  2209. ASSERT_TRUE(!res);
  2210. EXPECT_TRUE(Error::Connection == res.error() ||
  2211. Error::ConnectionTimeout == res.error());
  2212. }
  2213. TEST(ConnectionErrorTest, Timeout_Online) {
  2214. auto host = "google.com";
  2215. #ifdef CPPHTTPLIB_SSL_ENABLED
  2216. auto port = 44380;
  2217. SSLClient cli(host, port);
  2218. #else
  2219. auto port = 8080;
  2220. Client cli(host, port);
  2221. #endif
  2222. cli.set_connection_timeout(std::chrono::seconds(2));
  2223. // only probe one address type so that the error reason
  2224. // correlates to the timed-out IPv4, not the unsupported
  2225. // IPv6 connection attempt
  2226. cli.set_address_family(AF_INET);
  2227. auto res = cli.Get("/");
  2228. ASSERT_TRUE(!res);
  2229. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2230. }
  2231. TEST(CancelTest, NoCancel_Online) {
  2232. auto host = "httpbingo.org";
  2233. auto path = std::string{"/range/32"};
  2234. #ifdef CPPHTTPLIB_SSL_ENABLED
  2235. auto port = 443;
  2236. SSLClient cli(host, port);
  2237. #else
  2238. auto port = 80;
  2239. Client cli(host, port);
  2240. #endif
  2241. cli.set_connection_timeout(std::chrono::seconds(5));
  2242. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2244. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2245. EXPECT_EQ(StatusCode::OK_200, res->status);
  2246. }
  2247. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2248. // Use /bytes with a large payload so that the DownloadProgress callback
  2249. // (which only fires for Content-Length responses) is invoked before the
  2250. // entire body is received, giving cancellation a chance to fire.
  2251. auto host = "httpbingo.org";
  2252. auto path = std::string{"/bytes/524288"};
  2253. #ifdef CPPHTTPLIB_SSL_ENABLED
  2254. auto port = 443;
  2255. SSLClient cli(host, port);
  2256. #else
  2257. auto port = 80;
  2258. Client cli(host, port);
  2259. #endif
  2260. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2261. cli.set_connection_timeout(std::chrono::seconds(5));
  2262. ASSERT_TRUE(!res);
  2263. EXPECT_EQ(Error::Canceled, res.error());
  2264. }
  2265. TEST(CancelTest, WithCancelLargePayload_Online) {
  2266. auto host = "httpbingo.org";
  2267. auto path = std::string{"/bytes/524288"};
  2268. #ifdef CPPHTTPLIB_SSL_ENABLED
  2269. auto port = 443;
  2270. SSLClient cli(host, port);
  2271. #else
  2272. auto port = 80;
  2273. Client cli(host, port);
  2274. #endif
  2275. cli.set_connection_timeout(std::chrono::seconds(5));
  2276. uint32_t count = 0;
  2277. auto res =
  2278. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2279. ASSERT_TRUE(!res);
  2280. EXPECT_EQ(Error::Canceled, res.error());
  2281. }
  2282. TEST(CancelTest, NoCancelPost) {
  2283. Server svr;
  2284. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2285. res.set_content("Hello World!", "text/plain");
  2286. });
  2287. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2288. auto se = detail::scope_exit([&] {
  2289. svr.stop();
  2290. thread.join();
  2291. ASSERT_FALSE(svr.is_running());
  2292. });
  2293. svr.wait_until_ready();
  2294. Client cli(HOST, PORT);
  2295. cli.set_connection_timeout(std::chrono::seconds(5));
  2296. auto res =
  2297. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2298. "application/json", [](uint64_t, uint64_t) { return true; });
  2299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2300. EXPECT_EQ("Hello World!", res->body);
  2301. EXPECT_EQ(StatusCode::OK_200, res->status);
  2302. }
  2303. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2304. Server svr;
  2305. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2306. res.set_content("Hello World!", "text/plain");
  2307. });
  2308. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2309. auto se = detail::scope_exit([&] {
  2310. svr.stop();
  2311. thread.join();
  2312. ASSERT_FALSE(svr.is_running());
  2313. });
  2314. svr.wait_until_ready();
  2315. Client cli(HOST, PORT);
  2316. cli.set_connection_timeout(std::chrono::seconds(5));
  2317. auto res =
  2318. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2319. "application/json", [](uint64_t, uint64_t) { return false; });
  2320. ASSERT_TRUE(!res);
  2321. EXPECT_EQ(Error::Canceled, res.error());
  2322. }
  2323. TEST(CancelTest, WithCancelLargePayloadPost) {
  2324. Server svr;
  2325. svr.set_payload_max_length(200 * 1024 * 1024);
  2326. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2327. res.set_content(LARGE_DATA, "text/plain");
  2328. });
  2329. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2330. auto se = detail::scope_exit([&] {
  2331. svr.stop();
  2332. thread.join();
  2333. ASSERT_FALSE(svr.is_running());
  2334. });
  2335. svr.wait_until_ready();
  2336. Client cli(HOST, PORT);
  2337. cli.set_payload_max_length(200 * 1024 * 1024);
  2338. cli.set_connection_timeout(std::chrono::seconds(5));
  2339. auto res =
  2340. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2341. "application/json", [](uint64_t, uint64_t) { return false; });
  2342. ASSERT_TRUE(!res);
  2343. EXPECT_EQ(Error::Canceled, res.error());
  2344. }
  2345. TEST(CancelTest, NoCancelPut) {
  2346. Server svr;
  2347. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2348. res.set_content("Hello World!", "text/plain");
  2349. });
  2350. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2351. auto se = detail::scope_exit([&] {
  2352. svr.stop();
  2353. thread.join();
  2354. ASSERT_FALSE(svr.is_running());
  2355. });
  2356. svr.wait_until_ready();
  2357. Client cli(HOST, PORT);
  2358. cli.set_connection_timeout(std::chrono::seconds(5));
  2359. auto res =
  2360. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2361. "application/json", [](uint64_t, uint64_t) { return true; });
  2362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2363. EXPECT_EQ("Hello World!", res->body);
  2364. EXPECT_EQ(StatusCode::OK_200, res->status);
  2365. }
  2366. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2367. Server svr;
  2368. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2369. res.set_content("Hello World!", "text/plain");
  2370. });
  2371. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2372. auto se = detail::scope_exit([&] {
  2373. svr.stop();
  2374. thread.join();
  2375. ASSERT_FALSE(svr.is_running());
  2376. });
  2377. svr.wait_until_ready();
  2378. Client cli(HOST, PORT);
  2379. cli.set_connection_timeout(std::chrono::seconds(5));
  2380. auto res =
  2381. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2382. "application/json", [](uint64_t, uint64_t) { return false; });
  2383. ASSERT_TRUE(!res);
  2384. EXPECT_EQ(Error::Canceled, res.error());
  2385. }
  2386. TEST(CancelTest, WithCancelLargePayloadPut) {
  2387. Server svr;
  2388. svr.set_payload_max_length(200 * 1024 * 1024);
  2389. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2390. res.set_content(LARGE_DATA, "text/plain");
  2391. });
  2392. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2393. auto se = detail::scope_exit([&] {
  2394. svr.stop();
  2395. thread.join();
  2396. ASSERT_FALSE(svr.is_running());
  2397. });
  2398. svr.wait_until_ready();
  2399. Client cli(HOST, PORT);
  2400. cli.set_payload_max_length(200 * 1024 * 1024);
  2401. cli.set_connection_timeout(std::chrono::seconds(5));
  2402. auto res =
  2403. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2404. "application/json", [](uint64_t, uint64_t) { return false; });
  2405. ASSERT_TRUE(!res);
  2406. EXPECT_EQ(Error::Canceled, res.error());
  2407. }
  2408. TEST(CancelTest, NoCancelPatch) {
  2409. Server svr;
  2410. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2411. res.set_content("Hello World!", "text/plain");
  2412. });
  2413. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2414. auto se = detail::scope_exit([&] {
  2415. svr.stop();
  2416. thread.join();
  2417. ASSERT_FALSE(svr.is_running());
  2418. });
  2419. svr.wait_until_ready();
  2420. Client cli(HOST, PORT);
  2421. cli.set_connection_timeout(std::chrono::seconds(5));
  2422. auto res =
  2423. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2424. "application/json", [](uint64_t, uint64_t) { return true; });
  2425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2426. EXPECT_EQ("Hello World!", res->body);
  2427. EXPECT_EQ(StatusCode::OK_200, res->status);
  2428. }
  2429. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2430. Server svr;
  2431. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2432. res.set_content("Hello World!", "text/plain");
  2433. });
  2434. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2435. auto se = detail::scope_exit([&] {
  2436. svr.stop();
  2437. thread.join();
  2438. ASSERT_FALSE(svr.is_running());
  2439. });
  2440. svr.wait_until_ready();
  2441. Client cli(HOST, PORT);
  2442. cli.set_connection_timeout(std::chrono::seconds(5));
  2443. auto res =
  2444. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2445. "application/json", [](uint64_t, uint64_t) { return false; });
  2446. ASSERT_TRUE(!res);
  2447. EXPECT_EQ(Error::Canceled, res.error());
  2448. }
  2449. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2450. Server svr;
  2451. svr.set_payload_max_length(200 * 1024 * 1024);
  2452. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2453. res.set_content(LARGE_DATA, "text/plain");
  2454. });
  2455. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2456. auto se = detail::scope_exit([&] {
  2457. svr.stop();
  2458. thread.join();
  2459. ASSERT_FALSE(svr.is_running());
  2460. });
  2461. svr.wait_until_ready();
  2462. Client cli(HOST, PORT);
  2463. cli.set_payload_max_length(200 * 1024 * 1024);
  2464. cli.set_connection_timeout(std::chrono::seconds(5));
  2465. auto res =
  2466. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2467. "application/json", [](uint64_t, uint64_t) { return false; });
  2468. ASSERT_TRUE(!res);
  2469. EXPECT_EQ(Error::Canceled, res.error());
  2470. }
  2471. TEST(CancelTest, NoCancelDelete) {
  2472. Server svr;
  2473. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2474. res.set_content("Hello World!", "text/plain");
  2475. });
  2476. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2477. auto se = detail::scope_exit([&] {
  2478. svr.stop();
  2479. thread.join();
  2480. ASSERT_FALSE(svr.is_running());
  2481. });
  2482. svr.wait_until_ready();
  2483. Client cli(HOST, PORT);
  2484. cli.set_connection_timeout(std::chrono::seconds(5));
  2485. auto res =
  2486. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2487. "application/json", [](uint64_t, uint64_t) { return true; });
  2488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2489. EXPECT_EQ("Hello World!", res->body);
  2490. EXPECT_EQ(StatusCode::OK_200, res->status);
  2491. }
  2492. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2493. Server svr;
  2494. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2495. res.set_content("Hello World!", "text/plain");
  2496. });
  2497. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2498. auto se = detail::scope_exit([&] {
  2499. svr.stop();
  2500. thread.join();
  2501. ASSERT_FALSE(svr.is_running());
  2502. });
  2503. svr.wait_until_ready();
  2504. Client cli(HOST, PORT);
  2505. cli.set_connection_timeout(std::chrono::seconds(5));
  2506. auto res =
  2507. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2508. "application/json", [](uint64_t, uint64_t) { return false; });
  2509. ASSERT_TRUE(!res);
  2510. EXPECT_EQ(Error::Canceled, res.error());
  2511. }
  2512. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2513. Server svr;
  2514. svr.set_payload_max_length(200 * 1024 * 1024);
  2515. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2516. res.set_content(LARGE_DATA, "text/plain");
  2517. });
  2518. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2519. auto se = detail::scope_exit([&] {
  2520. svr.stop();
  2521. thread.join();
  2522. ASSERT_FALSE(svr.is_running());
  2523. });
  2524. svr.wait_until_ready();
  2525. Client cli(HOST, PORT);
  2526. cli.set_payload_max_length(200 * 1024 * 1024);
  2527. cli.set_connection_timeout(std::chrono::seconds(5));
  2528. auto res =
  2529. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2530. "application/json", [](uint64_t, uint64_t) { return false; });
  2531. ASSERT_TRUE(!res);
  2532. EXPECT_EQ(Error::Canceled, res.error());
  2533. }
  2534. static std::string remove_whitespace(const std::string &input) {
  2535. std::string output;
  2536. output.reserve(input.size());
  2537. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2538. [](unsigned char c) { return !std::isspace(c); });
  2539. return output;
  2540. }
  2541. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2542. auto host = "httpbingo.org";
  2543. auto path = std::string{"/basic-auth/hello/world"};
  2544. #ifdef CPPHTTPLIB_SSL_ENABLED
  2545. auto port = 443;
  2546. SSLClient cli(host, port);
  2547. #else
  2548. auto port = 80;
  2549. Client cli(host, port);
  2550. #endif
  2551. {
  2552. auto res = cli.Get(path);
  2553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2554. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2555. }
  2556. {
  2557. auto res = cli.Get(
  2558. path, Headers{make_basic_authentication_header("hello", "world")});
  2559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2560. auto body = remove_whitespace(res->body);
  2561. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2562. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2563. EXPECT_EQ(StatusCode::OK_200, res->status);
  2564. }
  2565. {
  2566. cli.set_basic_auth("hello", "world");
  2567. auto res = cli.Get(path);
  2568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2569. auto body = remove_whitespace(res->body);
  2570. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2571. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2572. EXPECT_EQ(StatusCode::OK_200, res->status);
  2573. }
  2574. {
  2575. cli.set_basic_auth("hello", "bad");
  2576. auto res = cli.Get(path);
  2577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2578. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2579. }
  2580. {
  2581. cli.set_basic_auth("bad", "world");
  2582. auto res = cli.Get(path);
  2583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2584. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2585. }
  2586. }
  2587. #ifdef CPPHTTPLIB_SSL_ENABLED
  2588. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2589. auto host = "httpbingo.org";
  2590. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2591. auto paths = std::vector<std::string>{
  2592. "/digest-auth/auth/hello/world/MD5",
  2593. "/digest-auth/auth/hello/world/SHA-256",
  2594. };
  2595. auto port = 443;
  2596. SSLClient cli(host, port);
  2597. {
  2598. auto res = cli.Get(unauth_path);
  2599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2600. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2601. }
  2602. {
  2603. cli.set_digest_auth("hello", "world");
  2604. for (const auto &path : paths) {
  2605. auto res = cli.Get(path.c_str());
  2606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2607. auto body = remove_whitespace(res->body);
  2608. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2609. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2610. EXPECT_EQ(StatusCode::OK_200, res->status);
  2611. }
  2612. cli.set_digest_auth("hello", "bad");
  2613. for (const auto &path : paths) {
  2614. auto res = cli.Get(path.c_str());
  2615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2616. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2617. }
  2618. }
  2619. }
  2620. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2621. // comma-separated list of challenges, and each challenge may itself carry a
  2622. // comma-separated auth-param list, so a server can legally offer Basic
  2623. // before Digest, either as two field lines or packed into one. Runs one 401
  2624. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2625. // value() joins them in receipt order) and checks that the retry carries a
  2626. // well-formed Digest Authorization header naming expected_realm.
  2627. static void
  2628. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2629. const std::string &expected_realm) {
  2630. std::atomic<int> hits{0};
  2631. Server svr;
  2632. svr.Get("/x", [&](const Request &req, Response &res) {
  2633. if (++hits == 1) {
  2634. res.status = StatusCode::Unauthorized_401;
  2635. for (const auto &challenge : challenges) {
  2636. res.set_header("WWW-Authenticate", challenge);
  2637. }
  2638. } else {
  2639. auto authorization = req.get_header_value("Authorization");
  2640. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2641. EXPECT_NE(std::string::npos,
  2642. authorization.find("realm=\"" + expected_realm + "\""));
  2643. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2644. res.set_content("ok", "text/plain");
  2645. }
  2646. });
  2647. auto port = svr.bind_to_any_port(HOST);
  2648. std::thread t([&]() { svr.listen_after_bind(); });
  2649. auto se = detail::scope_exit([&] {
  2650. svr.stop();
  2651. t.join();
  2652. });
  2653. svr.wait_until_ready();
  2654. Client cli(HOST, port);
  2655. cli.set_digest_auth("hello", "world");
  2656. auto res = cli.Get("/x");
  2657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2658. EXPECT_EQ(2, hits.load());
  2659. }
  2660. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2661. static const char *kDigestChallenge =
  2662. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2663. "algorithm=MD5";
  2664. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2665. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2666. "testrealm");
  2667. }
  2668. // Same challenge list with the schemes in the opposite order, to make sure
  2669. // the fix above didn't just special-case "Basic first".
  2670. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2671. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2672. "testrealm");
  2673. }
  2674. // A comma inside a quoted auth-param value must not be mistaken for the
  2675. // separator between two challenges (or two auth-params).
  2676. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2677. run_digest_challenge_list_test(
  2678. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2679. "algorithm=MD5"},
  2680. "test,realm");
  2681. }
  2682. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2683. // make_digest_authentication_header() dereferences both unconditionally, so
  2684. // a server sending a challenge missing either one must not be treated as
  2685. // usable -- doing so used to crash the client with std::out_of_range.
  2686. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2687. Server svr;
  2688. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2689. res.status = StatusCode::Unauthorized_401;
  2690. res.set_header("WWW-Authenticate", challenge);
  2691. });
  2692. auto port = svr.bind_to_any_port(HOST);
  2693. std::thread t([&]() { svr.listen_after_bind(); });
  2694. auto se = detail::scope_exit([&] {
  2695. svr.stop();
  2696. t.join();
  2697. });
  2698. svr.wait_until_ready();
  2699. Client cli(HOST, port);
  2700. cli.set_digest_auth("hello", "world");
  2701. auto res = cli.Get("/x");
  2702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2703. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2704. }
  2705. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2706. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2707. }
  2708. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2709. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2710. }
  2711. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2712. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2713. }
  2714. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  2715. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  2716. // when storing the values, so the header builder has to re-escape them (and
  2717. // keep algorithm a bare token); otherwise the value breaks out of its
  2718. // quoted-string and injects extra auth-params into the client's Authorization.
  2719. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  2720. std::atomic<int> hits{0};
  2721. std::string authorization;
  2722. Server svr;
  2723. svr.Get("/x", [&](const Request &req, Response &res) {
  2724. if (++hits == 1) {
  2725. res.status = StatusCode::Unauthorized_401;
  2726. // On the wire the quotes embedded in the values are backslash-escaped.
  2727. res.set_header("WWW-Authenticate",
  2728. "Digest realm=\"testrealm\", "
  2729. "nonce=\"n\\\"; injected=\\\"x\", "
  2730. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  2731. } else {
  2732. authorization = req.get_header_value("Authorization");
  2733. res.set_content("ok", "text/plain");
  2734. }
  2735. });
  2736. auto port = svr.bind_to_any_port(HOST);
  2737. std::thread t([&]() { svr.listen_after_bind(); });
  2738. auto se = detail::scope_exit([&] {
  2739. svr.stop();
  2740. t.join();
  2741. });
  2742. svr.wait_until_ready();
  2743. Client cli(HOST, port);
  2744. cli.set_digest_auth("hello", "world");
  2745. auto res = cli.Get("/x");
  2746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2747. EXPECT_EQ(2, hits.load());
  2748. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2749. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  2750. // inside its quoted-string rather than starting an "injected" auth-param.
  2751. EXPECT_NE(std::string::npos,
  2752. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  2753. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  2754. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  2755. }
  2756. #endif
  2757. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2758. auto host = "google.com";
  2759. auto another_host = "example.com";
  2760. auto wrong_ip = "0.0.0.0";
  2761. #ifdef CPPHTTPLIB_SSL_ENABLED
  2762. SSLClient cli(host);
  2763. #else
  2764. Client cli(host);
  2765. #endif
  2766. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2767. auto res = cli.Get("/");
  2768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2769. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2770. }
  2771. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2772. auto host = "google.com";
  2773. auto wrong_ip = "0.0.0.0";
  2774. #ifdef CPPHTTPLIB_SSL_ENABLED
  2775. SSLClient cli(host);
  2776. #else
  2777. Client cli(host);
  2778. #endif
  2779. cli.set_hostname_addr_map({{host, wrong_ip}});
  2780. auto res = cli.Get("/");
  2781. ASSERT_TRUE(!res);
  2782. EXPECT_EQ(Error::Connection, res.error());
  2783. }
  2784. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2785. // A mapped value that is not an IP literal must be resolved. "localhost"
  2786. // resolves from the hosts file, so this test needs no external DNS.
  2787. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2788. auto host = "target.invalid";
  2789. Server svr;
  2790. std::string received_host;
  2791. svr.Get("/hi", [&](const Request &req, Response &res) {
  2792. received_host = req.get_header_value("Host");
  2793. res.set_content("Hello World!", "text/plain");
  2794. });
  2795. auto port = svr.bind_to_any_port(HOST);
  2796. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2797. auto se = detail::scope_exit([&] {
  2798. svr.stop();
  2799. thread.join();
  2800. ASSERT_FALSE(svr.is_running());
  2801. });
  2802. svr.wait_until_ready();
  2803. Client cli(host, port);
  2804. cli.set_hostname_addr_map({{host, HOST}});
  2805. auto res = cli.Get("/hi");
  2806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2807. EXPECT_EQ(StatusCode::OK_200, res->status);
  2808. // The mapping only redirects the connection; the identity stays host_.
  2809. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2810. }
  2811. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2812. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2813. auto host = "target.invalid";
  2814. Server svr;
  2815. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2816. res.set_content("Hello World!", "text/plain");
  2817. });
  2818. auto port = svr.bind_to_any_port("127.0.0.1");
  2819. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2820. auto se = detail::scope_exit([&] {
  2821. svr.stop();
  2822. thread.join();
  2823. ASSERT_FALSE(svr.is_running());
  2824. });
  2825. svr.wait_until_ready();
  2826. Client cli(host, port);
  2827. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2828. auto res = cli.Get("/hi");
  2829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2830. EXPECT_EQ(StatusCode::OK_200, res->status);
  2831. }
  2832. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2833. // An empty mapped value must leave host_ as the connection target. Without
  2834. // that guard the empty value would become the host argument, getaddrinfo
  2835. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2836. // loopback - silently connecting somewhere the caller never asked for.
  2837. // The server listens on loopback, so such a fallback would succeed and is
  2838. // therefore observable as a failure of this test.
  2839. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2840. Server svr;
  2841. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2842. res.set_content("Hello World!", "text/plain");
  2843. });
  2844. auto port = svr.bind_to_any_port(HOST);
  2845. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2846. auto se = detail::scope_exit([&] {
  2847. svr.stop();
  2848. thread.join();
  2849. ASSERT_FALSE(svr.is_running());
  2850. });
  2851. svr.wait_until_ready();
  2852. Client cli(blackhole, port);
  2853. cli.set_hostname_addr_map({{blackhole, ""}});
  2854. cli.set_connection_timeout(1);
  2855. auto res = cli.Get("/hi");
  2856. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2857. }
  2858. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2859. auto host = "httpbingo.org";
  2860. auto path = std::string{"/absolute-redirect/3"};
  2861. #ifdef CPPHTTPLIB_SSL_ENABLED
  2862. SSLClient cli(host);
  2863. #else
  2864. Client cli(host);
  2865. #endif
  2866. cli.set_follow_location(true);
  2867. auto res = cli.Get(path);
  2868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2869. EXPECT_EQ(StatusCode::OK_200, res->status);
  2870. }
  2871. TEST(RedirectTest, Redirect_Online) {
  2872. auto host = "httpbingo.org";
  2873. auto path = std::string{"/redirect/3"};
  2874. #ifdef CPPHTTPLIB_SSL_ENABLED
  2875. SSLClient cli(host);
  2876. #else
  2877. Client cli(host);
  2878. #endif
  2879. cli.set_follow_location(true);
  2880. auto res = cli.Get(path);
  2881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2882. EXPECT_EQ(StatusCode::OK_200, res->status);
  2883. }
  2884. TEST(RelativeRedirectTest, Redirect_Online) {
  2885. auto host = "httpbingo.org";
  2886. auto path = std::string{"/relative-redirect/3"};
  2887. #ifdef CPPHTTPLIB_SSL_ENABLED
  2888. SSLClient cli(host);
  2889. #else
  2890. Client cli(host);
  2891. #endif
  2892. cli.set_follow_location(true);
  2893. auto res = cli.Get(path);
  2894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2895. EXPECT_EQ(StatusCode::OK_200, res->status);
  2896. }
  2897. TEST(TooManyRedirectTest, Redirect_Online) {
  2898. auto host = "httpbingo.org";
  2899. auto path = std::string{"/redirect/21"};
  2900. #ifdef CPPHTTPLIB_SSL_ENABLED
  2901. SSLClient cli(host);
  2902. #else
  2903. Client cli(host);
  2904. #endif
  2905. cli.set_follow_location(true);
  2906. auto res = cli.Get(path);
  2907. ASSERT_TRUE(!res);
  2908. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2909. }
  2910. #ifdef CPPHTTPLIB_SSL_ENABLED
  2911. TEST(YahooRedirectTest, Redirect_Online) {
  2912. Client cli("yahoo.com");
  2913. auto res = cli.Get("/");
  2914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2915. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2916. cli.set_follow_location(true);
  2917. res = cli.Get("/");
  2918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2919. EXPECT_EQ(StatusCode::OK_200, res->status);
  2920. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2921. }
  2922. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2923. #define REDIR_HOST "httpbingo.org"
  2924. #define REDIR_PATH "/redirect-to"
  2925. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2926. SSLClient cli(REDIR_HOST);
  2927. cli.set_follow_location(true);
  2928. auto res =
  2929. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2931. EXPECT_EQ(StatusCode::OK_200, res->status);
  2932. }
  2933. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2934. SSLClient cli(REDIR_HOST);
  2935. cli.set_follow_location(true);
  2936. Params params;
  2937. params.emplace("url", "http://example.com");
  2938. params.emplace("status_code", "302");
  2939. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2941. EXPECT_EQ(StatusCode::OK_200, res->status);
  2942. }
  2943. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2944. SSLClient cli(REDIR_HOST);
  2945. cli.set_follow_location(true);
  2946. Params params;
  2947. params.emplace("url", "http://example.com");
  2948. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2950. EXPECT_EQ(StatusCode::OK_200, res->status);
  2951. }
  2952. TEST(UrlWithSpace, Redirect_Online) {
  2953. SSLClient cli("edge.forgecdn.net");
  2954. cli.set_follow_location(true);
  2955. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2957. EXPECT_EQ(StatusCode::OK_200, res->status);
  2958. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2959. }
  2960. #endif
  2961. #if !defined(_WIN32) && !defined(_WIN64)
  2962. TEST(ReceiveSignals, Signal) {
  2963. auto setupSignalHandlers = []() {
  2964. struct sigaction act;
  2965. sigemptyset(&act.sa_mask);
  2966. act.sa_flags = SA_SIGINFO;
  2967. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2968. switch (sig) {
  2969. case SIGINT:
  2970. default: break;
  2971. }
  2972. };
  2973. ::sigaction(SIGINT, &act, nullptr);
  2974. };
  2975. Server svr;
  2976. int port = 0;
  2977. auto thread = std::thread([&]() {
  2978. setupSignalHandlers();
  2979. port = svr.bind_to_any_port(HOST);
  2980. svr.listen_after_bind();
  2981. });
  2982. auto se = detail::scope_exit([&] {
  2983. svr.stop();
  2984. thread.join();
  2985. ASSERT_FALSE(svr.is_running());
  2986. });
  2987. svr.wait_until_ready();
  2988. ASSERT_TRUE(svr.is_running());
  2989. pthread_kill(thread.native_handle(), SIGINT);
  2990. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2991. ASSERT_TRUE(svr.is_running());
  2992. }
  2993. #endif
  2994. TEST(RedirectToDifferentPort, Redirect) {
  2995. Server svr1;
  2996. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2997. res.set_content("Hello World!", "text/plain");
  2998. });
  2999. int svr1_port = 0;
  3000. auto thread1 = std::thread([&]() {
  3001. svr1_port = svr1.bind_to_any_port(HOST);
  3002. svr1.listen_after_bind();
  3003. });
  3004. Server svr2;
  3005. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3006. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3007. });
  3008. int svr2_port = 0;
  3009. auto thread2 = std::thread([&]() {
  3010. svr2_port = svr2.bind_to_any_port(HOST);
  3011. svr2.listen_after_bind();
  3012. });
  3013. auto se = detail::scope_exit([&] {
  3014. svr2.stop();
  3015. thread2.join();
  3016. svr1.stop();
  3017. thread1.join();
  3018. ASSERT_FALSE(svr2.is_running());
  3019. ASSERT_FALSE(svr1.is_running());
  3020. });
  3021. svr1.wait_until_ready();
  3022. svr2.wait_until_ready();
  3023. Client cli("localhost", svr2_port);
  3024. cli.set_follow_location(true);
  3025. auto res = cli.Get("/2");
  3026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3027. EXPECT_EQ(StatusCode::OK_200, res->status);
  3028. EXPECT_EQ("Hello World!", res->body);
  3029. }
  3030. static void
  3031. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3032. Server svr1;
  3033. std::string captured_authorization;
  3034. svr1.Get("/target", [&](const Request &req, Response &res) {
  3035. captured_authorization = req.get_header_value("Authorization");
  3036. res.set_content("OK", "text/plain");
  3037. });
  3038. int svr1_port = 0;
  3039. auto thread1 = std::thread([&]() {
  3040. svr1_port = svr1.bind_to_any_port(HOST);
  3041. svr1.listen_after_bind();
  3042. });
  3043. Server svr2;
  3044. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3045. res.set_redirect(
  3046. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3047. });
  3048. int svr2_port = 0;
  3049. auto thread2 = std::thread([&]() {
  3050. svr2_port = svr2.bind_to_any_port(HOST);
  3051. svr2.listen_after_bind();
  3052. });
  3053. auto se = detail::scope_exit([&] {
  3054. svr2.stop();
  3055. thread2.join();
  3056. svr1.stop();
  3057. thread1.join();
  3058. ASSERT_FALSE(svr2.is_running());
  3059. ASSERT_FALSE(svr1.is_running());
  3060. });
  3061. svr1.wait_until_ready();
  3062. svr2.wait_until_ready();
  3063. Client cli("localhost", svr2_port);
  3064. cli.set_follow_location(true);
  3065. set_auth(cli);
  3066. auto res = cli.Get("/redir");
  3067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3068. EXPECT_EQ(StatusCode::OK_200, res->status);
  3069. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3070. EXPECT_TRUE(captured_authorization.empty());
  3071. }
  3072. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3073. TestDoNotForwardCredentialsOnRedirect(
  3074. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3075. }
  3076. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3077. TestDoNotForwardCredentialsOnRedirect(
  3078. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3079. }
  3080. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3081. Server svr1;
  3082. std::string captured_cookie;
  3083. bool target_hit = false;
  3084. svr1.Get("/target", [&](const Request &req, Response &res) {
  3085. captured_cookie = req.get_header_value("Cookie");
  3086. target_hit = true;
  3087. res.set_content("OK", "text/plain");
  3088. });
  3089. int svr1_port = 0;
  3090. auto thread1 = std::thread([&]() {
  3091. svr1_port = svr1.bind_to_any_port(HOST);
  3092. svr1.listen_after_bind();
  3093. });
  3094. Server svr2;
  3095. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3096. res.set_redirect(
  3097. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3098. });
  3099. int svr2_port = 0;
  3100. auto thread2 = std::thread([&]() {
  3101. svr2_port = svr2.bind_to_any_port(HOST);
  3102. svr2.listen_after_bind();
  3103. });
  3104. auto se = detail::scope_exit([&] {
  3105. svr2.stop();
  3106. thread2.join();
  3107. svr1.stop();
  3108. thread1.join();
  3109. ASSERT_FALSE(svr2.is_running());
  3110. ASSERT_FALSE(svr1.is_running());
  3111. });
  3112. svr1.wait_until_ready();
  3113. svr2.wait_until_ready();
  3114. Client cli("localhost", svr2_port);
  3115. cli.set_follow_location(true);
  3116. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  3117. auto res = cli.Get("/redir", headers);
  3118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3119. EXPECT_EQ(StatusCode::OK_200, res->status);
  3120. EXPECT_TRUE(target_hit);
  3121. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3122. EXPECT_TRUE(captured_cookie.empty());
  3123. }
  3124. TEST(RedirectToSamePort, ForwardCookie) {
  3125. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3126. // header so that ordinary session flows keep working.
  3127. Server svr;
  3128. std::string captured_cookie;
  3129. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3130. res.set_redirect("/target", 302);
  3131. });
  3132. svr.Get("/target", [&](const Request &req, Response &res) {
  3133. captured_cookie = req.get_header_value("Cookie");
  3134. res.set_content("OK", "text/plain");
  3135. });
  3136. auto port = svr.bind_to_any_port(HOST);
  3137. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3138. auto se = detail::scope_exit([&] {
  3139. svr.stop();
  3140. thread.join();
  3141. ASSERT_FALSE(svr.is_running());
  3142. });
  3143. svr.wait_until_ready();
  3144. Client cli(HOST, port);
  3145. cli.set_follow_location(true);
  3146. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3147. auto res = cli.Get("/redir", headers);
  3148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3149. EXPECT_EQ(StatusCode::OK_200, res->status);
  3150. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3151. }
  3152. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3153. Server svr;
  3154. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3155. // Port number that overflows int — should not crash
  3156. res.set_redirect("http://localhost:99999999999999999999/target");
  3157. });
  3158. auto port = svr.bind_to_any_port(HOST);
  3159. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3160. auto se = detail::scope_exit([&] {
  3161. svr.stop();
  3162. thread.join();
  3163. ASSERT_FALSE(svr.is_running());
  3164. });
  3165. svr.wait_until_ready();
  3166. Client cli(HOST, port);
  3167. cli.set_follow_location(true);
  3168. auto res = cli.Get("/redir");
  3169. // Should fail gracefully, not crash (no valid response due to bad port)
  3170. EXPECT_FALSE(res);
  3171. }
  3172. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3173. Server svr;
  3174. auto port = svr.bind_to_any_port(HOST);
  3175. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3176. // The server's own port followed by junk must not be followed
  3177. res.set_redirect("http://" + std::string(HOST) + ":" +
  3178. std::to_string(port) + "junk/target");
  3179. });
  3180. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3181. res.set_content("target", "text/plain");
  3182. });
  3183. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3184. auto se = detail::scope_exit([&] {
  3185. svr.stop();
  3186. thread.join();
  3187. ASSERT_FALSE(svr.is_running());
  3188. });
  3189. svr.wait_until_ready();
  3190. Client cli(HOST, port);
  3191. cli.set_follow_location(true);
  3192. auto res = cli.Get("/redir");
  3193. EXPECT_FALSE(res);
  3194. }
  3195. TEST(RedirectFromPageWithContent, Redirect) {
  3196. Server svr;
  3197. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3198. res.set_content("___", "text/plain");
  3199. res.set_redirect("/2");
  3200. });
  3201. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3202. res.set_content("Hello World!", "text/plain");
  3203. });
  3204. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3205. auto se = detail::scope_exit([&] {
  3206. svr.stop();
  3207. th.join();
  3208. ASSERT_FALSE(svr.is_running());
  3209. });
  3210. svr.wait_until_ready();
  3211. {
  3212. Client cli("localhost", PORT);
  3213. cli.set_follow_location(true);
  3214. std::string body;
  3215. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3216. body.append(data, data_length);
  3217. return true;
  3218. });
  3219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3220. EXPECT_EQ(StatusCode::OK_200, res->status);
  3221. EXPECT_EQ("Hello World!", body);
  3222. }
  3223. {
  3224. Client cli("localhost", PORT);
  3225. std::string body;
  3226. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3227. body.append(data, data_length);
  3228. return true;
  3229. });
  3230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3231. EXPECT_EQ(StatusCode::Found_302, res->status);
  3232. EXPECT_EQ("___", body);
  3233. }
  3234. }
  3235. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3236. Server svr;
  3237. auto port_str = std::to_string(PORT);
  3238. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3239. auto expected_host = "[::1]:" + port_str;
  3240. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3241. res.set_content("___", "text/plain");
  3242. // res.set_redirect("/2");
  3243. res.set_redirect(redirect_url);
  3244. });
  3245. svr.Get("/2", [&](const Request &req, Response &res) {
  3246. auto host_header = req.headers.find("Host");
  3247. ASSERT_TRUE(host_header != req.headers.end());
  3248. EXPECT_EQ(expected_host, host_header->second);
  3249. res.set_content("Hello World!", "text/plain");
  3250. });
  3251. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3252. auto se = detail::scope_exit([&] {
  3253. svr.stop();
  3254. th.join();
  3255. ASSERT_FALSE(svr.is_running());
  3256. });
  3257. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3258. // actually starts anything, so the condition !svr.is_running() will
  3259. // always remain true, and the loop never stops.
  3260. // This basically counts how many milliseconds have passed since the
  3261. // call to svr.listen(), and if after 5 seconds nothing started yet
  3262. // aborts the test.
  3263. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3264. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3265. ASSERT_LT(milliseconds, 5000U);
  3266. }
  3267. {
  3268. Client cli("::1", PORT);
  3269. cli.set_follow_location(true);
  3270. std::string body;
  3271. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3272. body.append(data, data_length);
  3273. return true;
  3274. });
  3275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3276. EXPECT_EQ(StatusCode::OK_200, res->status);
  3277. EXPECT_EQ("Hello World!", body);
  3278. }
  3279. {
  3280. Client cli("::1", PORT);
  3281. std::string body;
  3282. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3283. body.append(data, data_length);
  3284. return true;
  3285. });
  3286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3287. EXPECT_EQ(StatusCode::Found_302, res->status);
  3288. EXPECT_EQ("___", body);
  3289. }
  3290. }
  3291. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3292. Server svr;
  3293. svr.Get("/foo", [](const Request &req, Response &res) {
  3294. auto a = req.params.find("a");
  3295. if (a != req.params.end()) {
  3296. res.set_content((*a).second, "text/plain");
  3297. res.status = StatusCode::OK_200;
  3298. } else {
  3299. res.status = StatusCode::BadRequest_400;
  3300. }
  3301. });
  3302. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3303. auto se = detail::scope_exit([&] {
  3304. svr.stop();
  3305. thread.join();
  3306. ASSERT_FALSE(svr.is_running());
  3307. });
  3308. svr.wait_until_ready();
  3309. {
  3310. Client cli(HOST, PORT);
  3311. cli.set_path_encode(false);
  3312. auto res = cli.Get("/foo?a=explicitly+encoded");
  3313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3314. EXPECT_EQ(StatusCode::OK_200, res->status);
  3315. // This expects it back with a space, as the `+` won't have been
  3316. // url-encoded, and server-side the params get decoded turning `+`
  3317. // into spaces.
  3318. EXPECT_EQ("explicitly encoded", res->body);
  3319. }
  3320. }
  3321. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3322. // When path encoding is disabled the client must transmit the supplied
  3323. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3324. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3325. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3326. // than a space (0x20). Assert on the raw wire target to catch this.
  3327. Server svr;
  3328. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3329. svr.Get("/foo", [&](const Request &req, Response &res) {
  3330. EXPECT_EQ(expected_target, req.target);
  3331. res.status = StatusCode::OK_200;
  3332. });
  3333. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3334. auto se = detail::scope_exit([&] {
  3335. svr.stop();
  3336. thread.join();
  3337. ASSERT_FALSE(svr.is_running());
  3338. });
  3339. svr.wait_until_ready();
  3340. {
  3341. Client cli(HOST, PORT);
  3342. cli.set_path_encode(false);
  3343. auto res = cli.Get(expected_target.c_str());
  3344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3345. EXPECT_EQ(StatusCode::OK_200, res->status);
  3346. }
  3347. }
  3348. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3349. // `open_stream()` used to skip the path encoding that the buffered send
  3350. // path applies, so the same `path` produced different bytes in the request
  3351. // line depending on which API was used. Assert the two agree.
  3352. Server svr;
  3353. std::string target;
  3354. svr.Get(".*", [&](const Request &req, Response &res) {
  3355. target = req.target;
  3356. res.status = StatusCode::OK_200;
  3357. });
  3358. auto port = svr.bind_to_any_port(HOST);
  3359. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3360. auto se = detail::scope_exit([&] {
  3361. svr.stop();
  3362. thread.join();
  3363. ASSERT_FALSE(svr.is_running());
  3364. });
  3365. svr.wait_until_ready();
  3366. struct {
  3367. const char *path;
  3368. const char *expected;
  3369. } cases[] = {
  3370. {"/a b?x=1", "/a%20b?x=1"},
  3371. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3372. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3373. };
  3374. for (const auto &c : cases) {
  3375. Client cli(HOST, port);
  3376. target.clear();
  3377. auto res = cli.Get(c.path);
  3378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3379. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3380. auto buffered_target = target;
  3381. target.clear();
  3382. auto handle = cli.open_stream("GET", c.path);
  3383. EXPECT_TRUE(handle.is_valid())
  3384. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3385. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3386. }
  3387. }
  3388. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3389. // The `set_path_encode(false)` contract — transmit the supplied target
  3390. // verbatim — must hold for the streaming API too.
  3391. Server svr;
  3392. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3393. std::string target;
  3394. svr.Get("/foo", [&](const Request &req, Response &res) {
  3395. target = req.target;
  3396. res.status = StatusCode::OK_200;
  3397. });
  3398. auto port = svr.bind_to_any_port(HOST);
  3399. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3400. auto se = detail::scope_exit([&] {
  3401. svr.stop();
  3402. thread.join();
  3403. ASSERT_FALSE(svr.is_running());
  3404. });
  3405. svr.wait_until_ready();
  3406. {
  3407. Client cli(HOST, port);
  3408. cli.set_path_encode(false);
  3409. auto handle = cli.open_stream("GET", expected_target);
  3410. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3411. EXPECT_EQ(expected_target, target);
  3412. }
  3413. }
  3414. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3415. // With path encoding enabled a CR/LF in the target is percent-encoded
  3416. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3417. // write_request_line still backstops `set_path_encode(false)`, which is
  3418. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3419. Server svr;
  3420. // Captured before routing: the decoded path contains a newline, which a
  3421. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3422. std::string target;
  3423. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3424. target = req.target;
  3425. res.status = StatusCode::OK_200;
  3426. return Server::HandlerResponse::Handled;
  3427. });
  3428. auto port = svr.bind_to_any_port(HOST);
  3429. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3430. auto se = detail::scope_exit([&] {
  3431. svr.stop();
  3432. thread.join();
  3433. ASSERT_FALSE(svr.is_running());
  3434. });
  3435. svr.wait_until_ready();
  3436. {
  3437. Client cli(HOST, port);
  3438. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3439. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3440. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3441. }
  3442. }
  3443. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3444. // Every control character is percent-encoded, not just CR/LF, so the target
  3445. // passes the request-target check in write_request_line.
  3446. Server svr;
  3447. std::string target;
  3448. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3449. target = req.target;
  3450. res.status = StatusCode::OK_200;
  3451. return Server::HandlerResponse::Handled;
  3452. });
  3453. auto port = svr.bind_to_any_port(HOST);
  3454. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3455. auto se = detail::scope_exit([&] {
  3456. svr.stop();
  3457. thread.join();
  3458. ASSERT_FALSE(svr.is_running());
  3459. });
  3460. svr.wait_until_ready();
  3461. {
  3462. Client cli(HOST, port);
  3463. auto res = cli.Get("/a\tb\x1b\x7f");
  3464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3465. EXPECT_EQ("/a%09b%1B%7F", target);
  3466. }
  3467. }
  3468. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3469. // Nothing may reach the wire: a raw CR/LF target would split the request
  3470. // line and inject headers.
  3471. Server svr;
  3472. // Pre-routing so that "not called" means nothing reached the server at all,
  3473. // rather than merely failing to match a handler pattern.
  3474. auto handler_called = false;
  3475. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3476. handler_called = true;
  3477. res.status = StatusCode::OK_200;
  3478. return Server::HandlerResponse::Handled;
  3479. });
  3480. auto port = svr.bind_to_any_port(HOST);
  3481. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3482. auto se = detail::scope_exit([&] {
  3483. svr.stop();
  3484. thread.join();
  3485. ASSERT_FALSE(svr.is_running());
  3486. });
  3487. svr.wait_until_ready();
  3488. {
  3489. Client cli(HOST, port);
  3490. cli.set_path_encode(false);
  3491. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3492. EXPECT_FALSE(handle.is_valid());
  3493. EXPECT_EQ(Error::Write, handle.error);
  3494. EXPECT_FALSE(handler_called);
  3495. }
  3496. }
  3497. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3498. // Which of the two branches runs is decided by whether the query component
  3499. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3500. // an empty query and must still fall back to building one from
  3501. // `req.params`, while a non-empty query must win over `req.params`.
  3502. Server svr;
  3503. std::string target;
  3504. svr.Get("/foo", [&](const Request &req, Response &res) {
  3505. target = req.target;
  3506. res.status = StatusCode::OK_200;
  3507. });
  3508. auto port = svr.bind_to_any_port(HOST);
  3509. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3510. auto se = detail::scope_exit([&] {
  3511. svr.stop();
  3512. thread.join();
  3513. ASSERT_FALSE(svr.is_running());
  3514. });
  3515. svr.wait_until_ready();
  3516. {
  3517. // Trailing `?` -> empty query component -> `req.params` is used.
  3518. Client cli(HOST, port);
  3519. Request req;
  3520. req.method = "GET";
  3521. req.path = "/foo?";
  3522. req.params.emplace("a", "1");
  3523. target.clear();
  3524. auto res = cli.send(req);
  3525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3526. EXPECT_EQ("/foo?a=1", target);
  3527. }
  3528. {
  3529. // Non-empty query in `req.path` -> `req.params` is not appended.
  3530. Client cli(HOST, port);
  3531. Request req;
  3532. req.method = "GET";
  3533. req.path = "/foo?b=2";
  3534. req.params.emplace("a", "1");
  3535. target.clear();
  3536. auto res = cli.send(req);
  3537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3538. EXPECT_EQ("/foo?b=2", target);
  3539. }
  3540. }
  3541. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3542. Server svr;
  3543. svr.Get("/", [](const Request &req, Response &) {
  3544. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3545. });
  3546. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3547. auto se = detail::scope_exit([&] {
  3548. svr.stop();
  3549. thread.join();
  3550. ASSERT_FALSE(svr.is_running());
  3551. });
  3552. svr.wait_until_ready();
  3553. {
  3554. Client cli(HOST, PORT);
  3555. cli.set_path_encode(false);
  3556. auto res = cli.Get("/?something=%0A");
  3557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3558. EXPECT_EQ(StatusCode::OK_200, res->status);
  3559. }
  3560. }
  3561. TEST(BindServerTest, BindDualStack) {
  3562. Server svr;
  3563. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3564. res.set_content("Hello World!", "text/plain");
  3565. });
  3566. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3567. auto se = detail::scope_exit([&] {
  3568. svr.stop();
  3569. thread.join();
  3570. ASSERT_FALSE(svr.is_running());
  3571. });
  3572. svr.wait_until_ready();
  3573. {
  3574. Client cli("127.0.0.1", PORT);
  3575. auto res = cli.Get("/1");
  3576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3577. EXPECT_EQ(StatusCode::OK_200, res->status);
  3578. EXPECT_EQ("Hello World!", res->body);
  3579. }
  3580. {
  3581. Client cli("::1", PORT);
  3582. auto res = cli.Get("/1");
  3583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3584. EXPECT_EQ(StatusCode::OK_200, res->status);
  3585. EXPECT_EQ("Hello World!", res->body);
  3586. }
  3587. }
  3588. TEST(BindServerTest, BindAndListenSeparately) {
  3589. Server svr;
  3590. int port = svr.bind_to_any_port("0.0.0.0");
  3591. ASSERT_TRUE(svr.is_valid());
  3592. ASSERT_TRUE(port > 0);
  3593. svr.stop();
  3594. }
  3595. // Reports whether anything is still listening on a loopback port. A plain
  3596. // connect() is used instead of a Client request because a socket left bound by
  3597. // mistake accepts the connection into its backlog and never answers, which
  3598. // would hang the test instead of failing it.
  3599. static bool is_loopback_port_accepting(int port) {
  3600. sockaddr_in addr{};
  3601. addr.sin_family = AF_INET;
  3602. addr.sin_port = htons(static_cast<uint16_t>(port));
  3603. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3604. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3605. EXPECT_NE(sock, INVALID_SOCKET);
  3606. if (sock == INVALID_SOCKET) { return false; }
  3607. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3608. static_cast<socklen_t>(sizeof(addr)));
  3609. detail::close_socket(sock);
  3610. return ret == 0;
  3611. }
  3612. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3613. Server svr;
  3614. auto port = svr.bind_to_any_port("127.0.0.1");
  3615. ASSERT_TRUE(port > 0);
  3616. svr.stop();
  3617. // bind_to_any_port() already called listen(2), so until stop() closed the
  3618. // descriptor the port kept accepting connections into the backlog. ASSERT
  3619. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3620. // below blocks forever in the accept loop.
  3621. ASSERT_FALSE(is_loopback_port_accepting(port));
  3622. // Nothing is left to accept on, so listen_after_bind() must report failure
  3623. // instead of returning success without ever serving.
  3624. EXPECT_FALSE(svr.listen_after_bind());
  3625. // The failed listen marks the server decommissioned, so a waiter returns
  3626. // instead of spinning forever.
  3627. svr.wait_until_ready();
  3628. }
  3629. #ifdef CPPHTTPLIB_SSL_ENABLED
  3630. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3631. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3632. CLIENT_CA_CERT_DIR);
  3633. int port = svr.bind_to_any_port("0.0.0.0");
  3634. ASSERT_TRUE(svr.is_valid());
  3635. ASSERT_TRUE(port > 0);
  3636. svr.stop();
  3637. }
  3638. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3639. // or a rejected CustomRoute() registration would not stop the server binding.
  3640. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3641. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3642. CLIENT_CA_CERT_DIR);
  3643. ASSERT_TRUE(svr.is_valid());
  3644. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3645. EXPECT_FALSE(svr.is_valid());
  3646. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3647. }
  3648. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3649. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3650. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3651. int port = svr.bind_to_any_port("0.0.0.0");
  3652. ASSERT_TRUE(svr.is_valid());
  3653. ASSERT_TRUE(port > 0);
  3654. svr.stop();
  3655. }
  3656. TEST(BindServerTest, UpdateCertsPem) {
  3657. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3658. int port = svr.bind_to_any_port("0.0.0.0");
  3659. ASSERT_TRUE(svr.is_valid());
  3660. ASSERT_TRUE(port > 0);
  3661. // Read PEM files
  3662. std::string cert_pem, key_pem, ca_pem;
  3663. read_file(SERVER_CERT_FILE, cert_pem);
  3664. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3665. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3666. // Update server certificates using PEM API
  3667. ASSERT_TRUE(
  3668. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3669. ASSERT_TRUE(svr.is_valid());
  3670. svr.stop();
  3671. }
  3672. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3673. // Start server with client CA (enables client auth)
  3674. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3675. ASSERT_TRUE(svr.is_valid());
  3676. bool handler_called = false;
  3677. svr.Get("/test", [&](const Request &req, Response &res) {
  3678. handler_called = true;
  3679. // Verify client certificate is present
  3680. auto cert = req.peer_cert();
  3681. EXPECT_TRUE(static_cast<bool>(cert));
  3682. res.set_content("ok", "text/plain");
  3683. });
  3684. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3685. auto se = detail::scope_exit([&] {
  3686. svr.stop();
  3687. t.join();
  3688. ASSERT_FALSE(svr.is_running());
  3689. });
  3690. svr.wait_until_ready();
  3691. // Read PEM files
  3692. std::string cert_pem, key_pem, ca_pem;
  3693. read_file(SERVER_CERT_FILE, cert_pem);
  3694. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3695. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3696. // Update server certificates and client CA using PEM API while server running
  3697. ASSERT_TRUE(
  3698. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3699. // Connect with client certificate
  3700. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3701. cli.enable_server_certificate_verification(false);
  3702. cli.set_connection_timeout(30);
  3703. auto res = cli.Get("/test");
  3704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3705. ASSERT_EQ(StatusCode::OK_200, res->status);
  3706. ASSERT_TRUE(handler_called);
  3707. EXPECT_EQ("ok", res->body);
  3708. }
  3709. #endif
  3710. TEST(ErrorHandlerTest, ContentLength) {
  3711. Server svr;
  3712. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3713. res.status = StatusCode::OK_200;
  3714. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3715. "text/html"); // <= Content-Length still 13
  3716. });
  3717. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3718. res.set_content("Hello World!\n", "text/plain");
  3719. res.status = 524;
  3720. });
  3721. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3722. auto se = detail::scope_exit([&] {
  3723. svr.stop();
  3724. thread.join();
  3725. ASSERT_FALSE(svr.is_running());
  3726. });
  3727. svr.wait_until_ready();
  3728. {
  3729. Client cli(HOST, PORT);
  3730. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3732. EXPECT_EQ(StatusCode::OK_200, res->status);
  3733. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3734. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3735. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3736. }
  3737. }
  3738. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3739. TEST(ExceptionTest, WithoutExceptionHandler) {
  3740. Server svr;
  3741. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3742. throw std::runtime_error("exception...");
  3743. });
  3744. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3745. throw std::runtime_error("exception\r\n...");
  3746. });
  3747. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3748. auto se = detail::scope_exit([&] {
  3749. svr.stop();
  3750. listen_thread.join();
  3751. ASSERT_FALSE(svr.is_running());
  3752. });
  3753. svr.wait_until_ready();
  3754. Client cli("localhost", PORT);
  3755. {
  3756. auto res = cli.Get("/exception");
  3757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3758. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3759. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3760. }
  3761. {
  3762. auto res = cli.Get("/unknown");
  3763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3764. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3765. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3766. }
  3767. }
  3768. TEST(ExceptionTest, WithExceptionHandler) {
  3769. Server svr;
  3770. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3771. std::exception_ptr ep) {
  3772. EXPECT_FALSE(ep == nullptr);
  3773. try {
  3774. std::rethrow_exception(ep);
  3775. } catch (std::exception &e) {
  3776. EXPECT_EQ("abc", std::string(e.what()));
  3777. } catch (...) {}
  3778. res.status = StatusCode::InternalServerError_500;
  3779. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3780. "text/html"); // <= Content-Length still 13 at this point
  3781. });
  3782. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3783. res.set_content("Hello World!\n", "text/plain");
  3784. throw std::runtime_error("abc");
  3785. });
  3786. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3787. auto se = detail::scope_exit([&] {
  3788. svr.stop();
  3789. thread.join();
  3790. ASSERT_FALSE(svr.is_running());
  3791. });
  3792. svr.wait_until_ready();
  3793. for (size_t i = 0; i < 10; i++) {
  3794. Client cli(HOST, PORT);
  3795. for (size_t j = 0; j < 100; j++) {
  3796. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3798. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3799. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3800. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3801. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3802. }
  3803. cli.set_keep_alive(true);
  3804. for (size_t j = 0; j < 100; j++) {
  3805. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3807. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3808. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3809. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3810. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3811. }
  3812. }
  3813. }
  3814. TEST(ExceptionTest, AndErrorHandler) {
  3815. Server svr;
  3816. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3817. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3818. });
  3819. svr.set_exception_handler(
  3820. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3821. EXPECT_FALSE(ep == nullptr);
  3822. try {
  3823. std::rethrow_exception(ep);
  3824. } catch (std::exception &e) {
  3825. res.set_content(e.what(), "text/html");
  3826. } catch (...) {}
  3827. res.status = StatusCode::InternalServerError_500;
  3828. });
  3829. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3830. throw std::runtime_error("EXCEPTION");
  3831. });
  3832. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3833. res.set_content("ERROR", "text/html");
  3834. res.status = StatusCode::InternalServerError_500;
  3835. });
  3836. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3837. auto se = detail::scope_exit([&] {
  3838. svr.stop();
  3839. thread.join();
  3840. ASSERT_FALSE(svr.is_running());
  3841. });
  3842. svr.wait_until_ready();
  3843. Client cli(HOST, PORT);
  3844. {
  3845. auto res = cli.Get("/exception");
  3846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3847. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3848. EXPECT_EQ("EXCEPTION", res->body);
  3849. }
  3850. {
  3851. auto res = cli.Get("/error");
  3852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3853. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3854. EXPECT_EQ("ERROR", res->body);
  3855. }
  3856. {
  3857. auto res = cli.Get("/invalid");
  3858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3859. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3860. EXPECT_EQ("NOT_FOUND", res->body);
  3861. }
  3862. }
  3863. #endif
  3864. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3865. // process_request() wraps only routing() in a try/catch, so an exception from
  3866. // any other user callback used to unwind into the task queue - which does not
  3867. // catch - and terminate the process. Each test below runs the server on a
  3868. // single worker thread: a guard that catches the exception but still loses the
  3869. // thread would otherwise be hidden by a spare worker serving the follow-up
  3870. // request. Note that a regression here aborts the whole test binary rather
  3871. // than failing one test.
  3872. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  3873. Server svr;
  3874. svr.new_task_queue = [] { return new ThreadPool(1); };
  3875. std::atomic<int> reported{0};
  3876. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3877. if (err == Error::UserCallbackException) { reported++; }
  3878. });
  3879. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3880. res.set_content_provider(
  3881. 1024, "text/plain",
  3882. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3883. sink.write("hello", 5);
  3884. throw std::runtime_error("from the content provider");
  3885. });
  3886. });
  3887. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3888. res.set_content("ok", "text/plain");
  3889. });
  3890. auto port = svr.bind_to_any_port(HOST);
  3891. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3892. auto se = detail::scope_exit([&] {
  3893. svr.stop();
  3894. listen_thread.join();
  3895. ASSERT_FALSE(svr.is_running());
  3896. });
  3897. svr.wait_until_ready();
  3898. {
  3899. Client cli(HOST, port);
  3900. cli.set_read_timeout(5, 0);
  3901. EXPECT_FALSE(cli.Get("/throw"));
  3902. }
  3903. EXPECT_TRUE(svr.is_running());
  3904. EXPECT_EQ(1, reported.load());
  3905. // A request on a fresh connection is still served.
  3906. {
  3907. Client cli(HOST, port);
  3908. auto res = cli.Get("/ok");
  3909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3910. EXPECT_EQ(StatusCode::OK_200, res->status);
  3911. EXPECT_EQ("ok", res->body);
  3912. }
  3913. }
  3914. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  3915. Server svr;
  3916. svr.new_task_queue = [] { return new ThreadPool(1); };
  3917. std::atomic<bool> should_throw{true};
  3918. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3919. res.set_content("hi", "text/plain");
  3920. });
  3921. svr.set_post_routing_handler(
  3922. [&](const Request & /*req*/, Response & /*res*/) {
  3923. if (should_throw) {
  3924. throw std::runtime_error("from the post-routing handler");
  3925. }
  3926. });
  3927. auto port = svr.bind_to_any_port(HOST);
  3928. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3929. auto se = detail::scope_exit([&] {
  3930. svr.stop();
  3931. listen_thread.join();
  3932. ASSERT_FALSE(svr.is_running());
  3933. });
  3934. svr.wait_until_ready();
  3935. {
  3936. Client cli(HOST, port);
  3937. cli.set_read_timeout(5, 0);
  3938. EXPECT_FALSE(cli.Get("/hi"));
  3939. }
  3940. EXPECT_TRUE(svr.is_running());
  3941. should_throw = false;
  3942. {
  3943. Client cli(HOST, port);
  3944. auto res = cli.Get("/hi");
  3945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3946. EXPECT_EQ(StatusCode::OK_200, res->status);
  3947. EXPECT_EQ("hi", res->body);
  3948. }
  3949. }
  3950. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  3951. // The guard reports the caught exception through the error logger, which is
  3952. // a user callback too. A logger that throws has to be contained as well, or
  3953. // the process would terminate from inside the catch.
  3954. Server svr;
  3955. svr.new_task_queue = [] { return new ThreadPool(1); };
  3956. std::atomic<int> reported{0};
  3957. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3958. if (err == Error::UserCallbackException) {
  3959. reported++;
  3960. throw std::runtime_error("from the error logger");
  3961. }
  3962. });
  3963. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3964. res.set_content_provider(
  3965. 1024, "text/plain",
  3966. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3967. sink.write("hello", 5);
  3968. throw std::runtime_error("from the content provider");
  3969. });
  3970. });
  3971. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3972. res.set_content("ok", "text/plain");
  3973. });
  3974. auto port = svr.bind_to_any_port(HOST);
  3975. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3976. auto se = detail::scope_exit([&] {
  3977. svr.stop();
  3978. listen_thread.join();
  3979. ASSERT_FALSE(svr.is_running());
  3980. });
  3981. svr.wait_until_ready();
  3982. {
  3983. Client cli(HOST, port);
  3984. cli.set_read_timeout(5, 0);
  3985. EXPECT_FALSE(cli.Get("/throw"));
  3986. }
  3987. EXPECT_TRUE(svr.is_running());
  3988. EXPECT_EQ(1, reported.load());
  3989. {
  3990. Client cli(HOST, port);
  3991. auto res = cli.Get("/ok");
  3992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3993. EXPECT_EQ(StatusCode::OK_200, res->status);
  3994. EXPECT_EQ("ok", res->body);
  3995. }
  3996. }
  3997. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  3998. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  3999. // so the exception unwinds through the ws::WebSocket object on its way to
  4000. // the guard. None of the HTTP cases above cross that.
  4001. Server svr;
  4002. svr.new_task_queue = [] { return new ThreadPool(1); };
  4003. std::atomic<int> reported{0};
  4004. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4005. if (err == Error::UserCallbackException) { reported++; }
  4006. });
  4007. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4008. throw std::runtime_error("from the WebSocket handler");
  4009. });
  4010. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4011. res.set_content("ok", "text/plain");
  4012. });
  4013. auto port = svr.bind_to_any_port(HOST);
  4014. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4015. auto se = detail::scope_exit([&] {
  4016. svr.stop();
  4017. listen_thread.join();
  4018. ASSERT_FALSE(svr.is_running());
  4019. });
  4020. svr.wait_until_ready();
  4021. {
  4022. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4023. "/ws");
  4024. auto res = client.connect();
  4025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4026. // The server dropped the connection instead of dying.
  4027. std::string msg;
  4028. EXPECT_FALSE(client.read(msg));
  4029. client.close();
  4030. }
  4031. EXPECT_TRUE(svr.is_running());
  4032. EXPECT_EQ(1, reported.load());
  4033. {
  4034. Client cli(HOST, port);
  4035. auto res = cli.Get("/ok");
  4036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4037. EXPECT_EQ(StatusCode::OK_200, res->status);
  4038. EXPECT_EQ("ok", res->body);
  4039. }
  4040. }
  4041. #ifdef CPPHTTPLIB_SSL_ENABLED
  4042. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4043. // SSLServer::process_and_close_socket() is a separate overload with its own
  4044. // guard, so it is exercised on its own.
  4045. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4046. ASSERT_TRUE(svr.is_valid());
  4047. svr.new_task_queue = [] { return new ThreadPool(1); };
  4048. std::atomic<int> reported{0};
  4049. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4050. if (err == Error::UserCallbackException) { reported++; }
  4051. });
  4052. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4053. res.set_content_provider(
  4054. 1024, "text/plain",
  4055. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4056. sink.write("hello", 5);
  4057. throw std::runtime_error("from the content provider");
  4058. });
  4059. });
  4060. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4061. res.set_content("ok", "text/plain");
  4062. });
  4063. auto port = svr.bind_to_any_port(HOST);
  4064. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4065. auto se = detail::scope_exit([&] {
  4066. svr.stop();
  4067. listen_thread.join();
  4068. ASSERT_FALSE(svr.is_running());
  4069. });
  4070. svr.wait_until_ready();
  4071. {
  4072. SSLClient cli(HOST, port);
  4073. cli.enable_server_certificate_verification(false);
  4074. cli.set_read_timeout(5, 0);
  4075. EXPECT_FALSE(cli.Get("/throw"));
  4076. }
  4077. EXPECT_TRUE(svr.is_running());
  4078. EXPECT_EQ(1, reported.load());
  4079. {
  4080. SSLClient cli(HOST, port);
  4081. cli.enable_server_certificate_verification(false);
  4082. auto res = cli.Get("/ok");
  4083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4084. EXPECT_EQ(StatusCode::OK_200, res->status);
  4085. EXPECT_EQ("ok", res->body);
  4086. }
  4087. }
  4088. #endif
  4089. #endif
  4090. TEST(NoContentTest, ContentLength) {
  4091. Server svr;
  4092. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4093. res.status = StatusCode::NoContent_204;
  4094. });
  4095. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4096. auto se = detail::scope_exit([&] {
  4097. svr.stop();
  4098. thread.join();
  4099. ASSERT_FALSE(svr.is_running());
  4100. });
  4101. svr.wait_until_ready();
  4102. {
  4103. Client cli(HOST, PORT);
  4104. auto res = cli.Get("/hi");
  4105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4106. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4107. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4108. }
  4109. }
  4110. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4111. #ifdef CPPHTTPLIB_SSL_ENABLED
  4112. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4113. ASSERT_TRUE(svr.is_valid());
  4114. #else
  4115. Server svr;
  4116. #endif
  4117. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4118. if (req.path == "/routing_handler") {
  4119. res.set_header("PRE_ROUTING", "on");
  4120. res.set_content("Routing Handler", "text/plain");
  4121. return httplib::Server::HandlerResponse::Handled;
  4122. }
  4123. return httplib::Server::HandlerResponse::Unhandled;
  4124. });
  4125. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4126. res.set_content("Error", "text/html");
  4127. });
  4128. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4129. if (req.path == "/routing_handler") {
  4130. res.set_header("POST_ROUTING", "on");
  4131. }
  4132. });
  4133. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4134. res.set_content("Hello World!\n", "text/plain");
  4135. });
  4136. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4137. auto se = detail::scope_exit([&] {
  4138. svr.stop();
  4139. thread.join();
  4140. ASSERT_FALSE(svr.is_running());
  4141. });
  4142. svr.wait_until_ready();
  4143. {
  4144. #ifdef CPPHTTPLIB_SSL_ENABLED
  4145. SSLClient cli(HOST, PORT);
  4146. cli.enable_server_certificate_verification(false);
  4147. #else
  4148. Client cli(HOST, PORT);
  4149. #endif
  4150. auto res = cli.Get("/routing_handler");
  4151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4152. EXPECT_EQ(StatusCode::OK_200, res->status);
  4153. EXPECT_EQ("Routing Handler", res->body);
  4154. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4155. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4156. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4157. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4158. }
  4159. {
  4160. #ifdef CPPHTTPLIB_SSL_ENABLED
  4161. SSLClient cli(HOST, PORT);
  4162. cli.enable_server_certificate_verification(false);
  4163. #else
  4164. Client cli(HOST, PORT);
  4165. #endif
  4166. auto res = cli.Get("/hi");
  4167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4168. EXPECT_EQ(StatusCode::OK_200, res->status);
  4169. EXPECT_EQ("Hello World!\n", res->body);
  4170. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4171. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4172. }
  4173. {
  4174. #ifdef CPPHTTPLIB_SSL_ENABLED
  4175. SSLClient cli(HOST, PORT);
  4176. cli.enable_server_certificate_verification(false);
  4177. #else
  4178. Client cli(HOST, PORT);
  4179. #endif
  4180. auto res = cli.Get("/aaa");
  4181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4182. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4183. EXPECT_EQ("Error", res->body);
  4184. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4185. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4186. }
  4187. }
  4188. TEST(RequestHandlerTest, PreRequestHandler) {
  4189. auto route_path = "/user/:user";
  4190. Server svr;
  4191. svr.Get("/hi", [](const Request &, Response &res) {
  4192. res.set_content("hi", "text/plain");
  4193. });
  4194. svr.Get(route_path, [](const Request &req, Response &res) {
  4195. res.set_content(req.path_params.at("user"), "text/plain");
  4196. });
  4197. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4198. if (req.matched_route == route_path) {
  4199. auto user = req.path_params.at("user");
  4200. if (user != "john") {
  4201. res.status = StatusCode::Forbidden_403;
  4202. res.set_content("error", "text/html");
  4203. return Server::HandlerResponse::Handled;
  4204. }
  4205. }
  4206. return Server::HandlerResponse::Unhandled;
  4207. });
  4208. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4209. auto se = detail::scope_exit([&] {
  4210. svr.stop();
  4211. thread.join();
  4212. ASSERT_FALSE(svr.is_running());
  4213. });
  4214. svr.wait_until_ready();
  4215. Client cli(HOST, PORT);
  4216. {
  4217. auto res = cli.Get("/hi");
  4218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4219. EXPECT_EQ(StatusCode::OK_200, res->status);
  4220. EXPECT_EQ("hi", res->body);
  4221. }
  4222. {
  4223. auto res = cli.Get("/user/john");
  4224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4225. EXPECT_EQ(StatusCode::OK_200, res->status);
  4226. EXPECT_EQ("john", res->body);
  4227. }
  4228. {
  4229. auto res = cli.Get("/user/invalid-user");
  4230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4231. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4232. EXPECT_EQ("error", res->body);
  4233. }
  4234. }
  4235. // The pre-request handler must run before the request body is read, so a
  4236. // rejected request never forces the server to buffer a (potentially large)
  4237. // body. Here the posted body is larger than the payload limit: if the body
  4238. // were read first the server would answer 413, but because the pre-request
  4239. // handler runs first it answers 403 and the body is never read.
  4240. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4241. Server svr;
  4242. svr.set_payload_max_length(8);
  4243. auto handler_ran = false;
  4244. svr.Post("/reject", [&](const Request &req, Response &res) {
  4245. handler_ran = true;
  4246. res.set_content(req.body, "text/plain");
  4247. });
  4248. svr.Post("/accept", [](const Request &req, Response &res) {
  4249. res.set_content(req.body, "text/plain");
  4250. });
  4251. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4252. if (req.matched_route == "/reject") {
  4253. res.status = StatusCode::Forbidden_403;
  4254. res.set_content("denied", "text/plain");
  4255. return Server::HandlerResponse::Handled;
  4256. }
  4257. return Server::HandlerResponse::Unhandled;
  4258. });
  4259. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4260. auto se = detail::scope_exit([&] {
  4261. svr.stop();
  4262. thread.join();
  4263. ASSERT_FALSE(svr.is_running());
  4264. });
  4265. svr.wait_until_ready();
  4266. Client cli(HOST, PORT);
  4267. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4268. // rejects with 403 before the body is read, so 413 is never reached.
  4269. {
  4270. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4272. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4273. EXPECT_EQ("denied", res->body);
  4274. EXPECT_FALSE(handler_ran);
  4275. }
  4276. // An approved route still reads the body and enforces the payload limit.
  4277. {
  4278. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4280. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4281. }
  4282. }
  4283. TEST(UserDataTest, BasicOperations) {
  4284. httplib::UserData ud;
  4285. // Initially empty
  4286. EXPECT_FALSE(ud.has("key"));
  4287. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4288. // set and get
  4289. ud.set("key", 42);
  4290. EXPECT_TRUE(ud.has("key"));
  4291. auto *p = ud.get<int>("key");
  4292. ASSERT_NE(nullptr, p);
  4293. EXPECT_EQ(42, *p);
  4294. // Type mismatch → nullptr
  4295. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4296. // Overwrite with different type
  4297. ud.set("key", std::string("hello"));
  4298. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4299. auto *s = ud.get<std::string>("key");
  4300. ASSERT_NE(nullptr, s);
  4301. EXPECT_EQ("hello", *s);
  4302. // erase
  4303. ud.erase("key");
  4304. EXPECT_FALSE(ud.has("key"));
  4305. // clear
  4306. ud.set("a", 1);
  4307. ud.set("b", 2);
  4308. ud.clear();
  4309. EXPECT_FALSE(ud.has("a"));
  4310. EXPECT_FALSE(ud.has("b"));
  4311. }
  4312. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4313. struct AuthCtx {
  4314. std::string user_id;
  4315. };
  4316. Server svr;
  4317. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4318. res.user_data.set("auth", AuthCtx{"alice"});
  4319. return Server::HandlerResponse::Unhandled;
  4320. });
  4321. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4322. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4323. ASSERT_NE(nullptr, ctx);
  4324. res.set_content("Hello " + ctx->user_id, "text/plain");
  4325. });
  4326. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4327. auto se = detail::scope_exit([&] {
  4328. svr.stop();
  4329. thread.join();
  4330. ASSERT_FALSE(svr.is_running());
  4331. });
  4332. svr.wait_until_ready();
  4333. Client cli(HOST, PORT);
  4334. auto res = cli.Get("/me");
  4335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4336. EXPECT_EQ(StatusCode::OK_200, res->status);
  4337. EXPECT_EQ("Hello alice", res->body);
  4338. }
  4339. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4340. struct RoleCtx {
  4341. std::string role;
  4342. };
  4343. Server svr;
  4344. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4345. res.user_data.set("role", RoleCtx{"admin"});
  4346. return Server::HandlerResponse::Unhandled;
  4347. });
  4348. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4349. auto *ctx = res.user_data.get<RoleCtx>("role");
  4350. ASSERT_NE(nullptr, ctx);
  4351. res.set_content(ctx->role, "text/plain");
  4352. });
  4353. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4354. auto se = detail::scope_exit([&] {
  4355. svr.stop();
  4356. thread.join();
  4357. ASSERT_FALSE(svr.is_running());
  4358. });
  4359. svr.wait_until_ready();
  4360. Client cli(HOST, PORT);
  4361. auto res = cli.Get("/role");
  4362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4363. EXPECT_EQ(StatusCode::OK_200, res->status);
  4364. EXPECT_EQ("admin", res->body);
  4365. }
  4366. TEST(InvalidFormatTest, StatusCode) {
  4367. Server svr;
  4368. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4369. res.set_content("Hello World!\n", "text/plain");
  4370. res.status = 9999; // Status should be a three-digit code...
  4371. });
  4372. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4373. auto se = detail::scope_exit([&] {
  4374. svr.stop();
  4375. thread.join();
  4376. ASSERT_FALSE(svr.is_running());
  4377. });
  4378. svr.wait_until_ready();
  4379. {
  4380. Client cli(HOST, PORT);
  4381. auto res = cli.Get("/hi");
  4382. ASSERT_FALSE(res);
  4383. }
  4384. }
  4385. TEST(URLFragmentTest, WithFragment) {
  4386. Server svr;
  4387. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4388. EXPECT_TRUE(req.target == "/hi");
  4389. });
  4390. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4391. auto se = detail::scope_exit([&] {
  4392. svr.stop();
  4393. thread.join();
  4394. ASSERT_FALSE(svr.is_running());
  4395. });
  4396. svr.wait_until_ready();
  4397. {
  4398. Client cli(HOST, PORT);
  4399. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4400. EXPECT_TRUE(res);
  4401. EXPECT_EQ(StatusCode::OK_200, res->status);
  4402. res = cli.Get("/hi%23key1=val1=key2=val2");
  4403. EXPECT_TRUE(res);
  4404. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4405. }
  4406. }
  4407. TEST(HeaderWriter, SetHeaderWriter) {
  4408. Server svr;
  4409. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4410. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4411. return detail::write_headers(strm, hdrs);
  4412. });
  4413. svr.Get("/hi", [](const Request &req, Response &res) {
  4414. auto it = req.headers.find("CustomClientHeader");
  4415. EXPECT_TRUE(it != req.headers.end());
  4416. EXPECT_EQ(it->second, "CustomClientValue");
  4417. res.set_content("Hello World!\n", "text/plain");
  4418. });
  4419. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4420. auto se = detail::scope_exit([&] {
  4421. svr.stop();
  4422. thread.join();
  4423. ASSERT_FALSE(svr.is_running());
  4424. });
  4425. svr.wait_until_ready();
  4426. {
  4427. Client cli(HOST, PORT);
  4428. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4429. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4430. return detail::write_headers(strm, hdrs);
  4431. });
  4432. auto res = cli.Get("/hi");
  4433. EXPECT_TRUE(res);
  4434. EXPECT_EQ(StatusCode::OK_200, res->status);
  4435. auto it = res->headers.find("CustomServerHeader");
  4436. EXPECT_TRUE(it != res->headers.end());
  4437. EXPECT_EQ(it->second, "CustomServerValue");
  4438. }
  4439. }
  4440. class ServerTest : public ::testing::Test {
  4441. protected:
  4442. ServerTest()
  4443. : cli_(HOST, PORT)
  4444. #ifdef CPPHTTPLIB_SSL_ENABLED
  4445. ,
  4446. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4447. #endif
  4448. {
  4449. #ifdef CPPHTTPLIB_SSL_ENABLED
  4450. cli_.enable_server_certificate_verification(false);
  4451. #endif
  4452. // Allow LARGE_DATA (100MB) responses
  4453. cli_.set_payload_max_length(200 * 1024 * 1024);
  4454. }
  4455. virtual void SetUp() {
  4456. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4457. svr_.set_payload_max_length(200 * 1024 * 1024);
  4458. svr_.set_mount_point("/", "./www");
  4459. svr_.set_mount_point("/mount", "./www2");
  4460. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4461. svr_.Get("/hi",
  4462. [&](const Request & /*req*/, Response &res) {
  4463. res.set_content("Hello World!", "text/plain");
  4464. })
  4465. .Get("/file_content",
  4466. [&](const Request & /*req*/, Response &res) {
  4467. res.set_file_content("./www/dir/test.html");
  4468. })
  4469. .Get("/file_content_with_content_type",
  4470. [&](const Request & /*req*/, Response &res) {
  4471. res.set_file_content("./www/file", "text/plain");
  4472. })
  4473. .Get("/invalid_file_content",
  4474. [&](const Request & /*req*/, Response &res) {
  4475. res.set_file_content("./www/dir/invalid_file_path");
  4476. })
  4477. .Get("/http_response_splitting",
  4478. [&](const Request & /*req*/, Response &res) {
  4479. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4480. EXPECT_EQ(0U, res.headers.size());
  4481. EXPECT_FALSE(res.has_header("a"));
  4482. res.set_header("a", "1\nSet-Cookie: a=1");
  4483. EXPECT_EQ(0U, res.headers.size());
  4484. EXPECT_FALSE(res.has_header("a"));
  4485. res.set_header("a", "1\rSet-Cookie: a=1");
  4486. EXPECT_EQ(0U, res.headers.size());
  4487. EXPECT_FALSE(res.has_header("a"));
  4488. res.set_header("a\r\nb", "0");
  4489. EXPECT_EQ(0U, res.headers.size());
  4490. EXPECT_FALSE(res.has_header("a"));
  4491. res.set_header("a\rb", "0");
  4492. EXPECT_EQ(0U, res.headers.size());
  4493. EXPECT_FALSE(res.has_header("a"));
  4494. res.set_header("a\nb", "0");
  4495. EXPECT_EQ(0U, res.headers.size());
  4496. EXPECT_FALSE(res.has_header("a"));
  4497. res.set_redirect("1\r\nSet-Cookie: a=1");
  4498. EXPECT_EQ(0U, res.headers.size());
  4499. EXPECT_FALSE(res.has_header("Location"));
  4500. })
  4501. .Get("/slow",
  4502. [&](const Request & /*req*/, Response &res) {
  4503. std::this_thread::sleep_for(std::chrono::seconds(4));
  4504. res.set_content("slow", "text/plain");
  4505. })
  4506. #if 0
  4507. .Post("/slowpost",
  4508. [&](const Request & /*req*/, Response &res) {
  4509. std::this_thread::sleep_for(std::chrono::seconds(2));
  4510. res.set_content("slow", "text/plain");
  4511. })
  4512. #endif
  4513. .Get("/remote_addr",
  4514. [&](const Request &req, Response &res) {
  4515. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4516. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4517. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4518. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4519. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4520. #endif
  4521. res.set_content(req.remote_addr, "text/plain");
  4522. })
  4523. .Get("/local_addr",
  4524. [&](const Request &req, Response &res) {
  4525. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4526. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4527. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4528. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4529. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4530. #endif
  4531. auto local_addr = req.local_addr;
  4532. auto local_port = std::to_string(req.local_port);
  4533. res.set_content(local_addr.append(":").append(local_port),
  4534. "text/plain");
  4535. })
  4536. .Get("/endwith%",
  4537. [&](const Request & /*req*/, Response &res) {
  4538. res.set_content("Hello World!", "text/plain");
  4539. })
  4540. .Get("/a\\+\\+b",
  4541. [&](const Request &req, Response &res) {
  4542. ASSERT_TRUE(req.has_param("a +b"));
  4543. auto val = req.get_param_value("a +b");
  4544. res.set_content(val, "text/plain");
  4545. })
  4546. .Get("/", [&](const Request & /*req*/,
  4547. Response &res) { res.set_redirect("/hi"); })
  4548. .Post("/1",
  4549. [](const Request & /*req*/, Response &res) {
  4550. res.set_redirect("/2", StatusCode::SeeOther_303);
  4551. })
  4552. .Get("/2",
  4553. [](const Request & /*req*/, Response &res) {
  4554. res.set_content("redirected.", "text/plain");
  4555. res.status = StatusCode::OK_200;
  4556. })
  4557. .Post("/person",
  4558. [&](const Request &req, Response &res) {
  4559. if (req.has_param("name") && req.has_param("note")) {
  4560. persons_[req.get_param_value("name")] =
  4561. req.get_param_value("note");
  4562. } else {
  4563. res.status = StatusCode::BadRequest_400;
  4564. }
  4565. })
  4566. .Put("/person",
  4567. [&](const Request &req, Response &res) {
  4568. if (req.has_param("name") && req.has_param("note")) {
  4569. persons_[req.get_param_value("name")] =
  4570. req.get_param_value("note");
  4571. } else {
  4572. res.status = StatusCode::BadRequest_400;
  4573. }
  4574. })
  4575. .Get("/person/(.*)",
  4576. [&](const Request &req, Response &res) {
  4577. string name = req.matches[1];
  4578. if (persons_.find(name) != persons_.end()) {
  4579. auto note = persons_[name];
  4580. res.set_content(note, "text/plain");
  4581. } else {
  4582. res.status = StatusCode::NotFound_404;
  4583. }
  4584. })
  4585. .Delete("/person",
  4586. [&](const Request &req, Response &res) {
  4587. if (req.has_param("name")) {
  4588. string name = req.get_param_value("name");
  4589. if (persons_.find(name) != persons_.end()) {
  4590. persons_.erase(name);
  4591. res.set_content("DELETED", "text/plain");
  4592. } else {
  4593. res.status = StatusCode::NotFound_404;
  4594. }
  4595. } else {
  4596. res.status = StatusCode::BadRequest_400;
  4597. }
  4598. })
  4599. .Post("/x-www-form-urlencoded-json",
  4600. [&](const Request &req, Response &res) {
  4601. auto json = req.get_param_value("json");
  4602. ASSERT_EQ(JSON_DATA, json);
  4603. res.set_content(json, "appliation/json");
  4604. res.status = StatusCode::OK_200;
  4605. })
  4606. .Get("/streamed-chunked",
  4607. [&](const Request & /*req*/, Response &res) {
  4608. res.set_chunked_content_provider(
  4609. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4610. sink.os << "123";
  4611. sink.os << "456";
  4612. sink.os << "789";
  4613. sink.done();
  4614. return true;
  4615. });
  4616. })
  4617. .Get("/streamed-chunked-with-prohibited-trailer",
  4618. [&](const Request & /*req*/, Response &res) {
  4619. auto i = new int(0);
  4620. // Declare both a prohibited trailer (Content-Length) and an
  4621. // allowed one
  4622. res.set_header("Trailer", "Content-Length, X-Allowed");
  4623. res.set_chunked_content_provider(
  4624. "text/plain",
  4625. [i](size_t /*offset*/, DataSink &sink) {
  4626. switch (*i) {
  4627. case 0: sink.os << "123"; break;
  4628. case 1: sink.os << "456"; break;
  4629. case 2: sink.os << "789"; break;
  4630. case 3: {
  4631. sink.done_with_trailer(
  4632. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4633. } break;
  4634. }
  4635. (*i)++;
  4636. return true;
  4637. },
  4638. [i](bool success) {
  4639. EXPECT_TRUE(success);
  4640. delete i;
  4641. });
  4642. })
  4643. .Get("/streamed-chunked2",
  4644. [&](const Request & /*req*/, Response &res) {
  4645. auto i = new int(0);
  4646. res.set_chunked_content_provider(
  4647. "text/plain",
  4648. [i](size_t /*offset*/, DataSink &sink) {
  4649. switch (*i) {
  4650. case 0: sink.os << "123"; break;
  4651. case 1: sink.os << "456"; break;
  4652. case 2: sink.os << "789"; break;
  4653. case 3: sink.done(); break;
  4654. }
  4655. (*i)++;
  4656. return true;
  4657. },
  4658. [i](bool success) {
  4659. EXPECT_TRUE(success);
  4660. delete i;
  4661. });
  4662. })
  4663. .Get("/streamed-chunked-with-trailer",
  4664. [&](const Request & /*req*/, Response &res) {
  4665. auto i = new int(0);
  4666. res.set_header("Trailer", "Dummy1, Dummy2");
  4667. res.set_chunked_content_provider(
  4668. "text/plain",
  4669. [i](size_t /*offset*/, DataSink &sink) {
  4670. switch (*i) {
  4671. case 0: sink.os << "123"; break;
  4672. case 1: sink.os << "456"; break;
  4673. case 2: sink.os << "789"; break;
  4674. case 3: {
  4675. sink.done_with_trailer(
  4676. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4677. } break;
  4678. }
  4679. (*i)++;
  4680. return true;
  4681. },
  4682. [i](bool success) {
  4683. EXPECT_TRUE(success);
  4684. delete i;
  4685. });
  4686. })
  4687. .Get("/streamed",
  4688. [&](const Request & /*req*/, Response &res) {
  4689. res.set_content_provider(
  4690. 6, "text/plain",
  4691. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4692. sink.os << (offset < 3 ? "a" : "b");
  4693. return true;
  4694. });
  4695. })
  4696. .Get("/streamed-without-length",
  4697. [&](const Request & /*req*/, Response &res) {
  4698. auto data = new std::string("abcdefg");
  4699. res.set_content_provider(
  4700. "text/plain",
  4701. [data](size_t offset, DataSink &sink) {
  4702. if (offset < data->size()) {
  4703. sink.os << data->substr(offset);
  4704. }
  4705. sink.done();
  4706. return true;
  4707. },
  4708. [data](bool success) {
  4709. EXPECT_TRUE(success);
  4710. delete data;
  4711. });
  4712. })
  4713. .Get("/streamed-with-range",
  4714. [&](const Request &req, Response &res) {
  4715. auto data = new std::string("abcdefg");
  4716. // An explicit status keeps the server from picking the 206 it
  4717. // would otherwise choose for a ranged request, so the response
  4718. // is not a partial representation.
  4719. auto status = req.get_param_value("status");
  4720. if (status == "200") {
  4721. res.status = StatusCode::OK_200;
  4722. } else if (status == "403") {
  4723. res.status = StatusCode::Forbidden_403;
  4724. }
  4725. res.set_content_provider(
  4726. data->size(), "text/plain",
  4727. [data](size_t offset, size_t length, DataSink &sink) {
  4728. size_t DATA_CHUNK_SIZE = 4;
  4729. const auto &d = *data;
  4730. auto out_len =
  4731. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4732. auto ret =
  4733. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4734. EXPECT_TRUE(ret);
  4735. return true;
  4736. },
  4737. [data, &req](bool success) {
  4738. EXPECT_EQ(success, !req.has_param("error"));
  4739. delete data;
  4740. });
  4741. })
  4742. .Get("/streamed-cancel",
  4743. [&](const Request & /*req*/, Response &res) {
  4744. res.set_content_provider(
  4745. size_t(-1), "text/plain",
  4746. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4747. sink.os << "data_chunk";
  4748. return true;
  4749. });
  4750. })
  4751. .Get("/regex-with-delimiter",
  4752. [&](const Request &req, Response & /*res*/) {
  4753. ASSERT_TRUE(req.has_param("key"));
  4754. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4755. })
  4756. .Get("/with-range",
  4757. [&](const Request & /*req*/, Response &res) {
  4758. res.set_content("abcdefg", "text/plain");
  4759. })
  4760. .Get("/test-start-time",
  4761. [&](const Request &req, Response & /*res*/) {
  4762. EXPECT_NE(req.start_time_,
  4763. std::chrono::steady_clock::time_point::min());
  4764. })
  4765. .Get("/with-range-customized-response",
  4766. [&](const Request & /*req*/, Response &res) {
  4767. res.status = StatusCode::BadRequest_400;
  4768. res.set_content(JSON_DATA, "application/json");
  4769. })
  4770. .Post("/chunked",
  4771. [&](const Request &req, Response & /*res*/) {
  4772. EXPECT_EQ(req.body, "dechunked post body");
  4773. })
  4774. .Post("/large-chunked",
  4775. [&](const Request &req, Response & /*res*/) {
  4776. std::string expected(6 * 30 * 1024u, 'a');
  4777. EXPECT_EQ(req.body, expected);
  4778. })
  4779. .Post("/multipart",
  4780. [&](const Request &req, Response & /*res*/) {
  4781. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4782. req.form.get_field_count("text2") +
  4783. req.form.get_field_count("file3") +
  4784. req.form.get_field_count("file4"));
  4785. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4786. req.form.get_file_count("file2"));
  4787. ASSERT_TRUE(!req.form.has_file("???"));
  4788. ASSERT_TRUE(!req.form.has_field("???"));
  4789. ASSERT_TRUE(req.body.empty());
  4790. {
  4791. const auto &text = req.form.get_field("text1");
  4792. EXPECT_EQ("text default", text);
  4793. }
  4794. {
  4795. const auto &text = req.form.get_field("text2");
  4796. EXPECT_EQ("aωb", text);
  4797. }
  4798. {
  4799. const auto &file = req.form.get_file("file1");
  4800. EXPECT_EQ("hello.txt", file.filename);
  4801. EXPECT_EQ("text/plain", file.content_type);
  4802. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4803. }
  4804. {
  4805. const auto &file = req.form.get_file("file2");
  4806. EXPECT_EQ("world.json", file.filename);
  4807. EXPECT_EQ("application/json", file.content_type);
  4808. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4809. }
  4810. {
  4811. const auto &text = req.form.get_field("file3");
  4812. EXPECT_EQ(0u, text.size());
  4813. }
  4814. {
  4815. const auto &text = req.form.get_field("file4");
  4816. EXPECT_EQ(0u, text.size());
  4817. }
  4818. })
  4819. .Post("/multipart/multi_file_values",
  4820. [&](const Request &req, Response & /*res*/) {
  4821. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4822. req.form.get_field_count("multi_text1"));
  4823. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4824. ASSERT_TRUE(!req.form.has_file("???"));
  4825. ASSERT_TRUE(!req.form.has_field("???"));
  4826. ASSERT_TRUE(req.body.empty());
  4827. {
  4828. const auto &text = req.form.get_field("text");
  4829. EXPECT_EQ("default text", text);
  4830. }
  4831. {
  4832. const auto &text1_values = req.form.get_fields("multi_text1");
  4833. EXPECT_EQ(2u, text1_values.size());
  4834. EXPECT_EQ("aaaaa", text1_values[0]);
  4835. EXPECT_EQ("bbbbb", text1_values[1]);
  4836. }
  4837. {
  4838. const auto &file1_values = req.form.get_files("multi_file1");
  4839. EXPECT_EQ(2u, file1_values.size());
  4840. auto file1 = file1_values[0];
  4841. EXPECT_EQ(file1.filename, "hello.txt");
  4842. EXPECT_EQ(file1.content_type, "text/plain");
  4843. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4844. auto file2 = file1_values[1];
  4845. EXPECT_EQ(file2.filename, "world.json");
  4846. EXPECT_EQ(file2.content_type, "application/json");
  4847. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4848. }
  4849. })
  4850. .Post("/empty",
  4851. [&](const Request &req, Response &res) {
  4852. EXPECT_EQ(req.body, "");
  4853. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4854. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4855. res.set_content("empty", "text/plain");
  4856. })
  4857. .Post("/empty-no-content-type",
  4858. [&](const Request &req, Response &res) {
  4859. EXPECT_EQ(req.body, "");
  4860. EXPECT_FALSE(req.has_header("Content-Type"));
  4861. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4862. res.set_content("empty-no-content-type", "text/plain");
  4863. })
  4864. .Post("/path-only",
  4865. [&](const Request &req, Response &res) {
  4866. EXPECT_EQ(req.body, "");
  4867. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4868. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4869. res.set_content("path-only", "text/plain");
  4870. })
  4871. .Post("/path-headers-only",
  4872. [&](const Request &req, Response &res) {
  4873. EXPECT_EQ(req.body, "");
  4874. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4875. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4876. EXPECT_EQ("world", req.get_header_value("hello"));
  4877. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4878. res.set_content("path-headers-only", "text/plain");
  4879. })
  4880. .Post("/post-large",
  4881. [&](const Request &req, Response &res) {
  4882. EXPECT_EQ(req.body, LARGE_DATA);
  4883. res.set_content(req.body, "text/plain");
  4884. })
  4885. .Post("/post-loopback",
  4886. [&](const Request &, Response &res,
  4887. ContentReader const &content_reader) {
  4888. std::string body;
  4889. content_reader([&](const char *data, size_t data_length) {
  4890. body.append(data, data_length);
  4891. return true;
  4892. });
  4893. res.set_content(body, "text/plain");
  4894. })
  4895. .Put("/put-loopback",
  4896. [&](const Request &, Response &res,
  4897. ContentReader const &content_reader) {
  4898. std::string body;
  4899. content_reader([&](const char *data, size_t data_length) {
  4900. body.append(data, data_length);
  4901. return true;
  4902. });
  4903. res.set_content(body, "text/plain");
  4904. })
  4905. .Patch("/patch-loopback",
  4906. [&](const Request &, Response &res,
  4907. ContentReader const &content_reader) {
  4908. std::string body;
  4909. content_reader([&](const char *data, size_t data_length) {
  4910. body.append(data, data_length);
  4911. return true;
  4912. });
  4913. res.set_content(body, "text/plain");
  4914. })
  4915. .Put("/empty-no-content-type",
  4916. [&](const Request &req, Response &res) {
  4917. EXPECT_EQ(req.body, "");
  4918. EXPECT_FALSE(req.has_header("Content-Type"));
  4919. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4920. res.set_content("empty-no-content-type", "text/plain");
  4921. })
  4922. .Put("/put",
  4923. [&](const Request &req, Response &res) {
  4924. EXPECT_EQ(req.body, "PUT");
  4925. res.set_content(req.body, "text/plain");
  4926. })
  4927. .Put("/put-large",
  4928. [&](const Request &req, Response &res) {
  4929. EXPECT_EQ(req.body, LARGE_DATA);
  4930. res.set_content(req.body, "text/plain");
  4931. })
  4932. .Patch("/patch",
  4933. [&](const Request &req, Response &res) {
  4934. EXPECT_EQ(req.body, "PATCH");
  4935. res.set_content(req.body, "text/plain");
  4936. })
  4937. .Delete("/delete",
  4938. [&](const Request & /*req*/, Response &res) {
  4939. res.set_content("DELETE", "text/plain");
  4940. })
  4941. .Delete("/delete-body",
  4942. [&](const Request &req, Response &res) {
  4943. EXPECT_EQ(req.body, "content");
  4944. res.set_content(req.body, "text/plain");
  4945. })
  4946. .Options(R"(\*)",
  4947. [&](const Request & /*req*/, Response &res) {
  4948. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4949. })
  4950. .CustomRoute("PROPFIND", "/dav/:id",
  4951. [&](const Request &req, Response &res) {
  4952. res.set_header("x-body-size",
  4953. std::to_string(req.body.size()));
  4954. res.set_header("x-matched-route", req.matched_route);
  4955. res.set_header("x-dav-id", req.path_params.at("id"));
  4956. res.status = StatusCode::MultiStatus_207;
  4957. res.set_content(req.body, "application/xml");
  4958. })
  4959. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  4960. [&](const Request &req, Response &res) {
  4961. res.set_header("x-dav-match", req.matches[1]);
  4962. res.status = StatusCode::MultiStatus_207;
  4963. })
  4964. .CustomRoute("MKCOL", "/dav-mkcol",
  4965. [&](const Request &req, Response &res) {
  4966. EXPECT_TRUE(req.body.empty());
  4967. res.status = StatusCode::Created_201;
  4968. })
  4969. .CustomRoute(
  4970. "REPORT", "/dav-report",
  4971. [&](const Request & /*req*/, Response &res,
  4972. const ContentReader &content_reader) {
  4973. std::string body;
  4974. content_reader([&](const char *data, size_t data_length) {
  4975. body.append(data, data_length);
  4976. return true;
  4977. });
  4978. res.set_header("x-body-size", std::to_string(body.size()));
  4979. res.status = StatusCode::MultiStatus_207;
  4980. res.set_content(body, "application/xml");
  4981. })
  4982. .Get("/request-target",
  4983. [&](const Request &req, Response & /*res*/) {
  4984. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4985. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4986. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4987. })
  4988. .Get("/long-query-value",
  4989. [&](const Request &req, Response & /*res*/) {
  4990. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4991. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4992. })
  4993. .Get("/too-long-query-value",
  4994. [&](const Request &req, Response & /*res*/) {
  4995. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4996. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4997. })
  4998. .Get("/array-param",
  4999. [&](const Request &req, Response & /*res*/) {
  5000. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5001. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5002. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5003. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5004. })
  5005. .Get("/array-param-values",
  5006. [&](const Request &req, Response & /*res*/) {
  5007. auto values = req.get_param_values("array");
  5008. EXPECT_EQ(3u, values.size());
  5009. EXPECT_EQ("value1", values[0]);
  5010. EXPECT_EQ("value2", values[1]);
  5011. EXPECT_EQ("value3", values[2]);
  5012. auto empty = req.get_param_values("nonexistent");
  5013. EXPECT_TRUE(empty.empty());
  5014. })
  5015. .Post("/validate-no-multiple-headers",
  5016. [&](const Request &req, Response & /*res*/) {
  5017. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5018. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5019. })
  5020. .Post("/content_receiver",
  5021. [&](const Request &req, Response &res,
  5022. const ContentReader &content_reader) {
  5023. if (req.is_multipart_form_data()) {
  5024. std::vector<FormData> items;
  5025. content_reader(
  5026. [&](const FormData &file) {
  5027. items.push_back(file);
  5028. return true;
  5029. },
  5030. [&](const char *data, size_t data_length) {
  5031. items.back().content.append(data, data_length);
  5032. return true;
  5033. });
  5034. EXPECT_EQ(5u, items.size());
  5035. {
  5036. const auto &file = get_file_value(items, "text1");
  5037. EXPECT_TRUE(file.filename.empty());
  5038. EXPECT_EQ("text default", file.content);
  5039. }
  5040. {
  5041. const auto &file = get_file_value(items, "text2");
  5042. EXPECT_TRUE(file.filename.empty());
  5043. EXPECT_EQ("aωb", file.content);
  5044. }
  5045. {
  5046. const auto &file = get_file_value(items, "file1");
  5047. EXPECT_EQ("hello.txt", file.filename);
  5048. EXPECT_EQ("text/plain", file.content_type);
  5049. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5050. }
  5051. {
  5052. const auto &file = get_file_value(items, "file2");
  5053. EXPECT_EQ("world.json", file.filename);
  5054. EXPECT_EQ("application/json", file.content_type);
  5055. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5056. }
  5057. {
  5058. const auto &file = get_file_value(items, "file3");
  5059. EXPECT_TRUE(file.filename.empty());
  5060. EXPECT_EQ("application/octet-stream", file.content_type);
  5061. EXPECT_EQ(0u, file.content.size());
  5062. }
  5063. } else {
  5064. std::string body;
  5065. content_reader([&](const char *data, size_t data_length) {
  5066. EXPECT_EQ(7U, data_length);
  5067. body.append(data, data_length);
  5068. return true;
  5069. });
  5070. EXPECT_EQ(body, "content");
  5071. res.set_content(body, "text/plain");
  5072. }
  5073. })
  5074. .Put("/content_receiver",
  5075. [&](const Request & /*req*/, Response &res,
  5076. const ContentReader &content_reader) {
  5077. std::string body;
  5078. content_reader([&](const char *data, size_t data_length) {
  5079. body.append(data, data_length);
  5080. return true;
  5081. });
  5082. EXPECT_EQ(body, "content");
  5083. res.set_content(body, "text/plain");
  5084. })
  5085. .Patch("/content_receiver",
  5086. [&](const Request & /*req*/, Response &res,
  5087. const ContentReader &content_reader) {
  5088. std::string body;
  5089. content_reader([&](const char *data, size_t data_length) {
  5090. body.append(data, data_length);
  5091. return true;
  5092. });
  5093. EXPECT_EQ(body, "content");
  5094. res.set_content(body, "text/plain");
  5095. })
  5096. .Post("/query-string-and-body",
  5097. [&](const Request &req, Response & /*res*/) {
  5098. ASSERT_TRUE(req.has_param("key"));
  5099. EXPECT_EQ(req.get_param_value("key"), "value");
  5100. EXPECT_EQ(req.body, "content");
  5101. })
  5102. .Get("/last-request",
  5103. [&](const Request &req, Response & /*res*/) {
  5104. EXPECT_EQ("close", req.get_header_value("Connection"));
  5105. })
  5106. .Get(R"(/redirect/(\d+))",
  5107. [&](const Request &req, Response &res) {
  5108. auto num = std::stoi(req.matches[1]) + 1;
  5109. std::string url = "/redirect/" + std::to_string(num);
  5110. res.set_redirect(url);
  5111. })
  5112. .Post("/binary",
  5113. [&](const Request &req, Response &res) {
  5114. EXPECT_EQ(4U, req.body.size());
  5115. EXPECT_EQ("application/octet-stream",
  5116. req.get_header_value("Content-Type"));
  5117. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5118. res.set_content(req.body, "application/octet-stream");
  5119. })
  5120. .Put("/binary",
  5121. [&](const Request &req, Response &res) {
  5122. EXPECT_EQ(4U, req.body.size());
  5123. EXPECT_EQ("application/octet-stream",
  5124. req.get_header_value("Content-Type"));
  5125. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5126. res.set_content(req.body, "application/octet-stream");
  5127. })
  5128. .Patch("/binary",
  5129. [&](const Request &req, Response &res) {
  5130. EXPECT_EQ(4U, req.body.size());
  5131. EXPECT_EQ("application/octet-stream",
  5132. req.get_header_value("Content-Type"));
  5133. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5134. res.set_content(req.body, "application/octet-stream");
  5135. })
  5136. .Delete("/binary",
  5137. [&](const Request &req, Response &res) {
  5138. EXPECT_EQ(4U, req.body.size());
  5139. EXPECT_EQ("application/octet-stream",
  5140. req.get_header_value("Content-Type"));
  5141. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5142. res.set_content(req.body, "application/octet-stream");
  5143. })
  5144. .Get("/issue1772",
  5145. [&](const Request & /*req*/, Response &res) {
  5146. res.status = 401;
  5147. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5148. })
  5149. .Delete("/issue609",
  5150. [](const httplib::Request &, httplib::Response &res,
  5151. const httplib::ContentReader &) {
  5152. res.set_content("ok", "text/plain");
  5153. })
  5154. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5155. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5156. .Get("/compress",
  5157. [&](const Request & /*req*/, Response &res) {
  5158. res.set_content(
  5159. "12345678901234567890123456789012345678901234567890123456789"
  5160. "01234567890123456789012345678901234567890",
  5161. "text/plain");
  5162. })
  5163. .Get("/compress-with-charset",
  5164. [&](const Request & /*req*/, Response &res) {
  5165. res.set_content(
  5166. "12345678901234567890123456789012345678901234567890123456789"
  5167. "01234567890123456789012345678901234567890",
  5168. "application/json; charset=utf-8");
  5169. })
  5170. .Get("/nocompress",
  5171. [&](const Request & /*req*/, Response &res) {
  5172. res.set_content(
  5173. "12345678901234567890123456789012345678901234567890123456789"
  5174. "01234567890123456789012345678901234567890",
  5175. "application/octet-stream");
  5176. })
  5177. .Post("/compress-multipart",
  5178. [&](const Request &req, Response & /*res*/) {
  5179. EXPECT_EQ(2u, req.form.fields.size());
  5180. ASSERT_TRUE(!req.form.has_field("???"));
  5181. {
  5182. const auto &text = req.form.get_field("key1");
  5183. EXPECT_EQ("test", text);
  5184. }
  5185. {
  5186. const auto &text = req.form.get_field("key2");
  5187. EXPECT_EQ("--abcdefg123", text);
  5188. }
  5189. })
  5190. #endif
  5191. ;
  5192. persons_["john"] = "programmer";
  5193. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5194. svr_.wait_until_ready();
  5195. }
  5196. virtual void TearDown() {
  5197. svr_.stop();
  5198. if (!request_threads_.empty()) {
  5199. std::this_thread::sleep_for(std::chrono::seconds(1));
  5200. for (auto &t : request_threads_) {
  5201. t.join();
  5202. }
  5203. }
  5204. t_.join();
  5205. }
  5206. map<string, string> persons_;
  5207. #ifdef CPPHTTPLIB_SSL_ENABLED
  5208. SSLClient cli_;
  5209. SSLServer svr_;
  5210. #else
  5211. Client cli_;
  5212. Server svr_;
  5213. #endif
  5214. thread t_;
  5215. std::vector<thread> request_threads_;
  5216. };
  5217. TEST_F(ServerTest, GetMethod200) {
  5218. auto res = cli_.Get("/hi");
  5219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5220. EXPECT_EQ("HTTP/1.1", res->version);
  5221. EXPECT_EQ(StatusCode::OK_200, res->status);
  5222. EXPECT_EQ("OK", res->reason);
  5223. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5224. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5225. EXPECT_EQ("Hello World!", res->body);
  5226. }
  5227. TEST_F(ServerTest, GetEmptyFile) {
  5228. auto res = cli_.Get("/empty_file");
  5229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5230. EXPECT_EQ(StatusCode::OK_200, res->status);
  5231. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5232. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5233. EXPECT_EQ("", res->body);
  5234. }
  5235. TEST_F(ServerTest, GetFileContent) {
  5236. auto res = cli_.Get("/file_content");
  5237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5238. EXPECT_EQ(StatusCode::OK_200, res->status);
  5239. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5240. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5241. EXPECT_EQ("test.html", res->body);
  5242. }
  5243. TEST_F(ServerTest, GetFileContentWithRange) {
  5244. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5246. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5247. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5248. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5249. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5250. EXPECT_EQ("est", res->body);
  5251. }
  5252. TEST_F(ServerTest, GetFileContentWithContentType) {
  5253. auto res = cli_.Get("/file_content_with_content_type");
  5254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5255. EXPECT_EQ(StatusCode::OK_200, res->status);
  5256. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5257. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5258. EXPECT_EQ("file\n", res->body);
  5259. }
  5260. TEST_F(ServerTest, GetInvalidFileContent) {
  5261. auto res = cli_.Get("/invalid_file_content");
  5262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5263. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5264. }
  5265. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5266. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5268. EXPECT_EQ("HTTP/1.1", res->version);
  5269. EXPECT_EQ(StatusCode::OK_200, res->status);
  5270. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5271. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5272. EXPECT_EQ("Hello World!", res->body);
  5273. }
  5274. TEST_F(ServerTest, GetMethod302) {
  5275. auto res = cli_.Get("/");
  5276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5277. EXPECT_EQ(StatusCode::Found_302, res->status);
  5278. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5279. }
  5280. TEST_F(ServerTest, GetMethod302Redirect) {
  5281. cli_.set_follow_location(true);
  5282. auto res = cli_.Get("/");
  5283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5284. EXPECT_EQ(StatusCode::OK_200, res->status);
  5285. EXPECT_EQ("Hello World!", res->body);
  5286. EXPECT_EQ("/hi", res->location);
  5287. }
  5288. TEST_F(ServerTest, GetMethod404) {
  5289. auto res = cli_.Get("/invalid");
  5290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5291. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5292. }
  5293. TEST_F(ServerTest, HeadMethod200) {
  5294. auto res = cli_.Head("/hi");
  5295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5296. EXPECT_EQ(StatusCode::OK_200, res->status);
  5297. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5298. EXPECT_TRUE(res->body.empty());
  5299. }
  5300. TEST_F(ServerTest, HeadMethod200Static) {
  5301. auto res = cli_.Head("/mount/dir/index.html");
  5302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5303. EXPECT_EQ(StatusCode::OK_200, res->status);
  5304. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5305. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5306. EXPECT_TRUE(res->body.empty());
  5307. }
  5308. TEST_F(ServerTest, HeadMethod404) {
  5309. auto res = cli_.Head("/invalid");
  5310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5311. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5312. EXPECT_TRUE(res->body.empty());
  5313. }
  5314. TEST_F(ServerTest, GetMethodPersonJohn) {
  5315. auto res = cli_.Get("/person/john");
  5316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5317. EXPECT_EQ(StatusCode::OK_200, res->status);
  5318. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5319. EXPECT_EQ("programmer", res->body);
  5320. }
  5321. TEST_F(ServerTest, PostMethod1) {
  5322. auto res = cli_.Get("/person/john1");
  5323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5324. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5325. res = cli_.Post("/person", "name=john1&note=coder",
  5326. "application/x-www-form-urlencoded");
  5327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5328. ASSERT_EQ(StatusCode::OK_200, res->status);
  5329. res = cli_.Get("/person/john1");
  5330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5331. ASSERT_EQ(StatusCode::OK_200, res->status);
  5332. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5333. ASSERT_EQ("coder", res->body);
  5334. }
  5335. TEST_F(ServerTest, PostMethod2) {
  5336. auto res = cli_.Get("/person/john2");
  5337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5338. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5339. Params params;
  5340. params.emplace("name", "john2");
  5341. params.emplace("note", "coder");
  5342. res = cli_.Post("/person", params);
  5343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5344. ASSERT_EQ(StatusCode::OK_200, res->status);
  5345. res = cli_.Get("/person/john2");
  5346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5347. ASSERT_EQ(StatusCode::OK_200, res->status);
  5348. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5349. ASSERT_EQ("coder", res->body);
  5350. }
  5351. TEST_F(ServerTest, PutMethod3) {
  5352. auto res = cli_.Get("/person/john3");
  5353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5354. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5355. Params params;
  5356. params.emplace("name", "john3");
  5357. params.emplace("note", "coder");
  5358. res = cli_.Put("/person", params);
  5359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5360. ASSERT_EQ(StatusCode::OK_200, res->status);
  5361. res = cli_.Get("/person/john3");
  5362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5363. ASSERT_EQ(StatusCode::OK_200, res->status);
  5364. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5365. ASSERT_EQ("coder", res->body);
  5366. }
  5367. TEST_F(ServerTest, DeleteMethod1) {
  5368. auto res = cli_.Get("/person/john4");
  5369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5370. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5371. Params params;
  5372. params.emplace("name", "john4");
  5373. params.emplace("note", "coder");
  5374. res = cli_.Post("/person", params);
  5375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5376. ASSERT_EQ(StatusCode::OK_200, res->status);
  5377. res = cli_.Get("/person/john4");
  5378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5379. ASSERT_EQ(StatusCode::OK_200, res->status);
  5380. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5381. ASSERT_EQ("coder", res->body);
  5382. Params delete_params;
  5383. delete_params.emplace("name", "john4");
  5384. res = cli_.Delete("/person", delete_params);
  5385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5386. ASSERT_EQ(StatusCode::OK_200, res->status);
  5387. ASSERT_EQ("DELETED", res->body);
  5388. res = cli_.Get("/person/john4");
  5389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5390. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5391. }
  5392. TEST_F(ServerTest, DeleteMethod2) {
  5393. auto res = cli_.Get("/person/john5");
  5394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5395. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5396. Params params;
  5397. params.emplace("name", "john5");
  5398. params.emplace("note", "developer");
  5399. res = cli_.Post("/person", params);
  5400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5401. ASSERT_EQ(StatusCode::OK_200, res->status);
  5402. res = cli_.Get("/person/john5");
  5403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5404. ASSERT_EQ(StatusCode::OK_200, res->status);
  5405. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5406. ASSERT_EQ("developer", res->body);
  5407. Params delete_params;
  5408. delete_params.emplace("name", "john5");
  5409. Headers headers;
  5410. headers.emplace("Custom-Header", "test-value");
  5411. res = cli_.Delete("/person", headers, delete_params);
  5412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5413. ASSERT_EQ(StatusCode::OK_200, res->status);
  5414. ASSERT_EQ("DELETED", res->body);
  5415. res = cli_.Get("/person/john5");
  5416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5417. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5418. }
  5419. TEST_F(ServerTest, DeleteMethod3) {
  5420. auto res = cli_.Get("/person/john6");
  5421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5422. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5423. Params params;
  5424. params.emplace("name", "john6");
  5425. params.emplace("note", "tester");
  5426. res = cli_.Post("/person", params);
  5427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5428. ASSERT_EQ(StatusCode::OK_200, res->status);
  5429. res = cli_.Get("/person/john6");
  5430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5431. ASSERT_EQ(StatusCode::OK_200, res->status);
  5432. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5433. ASSERT_EQ("tester", res->body);
  5434. Params delete_params;
  5435. delete_params.emplace("name", "john6");
  5436. Headers headers;
  5437. headers.emplace("Custom-Header", "test-value");
  5438. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5440. ASSERT_EQ(StatusCode::OK_200, res->status);
  5441. ASSERT_EQ("DELETED", res->body);
  5442. res = cli_.Get("/person/john6");
  5443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5444. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5445. }
  5446. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5447. Params params;
  5448. params.emplace("json", JSON_DATA);
  5449. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5451. ASSERT_EQ(StatusCode::OK_200, res->status);
  5452. ASSERT_EQ(JSON_DATA, res->body);
  5453. }
  5454. TEST_F(ServerTest, PostEmptyContent) {
  5455. auto res = cli_.Post("/empty", "", "text/plain");
  5456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5457. ASSERT_EQ(StatusCode::OK_200, res->status);
  5458. ASSERT_EQ("empty", res->body);
  5459. }
  5460. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5461. auto res = cli_.Post("/empty-no-content-type");
  5462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5463. ASSERT_EQ(StatusCode::OK_200, res->status);
  5464. ASSERT_EQ("empty-no-content-type", res->body);
  5465. }
  5466. TEST_F(ServerTest, PostPathOnly) {
  5467. auto res = cli_.Post("/path-only");
  5468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5469. ASSERT_EQ(StatusCode::OK_200, res->status);
  5470. ASSERT_EQ("path-only", res->body);
  5471. }
  5472. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5473. auto res = cli_.Post("/path-headers-only",
  5474. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5476. ASSERT_EQ(StatusCode::OK_200, res->status);
  5477. ASSERT_EQ("path-headers-only", res->body);
  5478. }
  5479. TEST_F(ServerTest, PostLarge) {
  5480. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5482. ASSERT_EQ(StatusCode::OK_200, res->status);
  5483. EXPECT_EQ(LARGE_DATA, res->body);
  5484. }
  5485. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5486. auto res = cli_.Put("/empty-no-content-type");
  5487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5488. ASSERT_EQ(StatusCode::OK_200, res->status);
  5489. ASSERT_EQ("empty-no-content-type", res->body);
  5490. }
  5491. TEST_F(ServerTest, GetMethodDir) {
  5492. auto res = cli_.Get("/dir/");
  5493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5494. EXPECT_EQ(StatusCode::OK_200, res->status);
  5495. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5496. auto body = R"(<html>
  5497. <head>
  5498. </head>
  5499. <body>
  5500. <a href="/dir/test.html">Test</a>
  5501. <a href="/hi">hi</a>
  5502. </body>
  5503. </html>
  5504. )";
  5505. EXPECT_EQ(body, res->body);
  5506. }
  5507. TEST_F(ServerTest, GetMethodDirTest) {
  5508. auto res = cli_.Get("/dir/test.html");
  5509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5510. EXPECT_EQ(StatusCode::OK_200, res->status);
  5511. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5512. EXPECT_EQ("test.html", res->body);
  5513. }
  5514. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5515. auto res = cli_.Get("/dir/../dir/test.html");
  5516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5517. EXPECT_EQ(StatusCode::OK_200, res->status);
  5518. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5519. EXPECT_EQ("test.html", res->body);
  5520. }
  5521. TEST_F(ServerTest, GetMethodInvalidPath) {
  5522. auto res = cli_.Get("/dir/../test.html");
  5523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5524. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5525. }
  5526. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5527. auto res = cli_.Get("/../www/dir/test.html");
  5528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5529. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5530. }
  5531. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5532. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5534. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5535. }
  5536. TEST_F(ServerTest, GetMethodDirMountTest) {
  5537. auto res = cli_.Get("/mount/dir/test.html");
  5538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5539. EXPECT_EQ(StatusCode::OK_200, res->status);
  5540. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5541. EXPECT_EQ("test.html", res->body);
  5542. }
  5543. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5544. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5546. EXPECT_EQ(StatusCode::OK_200, res->status);
  5547. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5548. EXPECT_EQ("test.html", res->body);
  5549. }
  5550. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5551. auto res = cli_.Get("/mount/dir/../test.html");
  5552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5553. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5554. }
  5555. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5556. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5558. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5559. }
  5560. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5561. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5563. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5564. }
  5565. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5566. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5568. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5569. }
  5570. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5571. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5573. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5574. }
  5575. TEST_F(ServerTest, PostMethod303) {
  5576. auto res = cli_.Post("/1", "body", "text/plain");
  5577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5578. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5579. EXPECT_EQ("/2", res->get_header_value("Location"));
  5580. }
  5581. TEST_F(ServerTest, PostMethod303Redirect) {
  5582. cli_.set_follow_location(true);
  5583. auto res = cli_.Post("/1", "body", "text/plain");
  5584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5585. EXPECT_EQ(StatusCode::OK_200, res->status);
  5586. EXPECT_EQ("redirected.", res->body);
  5587. EXPECT_EQ("/2", res->location);
  5588. }
  5589. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5590. auto res = cli_.Get("/dir/test.abcde");
  5591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5592. EXPECT_EQ(StatusCode::OK_200, res->status);
  5593. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5594. EXPECT_EQ("abcde", res->body);
  5595. }
  5596. TEST_F(ServerTest, StaticFileRange) {
  5597. auto res =
  5598. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5600. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5601. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5602. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5603. EXPECT_EQ(true, res->has_header("Content-Range"));
  5604. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5605. EXPECT_EQ(std::string("cd"), res->body);
  5606. }
  5607. TEST_F(ServerTest, StaticFileRanges) {
  5608. auto res = cli_.Get("/dir/test.abcde",
  5609. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5611. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5612. EXPECT_TRUE(
  5613. res->get_header_value("Content-Type")
  5614. .find(
  5615. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5616. 0);
  5617. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5618. }
  5619. TEST_F(ServerTest, StaticFileRangeHead) {
  5620. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5622. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5623. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5624. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5625. EXPECT_EQ(true, res->has_header("Content-Range"));
  5626. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5627. }
  5628. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5629. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5631. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5632. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5633. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5634. EXPECT_EQ(true, res->has_header("Content-Range"));
  5635. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5636. res->get_header_value("Content-Range"));
  5637. EXPECT_EQ("LAST\n", res->body);
  5638. }
  5639. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5640. auto res =
  5641. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5643. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5644. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5645. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5646. EXPECT_EQ(true, res->has_header("Content-Range"));
  5647. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5648. }
  5649. TEST_F(ServerTest, StaticFileBigFile) {
  5650. auto res = cli_.Get("/dir/1MB.txt");
  5651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5652. EXPECT_EQ(StatusCode::OK_200, res->status);
  5653. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5654. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5655. }
  5656. TEST_F(ServerTest, InvalidBaseDirMount) {
  5657. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5658. }
  5659. TEST_F(ServerTest, Binary) {
  5660. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5661. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5662. "application/octet-stream");
  5663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5664. ASSERT_EQ(StatusCode::OK_200, res->status);
  5665. ASSERT_EQ(4U, res->body.size());
  5666. res = cli_.Put("/binary", binary.data(), binary.size(),
  5667. "application/octet-stream");
  5668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5669. ASSERT_EQ(StatusCode::OK_200, res->status);
  5670. ASSERT_EQ(4U, res->body.size());
  5671. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5672. "application/octet-stream");
  5673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5674. ASSERT_EQ(StatusCode::OK_200, res->status);
  5675. ASSERT_EQ(4U, res->body.size());
  5676. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5677. "application/octet-stream");
  5678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5679. ASSERT_EQ(StatusCode::OK_200, res->status);
  5680. ASSERT_EQ(4U, res->body.size());
  5681. }
  5682. TEST_F(ServerTest, BinaryString) {
  5683. auto binary = std::string("\x00\x01\x02\x03", 4);
  5684. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5686. ASSERT_EQ(StatusCode::OK_200, res->status);
  5687. ASSERT_EQ(4U, res->body.size());
  5688. res = cli_.Put("/binary", binary, "application/octet-stream");
  5689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5690. ASSERT_EQ(StatusCode::OK_200, res->status);
  5691. ASSERT_EQ(4U, res->body.size());
  5692. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5694. ASSERT_EQ(StatusCode::OK_200, res->status);
  5695. ASSERT_EQ(4U, res->body.size());
  5696. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5698. ASSERT_EQ(StatusCode::OK_200, res->status);
  5699. ASSERT_EQ(4U, res->body.size());
  5700. }
  5701. TEST_F(ServerTest, EmptyRequest) {
  5702. auto res = cli_.Get("");
  5703. ASSERT_TRUE(!res);
  5704. EXPECT_EQ(Error::Connection, res.error());
  5705. }
  5706. TEST_F(ServerTest, LongRequest) {
  5707. std::string request;
  5708. for (size_t i = 0; i < 545; i++) {
  5709. request += "/TooLongRequest";
  5710. }
  5711. request += "OK";
  5712. auto res = cli_.Get(request.c_str());
  5713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5714. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5715. }
  5716. TEST_F(ServerTest, TooLongRequest) {
  5717. std::string request;
  5718. for (size_t i = 0; i < 546; i++) {
  5719. request += "/TooLongRequest";
  5720. }
  5721. request += "_NG";
  5722. auto start = std::chrono::high_resolution_clock::now();
  5723. cli_.set_keep_alive(true);
  5724. auto res = cli_.Get(request.c_str());
  5725. auto end = std::chrono::high_resolution_clock::now();
  5726. auto elapsed =
  5727. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5728. .count();
  5729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5730. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5731. EXPECT_LE(elapsed, 1000);
  5732. EXPECT_EQ("close", res->get_header_value("Connection"));
  5733. EXPECT_FALSE(cli_.is_socket_open());
  5734. }
  5735. TEST_F(ServerTest, AlmostTooLongRequest) {
  5736. // test for #2046 - URI length check shouldn't include other content on req
  5737. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5738. // leading /, space, HTTP/1.1)
  5739. std::string request =
  5740. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5741. auto res = cli_.Get(request.c_str());
  5742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5743. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5744. }
  5745. TEST_F(ServerTest, LongHeader) {
  5746. Request req;
  5747. req.method = "GET";
  5748. req.path = "/hi";
  5749. std::string host_and_port;
  5750. host_and_port += HOST;
  5751. host_and_port += ":";
  5752. host_and_port += std::to_string(PORT);
  5753. req.headers.emplace("Host", host_and_port.c_str());
  5754. req.headers.emplace("Accept", "*/*");
  5755. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5756. req.headers.emplace(
  5757. "Header-Name",
  5758. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5759. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5760. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5761. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5762. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5763. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5764. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5765. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5766. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5767. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5768. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5769. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5770. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5771. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5772. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5773. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5774. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5775. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5776. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5777. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5778. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5779. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5780. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5781. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5782. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5783. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5784. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5785. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5786. "@@@@@@@@@@@@@@@@");
  5787. auto res = std::make_shared<Response>();
  5788. auto error = Error::Success;
  5789. auto ret = cli_.send(req, *res, error);
  5790. ASSERT_TRUE(ret);
  5791. EXPECT_EQ(StatusCode::OK_200, res->status);
  5792. }
  5793. TEST_F(ServerTest, LongQueryValue) {
  5794. auto start = std::chrono::high_resolution_clock::now();
  5795. cli_.set_keep_alive(true);
  5796. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5797. auto end = std::chrono::high_resolution_clock::now();
  5798. auto elapsed =
  5799. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5800. .count();
  5801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5802. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5803. EXPECT_LE(elapsed, 1000);
  5804. EXPECT_EQ("close", res->get_header_value("Connection"));
  5805. EXPECT_FALSE(cli_.is_socket_open());
  5806. }
  5807. TEST_F(ServerTest, TooLongQueryValue) {
  5808. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5809. ASSERT_FALSE(res);
  5810. EXPECT_EQ(Error::Read, res.error());
  5811. }
  5812. TEST_F(ServerTest, TooLongHeader) {
  5813. Request req;
  5814. req.method = "GET";
  5815. req.path = "/hi";
  5816. std::string host_and_port;
  5817. host_and_port += HOST;
  5818. host_and_port += ":";
  5819. host_and_port += std::to_string(PORT);
  5820. req.headers.emplace("Host", host_and_port.c_str());
  5821. req.headers.emplace("Accept", "*/*");
  5822. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5823. req.headers.emplace(
  5824. "Header-Name",
  5825. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5826. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5827. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5828. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5829. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5830. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5831. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5832. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5833. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5834. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5835. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5836. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5837. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5838. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5839. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5840. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5841. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5842. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5843. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5844. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5845. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5846. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5847. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5848. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5849. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5850. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5851. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5852. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5853. "@@@@@@@@@@@@@@@@@");
  5854. auto res = std::make_shared<Response>();
  5855. auto error = Error::Success;
  5856. auto ret = cli_.send(req, *res, error);
  5857. ASSERT_TRUE(ret);
  5858. EXPECT_EQ(StatusCode::OK_200, res->status);
  5859. }
  5860. TEST_F(ServerTest, HeaderCountAtLimit) {
  5861. // Test with headers just under the 100 limit
  5862. httplib::Headers headers;
  5863. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5864. // This should keep us just under the 100 header limit
  5865. for (int i = 0; i < 95; i++) {
  5866. std::string name = "X-Test-Header-" + std::to_string(i);
  5867. std::string value = "value" + std::to_string(i);
  5868. headers.emplace(name, value);
  5869. }
  5870. // This should work fine as we're under the limit
  5871. auto res = cli_.Get("/hi", headers);
  5872. EXPECT_TRUE(res);
  5873. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5874. }
  5875. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5876. // Test with many headers to exceed the 100 limit
  5877. httplib::Headers headers;
  5878. // Add 150 headers to definitely exceed the 100 limit
  5879. for (int i = 0; i < 150; i++) {
  5880. std::string name = "X-Test-Header-" + std::to_string(i);
  5881. std::string value = "value" + std::to_string(i);
  5882. headers.emplace(name, value);
  5883. }
  5884. // This should fail due to exceeding header count limit
  5885. cli_.set_keep_alive(true);
  5886. auto res = cli_.Get("/hi", headers);
  5887. // The server should respond with 400 Bad Request
  5888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5889. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5890. EXPECT_EQ("close", res->get_header_value("Connection"));
  5891. EXPECT_FALSE(cli_.is_socket_open());
  5892. }
  5893. TEST_F(ServerTest, PercentEncoding) {
  5894. auto res = cli_.Get("/e%6edwith%");
  5895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5896. EXPECT_EQ(StatusCode::OK_200, res->status);
  5897. }
  5898. TEST_F(ServerTest, PercentEncodingUnicode) {
  5899. auto res = cli_.Get("/e%u006edwith%");
  5900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5901. EXPECT_EQ(StatusCode::OK_200, res->status);
  5902. }
  5903. TEST_F(ServerTest, InvalidPercentEncoding) {
  5904. auto res = cli_.Get("/%endwith%");
  5905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5906. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5907. }
  5908. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5909. auto res = cli_.Get("/%uendwith%");
  5910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5911. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5912. }
  5913. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5914. auto res = cli_.Get("/hello?aaa=bbb%");
  5915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5916. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5917. }
  5918. TEST_F(ServerTest, PlusSignEncoding) {
  5919. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5921. EXPECT_EQ(StatusCode::OK_200, res->status);
  5922. EXPECT_EQ("a +b", res->body);
  5923. }
  5924. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5925. // This test simulates a potential DoS attack using many headers
  5926. // to verify our security fix prevents memory exhaustion
  5927. httplib::Headers attack_headers;
  5928. // Attempt to add many headers like an attacker would (200 headers to far
  5929. // exceed limit)
  5930. for (int i = 0; i < 200; i++) {
  5931. std::string name = "X-Attack-Header-" + std::to_string(i);
  5932. std::string value = "attack_payload_" + std::to_string(i);
  5933. attack_headers.emplace(name, value);
  5934. }
  5935. // Try to POST with excessive headers
  5936. cli_.set_keep_alive(true);
  5937. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5938. // Should either fail or return 400 Bad Request due to security limit
  5939. if (res) {
  5940. // If we get a response, it should be 400 Bad Request
  5941. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5942. EXPECT_EQ("close", res->get_header_value("Connection"));
  5943. }
  5944. EXPECT_FALSE(cli_.is_socket_open());
  5945. }
  5946. TEST_F(ServerTest, MultipartFormData) {
  5947. UploadFormDataItems items = {
  5948. {"text1", "text default", "", ""},
  5949. {"text2", "aωb", "", ""},
  5950. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5951. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5952. {"file3", "", "", "application/octet-stream"},
  5953. {"file4", "", "", " application/json tmp-string "}};
  5954. auto res = cli_.Post("/multipart", items);
  5955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5956. EXPECT_EQ(StatusCode::OK_200, res->status);
  5957. }
  5958. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5959. UploadFormDataItems items = {
  5960. {"text", "default text", "", ""},
  5961. {"multi_text1", "aaaaa", "", ""},
  5962. {"multi_text1", "bbbbb", "", ""},
  5963. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5964. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5965. "application/json"},
  5966. };
  5967. auto res = cli_.Post("/multipart/multi_file_values", items);
  5968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5969. EXPECT_EQ(StatusCode::OK_200, res->status);
  5970. }
  5971. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5972. auto res = cli_.Get("/hi");
  5973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5974. EXPECT_EQ(StatusCode::OK_200, res->status);
  5975. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5976. EXPECT_EQ("Hello World!", res->body);
  5977. }
  5978. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5979. Request req;
  5980. req.method = "POST";
  5981. req.path = "/chunked";
  5982. std::string host_and_port;
  5983. host_and_port += HOST;
  5984. host_and_port += ":";
  5985. host_and_port += std::to_string(PORT);
  5986. req.headers.emplace("Host", host_and_port.c_str());
  5987. req.headers.emplace("Accept", "*/*");
  5988. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5989. req.headers.emplace("Content-Type", "text/plain");
  5990. req.headers.emplace("Content-Length", "0");
  5991. req.headers.emplace(
  5992. "Transfer-Encoding",
  5993. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5994. // Client does not chunk, so make a chunked body manually.
  5995. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5996. auto res = std::make_shared<Response>();
  5997. auto error = Error::Success;
  5998. auto ret = cli_.send(req, *res, error);
  5999. ASSERT_TRUE(ret);
  6000. EXPECT_EQ(StatusCode::OK_200, res->status);
  6001. }
  6002. template <typename ClientT>
  6003. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6004. int expected_status) {
  6005. Request req;
  6006. req.method = "POST";
  6007. req.path = "/chunked";
  6008. std::string host_and_port;
  6009. host_and_port += HOST;
  6010. host_and_port += ":";
  6011. host_and_port += std::to_string(PORT);
  6012. req.headers.emplace("Host", host_and_port.c_str());
  6013. req.headers.emplace("Content-Length", "0");
  6014. req.headers.emplace("Transfer-Encoding", "chunked");
  6015. req.body = body;
  6016. auto res = std::make_shared<Response>();
  6017. auto error = Error::Success;
  6018. ASSERT_TRUE(cli.send(req, *res, error));
  6019. EXPECT_EQ(expected_status, res->status);
  6020. }
  6021. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6022. // rather than treat them as valid lengths.
  6023. template <typename ClientT>
  6024. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6025. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6026. }
  6027. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6028. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6029. }
  6030. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6031. expect_chunked_body_rejected(
  6032. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6033. }
  6034. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6035. // chunk-size line carries no CR, LF or other control character ahead of its
  6036. // terminator. Such a line must be refused rather than read as extension text.
  6037. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6038. expect_chunked_body_rejected(
  6039. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6040. }
  6041. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6042. expect_chunked_body_rejected(
  6043. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6044. }
  6045. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6046. expect_chunked_body_rejected(
  6047. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6048. }
  6049. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6050. // The literal stays split: a hex escape consumes every hex digit that
  6051. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6052. expect_chunked_body_rejected(
  6053. cli_, "4;a\x01"
  6054. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6055. }
  6056. TEST_F(ServerTest, AcceptsChunkExtension) {
  6057. expect_chunked_body_status(cli_,
  6058. "4;name=value\r\ndech\r\n"
  6059. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6060. "0;last\r\n\r\n",
  6061. StatusCode::OK_200);
  6062. }
  6063. TEST_F(ServerTest, GetStreamed2) {
  6064. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6066. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6067. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6068. EXPECT_EQ(true, res->has_header("Content-Range"));
  6069. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6070. EXPECT_EQ(std::string("ab"), res->body);
  6071. }
  6072. TEST_F(ServerTest, GetStreamed) {
  6073. auto res = cli_.Get("/streamed");
  6074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6075. EXPECT_EQ(StatusCode::OK_200, res->status);
  6076. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6077. EXPECT_EQ(std::string("aaabbb"), res->body);
  6078. }
  6079. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6080. auto res = cli_.Get("/streamed-without-length",
  6081. Headers{make_range_header({{0, -1}})});
  6082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6083. EXPECT_EQ(StatusCode::OK_200, res->status);
  6084. EXPECT_EQ(false, res->has_header("Content-Length"));
  6085. EXPECT_EQ(false, res->has_header("Content-Range"));
  6086. EXPECT_EQ(std::string("abcdefg"), res->body);
  6087. }
  6088. TEST_F(ServerTest, GetStreamedWithRange1) {
  6089. auto res =
  6090. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6092. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6093. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6094. EXPECT_EQ(true, res->has_header("Content-Range"));
  6095. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6096. EXPECT_EQ(std::string("def"), res->body);
  6097. }
  6098. TEST_F(ServerTest, GetStreamedWithRange2) {
  6099. auto res =
  6100. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6102. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6103. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6104. EXPECT_EQ(true, res->has_header("Content-Range"));
  6105. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6106. EXPECT_EQ(std::string("bcdefg"), res->body);
  6107. }
  6108. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6109. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6111. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6112. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6113. EXPECT_EQ(true, res->has_header("Content-Range"));
  6114. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6115. EXPECT_EQ(std::string("efg"), res->body);
  6116. }
  6117. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6118. auto res =
  6119. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  6120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6121. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6122. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6123. EXPECT_EQ(false, res->has_header("Content-Range"));
  6124. EXPECT_EQ(0U, res->body.size());
  6125. }
  6126. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6127. // Only a 206 is served as a partial representation. Under any other status
  6128. // `apply_ranges()` reported the full content length, so the body must match
  6129. // that header, and the content provider must never be asked for an offset
  6130. // outside the representation.
  6131. auto check = [&](int status, const char *range) {
  6132. auto path =
  6133. std::string("/streamed-with-range?status=") + std::to_string(status);
  6134. auto ctx = path + " Range: " + range;
  6135. auto res = cli_.Get(path, Headers{{"Range", range}});
  6136. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6137. EXPECT_EQ(status, res->status) << ctx;
  6138. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6139. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6140. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6141. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6142. };
  6143. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6144. check(403, "bytes=3-5");
  6145. // The offset is far past the representation.
  6146. check(403, "bytes=100000-100200");
  6147. // `first_pos` is still -1 here, and the bounds asserts in
  6148. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6149. check(403, "bytes=-3");
  6150. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6151. // multipart branch would have written one that is empty.
  6152. check(403, "bytes=1-2, 4-5");
  6153. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6154. // covers the whole representation.
  6155. check(200, "bytes=3-5");
  6156. check(200, "bytes=1-2, 4-5");
  6157. }
  6158. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6159. auto res =
  6160. cli_.Get("/streamed-with-range",
  6161. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6162. "92233720368547758079223372036854775807"}});
  6163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6164. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6165. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6166. EXPECT_EQ(false, res->has_header("Content-Range"));
  6167. EXPECT_EQ(0U, res->body.size());
  6168. }
  6169. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6170. auto res = cli_.Get(
  6171. "/with-range",
  6172. Headers{{"Range",
  6173. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6174. {"Accept-Encoding", ""}});
  6175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6176. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6177. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6178. EXPECT_EQ(true, res->has_header("Content-Range"));
  6179. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6180. EXPECT_EQ(std::string("abcdefg"), res->body);
  6181. }
  6182. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6183. auto res = cli_.Get("/with-range", Headers{
  6184. {"Range", "bytes=0-"},
  6185. {"Accept-Encoding", ""},
  6186. });
  6187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6188. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6189. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6190. EXPECT_EQ(true, res->has_header("Content-Range"));
  6191. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6192. EXPECT_EQ(std::string("abcdefg"), res->body);
  6193. }
  6194. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6195. auto res = cli_.Get("/streamed-with-range",
  6196. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6198. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6199. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6200. EXPECT_EQ(false, res->has_header("Content-Range"));
  6201. EXPECT_EQ(267U, res->body.size());
  6202. // Check that both range contents are present
  6203. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6204. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6205. // Check that Content-Range headers are present for both ranges
  6206. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6207. std::string::npos);
  6208. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6209. std::string::npos);
  6210. }
  6211. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6212. Ranges ranges;
  6213. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6214. ranges.emplace_back(0, -1);
  6215. }
  6216. auto res = cli_.Get("/streamed-with-range?error",
  6217. Headers{{make_range_header(ranges)}});
  6218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6219. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6220. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6221. EXPECT_EQ(false, res->has_header("Content-Range"));
  6222. EXPECT_EQ(0U, res->body.size());
  6223. }
  6224. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6225. auto res = cli_.Get("/streamed-with-range",
  6226. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6228. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6229. EXPECT_EQ(5U, res->body.size());
  6230. // Check that overlapping ranges are coalesced into a single range
  6231. EXPECT_EQ("bcdef", res->body);
  6232. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6233. // Should be single range, not multipart
  6234. EXPECT_TRUE(res->has_header("Content-Range"));
  6235. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6236. }
  6237. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6238. auto res = cli_.Get("/streamed-with-range",
  6239. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6241. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6242. EXPECT_EQ(268U, res->body.size());
  6243. // Check that both range contents are present
  6244. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6245. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6246. // Check that Content-Range headers are present for both ranges
  6247. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6248. std::string::npos);
  6249. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6250. std::string::npos);
  6251. }
  6252. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6253. auto res = cli_.Get("/streamed-with-range",
  6254. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6256. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6257. EXPECT_EQ(269U, res->body.size());
  6258. // Check that both duplicate range contents are present
  6259. size_t first_abc = res->body.find("abc\r\n");
  6260. EXPECT_TRUE(first_abc != std::string::npos);
  6261. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6262. EXPECT_TRUE(second_abc != std::string::npos);
  6263. // Check that Content-Range headers are present for both ranges
  6264. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6265. EXPECT_TRUE(first_range != std::string::npos);
  6266. size_t second_range =
  6267. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6268. EXPECT_TRUE(second_range != std::string::npos);
  6269. }
  6270. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6271. auto res =
  6272. cli_.Get("/streamed-with-range?error",
  6273. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6275. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6276. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6277. EXPECT_EQ(false, res->has_header("Content-Range"));
  6278. EXPECT_EQ(0U, res->body.size());
  6279. }
  6280. TEST_F(ServerTest, GetStreamedEndless) {
  6281. uint64_t offset = 0;
  6282. auto res = cli_.Get("/streamed-cancel",
  6283. [&](const char * /*data*/, uint64_t data_length) {
  6284. if (offset < 100) {
  6285. offset += data_length;
  6286. return true;
  6287. }
  6288. return false;
  6289. });
  6290. ASSERT_TRUE(!res);
  6291. EXPECT_EQ(Error::Canceled, res.error());
  6292. }
  6293. TEST_F(ServerTest, ClientStop) {
  6294. std::atomic_size_t count{4};
  6295. std::vector<std::thread> threads;
  6296. for (auto i = count.load(); i != 0; --i) {
  6297. threads.emplace_back([&]() {
  6298. auto res = cli_.Get("/streamed-cancel",
  6299. [&](const char *, uint64_t) { return true; });
  6300. --count;
  6301. ASSERT_TRUE(!res);
  6302. EXPECT_TRUE(res.error() == Error::Canceled ||
  6303. res.error() == Error::Read || res.error() == Error::Write);
  6304. });
  6305. }
  6306. std::this_thread::sleep_for(std::chrono::seconds(2));
  6307. while (count != 0) {
  6308. cli_.stop();
  6309. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6310. }
  6311. for (auto &t : threads) {
  6312. t.join();
  6313. }
  6314. }
  6315. TEST_F(ServerTest, GetWithRange1) {
  6316. auto res = cli_.Get("/with-range", Headers{
  6317. make_range_header({{3, 5}}),
  6318. {"Accept-Encoding", ""},
  6319. });
  6320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6321. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6322. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6323. EXPECT_EQ(true, res->has_header("Content-Range"));
  6324. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6325. EXPECT_EQ(std::string("def"), res->body);
  6326. }
  6327. TEST_F(ServerTest, GetWithRange2) {
  6328. auto res = cli_.Get("/with-range", Headers{
  6329. make_range_header({{1, -1}}),
  6330. {"Accept-Encoding", ""},
  6331. });
  6332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6333. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6334. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6335. EXPECT_EQ(true, res->has_header("Content-Range"));
  6336. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6337. EXPECT_EQ(std::string("bcdefg"), res->body);
  6338. }
  6339. TEST_F(ServerTest, GetWithRange3) {
  6340. auto res = cli_.Get("/with-range", Headers{
  6341. make_range_header({{0, 0}}),
  6342. {"Accept-Encoding", ""},
  6343. });
  6344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6345. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6346. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6347. EXPECT_EQ(true, res->has_header("Content-Range"));
  6348. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6349. EXPECT_EQ(std::string("a"), res->body);
  6350. }
  6351. TEST_F(ServerTest, GetWithRange4) {
  6352. auto res = cli_.Get("/with-range", Headers{
  6353. make_range_header({{-1, 2}}),
  6354. {"Accept-Encoding", ""},
  6355. });
  6356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6357. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6358. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6359. EXPECT_EQ(true, res->has_header("Content-Range"));
  6360. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6361. EXPECT_EQ(std::string("fg"), res->body);
  6362. }
  6363. TEST_F(ServerTest, GetWithRange5) {
  6364. auto res = cli_.Get("/with-range", Headers{
  6365. make_range_header({{0, 5}}),
  6366. {"Accept-Encoding", ""},
  6367. });
  6368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6369. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6370. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6371. EXPECT_EQ(true, res->has_header("Content-Range"));
  6372. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6373. EXPECT_EQ(std::string("abcdef"), res->body);
  6374. }
  6375. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6376. auto res =
  6377. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6379. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6380. }
  6381. TEST_F(ServerTest, GetWithRangeMultipart) {
  6382. auto res =
  6383. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6385. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6386. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6387. EXPECT_EQ(false, res->has_header("Content-Range"));
  6388. EXPECT_EQ(267U, res->body.size());
  6389. }
  6390. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6391. auto res = cli_.Get("/with-range",
  6392. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6394. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6395. }
  6396. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6397. auto res = cli_.Get("/with-range-customized-response",
  6398. Headers{{make_range_header({{1, 2}})}});
  6399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6400. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6401. EXPECT_EQ(true, res->has_header("Content-Length"));
  6402. EXPECT_EQ(false, res->has_header("Content-Range"));
  6403. EXPECT_EQ(JSON_DATA, res->body);
  6404. }
  6405. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6406. auto res = cli_.Get("/with-range-customized-response",
  6407. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6409. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6410. EXPECT_EQ(true, res->has_header("Content-Length"));
  6411. EXPECT_EQ(false, res->has_header("Content-Range"));
  6412. EXPECT_EQ(JSON_DATA, res->body);
  6413. }
  6414. TEST_F(ServerTest, Issue1772) {
  6415. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6417. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6418. }
  6419. TEST_F(ServerTest, Issue609) {
  6420. auto res = cli_.Delete("/issue609");
  6421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6422. EXPECT_EQ(StatusCode::OK_200, res->status);
  6423. EXPECT_EQ(std::string("ok"), res->body);
  6424. }
  6425. TEST_F(ServerTest, GetStreamedChunked) {
  6426. auto res = cli_.Get("/streamed-chunked");
  6427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6428. EXPECT_EQ(StatusCode::OK_200, res->status);
  6429. EXPECT_EQ(std::string("123456789"), res->body);
  6430. }
  6431. TEST_F(ServerTest, GetStreamedChunked2) {
  6432. auto res = cli_.Get("/streamed-chunked2");
  6433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6434. EXPECT_EQ(StatusCode::OK_200, res->status);
  6435. EXPECT_EQ(std::string("123456789"), res->body);
  6436. }
  6437. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6438. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6440. EXPECT_EQ(StatusCode::OK_200, res->status);
  6441. EXPECT_EQ(std::string("123456789"), res->body);
  6442. EXPECT_TRUE(res->has_header("Trailer"));
  6443. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6444. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6445. // Trailers are now stored separately from headers (security fix)
  6446. EXPECT_EQ(2U, res->trailers.size());
  6447. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6448. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6449. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6450. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6451. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6452. // Verify trailers are NOT in headers (security verification)
  6453. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6454. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6455. }
  6456. TEST_F(ServerTest, LargeChunkedPost) {
  6457. Request req;
  6458. req.method = "POST";
  6459. req.path = "/large-chunked";
  6460. std::string host_and_port;
  6461. host_and_port += HOST;
  6462. host_and_port += ":";
  6463. host_and_port += std::to_string(PORT);
  6464. req.headers.emplace("Host", host_and_port.c_str());
  6465. req.headers.emplace("Accept", "*/*");
  6466. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6467. req.headers.emplace("Content-Type", "text/plain");
  6468. req.headers.emplace("Content-Length", "0");
  6469. req.headers.emplace("Transfer-Encoding", "chunked");
  6470. std::string long_string(30 * 1024u, 'a');
  6471. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6472. // Attempt to make a large enough post to exceed OS buffers, to test that
  6473. // the server handles short reads if the full chunk data isn't available.
  6474. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6475. auto res = std::make_shared<Response>();
  6476. auto error = Error::Success;
  6477. auto ret = cli_.send(req, *res, error);
  6478. ASSERT_TRUE(ret);
  6479. EXPECT_EQ(StatusCode::OK_200, res->status);
  6480. }
  6481. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6482. auto res = cli_.Get("/remote_addr");
  6483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6484. EXPECT_EQ(StatusCode::OK_200, res->status);
  6485. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6486. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6487. }
  6488. TEST_F(ServerTest, GetMethodLocalAddr) {
  6489. auto res = cli_.Get("/local_addr");
  6490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6491. EXPECT_EQ(StatusCode::OK_200, res->status);
  6492. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6493. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6494. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6495. }
  6496. TEST_F(ServerTest, HTTPResponseSplitting) {
  6497. auto res = cli_.Get("/http_response_splitting");
  6498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6499. EXPECT_EQ(StatusCode::OK_200, res->status);
  6500. }
  6501. TEST_F(ServerTest, SlowRequest) {
  6502. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6503. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6504. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6505. }
  6506. #if 0
  6507. TEST_F(ServerTest, SlowPost) {
  6508. char buffer[64 * 1024];
  6509. memset(buffer, 0x42, sizeof(buffer));
  6510. auto res = cli_.Post(
  6511. "/slowpost", 64 * 1024 * 1024,
  6512. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6513. auto ret = sink.write(buffer, sizeof(buffer));
  6514. EXPECT_TRUE(ret);
  6515. return true;
  6516. },
  6517. "text/plain");
  6518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6519. EXPECT_EQ(StatusCode::OK_200, res->status);
  6520. }
  6521. TEST_F(ServerTest, SlowPostFail) {
  6522. char buffer[64 * 1024];
  6523. memset(buffer, 0x42, sizeof(buffer));
  6524. cli_.set_write_timeout(std::chrono::seconds(0));
  6525. auto res = cli_.Post(
  6526. "/slowpost", 64 * 1024 * 1024,
  6527. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6528. sink.write(buffer, sizeof(buffer));
  6529. return true;
  6530. },
  6531. "text/plain");
  6532. ASSERT_TRUE(!res);
  6533. EXPECT_EQ(Error::Write, res.error());
  6534. }
  6535. #endif
  6536. TEST_F(ServerTest, Put) {
  6537. auto res = cli_.Put("/put", "PUT", "text/plain");
  6538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6539. EXPECT_EQ(StatusCode::OK_200, res->status);
  6540. EXPECT_EQ("PUT", res->body);
  6541. }
  6542. TEST_F(ServerTest, PutWithContentProvider) {
  6543. auto res = cli_.Put(
  6544. "/put", 3,
  6545. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6546. sink.os << "PUT";
  6547. return true;
  6548. },
  6549. "text/plain");
  6550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6551. EXPECT_EQ(StatusCode::OK_200, res->status);
  6552. EXPECT_EQ("PUT", res->body);
  6553. }
  6554. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6555. auto res = cli_.Post(
  6556. "/post", 42,
  6557. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6558. return false;
  6559. },
  6560. "text/plain");
  6561. ASSERT_TRUE(!res);
  6562. EXPECT_EQ(Error::Canceled, res.error());
  6563. }
  6564. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6565. auto res = cli_.Put(
  6566. "/put",
  6567. [](size_t /*offset*/, DataSink &sink) {
  6568. sink.os << "PUT";
  6569. sink.done();
  6570. return true;
  6571. },
  6572. "text/plain");
  6573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6574. EXPECT_EQ(StatusCode::OK_200, res->status);
  6575. EXPECT_EQ("PUT", res->body);
  6576. }
  6577. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6578. auto res = cli_.Post(
  6579. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6580. "text/plain");
  6581. ASSERT_TRUE(!res);
  6582. EXPECT_EQ(Error::Canceled, res.error());
  6583. }
  6584. TEST_F(ServerTest, PostLoopBack) {
  6585. std::string body;
  6586. auto res = cli_.Post(
  6587. "/post-loopback", 9,
  6588. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6589. EXPECT_EQ(9u, length);
  6590. sink.write("123", 3);
  6591. sink.write("456", 3);
  6592. sink.write("789", 3);
  6593. return true;
  6594. },
  6595. "text/plain",
  6596. [&body](const char *data, size_t data_length) {
  6597. body.append(data, data_length);
  6598. return true;
  6599. });
  6600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6601. EXPECT_EQ(StatusCode::OK_200, res->status);
  6602. EXPECT_EQ("123456789", body);
  6603. }
  6604. TEST_F(ServerTest, PutLoopBack) {
  6605. std::string body;
  6606. auto res = cli_.Put(
  6607. "/put-loopback", 9,
  6608. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6609. EXPECT_EQ(9u, length);
  6610. sink.write("123", 3);
  6611. sink.write("456", 3);
  6612. sink.write("789", 3);
  6613. return true;
  6614. },
  6615. "text/plain",
  6616. [&body](const char *data, size_t data_length) {
  6617. body.append(data, data_length);
  6618. return true;
  6619. });
  6620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6621. EXPECT_EQ(StatusCode::OK_200, res->status);
  6622. EXPECT_EQ("123456789", body);
  6623. }
  6624. TEST_F(ServerTest, PatchLoopBack) {
  6625. std::string body;
  6626. auto res = cli_.Patch(
  6627. "/patch-loopback", 9,
  6628. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6629. EXPECT_EQ(9u, length);
  6630. sink.write("123", 3);
  6631. sink.write("456", 3);
  6632. sink.write("789", 3);
  6633. return true;
  6634. },
  6635. "text/plain",
  6636. [&body](const char *data, size_t data_length) {
  6637. body.append(data, data_length);
  6638. return true;
  6639. });
  6640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6641. EXPECT_EQ(StatusCode::OK_200, res->status);
  6642. EXPECT_EQ("123456789", body);
  6643. }
  6644. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6645. std::string body;
  6646. auto res = cli_.Post(
  6647. "/post-loopback",
  6648. [](size_t /*offset*/, DataSink &sink) {
  6649. sink.write("123", 3);
  6650. sink.write("456", 3);
  6651. sink.write("789", 3);
  6652. sink.done();
  6653. return true;
  6654. },
  6655. "text/plain",
  6656. [&body](const char *data, size_t data_length) {
  6657. body.append(data, data_length);
  6658. return true;
  6659. });
  6660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6661. EXPECT_EQ(StatusCode::OK_200, res->status);
  6662. EXPECT_EQ("123456789", body);
  6663. }
  6664. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6665. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6666. cli_.set_compress(true);
  6667. auto res = cli_.Put(
  6668. "/put", 3,
  6669. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6670. sink.os << "PUT";
  6671. return true;
  6672. },
  6673. "text/plain");
  6674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6675. EXPECT_EQ(StatusCode::OK_200, res->status);
  6676. EXPECT_EQ("PUT", res->body);
  6677. }
  6678. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6679. cli_.set_compress(true);
  6680. auto res = cli_.Post(
  6681. "/post", 42,
  6682. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6683. return false;
  6684. },
  6685. "text/plain");
  6686. ASSERT_TRUE(!res);
  6687. EXPECT_EQ(Error::Canceled, res.error());
  6688. }
  6689. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6690. cli_.set_compress(true);
  6691. auto res = cli_.Put(
  6692. "/put",
  6693. [](size_t /*offset*/, DataSink &sink) {
  6694. sink.os << "PUT";
  6695. sink.done();
  6696. return true;
  6697. },
  6698. "text/plain");
  6699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6700. EXPECT_EQ(StatusCode::OK_200, res->status);
  6701. EXPECT_EQ("PUT", res->body);
  6702. }
  6703. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6704. cli_.set_compress(true);
  6705. auto res = cli_.Post(
  6706. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6707. "text/plain");
  6708. ASSERT_TRUE(!res);
  6709. EXPECT_EQ(Error::Canceled, res.error());
  6710. }
  6711. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6712. cli_.set_compress(true);
  6713. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6715. EXPECT_EQ(StatusCode::OK_200, res->status);
  6716. EXPECT_EQ(LARGE_DATA, res->body);
  6717. }
  6718. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6719. #ifdef CPPHTTPLIB_SSL_ENABLED
  6720. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6721. Client cli(s.c_str());
  6722. cli.enable_server_certificate_verification(false);
  6723. #else
  6724. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6725. Client cli(s.c_str());
  6726. #endif
  6727. cli.set_compress(true);
  6728. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6730. EXPECT_EQ(StatusCode::OK_200, res->status);
  6731. EXPECT_EQ(LARGE_DATA, res->body);
  6732. // The compressed size should be less than a 10th of the original. May vary
  6733. // depending on the zlib library.
  6734. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6735. static_cast<uint64_t>(10 * 1024 * 1024));
  6736. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6737. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6738. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6739. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6740. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6741. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6742. #endif
  6743. }
  6744. TEST_F(ServerTest, PutContentWithDeflate) {
  6745. cli_.set_compress(false);
  6746. Headers headers;
  6747. headers.emplace("Content-Encoding", "deflate");
  6748. // PUT in deflate format:
  6749. auto res = cli_.Put("/put", headers,
  6750. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6752. EXPECT_EQ(StatusCode::OK_200, res->status);
  6753. EXPECT_EQ("PUT", res->body);
  6754. }
  6755. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6756. Headers headers;
  6757. headers.emplace("Accept-Encoding", "gzip, deflate");
  6758. auto res = cli_.Get("/streamed-chunked", headers);
  6759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6760. EXPECT_EQ(StatusCode::OK_200, res->status);
  6761. EXPECT_EQ(std::string("123456789"), res->body);
  6762. }
  6763. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6764. Headers headers;
  6765. headers.emplace("Accept-Encoding", "gzip, deflate");
  6766. auto res = cli_.Get("/streamed-chunked2", headers);
  6767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6768. EXPECT_EQ(StatusCode::OK_200, res->status);
  6769. EXPECT_EQ(std::string("123456789"), res->body);
  6770. }
  6771. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6772. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6774. EXPECT_EQ(StatusCode::OK_200, res->status);
  6775. }
  6776. TEST(GzipDecompressor, ChunkedDecompression) {
  6777. std::string data;
  6778. for (size_t i = 0; i < 32 * 1024; ++i) {
  6779. data.push_back(static_cast<char>('a' + i % 26));
  6780. }
  6781. std::string compressed_data;
  6782. {
  6783. httplib::detail::gzip_compressor compressor;
  6784. bool result = compressor.compress(
  6785. data.data(), data.size(),
  6786. /*last=*/true,
  6787. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6788. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6789. compressed_data_size);
  6790. return true;
  6791. });
  6792. ASSERT_TRUE(result);
  6793. }
  6794. std::string decompressed_data;
  6795. {
  6796. httplib::detail::gzip_decompressor decompressor;
  6797. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6798. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6799. size_t chunk_size = 130;
  6800. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6801. chunk_begin += chunk_size) {
  6802. size_t current_chunk_size =
  6803. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6804. bool result = decompressor.decompress(
  6805. compressed_data.data() + chunk_begin, current_chunk_size,
  6806. [&](const char *decompressed_data_chunk,
  6807. size_t decompressed_data_chunk_size) {
  6808. decompressed_data.insert(decompressed_data.size(),
  6809. decompressed_data_chunk,
  6810. decompressed_data_chunk_size);
  6811. return true;
  6812. });
  6813. ASSERT_TRUE(result);
  6814. }
  6815. }
  6816. ASSERT_EQ(data, decompressed_data);
  6817. }
  6818. TEST(GzipDecompressor, DeflateDecompression) {
  6819. std::string original_text = "Raw deflate without gzip";
  6820. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6821. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6822. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6823. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6824. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6825. std::string decompressed_data;
  6826. {
  6827. httplib::detail::gzip_decompressor decompressor;
  6828. bool result = decompressor.decompress(
  6829. compressed_data.data(), compressed_data.size(),
  6830. [&](const char *decompressed_data_chunk,
  6831. size_t decompressed_data_chunk_size) {
  6832. decompressed_data.insert(decompressed_data.size(),
  6833. decompressed_data_chunk,
  6834. decompressed_data_chunk_size);
  6835. return true;
  6836. });
  6837. ASSERT_TRUE(result);
  6838. }
  6839. ASSERT_EQ(original_text, decompressed_data);
  6840. }
  6841. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6842. std::string original_text = "Raw deflate without gzip";
  6843. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6844. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6845. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6846. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6847. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6848. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6849. std::string decompressed_data;
  6850. {
  6851. httplib::detail::gzip_decompressor decompressor;
  6852. bool result = decompressor.decompress(
  6853. compressed_data.data(), compressed_data.size(),
  6854. [&](const char *decompressed_data_chunk,
  6855. size_t decompressed_data_chunk_size) {
  6856. decompressed_data.insert(decompressed_data.size(),
  6857. decompressed_data_chunk,
  6858. decompressed_data_chunk_size);
  6859. return true;
  6860. });
  6861. ASSERT_TRUE(result);
  6862. }
  6863. ASSERT_EQ(original_text, decompressed_data);
  6864. }
  6865. #endif
  6866. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6867. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6868. Headers headers;
  6869. headers.emplace("Accept-Encoding", "br");
  6870. auto res = cli_.Get("/streamed-chunked", headers);
  6871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6872. EXPECT_EQ(StatusCode::OK_200, res->status);
  6873. EXPECT_EQ(std::string("123456789"), res->body);
  6874. }
  6875. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6876. Headers headers;
  6877. headers.emplace("Accept-Encoding", "br");
  6878. auto res = cli_.Get("/streamed-chunked2", headers);
  6879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6880. EXPECT_EQ(StatusCode::OK_200, res->status);
  6881. EXPECT_EQ(std::string("123456789"), res->body);
  6882. }
  6883. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6884. cli_.set_compress(true);
  6885. auto res = cli_.Put(
  6886. "/put", 3,
  6887. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6888. sink.os << "PUT";
  6889. return true;
  6890. },
  6891. "text/plain");
  6892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6893. EXPECT_EQ(StatusCode::OK_200, res->status);
  6894. EXPECT_EQ("PUT", res->body);
  6895. }
  6896. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6897. cli_.set_compress(true);
  6898. auto res = cli_.Put(
  6899. "/put",
  6900. [](size_t /*offset*/, DataSink &sink) {
  6901. sink.os << "PUT";
  6902. sink.done();
  6903. return true;
  6904. },
  6905. "text/plain");
  6906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6907. EXPECT_EQ(StatusCode::OK_200, res->status);
  6908. EXPECT_EQ("PUT", res->body);
  6909. }
  6910. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6911. cli_.set_compress(true);
  6912. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6914. EXPECT_EQ(StatusCode::OK_200, res->status);
  6915. EXPECT_EQ(LARGE_DATA, res->body);
  6916. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6917. }
  6918. #endif
  6919. TEST_F(ServerTest, Patch) {
  6920. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6922. EXPECT_EQ(StatusCode::OK_200, res->status);
  6923. EXPECT_EQ("PATCH", res->body);
  6924. }
  6925. TEST_F(ServerTest, Delete) {
  6926. auto res = cli_.Delete("/delete");
  6927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6928. EXPECT_EQ(StatusCode::OK_200, res->status);
  6929. EXPECT_EQ("DELETE", res->body);
  6930. }
  6931. TEST_F(ServerTest, DeleteContentReceiver) {
  6932. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6934. EXPECT_EQ(StatusCode::OK_200, res->status);
  6935. EXPECT_EQ("content", res->body);
  6936. }
  6937. TEST_F(ServerTest, Options) {
  6938. auto res = cli_.Options("*");
  6939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6940. EXPECT_EQ(StatusCode::OK_200, res->status);
  6941. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6942. EXPECT_TRUE(res->body.empty());
  6943. }
  6944. TEST_F(ServerTest, URL) {
  6945. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6947. EXPECT_EQ(StatusCode::OK_200, res->status);
  6948. }
  6949. TEST_F(ServerTest, ArrayParam) {
  6950. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6952. EXPECT_EQ(StatusCode::OK_200, res->status);
  6953. }
  6954. TEST_F(ServerTest, ArrayParamValues) {
  6955. auto res =
  6956. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6958. EXPECT_EQ(StatusCode::OK_200, res->status);
  6959. }
  6960. TEST_F(ServerTest, NoMultipleHeaders) {
  6961. Headers headers = {{"Content-Length", "5"}};
  6962. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6963. "text/plain");
  6964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6965. EXPECT_EQ(StatusCode::OK_200, res->status);
  6966. }
  6967. TEST_F(ServerTest, PostContentReceiver) {
  6968. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6970. ASSERT_EQ(StatusCode::OK_200, res->status);
  6971. ASSERT_EQ("content", res->body);
  6972. }
  6973. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6974. UploadFormDataItems items = {
  6975. {"text1", "text default", "", ""},
  6976. {"text2", "aωb", "", ""},
  6977. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6978. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6979. {"file3", "", "", "application/octet-stream"},
  6980. };
  6981. auto res = cli_.Post("/content_receiver", items);
  6982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6983. EXPECT_EQ(StatusCode::OK_200, res->status);
  6984. }
  6985. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6986. UploadFormDataItems items = {
  6987. {"text1", "text default", "", ""},
  6988. {"text2", "aωb", "", ""},
  6989. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6990. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6991. {"file3", "", "", "application/octet-stream"},
  6992. };
  6993. auto boundary = std::string("+++++");
  6994. std::string body;
  6995. for (const auto &item : items) {
  6996. body += "--" + boundary + "\r\n";
  6997. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6998. if (!item.filename.empty()) {
  6999. body += "; filename=\"" + item.filename + "\"";
  7000. }
  7001. body += "\r\n";
  7002. if (!item.content_type.empty()) {
  7003. body += "Content-Type: " + item.content_type + "\r\n";
  7004. }
  7005. body += "\r\n";
  7006. body += item.content + "\r\n";
  7007. }
  7008. body += "--" + boundary + "--\r\n";
  7009. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7010. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7012. EXPECT_EQ(StatusCode::OK_200, res->status);
  7013. }
  7014. TEST(MultipartFormDataTest, FieldEscaping) {
  7015. Server svr;
  7016. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7017. const ContentReader &content_reader) {
  7018. ASSERT_TRUE(req.is_multipart_form_data());
  7019. std::vector<FormData> received;
  7020. content_reader(
  7021. [&](const FormData &file) {
  7022. received.push_back(file);
  7023. return true;
  7024. },
  7025. [&](const char *data, size_t data_length) {
  7026. received.back().content.append(data, data_length);
  7027. return true;
  7028. });
  7029. // '"', CR and LF in names and filenames are escaped following the
  7030. // WHATWG HTML standard, so each part still parses as a single part
  7031. // with no injected headers. Content types get CR/LF escaped too,
  7032. // while '"' (legal there, e.g. quoted charset) is preserved.
  7033. ASSERT_EQ(4U, received.size());
  7034. EXPECT_EQ("na%22me", received[0].name);
  7035. EXPECT_EQ("quoted name", received[0].content);
  7036. EXPECT_EQ("file", received[1].name);
  7037. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7038. received[1].filename);
  7039. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7040. EXPECT_EQ("injected", received[1].content);
  7041. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7042. EXPECT_EQ("my%22file.txt", received[2].filename);
  7043. EXPECT_EQ("cr lf name", received[2].content);
  7044. EXPECT_EQ("typed", received[3].name);
  7045. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7046. received[3].content_type);
  7047. EXPECT_EQ("typed content", received[3].content);
  7048. });
  7049. auto port = svr.bind_to_any_port("localhost");
  7050. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7051. auto se = detail::scope_exit([&] {
  7052. svr.stop();
  7053. t.join();
  7054. ASSERT_FALSE(svr.is_running());
  7055. });
  7056. svr.wait_until_ready();
  7057. Client cli("localhost", port);
  7058. UploadFormDataItems items = {
  7059. {"na\"me", "quoted name", "", ""},
  7060. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7061. "application/octet-stream"},
  7062. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7063. {"typed", "typed content", "",
  7064. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7065. };
  7066. auto res = cli.Post("/post", items);
  7067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7068. EXPECT_EQ(StatusCode::OK_200, res->status);
  7069. }
  7070. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7071. const UploadFormDataItems items = {
  7072. {"name1", "Content 1", "", ""},
  7073. {"name2", "Content 2", "file2.txt", "text/plain"},
  7074. };
  7075. Server svr;
  7076. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7077. const ContentReader &content_reader) {
  7078. ASSERT_TRUE(req.is_multipart_form_data());
  7079. std::vector<FormData> received;
  7080. content_reader(
  7081. [&](const FormData &file) {
  7082. received.push_back(file);
  7083. return true;
  7084. },
  7085. [&](const char *data, size_t data_length) {
  7086. received.back().content.append(data, data_length);
  7087. return true;
  7088. });
  7089. ASSERT_EQ(2U, received.size());
  7090. EXPECT_EQ("name1", received[0].name);
  7091. EXPECT_EQ("Content 1", received[0].content);
  7092. EXPECT_EQ("name2", received[1].name);
  7093. EXPECT_EQ("Content 2", received[1].content);
  7094. EXPECT_EQ("file2.txt", received[1].filename);
  7095. EXPECT_EQ("text/plain", received[1].content_type);
  7096. });
  7097. auto port = svr.bind_to_any_port("localhost");
  7098. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7099. auto se = detail::scope_exit([&] {
  7100. svr.stop();
  7101. t.join();
  7102. ASSERT_FALSE(svr.is_running());
  7103. });
  7104. svr.wait_until_ready();
  7105. Client cli("localhost", port);
  7106. // Whole-body serialization with a generated boundary
  7107. {
  7108. MultipartFormDataWriter writer;
  7109. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7110. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7111. writer.content_type());
  7112. auto body = writer.serialize(items);
  7113. EXPECT_EQ(body.size(), writer.content_length(items));
  7114. auto res = cli.Post("/post", body, writer.content_type());
  7115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7116. EXPECT_EQ(StatusCode::OK_200, res->status);
  7117. }
  7118. // Per-part framing with a custom boundary via a content provider
  7119. {
  7120. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7121. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7122. MultipartFormDataWriter writer("custom-boundary_123");
  7123. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7124. std::string body;
  7125. for (const auto &item : items) {
  7126. body += writer.item_begin(item);
  7127. body += item.content;
  7128. body += MultipartFormDataWriter::item_end();
  7129. }
  7130. body += writer.finish();
  7131. EXPECT_EQ(body.size(), writer.content_length(items));
  7132. auto res = cli.Post(
  7133. "/post", body.size(),
  7134. [&](size_t offset, size_t length, DataSink &sink) {
  7135. sink.write(body.data() + offset, length);
  7136. return true;
  7137. },
  7138. writer.content_type());
  7139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7140. EXPECT_EQ(StatusCode::OK_200, res->status);
  7141. }
  7142. }
  7143. TEST_F(ServerTest, PostContentReceiverGzip) {
  7144. cli_.set_compress(true);
  7145. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7147. ASSERT_EQ(StatusCode::OK_200, res->status);
  7148. ASSERT_EQ("content", res->body);
  7149. }
  7150. TEST_F(ServerTest, PutContentReceiver) {
  7151. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7153. ASSERT_EQ(StatusCode::OK_200, res->status);
  7154. ASSERT_EQ("content", res->body);
  7155. }
  7156. TEST_F(ServerTest, PatchContentReceiver) {
  7157. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7159. ASSERT_EQ(StatusCode::OK_200, res->status);
  7160. ASSERT_EQ("content", res->body);
  7161. }
  7162. template <typename ClientType>
  7163. void TestWithHeadersAndContentReceiver(
  7164. ClientType &cli,
  7165. std::function<Result(ClientType &, const std::string &, const Headers &,
  7166. const std::string &, const std::string &,
  7167. ContentReceiver, DownloadProgress)>
  7168. request_func) {
  7169. Headers headers;
  7170. headers.emplace("X-Custom-Header", "test-value");
  7171. std::string received_body;
  7172. auto res = request_func(
  7173. cli, "/content_receiver", headers, "content", "application/json",
  7174. [&](const char *data, size_t data_length) {
  7175. received_body.append(data, data_length);
  7176. return true;
  7177. },
  7178. nullptr);
  7179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7180. EXPECT_EQ(StatusCode::OK_200, res->status);
  7181. EXPECT_EQ("content", received_body);
  7182. }
  7183. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7184. #ifdef CPPHTTPLIB_SSL_ENABLED
  7185. using ClientT = SSLClient;
  7186. #else
  7187. using ClientT = Client;
  7188. #endif
  7189. TestWithHeadersAndContentReceiver<ClientT>(
  7190. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7191. const std::string &body, const std::string &content_type,
  7192. ContentReceiver receiver, DownloadProgress progress) {
  7193. return cli.Post(path, headers, body, content_type, receiver, progress);
  7194. });
  7195. }
  7196. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7197. #ifdef CPPHTTPLIB_SSL_ENABLED
  7198. using ClientT = SSLClient;
  7199. #else
  7200. using ClientT = Client;
  7201. #endif
  7202. TestWithHeadersAndContentReceiver<ClientT>(
  7203. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7204. const std::string &body, const std::string &content_type,
  7205. ContentReceiver receiver, DownloadProgress progress) {
  7206. return cli.Put(path, headers, body, content_type, receiver, progress);
  7207. });
  7208. }
  7209. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7210. #ifdef CPPHTTPLIB_SSL_ENABLED
  7211. using ClientT = SSLClient;
  7212. #else
  7213. using ClientT = Client;
  7214. #endif
  7215. TestWithHeadersAndContentReceiver<ClientT>(
  7216. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7217. const std::string &body, const std::string &content_type,
  7218. ContentReceiver receiver, DownloadProgress progress) {
  7219. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7220. });
  7221. }
  7222. template <typename ClientType>
  7223. void TestWithHeadersAndContentReceiverWithProgress(
  7224. ClientType &cli,
  7225. std::function<Result(ClientType &, const std::string &, const Headers &,
  7226. const std::string &, const std::string &,
  7227. ContentReceiver, DownloadProgress)>
  7228. request_func) {
  7229. Headers headers;
  7230. headers.emplace("X-Test-Header", "progress-test");
  7231. std::string received_body;
  7232. auto progress_called = false;
  7233. auto res = request_func(
  7234. cli, "/content_receiver", headers, "content", "text/plain",
  7235. [&](const char *data, size_t data_length) {
  7236. received_body.append(data, data_length);
  7237. return true;
  7238. },
  7239. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7240. progress_called = true;
  7241. return true;
  7242. });
  7243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7244. EXPECT_EQ(StatusCode::OK_200, res->status);
  7245. EXPECT_EQ("content", received_body);
  7246. EXPECT_TRUE(progress_called);
  7247. }
  7248. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7249. #ifdef CPPHTTPLIB_SSL_ENABLED
  7250. using ClientT = SSLClient;
  7251. #else
  7252. using ClientT = Client;
  7253. #endif
  7254. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7255. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7256. const std::string &body, const std::string &content_type,
  7257. ContentReceiver receiver, DownloadProgress progress) {
  7258. return cli.Post(path, headers, body, content_type, receiver, progress);
  7259. });
  7260. }
  7261. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7262. #ifdef CPPHTTPLIB_SSL_ENABLED
  7263. using ClientT = SSLClient;
  7264. #else
  7265. using ClientT = Client;
  7266. #endif
  7267. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7268. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7269. const std::string &body, const std::string &content_type,
  7270. ContentReceiver receiver, DownloadProgress progress) {
  7271. return cli.Put(path, headers, body, content_type, receiver, progress);
  7272. });
  7273. }
  7274. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7275. #ifdef CPPHTTPLIB_SSL_ENABLED
  7276. using ClientT = SSLClient;
  7277. #else
  7278. using ClientT = Client;
  7279. #endif
  7280. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7281. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7282. const std::string &body, const std::string &content_type,
  7283. ContentReceiver receiver, DownloadProgress progress) {
  7284. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7285. });
  7286. }
  7287. template <typename ClientType>
  7288. void TestWithHeadersAndContentReceiverError(
  7289. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7290. const Headers &, const std::string &,
  7291. const std::string &, ContentReceiver)>
  7292. request_func) {
  7293. Headers headers;
  7294. headers.emplace("X-Error-Test", "true");
  7295. std::string received_body;
  7296. auto receiver_failed = false;
  7297. auto res =
  7298. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7299. [&](const char *data, size_t data_length) {
  7300. received_body.append(data, data_length);
  7301. receiver_failed = true;
  7302. return false;
  7303. });
  7304. ASSERT_FALSE(res);
  7305. EXPECT_TRUE(receiver_failed);
  7306. }
  7307. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7308. #ifdef CPPHTTPLIB_SSL_ENABLED
  7309. using ClientT = SSLClient;
  7310. #else
  7311. using ClientT = Client;
  7312. #endif
  7313. TestWithHeadersAndContentReceiverError<ClientT>(
  7314. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7315. const std::string &body, const std::string &content_type,
  7316. ContentReceiver receiver) {
  7317. return cli.Post(path, headers, body, content_type, receiver);
  7318. });
  7319. }
  7320. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7321. #ifdef CPPHTTPLIB_SSL_ENABLED
  7322. using ClientT = SSLClient;
  7323. #else
  7324. using ClientT = Client;
  7325. #endif
  7326. TestWithHeadersAndContentReceiverError<ClientT>(
  7327. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7328. const std::string &body, const std::string &content_type,
  7329. ContentReceiver receiver) {
  7330. return cli.Put(path, headers, body, content_type, receiver);
  7331. });
  7332. }
  7333. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7334. #ifdef CPPHTTPLIB_SSL_ENABLED
  7335. using ClientT = SSLClient;
  7336. #else
  7337. using ClientT = Client;
  7338. #endif
  7339. TestWithHeadersAndContentReceiverError<ClientT>(
  7340. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7341. const std::string &body, const std::string &content_type,
  7342. ContentReceiver receiver) {
  7343. return cli.Patch(path, headers, body, content_type, receiver);
  7344. });
  7345. }
  7346. TEST_F(ServerTest, PostQueryStringAndBody) {
  7347. auto res =
  7348. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7350. ASSERT_EQ(StatusCode::OK_200, res->status);
  7351. }
  7352. TEST_F(ServerTest, HTTP2Magic) {
  7353. Request req;
  7354. req.method = "PRI";
  7355. req.path = "*";
  7356. req.body = "SM";
  7357. auto res = std::make_shared<Response>();
  7358. auto error = Error::Success;
  7359. auto ret = cli_.send(req, *res, error);
  7360. ASSERT_TRUE(ret);
  7361. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7362. }
  7363. TEST_F(ServerTest, KeepAlive) {
  7364. auto res = cli_.Get("/hi");
  7365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7366. EXPECT_EQ(StatusCode::OK_200, res->status);
  7367. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7368. EXPECT_EQ("Hello World!", res->body);
  7369. res = cli_.Get("/hi");
  7370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7371. EXPECT_EQ(StatusCode::OK_200, res->status);
  7372. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7373. EXPECT_EQ("Hello World!", res->body);
  7374. res = cli_.Get("/hi");
  7375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7376. EXPECT_EQ(StatusCode::OK_200, res->status);
  7377. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7378. EXPECT_EQ("Hello World!", res->body);
  7379. res = cli_.Get("/not-exist");
  7380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7381. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7382. res = cli_.Post("/empty", "", "text/plain");
  7383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7384. EXPECT_EQ(StatusCode::OK_200, res->status);
  7385. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7386. EXPECT_EQ("empty", res->body);
  7387. EXPECT_EQ("close", res->get_header_value("Connection"));
  7388. res = cli_.Post(
  7389. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7390. "text/plain");
  7391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7392. EXPECT_EQ(StatusCode::OK_200, res->status);
  7393. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7394. EXPECT_EQ("empty", res->body);
  7395. cli_.set_keep_alive(false);
  7396. res = cli_.Get("/last-request");
  7397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7398. EXPECT_EQ(StatusCode::OK_200, res->status);
  7399. EXPECT_EQ("close", res->get_header_value("Connection"));
  7400. }
  7401. TEST_F(ServerTest, TooManyRedirect) {
  7402. cli_.set_follow_location(true);
  7403. auto res = cli_.Get("/redirect/0");
  7404. ASSERT_TRUE(!res);
  7405. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7406. }
  7407. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7408. Request req;
  7409. req.method = "FOOBAR";
  7410. req.path = "/hi";
  7411. cli_.set_keep_alive(true);
  7412. auto res = cli_.send(req);
  7413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7414. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7415. EXPECT_EQ("close", res->get_header_value("Connection"));
  7416. EXPECT_FALSE(cli_.is_socket_open());
  7417. }
  7418. TEST_F(ServerTest, CustomRouteReadsBody) {
  7419. const std::string xml =
  7420. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7421. Request req;
  7422. req.method = "PROPFIND";
  7423. req.path = "/dav/dir";
  7424. req.set_header("Depth", "1");
  7425. req.body = xml;
  7426. auto res = cli_.send(req);
  7427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7428. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7429. EXPECT_EQ(xml, res->body);
  7430. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7431. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7432. }
  7433. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7434. Request req;
  7435. req.method = "PROPFIND";
  7436. req.path = "/dav/42";
  7437. auto res = cli_.send(req);
  7438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7439. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7440. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7441. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7442. }
  7443. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7444. Request req;
  7445. req.method = "PROPFIND";
  7446. req.path = "/dav-re/123";
  7447. auto res = cli_.send(req);
  7448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7449. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7450. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7451. }
  7452. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7453. Request req;
  7454. req.method = "MKCOL";
  7455. req.path = "/dav-mkcol";
  7456. auto res = cli_.send(req);
  7457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7458. EXPECT_EQ(StatusCode::Created_201, res->status);
  7459. }
  7460. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7461. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7462. Request req;
  7463. req.method = "REPORT";
  7464. req.path = "/dav-report";
  7465. req.body = xml;
  7466. auto res = cli_.send(req);
  7467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7468. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7469. EXPECT_EQ(xml, res->body);
  7470. }
  7471. // A content reader route must fire even when the request carries no body,
  7472. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7473. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7474. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7475. Request req;
  7476. req.method = "REPORT";
  7477. req.path = "/dav-report";
  7478. auto res = cli_.send(req);
  7479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7480. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7481. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7482. }
  7483. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7484. Request req;
  7485. req.method = "PROPFIND";
  7486. req.path = "/not-dav";
  7487. auto res = cli_.send(req);
  7488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7489. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7490. }
  7491. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7492. Request req;
  7493. req.method = "UNLOCK";
  7494. req.path = "/dav/dir";
  7495. cli_.set_keep_alive(true);
  7496. auto res = cli_.send(req);
  7497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7498. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7499. EXPECT_EQ("close", res->get_header_value("Connection"));
  7500. EXPECT_FALSE(cli_.is_socket_open());
  7501. }
  7502. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7503. // The mount point serves this path, but only for GET and HEAD.
  7504. auto get_res = cli_.Get("/dir/index.html");
  7505. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7506. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7507. Request req;
  7508. req.method = "PROPFIND";
  7509. req.path = "/dir/index.html";
  7510. auto res = cli_.send(req);
  7511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7512. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7513. }
  7514. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7515. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7516. cli_.set_keep_alive(true);
  7517. for (auto i = 0; i < 2; i++) {
  7518. Request req;
  7519. req.method = "PROPFIND";
  7520. req.path = "/dav/dir";
  7521. req.body = xml;
  7522. auto res = cli_.send(req);
  7523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7524. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7525. EXPECT_EQ(xml, res->body);
  7526. EXPECT_TRUE(cli_.is_socket_open());
  7527. }
  7528. // A built-in method must still be served on the same connection.
  7529. cli_.set_keep_alive(false);
  7530. auto res = cli_.Get("/hi");
  7531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7532. EXPECT_EQ(StatusCode::OK_200, res->status);
  7533. EXPECT_EQ("close", res->get_header_value("Connection"));
  7534. }
  7535. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7536. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7537. Request req;
  7538. req.method = "PROPFIND";
  7539. req.path = "/dav/dir";
  7540. req.set_header("Expect", "100-continue");
  7541. req.body = xml;
  7542. auto res = cli_.send(req);
  7543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7544. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7545. EXPECT_EQ(xml, res->body);
  7546. }
  7547. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7548. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7549. TEST_F(ServerTest, Gzip) {
  7550. Headers headers;
  7551. headers.emplace("Accept-Encoding", "gzip, deflate");
  7552. auto res = cli_.Get("/compress", headers);
  7553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7554. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7555. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7556. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7557. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7558. "7890123456789012345678901234567890",
  7559. res->body);
  7560. EXPECT_EQ(StatusCode::OK_200, res->status);
  7561. }
  7562. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7563. Headers headers;
  7564. headers.emplace("Accept-Encoding", "gzip, deflate");
  7565. auto res = cli_.Get("/compress-with-charset", headers);
  7566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7567. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7568. EXPECT_EQ("application/json; charset=utf-8",
  7569. res->get_header_value("Content-Type"));
  7570. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7571. "7890123456789012345678901234567890",
  7572. res->body);
  7573. EXPECT_EQ(StatusCode::OK_200, res->status);
  7574. }
  7575. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7576. Headers headers;
  7577. headers.emplace("Accept-Encoding", "");
  7578. auto res = cli_.Get("/compress", headers);
  7579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7580. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7581. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7582. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7583. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7584. "7890123456789012345678901234567890",
  7585. res->body);
  7586. EXPECT_EQ(StatusCode::OK_200, res->status);
  7587. }
  7588. TEST_F(ServerTest, GzipWithContentReceiver) {
  7589. Headers headers;
  7590. headers.emplace("Accept-Encoding", "gzip, deflate");
  7591. std::string body;
  7592. auto res = cli_.Get("/compress", headers,
  7593. [&](const char *data, uint64_t data_length) {
  7594. EXPECT_EQ(100U, data_length);
  7595. body.append(data, data_length);
  7596. return true;
  7597. });
  7598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7599. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7600. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7601. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7602. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7603. "7890123456789012345678901234567890",
  7604. body);
  7605. EXPECT_EQ(StatusCode::OK_200, res->status);
  7606. }
  7607. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7608. Headers headers;
  7609. headers.emplace("Accept-Encoding", "gzip, deflate");
  7610. cli_.set_decompress(false);
  7611. auto res = cli_.Get("/compress", headers);
  7612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7613. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7614. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7615. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7616. EXPECT_EQ(33U, res->body.size());
  7617. EXPECT_EQ(StatusCode::OK_200, res->status);
  7618. }
  7619. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7620. Headers headers;
  7621. headers.emplace("Accept-Encoding", "");
  7622. std::string body;
  7623. auto res = cli_.Get("/compress", headers,
  7624. [&](const char *data, uint64_t data_length) {
  7625. EXPECT_EQ(100U, data_length);
  7626. body.append(data, data_length);
  7627. return true;
  7628. });
  7629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7630. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7631. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7632. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7633. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7634. "7890123456789012345678901234567890",
  7635. body);
  7636. EXPECT_EQ(StatusCode::OK_200, res->status);
  7637. }
  7638. TEST_F(ServerTest, NoGzip) {
  7639. Headers headers;
  7640. headers.emplace("Accept-Encoding", "gzip, deflate");
  7641. auto res = cli_.Get("/nocompress", headers);
  7642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7643. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7644. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7645. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7646. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7647. "7890123456789012345678901234567890",
  7648. res->body);
  7649. EXPECT_EQ(StatusCode::OK_200, res->status);
  7650. }
  7651. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7652. Headers headers;
  7653. headers.emplace("Accept-Encoding", "gzip, deflate");
  7654. std::string body;
  7655. auto res = cli_.Get("/nocompress", headers,
  7656. [&](const char *data, uint64_t data_length) {
  7657. EXPECT_EQ(100U, data_length);
  7658. body.append(data, data_length);
  7659. return true;
  7660. });
  7661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7662. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7663. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7664. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7665. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7666. "7890123456789012345678901234567890",
  7667. body);
  7668. EXPECT_EQ(StatusCode::OK_200, res->status);
  7669. }
  7670. TEST_F(ServerTest, MultipartFormDataGzip) {
  7671. UploadFormDataItems items = {
  7672. {"key1", "test", "", ""},
  7673. {"key2", "--abcdefg123", "", ""},
  7674. };
  7675. cli_.set_compress(true);
  7676. auto res = cli_.Post("/compress-multipart", items);
  7677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7678. EXPECT_EQ(StatusCode::OK_200, res->status);
  7679. }
  7680. #endif
  7681. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7682. // Static file compression is opt-in, so these run their own server rather than
  7683. // flipping it on for the shared ServerTest fixture, which would silently
  7684. // rewrite what every other static file test is asserting.
  7685. class StaticFileCompressionTest : public ::testing::Test {
  7686. protected:
  7687. void TearDown() override {
  7688. if (t_.joinable()) {
  7689. svr_.stop();
  7690. t_.join();
  7691. }
  7692. }
  7693. int start(const std::function<void(Server &)> &configure = nullptr) {
  7694. // Serves the same tree as a directory of build-time compressed assets
  7695. // would be served: the mount point names the coding the files are already
  7696. // stored in. Registered before "/" so it is the one that matches.
  7697. svr_.set_mount_point("/pre-encoded", "./www",
  7698. {{"Content-Encoding", "gzip"}});
  7699. svr_.set_mount_point("/", "./www");
  7700. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  7701. res.set_file_content("./www/dir/index.html", "text/html");
  7702. });
  7703. svr_.Get("/pre-encoded-file-content",
  7704. [](const Request & /*req*/, Response &res) {
  7705. res.set_header("Content-Encoding", "gzip");
  7706. res.set_file_content("./www/dir/index.html", "text/html");
  7707. });
  7708. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  7709. res.set_content_provider(
  7710. 6, "text/plain",
  7711. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7712. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  7713. return true;
  7714. });
  7715. });
  7716. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  7717. res.set_content_provider(
  7718. 1000, "text/plain",
  7719. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7720. if (offset < 100) {
  7721. std::string data(100, 'A');
  7722. sink.write(data.data(), data.size());
  7723. return true;
  7724. }
  7725. std::this_thread::sleep_for(std::chrono::seconds(2));
  7726. std::string data(900, 'B');
  7727. sink.write(data.data(), data.size());
  7728. return true;
  7729. });
  7730. });
  7731. if (configure) { configure(svr_); }
  7732. auto port = svr_.bind_to_any_port(HOST);
  7733. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  7734. svr_.wait_until_ready();
  7735. return port;
  7736. }
  7737. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  7738. // Every file under ./www except 1MB.txt is smaller than the default
  7739. // 1400-byte floor, so a test that needs a small file compressed has to lower
  7740. // it out of the way.
  7741. static void enable_without_floor(Server &svr) {
  7742. svr.set_static_file_compression(true);
  7743. svr.set_static_file_compression_min_length(0);
  7744. }
  7745. Server svr_;
  7746. std::thread t_;
  7747. };
  7748. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  7749. auto port = start();
  7750. Client cli(HOST, port);
  7751. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7753. EXPECT_EQ(StatusCode::OK_200, res->status);
  7754. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7755. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7756. EXPECT_EQ(1048576U, res->body.size());
  7757. }
  7758. TEST_F(StaticFileCompressionTest, MountPoint) {
  7759. auto port = start(enable);
  7760. Client cli(HOST, port);
  7761. cli.set_decompress(false);
  7762. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7764. EXPECT_EQ(StatusCode::OK_200, res->status);
  7765. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7766. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7767. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  7768. // The response stays self-delimiting: a length, not a chunked body.
  7769. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7770. EXPECT_EQ(std::to_string(res->body.size()),
  7771. res->get_header_value("Content-Length"));
  7772. EXPECT_LT(res->body.size(), 1048576U);
  7773. EXPECT_FALSE(res->body.empty());
  7774. }
  7775. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  7776. auto port = start(enable);
  7777. Client cli(HOST, port);
  7778. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7780. EXPECT_EQ(StatusCode::OK_200, res->status);
  7781. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7782. EXPECT_EQ(1048576U, res->body.size());
  7783. }
  7784. TEST_F(StaticFileCompressionTest, FileContent) {
  7785. auto port = start(enable_without_floor);
  7786. Client cli(HOST, port);
  7787. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  7788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7789. EXPECT_EQ(StatusCode::OK_200, res->status);
  7790. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7791. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7792. EXPECT_EQ(104U, res->body.size());
  7793. }
  7794. // A handler that serves an already-encoded file names the coding itself. The
  7795. // file-backed path decided its coding from Accept-Encoding and the content
  7796. // type alone, so it compressed the stored bytes a second time and appended a
  7797. // second Content-Encoding field line.
  7798. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  7799. auto port = start(enable_without_floor);
  7800. Client cli(HOST, port);
  7801. cli.set_decompress(false);
  7802. auto res = cli.Get("/pre-encoded-file-content",
  7803. Headers{{"Accept-Encoding", "gzip"}});
  7804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7805. EXPECT_EQ(StatusCode::OK_200, res->status);
  7806. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7807. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7808. // Vary belongs to a coding the server chose, and it chose none here.
  7809. EXPECT_FALSE(res->has_header("Vary"));
  7810. // The file travels exactly as it is stored on disk.
  7811. EXPECT_EQ(104U, res->body.size());
  7812. }
  7813. // The 1MB file clears the default floor, so this one runs the configuration a
  7814. // deployment would actually have.
  7815. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  7816. auto port = start(enable);
  7817. Client cli(HOST, port);
  7818. cli.set_decompress(false);
  7819. auto res =
  7820. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7822. EXPECT_EQ(StatusCode::OK_200, res->status);
  7823. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7824. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7825. EXPECT_FALSE(res->has_header("Vary"));
  7826. EXPECT_EQ(1048576U, res->body.size());
  7827. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7828. }
  7829. TEST_F(StaticFileCompressionTest, Head) {
  7830. auto port = start(enable);
  7831. Client cli(HOST, port);
  7832. cli.set_decompress(false);
  7833. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7834. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  7835. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7837. EXPECT_EQ(StatusCode::OK_200, res->status);
  7838. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7839. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7840. // HEAD still reports the size a GET would return.
  7841. EXPECT_EQ(get->get_header_value("Content-Length"),
  7842. res->get_header_value("Content-Length"));
  7843. EXPECT_TRUE(res->body.empty());
  7844. }
  7845. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  7846. auto port = start(enable);
  7847. Client cli(HOST, port);
  7848. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  7849. {"Accept-Encoding", "gzip"}});
  7850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7851. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7852. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7853. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7854. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7855. EXPECT_EQ("cd", res->body);
  7856. }
  7857. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  7858. auto port = start(enable);
  7859. Client cli(HOST, port);
  7860. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  7861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7862. EXPECT_EQ(StatusCode::OK_200, res->status);
  7863. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7864. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7865. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7866. }
  7867. TEST_F(StaticFileCompressionTest, EmptyFile) {
  7868. auto port = start(enable);
  7869. Client cli(HOST, port);
  7870. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  7871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7872. EXPECT_EQ(StatusCode::OK_200, res->status);
  7873. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7874. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7875. EXPECT_TRUE(res->body.empty());
  7876. }
  7877. TEST_F(StaticFileCompressionTest, MinLength) {
  7878. auto port = start(enable);
  7879. Client cli(HOST, port);
  7880. // 104 bytes, well under the default floor. Compressing it would add the
  7881. // gzip header and trailer to a body that already fits in one packet.
  7882. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7884. EXPECT_EQ(StatusCode::OK_200, res->status);
  7885. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7886. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  7887. }
  7888. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  7889. auto port = start([](Server &svr) {
  7890. svr.set_static_file_compression(true);
  7891. svr.set_static_file_compression_min_length(1);
  7892. });
  7893. Client cli(HOST, port);
  7894. cli.set_decompress(false);
  7895. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  7896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7897. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7898. // A 9-byte file comes back larger than it went in, because gzip's header and
  7899. // trailer outweigh anything deflate can save. That is the end of the range
  7900. // the floor exists to keep out.
  7901. EXPECT_GT(res->body.size(), 9U);
  7902. }
  7903. TEST_F(StaticFileCompressionTest, MaxLength) {
  7904. auto port = start([](Server &svr) {
  7905. svr.set_static_file_compression(true);
  7906. svr.set_static_file_compression_min_length(0);
  7907. svr.set_static_file_compression_max_length(1024);
  7908. });
  7909. Client cli(HOST, port);
  7910. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  7911. // defines `small` as a macro on Windows.
  7912. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7913. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  7914. EXPECT_FALSE(over->has_header("Content-Encoding"));
  7915. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  7916. // Under it: compressed.
  7917. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7918. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  7919. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  7920. }
  7921. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  7922. auto port = start(enable_without_floor);
  7923. Client cli(HOST, port);
  7924. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  7925. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  7926. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  7927. auto identity_etag = identity->get_header_value("ETag");
  7928. ASSERT_FALSE(identity_etag.empty());
  7929. auto gzipped =
  7930. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7931. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  7932. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  7933. auto gzip_etag = gzipped->get_header_value("ETag");
  7934. ASSERT_FALSE(gzip_etag.empty());
  7935. // Two representations, two validators.
  7936. EXPECT_NE(identity_etag, gzip_etag);
  7937. // Each one revalidates against the request that would produce it...
  7938. auto fresh =
  7939. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  7940. {"If-None-Match", gzip_etag}});
  7941. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  7942. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  7943. auto fresh_identity =
  7944. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  7945. {"If-None-Match", identity_etag}});
  7946. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  7947. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  7948. // ...and not against the other representation.
  7949. auto crossed =
  7950. cli.Get("/dir/index.html",
  7951. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  7952. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  7953. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  7954. }
  7955. // The opt-in covers responses the server reads off disk itself. A caller's own
  7956. // known-length provider keeps its Content-Length and, more importantly, keeps
  7957. // delivering incrementally: routing it through a compressor would hold every
  7958. // write back until zlib's window filled.
  7959. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  7960. auto port = start(enable);
  7961. Client cli(HOST, port);
  7962. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  7963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7964. EXPECT_EQ(StatusCode::OK_200, res->status);
  7965. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7966. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7967. EXPECT_EQ("aaabbb", res->body);
  7968. }
  7969. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  7970. auto port = start(enable);
  7971. Client cli(HOST, port);
  7972. cli.set_read_timeout(1, 0);
  7973. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  7974. Headers{{"Accept-Encoding", "gzip"}});
  7975. ASSERT_TRUE(handle.is_valid());
  7976. // The provider writes 100 bytes and then stalls for longer than the read
  7977. // timeout. Those first bytes have to arrive anyway: run the response through
  7978. // a compressor and zlib holds them until its window fills, so the read would
  7979. // come back empty instead.
  7980. char buf[256];
  7981. auto n = handle.read(buf, sizeof(buf));
  7982. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  7983. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  7984. }
  7985. #endif
  7986. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7987. TEST_F(ServerTest, Brotli) {
  7988. Headers headers;
  7989. headers.emplace("Accept-Encoding", "br");
  7990. auto res = cli_.Get("/compress", headers);
  7991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7992. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7993. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7994. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  7995. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7996. "7890123456789012345678901234567890",
  7997. res->body);
  7998. EXPECT_EQ(StatusCode::OK_200, res->status);
  7999. }
  8000. #endif
  8001. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8002. TEST_F(ServerTest, Zstd) {
  8003. Headers headers;
  8004. headers.emplace("Accept-Encoding", "zstd");
  8005. auto res = cli_.Get("/compress", headers);
  8006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8007. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8008. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8009. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8010. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8011. "7890123456789012345678901234567890",
  8012. res->body);
  8013. EXPECT_EQ(StatusCode::OK_200, res->status);
  8014. }
  8015. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8016. Headers headers;
  8017. headers.emplace("Accept-Encoding", "");
  8018. auto res = cli_.Get("/compress", headers);
  8019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8020. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8021. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8022. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8023. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8024. "7890123456789012345678901234567890",
  8025. res->body);
  8026. EXPECT_EQ(StatusCode::OK_200, res->status);
  8027. }
  8028. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8029. Headers headers;
  8030. headers.emplace("Accept-Encoding", "zstd");
  8031. std::string body;
  8032. auto res = cli_.Get("/compress", headers,
  8033. [&](const char *data, uint64_t data_length) {
  8034. EXPECT_EQ(100U, data_length);
  8035. body.append(data, data_length);
  8036. return true;
  8037. });
  8038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8039. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8040. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8041. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8042. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8043. "7890123456789012345678901234567890",
  8044. body);
  8045. EXPECT_EQ(StatusCode::OK_200, res->status);
  8046. }
  8047. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8048. Headers headers;
  8049. headers.emplace("Accept-Encoding", "zstd");
  8050. cli_.set_decompress(false);
  8051. auto res = cli_.Get("/compress", headers);
  8052. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8053. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8054. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8055. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8057. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8058. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8059. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8060. EXPECT_EQ(StatusCode::OK_200, res->status);
  8061. ASSERT_EQ(26U, res->body.size());
  8062. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8063. 0);
  8064. }
  8065. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8066. Headers headers;
  8067. headers.emplace("Accept-Encoding", "");
  8068. std::string body;
  8069. auto res = cli_.Get("/compress", headers,
  8070. [&](const char *data, uint64_t data_length) {
  8071. EXPECT_EQ(100U, data_length);
  8072. body.append(data, data_length);
  8073. return true;
  8074. });
  8075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8076. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8077. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8078. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8079. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8080. "7890123456789012345678901234567890",
  8081. body);
  8082. EXPECT_EQ(StatusCode::OK_200, res->status);
  8083. }
  8084. TEST_F(ServerTest, NoZstd) {
  8085. Headers headers;
  8086. headers.emplace("Accept-Encoding", "zstd");
  8087. auto res = cli_.Get("/nocompress", headers);
  8088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8089. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8090. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8091. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8092. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8093. "7890123456789012345678901234567890",
  8094. res->body);
  8095. EXPECT_EQ(StatusCode::OK_200, res->status);
  8096. }
  8097. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8098. Headers headers;
  8099. headers.emplace("Accept-Encoding", "zstd");
  8100. std::string body;
  8101. auto res = cli_.Get("/nocompress", headers,
  8102. [&](const char *data, uint64_t data_length) {
  8103. EXPECT_EQ(100U, data_length);
  8104. body.append(data, data_length);
  8105. return true;
  8106. });
  8107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8108. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8109. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8110. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8111. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8112. "7890123456789012345678901234567890",
  8113. body);
  8114. EXPECT_EQ(StatusCode::OK_200, res->status);
  8115. }
  8116. // TODO: How to enable zstd ??
  8117. TEST_F(ServerTest, MultipartFormDataZstd) {
  8118. UploadFormDataItems items = {
  8119. {"key1", "test", "", ""},
  8120. {"key2", "--abcdefg123", "", ""},
  8121. };
  8122. Headers headers;
  8123. headers.emplace("Accept-Encoding", "zstd");
  8124. cli_.set_compress(true);
  8125. auto res = cli_.Post("/compress-multipart", headers, items);
  8126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8127. EXPECT_EQ(StatusCode::OK_200, res->status);
  8128. }
  8129. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8130. Headers headers;
  8131. headers.emplace("Accept-Encoding", "zstd");
  8132. cli_.set_compress(true);
  8133. auto res = cli_.Put(
  8134. "/put", headers, 3,
  8135. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8136. sink.os << "PUT";
  8137. return true;
  8138. },
  8139. "text/plain");
  8140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8141. EXPECT_EQ(StatusCode::OK_200, res->status);
  8142. EXPECT_EQ("PUT", res->body);
  8143. }
  8144. // Pre-compression logging tests
  8145. TEST_F(ServerTest, PreCompressionLogging) {
  8146. // Test data for compression (matches the actual /compress endpoint content)
  8147. const std::string test_content =
  8148. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8149. "3456789012345678901234567890";
  8150. // Variables to capture logging data
  8151. std::string pre_compression_body;
  8152. std::string pre_compression_content_type;
  8153. std::string pre_compression_content_encoding;
  8154. std::string post_compression_body;
  8155. std::string post_compression_content_type;
  8156. std::string post_compression_content_encoding;
  8157. // Set up pre-compression logger
  8158. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8159. const Response &res) {
  8160. pre_compression_body = res.body;
  8161. pre_compression_content_type = res.get_header_value("Content-Type");
  8162. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8163. });
  8164. // Set up post-compression logger
  8165. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8166. post_compression_body = res.body;
  8167. post_compression_content_type = res.get_header_value("Content-Type");
  8168. post_compression_content_encoding =
  8169. res.get_header_value("Content-Encoding");
  8170. });
  8171. // Test with gzip compression
  8172. Headers headers;
  8173. headers.emplace("Accept-Encoding", "gzip");
  8174. auto res = cli_.Get("/compress", headers);
  8175. // Verify response was compressed
  8176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8177. EXPECT_EQ(StatusCode::OK_200, res->status);
  8178. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8179. // Verify pre-compression logger captured uncompressed content
  8180. EXPECT_EQ(test_content, pre_compression_body);
  8181. EXPECT_EQ("text/plain", pre_compression_content_type);
  8182. EXPECT_TRUE(pre_compression_content_encoding
  8183. .empty()); // No encoding header before compression
  8184. // Verify post-compression logger captured compressed content
  8185. EXPECT_NE(test_content,
  8186. post_compression_body); // Should be different after compression
  8187. EXPECT_EQ("text/plain", post_compression_content_type);
  8188. EXPECT_EQ("gzip", post_compression_content_encoding);
  8189. // Verify compressed content is smaller
  8190. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8191. }
  8192. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8193. const std::string test_content =
  8194. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8195. "3456789012345678901234567890";
  8196. std::string pre_compression_body;
  8197. std::string post_compression_body;
  8198. svr_.set_pre_compression_logger(
  8199. [&](const Request & /*req*/, const Response &res) {
  8200. pre_compression_body = res.body;
  8201. });
  8202. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8203. post_compression_body = res.body;
  8204. });
  8205. Headers headers;
  8206. headers.emplace("Accept-Encoding", "br");
  8207. auto res = cli_.Get("/compress", headers);
  8208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8209. EXPECT_EQ(StatusCode::OK_200, res->status);
  8210. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8211. // Verify pre-compression content is uncompressed
  8212. EXPECT_EQ(test_content, pre_compression_body);
  8213. // Verify post-compression content is compressed
  8214. EXPECT_NE(test_content, post_compression_body);
  8215. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8216. }
  8217. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8218. const std::string test_content =
  8219. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8220. "3456789012345678901234567890";
  8221. std::string pre_compression_body;
  8222. std::string post_compression_body;
  8223. svr_.set_pre_compression_logger(
  8224. [&](const Request & /*req*/, const Response &res) {
  8225. pre_compression_body = res.body;
  8226. });
  8227. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8228. post_compression_body = res.body;
  8229. });
  8230. // Request without compression (use /nocompress endpoint)
  8231. Headers headers;
  8232. auto res = cli_.Get("/nocompress", headers);
  8233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8234. EXPECT_EQ(StatusCode::OK_200, res->status);
  8235. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8236. // Pre-compression logger should not be called when no compression is applied
  8237. EXPECT_TRUE(
  8238. pre_compression_body.empty()); // Pre-compression logger not called
  8239. EXPECT_EQ(
  8240. test_content,
  8241. post_compression_body); // Post-compression logger captures final content
  8242. }
  8243. TEST_F(ServerTest, LoggerSeesContentLength) {
  8244. size_t logged_content_length = 0;
  8245. std::string logged_content_length_header;
  8246. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8247. logged_content_length = res.content_length_;
  8248. logged_content_length_header = res.get_header_value("Content-Length");
  8249. });
  8250. auto res = cli_.Get("/nocompress");
  8251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8252. EXPECT_EQ(StatusCode::OK_200, res->status);
  8253. EXPECT_EQ(res->body.size(), logged_content_length);
  8254. EXPECT_EQ(std::to_string(logged_content_length),
  8255. logged_content_length_header);
  8256. }
  8257. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8258. const std::string test_content =
  8259. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8260. "3456789012345678901234567890";
  8261. std::string pre_compression_body;
  8262. bool pre_logger_called = false;
  8263. // Set only pre-compression logger
  8264. svr_.set_pre_compression_logger(
  8265. [&](const Request & /*req*/, const Response &res) {
  8266. pre_compression_body = res.body;
  8267. pre_logger_called = true;
  8268. });
  8269. Headers headers;
  8270. headers.emplace("Accept-Encoding", "gzip");
  8271. auto res = cli_.Get("/compress", headers);
  8272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8273. EXPECT_EQ(StatusCode::OK_200, res->status);
  8274. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8275. // Verify pre-compression logger was called
  8276. EXPECT_TRUE(pre_logger_called);
  8277. EXPECT_EQ(test_content, pre_compression_body);
  8278. }
  8279. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8280. {
  8281. // Test with Expect: 100-continue header - success case
  8282. // Server returns 100 Continue, client sends body, server returns 200 OK
  8283. Request req;
  8284. req.method = "POST";
  8285. req.path = "/post-large";
  8286. req.set_header("Expect", "100-continue");
  8287. req.body = LARGE_DATA;
  8288. Response res;
  8289. auto error = Error::Success;
  8290. cli_.set_keep_alive(true);
  8291. auto ret = cli_.send(req, res, error);
  8292. EXPECT_TRUE(ret);
  8293. EXPECT_EQ(StatusCode::OK_200, res.status);
  8294. EXPECT_EQ(LARGE_DATA, res.body);
  8295. }
  8296. {
  8297. // Test with Expect: 100-continue header - error case
  8298. // Client should not send the body when server returns an error
  8299. Request req;
  8300. req.method = "POST";
  8301. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8302. req.set_header("Expect", "100-continue");
  8303. req.body = LARGE_DATA;
  8304. Response res;
  8305. auto error = Error::Success;
  8306. auto start = std::chrono::high_resolution_clock::now();
  8307. cli_.set_keep_alive(true);
  8308. auto ret = cli_.send(req, res, error);
  8309. auto end = std::chrono::high_resolution_clock::now();
  8310. auto elapsed =
  8311. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8312. .count();
  8313. // With Expect: 100-continue, request completes successfully but with error
  8314. EXPECT_TRUE(ret);
  8315. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8316. EXPECT_EQ("close", res.get_header_value("Connection"));
  8317. EXPECT_FALSE(cli_.is_socket_open());
  8318. EXPECT_LE(elapsed, 2000);
  8319. }
  8320. {
  8321. // Send an extra GET request to ensure error recovery without hanging
  8322. Request req;
  8323. req.method = "GET";
  8324. req.path = "/hi";
  8325. auto start = std::chrono::high_resolution_clock::now();
  8326. auto res = cli_.send(req);
  8327. auto end = std::chrono::high_resolution_clock::now();
  8328. auto elapsed =
  8329. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8330. .count();
  8331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8332. EXPECT_EQ(StatusCode::OK_200, res->status);
  8333. EXPECT_EQ("Hello World!", res->body);
  8334. EXPECT_LE(elapsed, 500);
  8335. }
  8336. }
  8337. TEST(ZstdDecompressor, ChunkedDecompression) {
  8338. std::string data;
  8339. for (size_t i = 0; i < 32 * 1024; ++i) {
  8340. data.push_back(static_cast<char>('a' + i % 26));
  8341. }
  8342. std::string compressed_data;
  8343. {
  8344. httplib::detail::zstd_compressor compressor;
  8345. bool result = compressor.compress(
  8346. data.data(), data.size(),
  8347. /*last=*/true,
  8348. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8349. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8350. compressed_data_size);
  8351. return true;
  8352. });
  8353. ASSERT_TRUE(result);
  8354. }
  8355. std::string decompressed_data;
  8356. {
  8357. httplib::detail::zstd_decompressor decompressor;
  8358. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8359. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8360. size_t chunk_size = 130;
  8361. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8362. chunk_begin += chunk_size) {
  8363. size_t current_chunk_size =
  8364. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8365. bool result = decompressor.decompress(
  8366. compressed_data.data() + chunk_begin, current_chunk_size,
  8367. [&](const char *decompressed_data_chunk,
  8368. size_t decompressed_data_chunk_size) {
  8369. decompressed_data.insert(decompressed_data.size(),
  8370. decompressed_data_chunk,
  8371. decompressed_data_chunk_size);
  8372. return true;
  8373. });
  8374. ASSERT_TRUE(result);
  8375. }
  8376. }
  8377. ASSERT_EQ(data, decompressed_data);
  8378. }
  8379. TEST(ZstdDecompressor, Decompress) {
  8380. std::string original_text = "Compressed with ZSTD";
  8381. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8382. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8383. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8384. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8385. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8386. std::string decompressed_data;
  8387. {
  8388. httplib::detail::zstd_decompressor decompressor;
  8389. bool result = decompressor.decompress(
  8390. compressed_data.data(), compressed_data.size(),
  8391. [&](const char *decompressed_data_chunk,
  8392. size_t decompressed_data_chunk_size) {
  8393. decompressed_data.insert(decompressed_data.size(),
  8394. decompressed_data_chunk,
  8395. decompressed_data_chunk_size);
  8396. return true;
  8397. });
  8398. ASSERT_TRUE(result);
  8399. }
  8400. ASSERT_EQ(original_text, decompressed_data);
  8401. }
  8402. #endif
  8403. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8404. // separate chunks so that the server sees each part in its own read(). Used to
  8405. // place a read boundary at a specific offset of a request body.
  8406. static bool send_request_in_parts(time_t read_timeout_sec,
  8407. const std::vector<std::string> &parts,
  8408. std::string *resp = nullptr,
  8409. int port = PORT) {
  8410. auto error = Error::Success;
  8411. auto client_sock = detail::create_client_socket(
  8412. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8413. /*connection_timeout_sec=*/5, 0,
  8414. /*read_timeout_sec=*/5, 0,
  8415. /*write_timeout_sec=*/5, 0, std::string(), error);
  8416. if (client_sock == INVALID_SOCKET) { return false; }
  8417. auto ret = detail::process_client_socket(
  8418. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8419. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8420. for (size_t i = 0; i < parts.size(); i++) {
  8421. const auto &part = parts[i];
  8422. if (part.size() !=
  8423. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8424. return false;
  8425. }
  8426. if (i + 1 < parts.size()) {
  8427. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8428. }
  8429. }
  8430. char buf[512];
  8431. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8432. while (line_reader.getline()) {
  8433. if (resp) { *resp += line_reader.ptr(); }
  8434. }
  8435. return true;
  8436. });
  8437. detail::close_socket(client_sock);
  8438. return ret;
  8439. }
  8440. // Sends a raw request to a server listening at HOST:PORT.
  8441. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8442. std::string *resp = nullptr, int port = PORT) {
  8443. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8444. }
  8445. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8446. Server svr;
  8447. std::string header_value;
  8448. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8449. header_value = req.get_header_value("foo");
  8450. res.set_content("ok", "text/plain");
  8451. });
  8452. thread t = thread([&] { svr.listen(HOST, PORT); });
  8453. auto se = detail::scope_exit([&] {
  8454. svr.stop();
  8455. t.join();
  8456. ASSERT_FALSE(svr.is_running());
  8457. });
  8458. svr.wait_until_ready();
  8459. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8460. // like characters are not treated the same - use vertical tab and escape.
  8461. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8462. "foo: \t \v bar \x1B\t \r\n"
  8463. "Connection: close\r\n"
  8464. "\r\n";
  8465. std::string res;
  8466. ASSERT_TRUE(send_request(5, req, &res));
  8467. EXPECT_EQ(header_value, "");
  8468. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8469. }
  8470. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8471. Server svr;
  8472. std::string received;
  8473. svr.Get("/order", [&](const Request &req, Response &res) {
  8474. received = entries_to_string(req.headers);
  8475. res.set_content("ok", "text/plain");
  8476. });
  8477. auto port = svr.bind_to_any_port(HOST);
  8478. thread t = thread([&] { svr.listen_after_bind(); });
  8479. auto se = detail::scope_exit([&] {
  8480. svr.stop();
  8481. t.join();
  8482. ASSERT_FALSE(svr.is_running());
  8483. });
  8484. svr.wait_until_ready();
  8485. const std::string req = "GET /order HTTP/1.1\r\n"
  8486. "X-First: 1\r\n"
  8487. "X-Dup: a\r\n"
  8488. "X-Second: 2\r\n"
  8489. "X-Dup: b\r\n"
  8490. "Connection: close\r\n"
  8491. "\r\n";
  8492. std::string res;
  8493. ASSERT_TRUE(send_request(5, req, &res, port));
  8494. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8495. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  8496. }
  8497. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8498. Server svr;
  8499. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8500. res.set_header("Set-Cookie", "first=1");
  8501. res.set_header("X-Between", "y");
  8502. res.set_header("Set-Cookie", "second=2");
  8503. res.set_content("ok", "text/plain");
  8504. });
  8505. auto port = svr.bind_to_any_port(HOST);
  8506. thread t = thread([&] { svr.listen_after_bind(); });
  8507. auto se = detail::scope_exit([&] {
  8508. svr.stop();
  8509. t.join();
  8510. ASSERT_FALSE(svr.is_running());
  8511. });
  8512. svr.wait_until_ready();
  8513. Client cli(HOST, port);
  8514. auto res = cli.Get("/cookies");
  8515. ASSERT_TRUE(res);
  8516. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8517. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8518. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8519. }
  8520. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8521. Server svr;
  8522. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8523. auto i = new int(0);
  8524. res.set_header("Trailer", "X-Safe, X-Reflected");
  8525. res.set_chunked_content_provider(
  8526. "text/plain",
  8527. [i](size_t /*offset*/, DataSink &sink) {
  8528. if (*i == 0) {
  8529. sink.os << "body";
  8530. } else {
  8531. Headers trailer;
  8532. // A valid trailer that must survive.
  8533. trailer.emplace("X-Safe", "safe");
  8534. // Attacker-controlled value carrying CR/LF (response splitting).
  8535. trailer.emplace("X-Reflected",
  8536. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8537. // Attacker-controlled name carrying CR/LF.
  8538. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8539. sink.done_with_trailer(trailer);
  8540. }
  8541. (*i)++;
  8542. return true;
  8543. },
  8544. [i](bool /*success*/) { delete i; });
  8545. });
  8546. thread t = thread([&] { svr.listen(HOST, PORT); });
  8547. auto se = detail::scope_exit([&] {
  8548. svr.stop();
  8549. t.join();
  8550. ASSERT_FALSE(svr.is_running());
  8551. });
  8552. svr.wait_until_ready();
  8553. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8554. "Host: " + HOST +
  8555. "\r\n"
  8556. "Connection: close\r\n"
  8557. "\r\n";
  8558. std::string res;
  8559. ASSERT_TRUE(send_request(5, req, &res));
  8560. // The injected fields must not appear anywhere in the raw response.
  8561. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8562. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8563. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8564. // Invalid trailers are dropped entirely, matching set_header().
  8565. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8566. // The valid trailer still passes through.
  8567. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8568. }
  8569. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8570. Server svr;
  8571. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8572. // res.headers is a public field an application can populate directly,
  8573. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8574. // A valid header that must survive.
  8575. res.headers.emplace("X-Safe", "safe");
  8576. // Attacker-controlled value carrying CR/LF (response splitting).
  8577. res.headers.emplace("X-Reflected",
  8578. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8579. // Attacker-controlled name carrying CR/LF.
  8580. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8581. res.set_content("body", "text/plain");
  8582. });
  8583. thread t = thread([&] { svr.listen(HOST, PORT); });
  8584. auto se = detail::scope_exit([&] {
  8585. svr.stop();
  8586. t.join();
  8587. ASSERT_FALSE(svr.is_running());
  8588. });
  8589. svr.wait_until_ready();
  8590. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8591. "Host: " + HOST +
  8592. "\r\n"
  8593. "Connection: close\r\n"
  8594. "\r\n";
  8595. std::string res;
  8596. ASSERT_TRUE(send_request(5, req, &res));
  8597. // The injected fields must not appear anywhere in the raw response.
  8598. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8599. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8600. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8601. // Invalid headers are dropped entirely, matching set_header().
  8602. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8603. // The valid header still passes through.
  8604. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8605. }
  8606. // Forward declaration: in split builds split.py strips `inline` and moves the
  8607. // definition into httplib.cc, so detail::write_request_line is not visible from
  8608. // the public httplib.h. Re-declaring it here lets the tests link against the
  8609. // symbol in both header-only and split builds.
  8610. namespace httplib {
  8611. namespace detail {
  8612. ssize_t write_request_line(Stream &strm, const std::string &method,
  8613. const std::string &path);
  8614. } // namespace detail
  8615. } // namespace httplib
  8616. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  8617. // A well-formed target is written verbatim.
  8618. {
  8619. detail::BufferStream strm;
  8620. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8621. EXPECT_GT(n, 0);
  8622. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8623. }
  8624. // A target carrying CR/LF, SP or other control octets must be rejected
  8625. // before anything reaches the wire, otherwise it splits the request line and
  8626. // injects a header or a whole request.
  8627. const std::string evil_targets[] = {
  8628. "/a\r\nInjected: pwned",
  8629. "/a\rInjected",
  8630. "/a\nInjected",
  8631. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8632. "/a b",
  8633. "/a\tb",
  8634. "/a\x7f",
  8635. };
  8636. for (const auto &evil : evil_targets) {
  8637. detail::BufferStream strm;
  8638. auto n = detail::write_request_line(strm, "GET", evil);
  8639. EXPECT_LT(n, 0);
  8640. EXPECT_TRUE(strm.get_buffer().empty());
  8641. }
  8642. }
  8643. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8644. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  8645. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  8646. // target reaches write_request. The client must fail cleanly with
  8647. // Error::Write instead of putting a request-line-less, header-injecting
  8648. // request on the wire.
  8649. Server svr;
  8650. svr.Get("/a", [](const Request &, Response &res) {
  8651. res.set_content("ok", "text/plain");
  8652. });
  8653. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8654. auto se = detail::scope_exit([&] {
  8655. svr.stop();
  8656. thread.join();
  8657. ASSERT_FALSE(svr.is_running());
  8658. });
  8659. svr.wait_until_ready();
  8660. {
  8661. Client cli(HOST, PORT);
  8662. cli.set_path_encode(false);
  8663. // The request is rejected before anything is written, so the connection
  8664. // stays silent and the subsequent response read would otherwise block for
  8665. // the full default read timeout. Shorten it -- the assertion is on the
  8666. // error, not the timeout.
  8667. cli.set_read_timeout(1, 0);
  8668. auto res = cli.Get("/a\r\nInjected: pwned");
  8669. EXPECT_FALSE(res);
  8670. EXPECT_EQ(Error::Write, res.error());
  8671. }
  8672. }
  8673. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  8674. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  8675. // including extension methods.
  8676. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  8677. for (const auto &method : good_methods) {
  8678. detail::BufferStream strm;
  8679. auto n = detail::write_request_line(strm, method, "/");
  8680. EXPECT_GT(n, 0);
  8681. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  8682. }
  8683. // A method carrying CR/LF would split the request line and smuggle a whole
  8684. // request ahead of the real one. A space or an empty method corrupts the
  8685. // request line. All must be rejected before anything reaches the wire.
  8686. const std::string evil_methods[] = {
  8687. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8688. "GET\r\nInjected: pwned",
  8689. "GET\r",
  8690. "GET\n",
  8691. "GE T",
  8692. "",
  8693. };
  8694. for (const auto &evil : evil_methods) {
  8695. detail::BufferStream strm;
  8696. auto n = detail::write_request_line(strm, evil, "/");
  8697. EXPECT_LT(n, 0);
  8698. EXPECT_TRUE(strm.get_buffer().empty());
  8699. }
  8700. }
  8701. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  8702. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  8703. // through Client::send must fail with Error::Write and no request, neither
  8704. // the smuggled one nor the real one, may reach the server.
  8705. Server svr;
  8706. std::atomic<int> request_count(0);
  8707. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  8708. request_count++;
  8709. res.status = StatusCode::OK_200;
  8710. return Server::HandlerResponse::Handled;
  8711. });
  8712. auto port = svr.bind_to_any_port(HOST);
  8713. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  8714. auto se = detail::scope_exit([&] {
  8715. svr.stop();
  8716. thread.join();
  8717. ASSERT_FALSE(svr.is_running());
  8718. });
  8719. svr.wait_until_ready();
  8720. {
  8721. Client cli(HOST, port);
  8722. const std::string evil_methods[] = {
  8723. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8724. "GE T",
  8725. "",
  8726. };
  8727. for (const auto &evil : evil_methods) {
  8728. Request req;
  8729. req.method = evil;
  8730. req.path = "/";
  8731. auto res = cli.send(req);
  8732. EXPECT_FALSE(res);
  8733. EXPECT_EQ(Error::Write, res.error());
  8734. }
  8735. auto handle =
  8736. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  8737. EXPECT_FALSE(handle.is_valid());
  8738. EXPECT_EQ(Error::Write, handle.error);
  8739. // A valid request on the same client still goes through.
  8740. auto res = cli.Get("/");
  8741. ASSERT_TRUE(res);
  8742. EXPECT_EQ(StatusCode::OK_200, res->status);
  8743. }
  8744. EXPECT_EQ(1, request_count.load());
  8745. }
  8746. // Sends a raw request and verifies that there isn't a crash or exception.
  8747. static void test_raw_request(const std::string &req,
  8748. std::string *out = nullptr) {
  8749. Server svr;
  8750. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8751. res.set_content("ok", "text/plain");
  8752. });
  8753. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  8754. res.set_content("ok", "text/plain");
  8755. });
  8756. svr.Get("/header_field_value_check",
  8757. [&](const Request & /*req*/, Response &res) {
  8758. res.set_content("ok", "text/plain");
  8759. });
  8760. svr.CustomRoute("PROPFIND", "/dav",
  8761. [&](const Request & /*req*/, Response &res) {
  8762. res.status = StatusCode::MultiStatus_207;
  8763. });
  8764. // Server read timeout must be longer than the client read timeout for the
  8765. // bug to reproduce, probably to force the server to process a request
  8766. // without a trailing blank line.
  8767. const time_t client_read_timeout_sec = 1;
  8768. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  8769. bool listen_thread_ok = false;
  8770. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  8771. auto se = detail::scope_exit([&] {
  8772. svr.stop();
  8773. t.join();
  8774. ASSERT_FALSE(svr.is_running());
  8775. EXPECT_TRUE(listen_thread_ok);
  8776. });
  8777. svr.wait_until_ready();
  8778. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  8779. }
  8780. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  8781. // A certain header line causes an exception if the header property is parsed
  8782. // naively with a single regex. This occurs with libc++ but not libstdc++.
  8783. test_raw_request(
  8784. "GET /hi HTTP/1.1\r\n"
  8785. " : "
  8786. " "
  8787. " ");
  8788. }
  8789. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  8790. // A certain header line causes an exception if the header property *name* is
  8791. // parsed with a regular expression starting with "(.+?):" - this is a non-
  8792. // greedy matcher and requires backtracking when there are a lot of ":"
  8793. // characters.
  8794. // This occurs with libc++ but not libstdc++.
  8795. test_raw_request(
  8796. "GET /hi HTTP/1.1\r\n"
  8797. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  8798. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8799. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  8800. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  8801. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  8802. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  8803. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  8804. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  8805. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8806. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8807. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  8808. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8809. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  8810. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8811. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  8812. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  8813. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8814. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  8815. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  8816. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  8817. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  8818. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  8819. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  8820. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  8821. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8822. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8823. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  8824. "&&&%%%");
  8825. }
  8826. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  8827. // Make sure this doesn't crash the server.
  8828. // In a previous version of the header line regex, the "\r" rendered the line
  8829. // unparsable and the regex engine repeatedly backtracked, trying to look for
  8830. // a new position where the leading white space ended and the field value
  8831. // began.
  8832. // The crash occurs with libc++ but not libstdc++.
  8833. test_raw_request("GET /hi HTTP/1.1\r\n"
  8834. "a:" +
  8835. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  8836. "\r\n"
  8837. "\r\n");
  8838. }
  8839. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  8840. std::string out;
  8841. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8842. "Content-Type: text/plain\r\n"
  8843. "Transfer-Encoding: chunked\r\n"
  8844. "\r\n"
  8845. "nothex\r\n",
  8846. &out);
  8847. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8848. }
  8849. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  8850. std::string out;
  8851. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8852. "Content-Type: text/plain\r\n"
  8853. "Transfer-Encoding: chunked\r\n"
  8854. "\r\n"
  8855. "3\r\n"
  8856. "xyz\r\n"
  8857. "NaN\r\n",
  8858. &out);
  8859. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8860. }
  8861. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  8862. std::string out;
  8863. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8864. "Content-Type: text/plain\r\n"
  8865. "Transfer-Encoding: chunked\r\n"
  8866. "\r\n"
  8867. // Length is too large for 64 bits.
  8868. "1ffffffffffffffff\r\n"
  8869. "xyz\r\n",
  8870. &out);
  8871. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8872. }
  8873. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  8874. test_raw_request("GET /hi HTTP/1.1\r\n"
  8875. "Content-Type: text/plain\r\n\r");
  8876. }
  8877. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  8878. std::string out;
  8879. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  8880. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8881. }
  8882. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  8883. for (auto target : {"/h\ri", "/h\x7fi"}) {
  8884. std::string out;
  8885. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  8886. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  8887. }
  8888. }
  8889. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  8890. std::string out;
  8891. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  8892. "Connection: close\r\n\r\n",
  8893. &out);
  8894. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8895. }
  8896. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  8897. Server svr;
  8898. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  8899. EXPECT_TRUE(!req.remote_addr.empty());
  8900. });
  8901. thread t = thread([&] { svr.listen(HOST, PORT); });
  8902. auto se = detail::scope_exit([&] {
  8903. svr.stop();
  8904. t.join();
  8905. ASSERT_FALSE(svr.is_running());
  8906. });
  8907. svr.wait_until_ready();
  8908. // Send an invalid request line to trigger Bad Request
  8909. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  8910. std::string out;
  8911. ASSERT_TRUE(send_request(5, bad_req, &out));
  8912. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8913. }
  8914. // A custom method with neither Content-Length nor Transfer-Encoding must be
  8915. // answered right away rather than blocking on a read that waits for EOF.
  8916. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  8917. std::string out;
  8918. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  8919. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  8920. }
  8921. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  8922. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  8923. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  8924. for (const auto *method : methods) {
  8925. Server svr;
  8926. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8927. EXPECT_FALSE(svr.is_valid()) << method;
  8928. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  8929. }
  8930. }
  8931. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  8932. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  8933. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  8934. for (const auto *method : methods) {
  8935. Server svr;
  8936. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8937. EXPECT_FALSE(svr.is_valid()) << method;
  8938. }
  8939. }
  8940. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  8941. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  8942. "COPY", "MOVE", "LOCK",
  8943. "UNLOCK", "REPORT", "SUBSCRIBE"};
  8944. Server svr;
  8945. for (const auto *method : methods) {
  8946. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8947. }
  8948. EXPECT_TRUE(svr.is_valid());
  8949. }
  8950. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  8951. Server svr;
  8952. svr.CustomRoute("POST", "/x",
  8953. [](const Request &, Response &, const ContentReader &) {});
  8954. EXPECT_FALSE(svr.is_valid());
  8955. }
  8956. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  8957. Server svr;
  8958. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  8959. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  8960. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  8961. EXPECT_FALSE(svr.is_valid());
  8962. }
  8963. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  8964. Server svr;
  8965. auto captured = Error::Success;
  8966. svr.set_error_logger(
  8967. [&](const Error &err, const Request * /*req*/) { captured = err; });
  8968. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  8969. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  8970. }
  8971. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  8972. std::string out;
  8973. std::string request(
  8974. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  8975. test_raw_request(request, &out);
  8976. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8977. }
  8978. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  8979. std::string out;
  8980. std::string request(
  8981. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  8982. test_raw_request(request, &out);
  8983. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8984. }
  8985. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  8986. std::string out;
  8987. std::string request(
  8988. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  8989. test_raw_request(request, &out);
  8990. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8991. }
  8992. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  8993. std::string out;
  8994. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  8995. "Test: \r\n\r\n",
  8996. &out);
  8997. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8998. }
  8999. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9000. Server svr;
  9001. std::string x_custom;
  9002. std::string cookie;
  9003. std::string xff;
  9004. std::string x_unicode;
  9005. std::string x_iis;
  9006. svr.Get("/check", [&](const Request &req, Response &res) {
  9007. x_custom = req.get_header_value("X-Custom");
  9008. cookie = req.get_header_value("Cookie");
  9009. xff = req.get_header_value("X-Forwarded-For");
  9010. x_unicode = req.get_header_value("X-Unicode");
  9011. x_iis = req.get_header_value("X-IIS");
  9012. res.set_content("ok", "text/plain");
  9013. });
  9014. thread t = thread([&] { svr.listen(HOST, PORT); });
  9015. auto se = detail::scope_exit([&] {
  9016. svr.stop();
  9017. t.join();
  9018. ASSERT_FALSE(svr.is_running());
  9019. });
  9020. svr.wait_until_ready();
  9021. const std::string req = "GET /check HTTP/1.1\r\n"
  9022. "Host: localhost\r\n"
  9023. "X-Custom: a%0D%0AInjected: b\r\n"
  9024. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9025. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9026. "X-Unicode: %E3%81%82\r\n"
  9027. "X-IIS: %u00E9\r\n"
  9028. "Connection: close\r\n"
  9029. "\r\n";
  9030. std::string res;
  9031. ASSERT_TRUE(send_request(5, req, &res));
  9032. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9033. // Every value must be returned verbatim (wire form), with no decoding.
  9034. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9035. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9036. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9037. EXPECT_EQ("%E3%81%82", x_unicode);
  9038. EXPECT_EQ("%u00E9", x_iis);
  9039. }
  9040. // Applications that previously relied on automatic percent-decoding can
  9041. // reproduce the old behavior by explicitly calling decode_path_component()
  9042. // or, for RFC 3986 conformance, decode_uri_component().
  9043. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9044. Server svr;
  9045. std::string decoded;
  9046. svr.Get("/check", [&](const Request &req, Response &res) {
  9047. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9048. res.set_content("ok", "text/plain");
  9049. });
  9050. thread t = thread([&] { svr.listen(HOST, PORT); });
  9051. auto se = detail::scope_exit([&] {
  9052. svr.stop();
  9053. t.join();
  9054. ASSERT_FALSE(svr.is_running());
  9055. });
  9056. svr.wait_until_ready();
  9057. const std::string req = "GET /check HTTP/1.1\r\n"
  9058. "Host: localhost\r\n"
  9059. "X-Custom: hello%20world\r\n"
  9060. "Connection: close\r\n"
  9061. "\r\n";
  9062. std::string res;
  9063. ASSERT_TRUE(send_request(5, req, &res));
  9064. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9065. EXPECT_EQ("hello world", decoded);
  9066. }
  9067. // Regression test for #2033. Browsers send Referer values that include
  9068. // percent-encoded characters such as %0A inside the URL. Decoding the
  9069. // header value would either trip the post-decode CR/LF/NUL guard (the
  9070. // original bug, returning 400) or, after that guard was relaxed, silently
  9071. // store a literal LF — both unacceptable. The wire form must round-trip.
  9072. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9073. Server svr;
  9074. std::string referer;
  9075. svr.Get("/check", [&](const Request &req, Response &res) {
  9076. referer = req.get_header_value("Referer");
  9077. res.set_content("ok", "text/plain");
  9078. });
  9079. thread t = thread([&] { svr.listen(HOST, PORT); });
  9080. auto se = detail::scope_exit([&] {
  9081. svr.stop();
  9082. t.join();
  9083. ASSERT_FALSE(svr.is_running());
  9084. });
  9085. svr.wait_until_ready();
  9086. const std::string req = "GET /check HTTP/1.1\r\n"
  9087. "Host: localhost\r\n"
  9088. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9089. "Connection: close\r\n"
  9090. "\r\n";
  9091. std::string res;
  9092. ASSERT_TRUE(send_request(5, req, &res));
  9093. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9094. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9095. }
  9096. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9097. Server svr;
  9098. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9099. res.set_header("Cache-Control", "no-cache");
  9100. res.set_chunked_content_provider(
  9101. "text/event-stream", [](size_t offset, DataSink &sink) {
  9102. std::string s = "data:";
  9103. s += std::to_string(offset);
  9104. s += "\n\n";
  9105. auto ret = sink.write(s.data(), s.size());
  9106. EXPECT_TRUE(ret);
  9107. std::this_thread::sleep_for(std::chrono::seconds(1));
  9108. return true;
  9109. });
  9110. });
  9111. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9112. svr.wait_until_ready();
  9113. Client client(HOST, PORT);
  9114. const Headers headers = {{"Accept", "text/event-stream"}};
  9115. auto get_thread = std::thread([&client, &headers]() {
  9116. auto res = client.Get(
  9117. "/events", headers,
  9118. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9119. });
  9120. auto se = detail::scope_exit([&] {
  9121. svr.stop();
  9122. get_thread.join();
  9123. listen_thread.join();
  9124. ASSERT_FALSE(svr.is_running());
  9125. });
  9126. // Give GET time to get a few messages.
  9127. std::this_thread::sleep_for(std::chrono::seconds(2));
  9128. }
  9129. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9130. httplib::Server svr;
  9131. svr.Post("/hi",
  9132. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9133. res.status = StatusCode::OK_200;
  9134. });
  9135. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9136. svr.wait_until_ready();
  9137. Client cli(HOST, PORT);
  9138. auto res = cli.Post("/hi", "data", "text/plain");
  9139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9140. EXPECT_EQ(StatusCode::OK_200, res->status);
  9141. svr.stop();
  9142. thread.join();
  9143. ASSERT_FALSE(svr.is_running());
  9144. res = cli.Post("/hi", "data", "text/plain");
  9145. ASSERT_FALSE(res);
  9146. }
  9147. TEST(ServerStopTest, ListenFailure) {
  9148. Server svr;
  9149. auto t = thread([&]() {
  9150. auto ret = svr.listen("????", PORT);
  9151. EXPECT_FALSE(ret);
  9152. });
  9153. svr.wait_until_ready();
  9154. svr.stop();
  9155. t.join();
  9156. }
  9157. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9158. TEST(ServerStopTest, Decommision) {
  9159. Server svr;
  9160. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9161. for (int i = 0; i < 4; i++) {
  9162. auto is_even = !(i % 2);
  9163. std::thread t{[&] {
  9164. try {
  9165. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9166. if (is_even) {
  9167. throw std::runtime_error("Some thing that happens to go wrong.");
  9168. }
  9169. svr.listen(HOST, PORT);
  9170. } catch (...) { svr.decommission(); }
  9171. }};
  9172. svr.wait_until_ready();
  9173. // Server is up
  9174. {
  9175. Client cli(HOST, PORT);
  9176. auto res = cli.Get("/hi");
  9177. if (is_even) {
  9178. EXPECT_FALSE(res);
  9179. } else {
  9180. EXPECT_TRUE(res);
  9181. EXPECT_EQ("hi...", res->body);
  9182. }
  9183. }
  9184. svr.stop();
  9185. t.join();
  9186. // Server is down...
  9187. {
  9188. Client cli(HOST, PORT);
  9189. auto res = cli.Get("/hi");
  9190. EXPECT_FALSE(res);
  9191. }
  9192. }
  9193. }
  9194. #endif
  9195. // Helper function for string body upload progress tests
  9196. template <typename SetupHandler, typename ClientCall>
  9197. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9198. ClientCall &&client_call,
  9199. const string &body) {
  9200. Server svr;
  9201. setup_handler(svr);
  9202. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9203. auto se = detail::scope_exit([&] {
  9204. svr.stop();
  9205. t.join();
  9206. });
  9207. svr.wait_until_ready();
  9208. Client cli(HOST, PORT);
  9209. vector<uint64_t> progress_values;
  9210. bool progress_called = false;
  9211. auto res =
  9212. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9213. progress_values.push_back(current);
  9214. progress_called = true;
  9215. return true;
  9216. });
  9217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9218. EXPECT_EQ(200, res->status);
  9219. EXPECT_TRUE(progress_called);
  9220. }
  9221. TEST(UploadProgressTest, PostStringBodyBasic) {
  9222. TestStringBodyUploadProgress(
  9223. [](Server &svr) {
  9224. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9225. res.set_content("received", "text/plain");
  9226. });
  9227. },
  9228. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9229. return cli.Post("/test", body, "text/plain", progress_callback);
  9230. },
  9231. "test data for upload progress");
  9232. }
  9233. TEST(UploadProgressTest, PutStringBodyBasic) {
  9234. TestStringBodyUploadProgress(
  9235. [](Server &svr) {
  9236. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9237. res.set_content("put received", "text/plain");
  9238. });
  9239. },
  9240. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9241. return cli.Put("/test", body, "text/plain", progress_callback);
  9242. },
  9243. "put test data for upload progress");
  9244. }
  9245. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9246. TestStringBodyUploadProgress(
  9247. [](Server &svr) {
  9248. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9249. res.set_content("patch received", "text/plain");
  9250. });
  9251. },
  9252. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9253. return cli.Patch("/test", body, "text/plain", progress_callback);
  9254. },
  9255. "patch test data for upload progress");
  9256. }
  9257. // Helper function for content provider upload progress tests
  9258. template <typename SetupHandler, typename ClientCall>
  9259. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9260. ClientCall &&client_call) {
  9261. Server svr;
  9262. setup_handler(svr);
  9263. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9264. auto se = detail::scope_exit([&] {
  9265. svr.stop();
  9266. t.join();
  9267. });
  9268. svr.wait_until_ready();
  9269. Client cli(HOST, PORT);
  9270. vector<uint64_t> progress_values;
  9271. auto res =
  9272. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9273. progress_values.push_back(current);
  9274. return true;
  9275. });
  9276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9277. EXPECT_EQ(200, res->status);
  9278. EXPECT_FALSE(progress_values.empty());
  9279. }
  9280. TEST(UploadProgressTest, PostContentProviderProgress) {
  9281. TestContentProviderUploadProgress(
  9282. [](Server &svr) {
  9283. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9284. res.set_content("provider received", "text/plain");
  9285. });
  9286. },
  9287. [](Client &cli, UploadProgress progress_callback) {
  9288. return cli.Post(
  9289. "/test", 10,
  9290. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9291. sink.os << "test data";
  9292. return true;
  9293. },
  9294. "text/plain", progress_callback);
  9295. });
  9296. }
  9297. // Helper function for multipart upload progress tests
  9298. template <typename SetupHandler, typename ClientCall>
  9299. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9300. ClientCall &&client_call,
  9301. const string &endpoint) {
  9302. Server svr;
  9303. setup_handler(svr);
  9304. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9305. auto se = detail::scope_exit([&] {
  9306. svr.stop();
  9307. t.join();
  9308. });
  9309. svr.wait_until_ready();
  9310. Client cli(HOST, PORT);
  9311. vector<uint64_t> progress_values;
  9312. UploadFormDataItems items = {
  9313. {"field1", "value1", "", ""},
  9314. {"field2", "longer value for progress tracking test", "", ""},
  9315. {"file1", "file content data for upload progress", "test.txt",
  9316. "text/plain"}};
  9317. auto res = client_call(cli, endpoint, items,
  9318. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9319. progress_values.push_back(current);
  9320. return true;
  9321. });
  9322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9323. EXPECT_EQ(200, res->status);
  9324. EXPECT_FALSE(progress_values.empty());
  9325. }
  9326. TEST(UploadProgressTest, PostMultipartProgress) {
  9327. TestMultipartUploadProgress(
  9328. [](Server &svr) {
  9329. svr.Post("/multipart", [](const Request &req, Response &res) {
  9330. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9331. res.set_content("multipart received", "text/plain");
  9332. });
  9333. },
  9334. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9335. UploadProgress progress_callback) {
  9336. return cli.Post(endpoint, items, progress_callback);
  9337. },
  9338. "/multipart");
  9339. }
  9340. // Helper function for basic download progress tests
  9341. template <typename SetupHandler, typename ClientCall>
  9342. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9343. ClientCall &&client_call, const string &endpoint,
  9344. size_t expected_content_size) {
  9345. Server svr;
  9346. setup_handler(svr);
  9347. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9348. auto se = detail::scope_exit([&] {
  9349. svr.stop();
  9350. t.join();
  9351. });
  9352. svr.wait_until_ready();
  9353. Client cli(HOST, PORT);
  9354. vector<uint64_t> progress_values;
  9355. auto res = client_call(cli, endpoint,
  9356. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9357. progress_values.push_back(current);
  9358. return true;
  9359. });
  9360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9361. EXPECT_EQ(200, res->status);
  9362. EXPECT_FALSE(progress_values.empty());
  9363. EXPECT_EQ(expected_content_size, res->body.size());
  9364. }
  9365. TEST(DownloadProgressTest, GetBasic) {
  9366. TestBasicDownloadProgress(
  9367. [](Server &svr) {
  9368. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9369. string content(1000, 'D');
  9370. res.set_content(content, "text/plain");
  9371. });
  9372. },
  9373. [](Client &cli, const string &endpoint,
  9374. DownloadProgress progress_callback) {
  9375. return cli.Get(endpoint, progress_callback);
  9376. },
  9377. "/download", 1000u);
  9378. }
  9379. // Helper function for content receiver download progress tests
  9380. template <typename SetupHandler, typename ClientCall>
  9381. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9382. ClientCall &&client_call,
  9383. const string &endpoint,
  9384. size_t expected_content_size) {
  9385. Server svr;
  9386. setup_handler(svr);
  9387. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9388. auto se = detail::scope_exit([&] {
  9389. svr.stop();
  9390. t.join();
  9391. });
  9392. svr.wait_until_ready();
  9393. Client cli(HOST, PORT);
  9394. vector<uint64_t> progress_values;
  9395. string received_body;
  9396. auto res = client_call(
  9397. cli, endpoint,
  9398. [&](const char *data, size_t data_length) -> bool {
  9399. received_body.append(data, data_length);
  9400. return true;
  9401. },
  9402. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9403. progress_values.push_back(current);
  9404. return true;
  9405. });
  9406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9407. EXPECT_EQ(200, res->status);
  9408. EXPECT_FALSE(progress_values.empty());
  9409. EXPECT_EQ(expected_content_size, received_body.size());
  9410. EXPECT_TRUE(res->body.empty());
  9411. }
  9412. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9413. TestContentReceiverDownloadProgress(
  9414. [](Server &svr) {
  9415. svr.Get("/download-receiver",
  9416. [](const Request & /*req*/, Response &res) {
  9417. string content(2000, 'R');
  9418. res.set_content(content, "text/plain");
  9419. });
  9420. },
  9421. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9422. DownloadProgress progress_callback) {
  9423. return cli.Get(endpoint, content_receiver, progress_callback);
  9424. },
  9425. "/download-receiver", 2000u);
  9426. }
  9427. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9428. // A provider reaching a pass with nothing to hand over - an empty buffer
  9429. // popped off a queue, say - must not be taken to mean the body is finished.
  9430. // It used to end the loop with the terminating chunk unwritten while the
  9431. // server still considered the response complete, so the peer waited for an
  9432. // end that never arrived.
  9433. Server svr;
  9434. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9435. auto step = std::make_shared<int>(0);
  9436. res.set_chunked_content_provider("text/plain",
  9437. [step](size_t /*offset*/, DataSink &sink) {
  9438. switch ((*step)++) {
  9439. case 0: sink.write("", 0); break;
  9440. case 1: sink.write("hello", 5); break;
  9441. default: sink.done(); break;
  9442. }
  9443. return true;
  9444. });
  9445. });
  9446. auto port = svr.bind_to_any_port(HOST);
  9447. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9448. auto listen_se = detail::scope_exit([&] {
  9449. svr.stop();
  9450. listen_thread.join();
  9451. ASSERT_FALSE(svr.is_running());
  9452. });
  9453. svr.wait_until_ready();
  9454. Client cli(HOST, port);
  9455. // Without the fix the body is never terminated, so bound the wait rather
  9456. // than letting the test hang on the default read timeout.
  9457. cli.set_read_timeout(5, 0);
  9458. auto res = cli.Get("/stream");
  9459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9460. EXPECT_EQ(StatusCode::OK_200, res->status);
  9461. EXPECT_EQ("hello", res->body);
  9462. }
  9463. TEST(StreamingTest, NoContentLengthStreaming) {
  9464. Server svr;
  9465. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9466. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9467. if (offset < 6) {
  9468. sink.os << (offset < 3 ? "a" : "b");
  9469. } else {
  9470. sink.done();
  9471. }
  9472. return true;
  9473. });
  9474. });
  9475. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9476. auto listen_se = detail::scope_exit([&] {
  9477. svr.stop();
  9478. listen_thread.join();
  9479. ASSERT_FALSE(svr.is_running());
  9480. });
  9481. svr.wait_until_ready();
  9482. Client client(HOST, PORT);
  9483. auto get_thread = std::thread([&client]() {
  9484. std::string s;
  9485. auto res =
  9486. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9487. s += std::string(data, len);
  9488. return true;
  9489. });
  9490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9491. EXPECT_EQ(StatusCode::OK_200, res->status);
  9492. EXPECT_EQ("aaabbb", s);
  9493. });
  9494. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9495. // Give GET time to get a few messages.
  9496. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9497. }
  9498. TEST(MountTest, Unmount) {
  9499. Server svr;
  9500. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9501. auto se = detail::scope_exit([&] {
  9502. svr.stop();
  9503. listen_thread.join();
  9504. ASSERT_FALSE(svr.is_running());
  9505. });
  9506. svr.wait_until_ready();
  9507. Client cli("localhost", PORT);
  9508. svr.set_mount_point("/mount2", "./www2");
  9509. auto res = cli.Get("/");
  9510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9511. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9512. res = cli.Get("/mount2/dir/test.html");
  9513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9514. EXPECT_EQ(StatusCode::OK_200, res->status);
  9515. svr.set_mount_point("/", "./www");
  9516. res = cli.Get("/dir/");
  9517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9518. EXPECT_EQ(StatusCode::OK_200, res->status);
  9519. svr.remove_mount_point("/");
  9520. res = cli.Get("/dir/");
  9521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9522. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9523. svr.remove_mount_point("/mount2");
  9524. res = cli.Get("/mount2/dir/test.html");
  9525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9526. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9527. }
  9528. TEST(MountTest, PathSegmentBoundary) {
  9529. Server svr;
  9530. svr.set_mount_point("/mount2", "./www2");
  9531. svr.set_mount_point("/", "./www");
  9532. auto port = svr.bind_to_any_port(HOST);
  9533. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9534. auto se = detail::scope_exit([&] {
  9535. svr.stop();
  9536. listen_thread.join();
  9537. ASSERT_FALSE(svr.is_running());
  9538. });
  9539. svr.wait_until_ready();
  9540. Client cli(HOST, port);
  9541. auto res = cli.Get("/mount2/dir/test.html");
  9542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9543. EXPECT_EQ(StatusCode::OK_200, res->status);
  9544. // "/mount2" must not match part-way through a path segment.
  9545. res = cli.Get("/mount2dir/test.html");
  9546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9547. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9548. // A mount point ending in '/' keeps matching every path below it.
  9549. res = cli.Get("/dir/test.html");
  9550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9551. EXPECT_EQ(StatusCode::OK_200, res->status);
  9552. }
  9553. TEST(MountTest, Redicect) {
  9554. Server svr;
  9555. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9556. auto se = detail::scope_exit([&] {
  9557. svr.stop();
  9558. listen_thread.join();
  9559. ASSERT_FALSE(svr.is_running());
  9560. });
  9561. svr.set_mount_point("/", "./www");
  9562. svr.wait_until_ready();
  9563. Client cli("localhost", PORT);
  9564. auto res = cli.Get("/dir/");
  9565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9566. EXPECT_EQ(StatusCode::OK_200, res->status);
  9567. res = cli.Get("/dir");
  9568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9569. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9570. res = cli.Get("/file");
  9571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9572. EXPECT_EQ(StatusCode::OK_200, res->status);
  9573. res = cli.Get("/file/");
  9574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9575. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9576. cli.set_follow_location(true);
  9577. res = cli.Get("/dir");
  9578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9579. EXPECT_EQ(StatusCode::OK_200, res->status);
  9580. }
  9581. TEST(MountTest, MultibytesPathName) {
  9582. Server svr;
  9583. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9584. auto se = detail::scope_exit([&] {
  9585. svr.stop();
  9586. listen_thread.join();
  9587. ASSERT_FALSE(svr.is_running());
  9588. });
  9589. svr.set_mount_point("/", "./www");
  9590. svr.wait_until_ready();
  9591. Client cli("localhost", PORT);
  9592. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  9593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9594. EXPECT_EQ(StatusCode::OK_200, res->status);
  9595. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  9596. }
  9597. #ifdef _WIN32
  9598. // Issue #2435: mmap::open() must succeed even when another handle holds
  9599. // the file open for writing (e.g. an active log file).
  9600. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  9601. const char *path = "mmap_concurrent_writer_test.txt";
  9602. const char *content = "hello";
  9603. {
  9604. std::ofstream f(path, std::ios::binary);
  9605. f.write(content, static_cast<std::streamsize>(strlen(content)));
  9606. }
  9607. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  9608. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  9609. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  9610. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  9611. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  9612. detail::mmap m(path);
  9613. ASSERT_TRUE(m.is_open());
  9614. EXPECT_EQ(strlen(content), m.size());
  9615. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  9616. }
  9617. #endif
  9618. #ifndef _WIN32
  9619. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  9620. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  9621. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  9622. TEST(MmapTest, FailedMappingIsNotOpen) {
  9623. const char *path = "./mmap_failed_mapping_test_dir";
  9624. ASSERT_EQ(0, ::mkdir(path, 0755));
  9625. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  9626. detail::mmap m(path);
  9627. EXPECT_FALSE(m.is_open());
  9628. EXPECT_EQ(0U, m.size());
  9629. EXPECT_NE(static_cast<const void *>(m.data()),
  9630. static_cast<const void *>(MAP_FAILED));
  9631. }
  9632. #endif
  9633. TEST(KeepAliveTest, ReadTimeout) {
  9634. Server svr;
  9635. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9636. std::this_thread::sleep_for(std::chrono::seconds(2));
  9637. res.set_content("a", "text/plain");
  9638. });
  9639. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9640. res.set_content("b", "text/plain");
  9641. });
  9642. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9643. auto se = detail::scope_exit([&] {
  9644. svr.stop();
  9645. listen_thread.join();
  9646. ASSERT_FALSE(svr.is_running());
  9647. });
  9648. svr.wait_until_ready();
  9649. Client cli("localhost", PORT);
  9650. cli.set_keep_alive(true);
  9651. cli.set_read_timeout(std::chrono::seconds(1));
  9652. auto resa = cli.Get("/a");
  9653. ASSERT_FALSE(resa);
  9654. EXPECT_EQ(Error::Read, resa.error());
  9655. auto resb = cli.Get("/b");
  9656. ASSERT_TRUE(resb);
  9657. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9658. EXPECT_EQ("b", resb->body);
  9659. }
  9660. TEST(KeepAliveTest, MaxCount) {
  9661. size_t keep_alive_max_count = 3;
  9662. Server svr;
  9663. svr.set_keep_alive_max_count(keep_alive_max_count);
  9664. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9665. res.set_content("Hello World!", "text/plain");
  9666. });
  9667. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9668. auto se = detail::scope_exit([&] {
  9669. svr.stop();
  9670. listen_thread.join();
  9671. ASSERT_FALSE(svr.is_running());
  9672. });
  9673. svr.wait_until_ready();
  9674. Client cli(HOST, PORT);
  9675. cli.set_keep_alive(true);
  9676. for (size_t i = 0; i < 5; i++) {
  9677. auto result = cli.Get("/hi");
  9678. ASSERT_TRUE(result);
  9679. EXPECT_EQ(StatusCode::OK_200, result->status);
  9680. if (i == keep_alive_max_count - 1) {
  9681. EXPECT_EQ("close", result->get_header_value("Connection"));
  9682. } else {
  9683. EXPECT_FALSE(result->has_header("Connection"));
  9684. }
  9685. }
  9686. }
  9687. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  9688. // can pull the next one into the server's buffer. The server must serve it
  9689. // without waiting for the socket to become readable again. The keep-alive
  9690. // timeout outlasts the client's read timeout, so a request left waiting for it
  9691. // shows up as a missing response.
  9692. static void serve_pipelining_routes(Server &svr,
  9693. const std::function<void(int)> &client) {
  9694. svr.set_keep_alive_timeout(5);
  9695. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  9696. res.set_content("hi " + req.matches[1].str(), "text/plain");
  9697. });
  9698. svr.Post("/echo", [](const Request &req, Response &res) {
  9699. res.set_content("echo " + req.body, "text/plain");
  9700. });
  9701. auto port = svr.bind_to_any_port(HOST);
  9702. thread t = thread([&] { svr.listen_after_bind(); });
  9703. auto se = detail::scope_exit([&] {
  9704. svr.stop();
  9705. t.join();
  9706. });
  9707. svr.wait_until_ready();
  9708. client(port);
  9709. }
  9710. static std::string
  9711. send_pipelined_requests(const std::vector<std::string> &parts) {
  9712. Server svr;
  9713. std::string res;
  9714. serve_pipelining_routes(svr, [&](int port) {
  9715. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  9716. });
  9717. return res;
  9718. }
  9719. static void expect_in_order(const std::string &res,
  9720. const std::vector<std::string> &bodies) {
  9721. size_t pos = 0;
  9722. for (const auto &body : bodies) {
  9723. pos = res.find(body, pos);
  9724. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  9725. pos += body.size();
  9726. }
  9727. }
  9728. TEST(KeepAliveTest, PipelinedRequests) {
  9729. auto res = send_pipelined_requests(
  9730. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9731. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  9732. "Content-Length: 4\r\n\r\nbody"
  9733. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  9734. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  9735. }
  9736. // The second request starts in the server's buffer and ends on the socket.
  9737. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  9738. auto res =
  9739. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9740. "GET /hi/2 HTTP/1.1\r\nHo",
  9741. "st: localhost\r\nConnection: close\r\n\r\n"});
  9742. expect_in_order(res, {"hi 1", "hi 2"});
  9743. }
  9744. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  9745. // CRLF after a body does not turn into a 400 for the next request.
  9746. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  9747. auto res = send_pipelined_requests(
  9748. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  9749. "Content-Length: 4\r\n\r\nbody\r\n"
  9750. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  9751. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  9752. expect_in_order(res, {"echo body", "hi 2"});
  9753. }
  9754. // Where an unparsable request ends is unknown, so what follows it in the buffer
  9755. // must not be served as the next request.
  9756. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  9757. auto res = send_pipelined_requests(
  9758. {"INVALID REQUEST LINE\r\n\r\n"
  9759. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  9760. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9761. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  9762. }
  9763. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9764. // Over TLS, the next request is held by the TLS library as already decrypted
  9765. // data rather than on the socket.
  9766. TEST(KeepAliveTest, SSLPipelinedRequests) {
  9767. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9768. std::string res;
  9769. serve_pipelining_routes(svr, [&](int port) {
  9770. auto error = Error::Success;
  9771. auto sock = detail::create_client_socket(
  9772. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9773. /*connection_timeout_sec=*/5, 0,
  9774. /*read_timeout_sec=*/2, 0,
  9775. /*write_timeout_sec=*/5, 0, std::string(), error);
  9776. ASSERT_NE(INVALID_SOCKET, sock);
  9777. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9778. auto ctx = SSL_CTX_new(TLS_client_method());
  9779. auto ssl = SSL_new(ctx);
  9780. auto ssl_se = detail::scope_exit([&] {
  9781. SSL_free(ssl);
  9782. SSL_CTX_free(ctx);
  9783. });
  9784. SSL_set_fd(ssl, static_cast<int>(sock));
  9785. ASSERT_EQ(1, SSL_connect(ssl));
  9786. // One write, so all three requests arrive in one TLS record
  9787. const std::string req =
  9788. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9789. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9790. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
  9791. ASSERT_EQ(static_cast<int>(req.size()),
  9792. SSL_write(ssl, req.data(), static_cast<int>(req.size())));
  9793. char buf[512];
  9794. int n;
  9795. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9796. res.append(buf, static_cast<size_t>(n));
  9797. }
  9798. });
  9799. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  9800. }
  9801. #endif
  9802. TEST(KeepAliveTest, Issue1041) {
  9803. Server svr;
  9804. svr.set_keep_alive_timeout(3);
  9805. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9806. res.set_content("Hello World!", "text/plain");
  9807. });
  9808. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9809. auto se = detail::scope_exit([&] {
  9810. svr.stop();
  9811. listen_thread.join();
  9812. ASSERT_FALSE(svr.is_running());
  9813. });
  9814. svr.wait_until_ready();
  9815. Client cli(HOST, PORT);
  9816. cli.set_keep_alive(true);
  9817. auto result = cli.Get("/hi");
  9818. ASSERT_TRUE(result);
  9819. EXPECT_EQ(StatusCode::OK_200, result->status);
  9820. std::this_thread::sleep_for(std::chrono::seconds(5));
  9821. result = cli.Get("/hi");
  9822. ASSERT_TRUE(result);
  9823. EXPECT_EQ(StatusCode::OK_200, result->status);
  9824. }
  9825. TEST(KeepAliveTest, Issue1959) {
  9826. Server svr;
  9827. svr.set_keep_alive_timeout(5);
  9828. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9829. res.set_content("a", "text/plain");
  9830. });
  9831. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9832. auto se = detail::scope_exit([&] {
  9833. if (!svr.is_running()) return;
  9834. svr.stop();
  9835. listen_thread.join();
  9836. ASSERT_FALSE(svr.is_running());
  9837. });
  9838. svr.wait_until_ready();
  9839. Client cli("localhost", PORT);
  9840. cli.set_keep_alive(true);
  9841. using namespace std::chrono;
  9842. auto start = steady_clock::now();
  9843. cli.Get("/a");
  9844. svr.stop();
  9845. listen_thread.join();
  9846. auto end = steady_clock::now();
  9847. auto elapsed = duration_cast<milliseconds>(end - start).count();
  9848. EXPECT_LT(elapsed, 5000);
  9849. }
  9850. #ifdef CPPHTTPLIB_SSL_ENABLED
  9851. TEST(KeepAliveTest, SSLClientReconnection) {
  9852. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9853. ASSERT_TRUE(svr.is_valid());
  9854. svr.set_keep_alive_timeout(1);
  9855. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9856. res.set_content("Hello World!", "text/plain");
  9857. });
  9858. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9859. auto se = detail::scope_exit([&] {
  9860. svr.stop();
  9861. listen_thread.join();
  9862. ASSERT_FALSE(svr.is_running());
  9863. });
  9864. svr.wait_until_ready();
  9865. SSLClient cli(HOST, PORT);
  9866. cli.enable_server_certificate_verification(false);
  9867. cli.set_keep_alive(true);
  9868. auto result = cli.Get("/hi");
  9869. ASSERT_TRUE(result);
  9870. EXPECT_EQ(StatusCode::OK_200, result->status);
  9871. result = cli.Get("/hi");
  9872. ASSERT_TRUE(result);
  9873. EXPECT_EQ(StatusCode::OK_200, result->status);
  9874. std::this_thread::sleep_for(std::chrono::seconds(2));
  9875. // Recoonect
  9876. result = cli.Get("/hi");
  9877. ASSERT_TRUE(result);
  9878. EXPECT_EQ(StatusCode::OK_200, result->status);
  9879. result = cli.Get("/hi");
  9880. ASSERT_TRUE(result);
  9881. EXPECT_EQ(StatusCode::OK_200, result->status);
  9882. }
  9883. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  9884. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9885. ASSERT_TRUE(svr.is_valid());
  9886. svr.set_keep_alive_timeout(1);
  9887. std::string content = "reconnect";
  9888. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  9889. res.set_content("Hello World!", "text/plain");
  9890. });
  9891. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9892. auto se = detail::scope_exit([&] {
  9893. svr.stop();
  9894. listen_thread.join();
  9895. ASSERT_FALSE(svr.is_running());
  9896. });
  9897. svr.wait_until_ready();
  9898. SSLClient cli(HOST, PORT);
  9899. cli.enable_server_certificate_verification(false);
  9900. cli.set_keep_alive(true);
  9901. auto result = cli.Post(
  9902. "/hi", content.size(),
  9903. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9904. sink.write(content.c_str(), content.size());
  9905. return true;
  9906. },
  9907. "text/plain");
  9908. ASSERT_TRUE(result);
  9909. EXPECT_EQ(200, result->status);
  9910. std::this_thread::sleep_for(std::chrono::seconds(2));
  9911. // Recoonect
  9912. result = cli.Post(
  9913. "/hi", content.size(),
  9914. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9915. sink.write(content.c_str(), content.size());
  9916. return true;
  9917. },
  9918. "text/plain");
  9919. ASSERT_TRUE(result);
  9920. EXPECT_EQ(200, result->status);
  9921. result = cli.Post(
  9922. "/hi", content.size(),
  9923. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9924. sink.write(content.c_str(), content.size());
  9925. return true;
  9926. },
  9927. "text/plain");
  9928. ASSERT_TRUE(result);
  9929. EXPECT_EQ(200, result->status);
  9930. }
  9931. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  9932. using namespace httplib::tls;
  9933. {
  9934. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9935. ASSERT_TRUE(svr.is_valid());
  9936. svr.Get("/sni", [&](const Request &req, Response &res) {
  9937. std::string expected = req.sni();
  9938. EXPECT_EQ(expected, req.get_param_value("expected"));
  9939. res.set_content("ok", "text/plain");
  9940. });
  9941. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9942. auto se = detail::scope_exit([&] {
  9943. svr.stop();
  9944. listen_thread.join();
  9945. ASSERT_FALSE(svr.is_running());
  9946. });
  9947. svr.wait_until_ready();
  9948. {
  9949. SSLClient cli("localhost", PORT);
  9950. cli.enable_server_certificate_verification(false);
  9951. auto res = cli.Get("/sni?expected=localhost");
  9952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9953. }
  9954. {
  9955. SSLClient cli("::1", PORT);
  9956. cli.enable_server_certificate_verification(false);
  9957. auto res = cli.Get("/sni?expected=");
  9958. // NOTE: This may fail if the server is listening on IPv4 only
  9959. // (e.g., when localhost resolves to 127.0.0.1 only)
  9960. if (res) {
  9961. EXPECT_EQ(StatusCode::OK_200, res->status);
  9962. } else {
  9963. EXPECT_EQ(Error::Connection, res.error());
  9964. }
  9965. }
  9966. }
  9967. }
  9968. #endif
  9969. TEST(ClientProblemDetectionTest, ContentProvider) {
  9970. Server svr;
  9971. size_t content_length = 1024 * 1024;
  9972. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9973. res.set_content_provider(
  9974. content_length, "text/plain",
  9975. [&](size_t offset, size_t length, DataSink &sink) {
  9976. auto out_len = std::min(length, static_cast<size_t>(1024));
  9977. std::string out(out_len, '@');
  9978. sink.write(out.data(), out_len);
  9979. return offset < 4096;
  9980. },
  9981. [](bool success) { ASSERT_FALSE(success); });
  9982. });
  9983. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  9984. res.set_content_provider(
  9985. 0, "text/plain",
  9986. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  9987. EXPECT_TRUE(false);
  9988. return true;
  9989. },
  9990. [](bool success) { ASSERT_FALSE(success); });
  9991. });
  9992. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9993. auto se = detail::scope_exit([&] {
  9994. svr.stop();
  9995. listen_thread.join();
  9996. ASSERT_FALSE(svr.is_running());
  9997. });
  9998. svr.wait_until_ready();
  9999. Client cli("localhost", PORT);
  10000. {
  10001. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10002. size_t /*data_length*/) { return false; });
  10003. ASSERT_FALSE(res);
  10004. }
  10005. {
  10006. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10007. size_t /*data_length*/) { return false; });
  10008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10009. }
  10010. }
  10011. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10012. // A provider that reports success without writing anything and without
  10013. // calling done() used to be handed the same offset and length again on every
  10014. // pass, so it spun for as long as the peer stayed connected.
  10015. Server svr;
  10016. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10017. res.set_content("ok", "text/plain");
  10018. });
  10019. auto port = svr.bind_to_any_port(HOST);
  10020. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10021. auto se = detail::scope_exit([&] {
  10022. svr.stop();
  10023. listen_thread.join();
  10024. ASSERT_FALSE(svr.is_running());
  10025. });
  10026. svr.wait_until_ready();
  10027. std::atomic<int> call_count{0};
  10028. Client cli(HOST, port);
  10029. auto res = cli.Post(
  10030. "/", 1024,
  10031. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10032. // Give up after enough passes to show the spin, so that losing the
  10033. // check below fails this test instead of hanging it.
  10034. return ++call_count < 100;
  10035. },
  10036. "text/plain");
  10037. ASSERT_FALSE(res);
  10038. EXPECT_EQ(Error::Write, res.error());
  10039. EXPECT_EQ(1, call_count.load());
  10040. }
  10041. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10042. // A writer only has to assign `write`. The other three used to be left as
  10043. // empty std::functions, so a provider calling one threw
  10044. // std::bad_function_call out of the thread running it and took the whole
  10045. // process down.
  10046. DataSink sink;
  10047. std::string written;
  10048. sink.write = [&](const char *data, size_t data_len) {
  10049. written.append(data, data_len);
  10050. return true;
  10051. };
  10052. EXPECT_TRUE(sink.is_writable());
  10053. sink.done();
  10054. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10055. EXPECT_TRUE(written.empty());
  10056. }
  10057. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10058. // A sink that cannot carry trailers still has to finish.
  10059. DataSink sink;
  10060. auto done_count = 0;
  10061. sink.done = [&]() { done_count++; };
  10062. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10063. EXPECT_EQ(1, done_count);
  10064. }
  10065. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10066. Server svr;
  10067. const std::string body(4096, 'x');
  10068. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10069. res.set_content_provider(body.size(), "text/plain",
  10070. [&](size_t offset, size_t length, DataSink &sink) {
  10071. sink.write(body.data() + offset, length);
  10072. sink.done();
  10073. return true;
  10074. });
  10075. });
  10076. auto port = svr.bind_to_any_port(HOST);
  10077. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10078. auto se = detail::scope_exit([&] {
  10079. svr.stop();
  10080. listen_thread.join();
  10081. ASSERT_FALSE(svr.is_running());
  10082. });
  10083. svr.wait_until_ready();
  10084. Client cli(HOST, port);
  10085. auto res = cli.Get("/");
  10086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10087. EXPECT_EQ(StatusCode::OK_200, res->status);
  10088. EXPECT_EQ(body, res->body);
  10089. }
  10090. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10091. Server svr;
  10092. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10093. res.set_content_provider(
  10094. 1024, "text/plain",
  10095. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10096. sink.write("hello", 5);
  10097. sink.done(); // short of the 1024 bytes the response promised
  10098. return true;
  10099. });
  10100. });
  10101. auto port = svr.bind_to_any_port(HOST);
  10102. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10103. auto se = detail::scope_exit([&] {
  10104. svr.stop();
  10105. listen_thread.join();
  10106. ASSERT_FALSE(svr.is_running());
  10107. });
  10108. svr.wait_until_ready();
  10109. Client cli(HOST, port);
  10110. cli.set_read_timeout(5, 0);
  10111. // The response is short of its Content-Length, so the client cannot read a
  10112. // complete body. What matters is that this returns at all: a no-op done()
  10113. // would leave the writer looping over a provider that never makes progress.
  10114. auto res = cli.Get("/");
  10115. EXPECT_FALSE(res);
  10116. }
  10117. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10118. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10119. // The compressed path builds the whole body before connecting, so this
  10120. // fails client-side and never reaches a server.
  10121. Client cli(HOST, PORT);
  10122. cli.set_compress(true);
  10123. auto res = cli.Post(
  10124. "/", 1024,
  10125. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10126. sink.write("hello", 5);
  10127. sink.done(); // short of the 1024 bytes the request announced
  10128. return true;
  10129. },
  10130. "text/plain");
  10131. ASSERT_FALSE(res);
  10132. EXPECT_EQ(Error::Write, res.error());
  10133. }
  10134. #endif
  10135. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  10136. Server svr;
  10137. svr.set_error_handler([](Request const &, Response &res) -> void {
  10138. res.set_chunked_content_provider(
  10139. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10140. sink.os << "hello";
  10141. sink.os << "world";
  10142. sink.done();
  10143. return true;
  10144. });
  10145. });
  10146. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10147. auto se = detail::scope_exit([&] {
  10148. svr.stop();
  10149. listen_thread.join();
  10150. ASSERT_FALSE(svr.is_running());
  10151. });
  10152. svr.wait_until_ready();
  10153. Client cli("localhost", PORT);
  10154. auto res = cli.Get("/");
  10155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10156. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10157. EXPECT_EQ("helloworld", res->body);
  10158. }
  10159. TEST(LongPollingTest, ClientCloseDetection) {
  10160. Server svr;
  10161. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10162. res.set_chunked_content_provider(
  10163. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10164. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10165. sink.os << "hello";
  10166. auto count = 10;
  10167. while (count > 0 && sink.is_writable()) {
  10168. this_thread::sleep_for(chrono::milliseconds(10));
  10169. count--;
  10170. }
  10171. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  10172. return true;
  10173. });
  10174. });
  10175. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10176. auto se = detail::scope_exit([&] {
  10177. svr.stop();
  10178. listen_thread.join();
  10179. ASSERT_FALSE(svr.is_running());
  10180. });
  10181. svr.wait_until_ready();
  10182. Client cli("localhost", PORT);
  10183. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10184. EXPECT_EQ("hello", string(data, data_length));
  10185. return false; // close the socket immediately.
  10186. });
  10187. ASSERT_FALSE(res);
  10188. }
  10189. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  10190. Server svr;
  10191. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10192. res.set_chunked_content_provider(
  10193. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10194. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10195. sink.os << "hello";
  10196. EXPECT_TRUE(sink.os.good());
  10197. // Wait for the client to close the connection
  10198. auto count = 10;
  10199. while (count > 0 && sink.is_writable()) {
  10200. this_thread::sleep_for(chrono::milliseconds(10));
  10201. count--;
  10202. }
  10203. // After client disconnect, write repeatedly until the socket
  10204. // write actually fails (small writes may be absorbed by the
  10205. // kernel buffer)
  10206. std::string chunk(1024, 'x');
  10207. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  10208. sink.os << chunk;
  10209. }
  10210. EXPECT_TRUE(sink.os.fail());
  10211. return true;
  10212. });
  10213. });
  10214. auto port = svr.bind_to_any_port("localhost");
  10215. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10216. auto se = detail::scope_exit([&] {
  10217. svr.stop();
  10218. listen_thread.join();
  10219. ASSERT_FALSE(svr.is_running());
  10220. });
  10221. svr.wait_until_ready();
  10222. Client cli("localhost", port);
  10223. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10224. EXPECT_EQ("hello", string(data, data_length));
  10225. return false; // close the socket immediately.
  10226. });
  10227. ASSERT_FALSE(res);
  10228. }
  10229. TEST(GetWithParametersTest, GetWithParameters) {
  10230. Server svr;
  10231. svr.Get("/", [&](const Request &req, Response &) {
  10232. EXPECT_EQ("world", req.get_param_value("hello"));
  10233. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10234. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10235. });
  10236. svr.Get("/params", [&](const Request &req, Response &) {
  10237. EXPECT_EQ("world", req.get_param_value("hello"));
  10238. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10239. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10240. });
  10241. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10242. EXPECT_EQ("resource-id", req.matches[1]);
  10243. EXPECT_EQ("foo", req.get_param_value("param1"));
  10244. EXPECT_EQ("bar", req.get_param_value("param2"));
  10245. });
  10246. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10247. EXPECT_EQ("user-id", req.path_params.at("id"));
  10248. EXPECT_EQ("foo", req.get_param_value("param1"));
  10249. EXPECT_EQ("bar", req.get_param_value("param2"));
  10250. });
  10251. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10252. auto se = detail::scope_exit([&] {
  10253. svr.stop();
  10254. listen_thread.join();
  10255. ASSERT_FALSE(svr.is_running());
  10256. });
  10257. svr.wait_until_ready();
  10258. {
  10259. Client cli(HOST, PORT);
  10260. Params params;
  10261. params.emplace("hello", "world");
  10262. params.emplace("hello2", "world2");
  10263. params.emplace("hello3", "world3");
  10264. auto res = cli.Get("/", params, Headers{});
  10265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10266. EXPECT_EQ(StatusCode::OK_200, res->status);
  10267. }
  10268. {
  10269. Client cli(HOST, PORT);
  10270. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10272. EXPECT_EQ(StatusCode::OK_200, res->status);
  10273. }
  10274. {
  10275. Client cli(HOST, PORT);
  10276. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  10277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10278. EXPECT_EQ(StatusCode::OK_200, res->status);
  10279. }
  10280. {
  10281. Client cli(HOST, PORT);
  10282. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  10283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10284. EXPECT_EQ(StatusCode::OK_200, res->status);
  10285. }
  10286. }
  10287. TEST(GetWithParametersTest, GetWithParameters2) {
  10288. Server svr;
  10289. svr.Get("/", [&](const Request &req, Response &res) {
  10290. auto text = req.get_param_value("hello");
  10291. res.set_content(text, "text/plain");
  10292. });
  10293. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10294. auto se = detail::scope_exit([&] {
  10295. svr.stop();
  10296. listen_thread.join();
  10297. ASSERT_FALSE(svr.is_running());
  10298. });
  10299. svr.wait_until_ready();
  10300. Client cli("localhost", PORT);
  10301. Params params;
  10302. params.emplace("hello", "world");
  10303. std::string body;
  10304. auto res = cli.Get("/", params, Headers{},
  10305. [&](const char *data, size_t data_length) {
  10306. body.append(data, data_length);
  10307. return true;
  10308. });
  10309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10310. EXPECT_EQ(StatusCode::OK_200, res->status);
  10311. EXPECT_EQ("world", body);
  10312. }
  10313. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  10314. Server svr;
  10315. svr.Get("/search", [&](const Request &req, Response &res) {
  10316. auto q = req.get_param_value("q");
  10317. res.set_content(q, "text/plain");
  10318. });
  10319. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10320. auto se = detail::scope_exit([&] {
  10321. svr.stop();
  10322. listen_thread.join();
  10323. ASSERT_FALSE(svr.is_running());
  10324. });
  10325. svr.wait_until_ready();
  10326. Client cli("localhost", PORT);
  10327. // Verify that Get(path, params) works without requiring Headers argument
  10328. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  10329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10330. EXPECT_EQ(StatusCode::OK_200, res->status);
  10331. EXPECT_EQ("cpp-httplib", res->body);
  10332. }
  10333. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  10334. auto host = "httpbingo.org";
  10335. auto path = std::string{"/range/32"};
  10336. #ifdef CPPHTTPLIB_SSL_ENABLED
  10337. SSLClient cli(host);
  10338. #else
  10339. Client cli(host);
  10340. #endif
  10341. cli.set_default_headers({make_range_header({{1, 10}})});
  10342. cli.set_connection_timeout(5);
  10343. {
  10344. auto res = cli.Get(path);
  10345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10346. EXPECT_EQ("bcdefghijk", res->body);
  10347. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10348. }
  10349. {
  10350. auto res = cli.Get(path);
  10351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10352. EXPECT_EQ("bcdefghijk", res->body);
  10353. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10354. }
  10355. }
  10356. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  10357. Server svr;
  10358. svr.set_default_headers({{"Hello", "World"}});
  10359. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10360. res.set_content("ok", "text/plain");
  10361. });
  10362. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  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. Client cli("localhost", PORT);
  10370. auto res = cli.Get("/");
  10371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10372. EXPECT_EQ(StatusCode::OK_200, res->status);
  10373. EXPECT_EQ("ok", res->body);
  10374. EXPECT_EQ("World", res->get_header_value("Hello"));
  10375. }
  10376. #ifdef CPPHTTPLIB_SSL_ENABLED
  10377. TEST(KeepAliveTest, ReadTimeoutSSL) {
  10378. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10379. ASSERT_TRUE(svr.is_valid());
  10380. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10381. std::this_thread::sleep_for(std::chrono::seconds(2));
  10382. res.set_content("a", "text/plain");
  10383. });
  10384. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10385. res.set_content("b", "text/plain");
  10386. });
  10387. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10388. auto se = detail::scope_exit([&] {
  10389. svr.stop();
  10390. listen_thread.join();
  10391. ASSERT_FALSE(svr.is_running());
  10392. });
  10393. svr.wait_until_ready();
  10394. SSLClient cli("localhost", PORT);
  10395. cli.enable_server_certificate_verification(false);
  10396. cli.set_keep_alive(true);
  10397. cli.set_read_timeout(std::chrono::seconds(1));
  10398. auto resa = cli.Get("/a");
  10399. ASSERT_TRUE(!resa);
  10400. EXPECT_EQ(Error::Read, resa.error());
  10401. auto resb = cli.Get("/b");
  10402. ASSERT_TRUE(resb);
  10403. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10404. EXPECT_EQ("b", resb->body);
  10405. }
  10406. // Closing an idle keep-alive connection sends close_notify and returns. The
  10407. // server must not wait for the client's close_notify: an idle client never
  10408. // sends one, so the worker would be held until the read timeout expires, and
  10409. // stop() would wait for it.
  10410. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  10411. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10412. ASSERT_TRUE(svr.is_valid());
  10413. svr.set_keep_alive_timeout(1);
  10414. svr.set_read_timeout(10, 0);
  10415. svr.Get("/", [](const Request &, Response &res) {
  10416. res.set_content("ok", "text/plain");
  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. if (listen_thread.joinable()) {
  10422. svr.stop();
  10423. listen_thread.join();
  10424. }
  10425. });
  10426. svr.wait_until_ready();
  10427. SSLClient cli(HOST, port);
  10428. cli.enable_server_certificate_verification(false);
  10429. cli.set_keep_alive(true);
  10430. auto res = cli.Get("/");
  10431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10432. EXPECT_EQ(StatusCode::OK_200, res->status);
  10433. // Stay idle past the keep-alive timeout so the server closes the connection.
  10434. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  10435. auto start = std::chrono::steady_clock::now();
  10436. svr.stop();
  10437. listen_thread.join();
  10438. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10439. std::chrono::steady_clock::now() - start)
  10440. .count();
  10441. EXPECT_LT(elapsed, 3000);
  10442. }
  10443. #endif
  10444. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  10445. protected:
  10446. ServerTestWithAI_PASSIVE()
  10447. : cli_(HOST, PORT)
  10448. #ifdef CPPHTTPLIB_SSL_ENABLED
  10449. ,
  10450. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10451. #endif
  10452. {
  10453. #ifdef CPPHTTPLIB_SSL_ENABLED
  10454. cli_.enable_server_certificate_verification(false);
  10455. #endif
  10456. }
  10457. virtual void SetUp() {
  10458. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10459. res.set_content("Hello World!", "text/plain");
  10460. });
  10461. t_ = thread(
  10462. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  10463. svr_.wait_until_ready();
  10464. }
  10465. virtual void TearDown() {
  10466. svr_.stop();
  10467. t_.join();
  10468. }
  10469. #ifdef CPPHTTPLIB_SSL_ENABLED
  10470. SSLClient cli_;
  10471. SSLServer svr_;
  10472. #else
  10473. Client cli_;
  10474. Server svr_;
  10475. #endif
  10476. thread t_;
  10477. };
  10478. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  10479. auto res = cli_.Get("/hi");
  10480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10481. EXPECT_EQ(StatusCode::OK_200, res->status);
  10482. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  10483. EXPECT_EQ("Hello World!", res->body);
  10484. }
  10485. class ServerUpDownTest : public ::testing::Test {
  10486. protected:
  10487. ServerUpDownTest() : cli_(HOST, PORT) {}
  10488. virtual void SetUp() {
  10489. t_ = thread([&]() {
  10490. svr_.bind_to_any_port(HOST);
  10491. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10492. ASSERT_TRUE(svr_.listen_after_bind());
  10493. });
  10494. svr_.wait_until_ready();
  10495. }
  10496. virtual void TearDown() {
  10497. svr_.stop();
  10498. t_.join();
  10499. }
  10500. Client cli_;
  10501. Server svr_;
  10502. thread t_;
  10503. };
  10504. TEST_F(ServerUpDownTest, QuickStartStop) {
  10505. // Should not crash, especially when run with
  10506. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  10507. }
  10508. class PayloadMaxLengthTest : public ::testing::Test {
  10509. protected:
  10510. PayloadMaxLengthTest()
  10511. : cli_(HOST, PORT)
  10512. #ifdef CPPHTTPLIB_SSL_ENABLED
  10513. ,
  10514. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10515. #endif
  10516. {
  10517. #ifdef CPPHTTPLIB_SSL_ENABLED
  10518. cli_.enable_server_certificate_verification(false);
  10519. #endif
  10520. }
  10521. virtual void SetUp() {
  10522. svr_.set_payload_max_length(8);
  10523. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10524. res.set_content("test", "text/plain");
  10525. });
  10526. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10527. svr_.wait_until_ready();
  10528. }
  10529. virtual void TearDown() {
  10530. svr_.stop();
  10531. t_.join();
  10532. }
  10533. #ifdef CPPHTTPLIB_SSL_ENABLED
  10534. SSLClient cli_;
  10535. SSLServer svr_;
  10536. #else
  10537. Client cli_;
  10538. Server svr_;
  10539. #endif
  10540. thread t_;
  10541. };
  10542. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  10543. auto res = cli_.Post("/test", "123456789", "text/plain");
  10544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10545. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10546. res = cli_.Post("/test", "12345678", "text/plain");
  10547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10548. EXPECT_EQ(StatusCode::OK_200, res->status);
  10549. }
  10550. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  10551. // Test chunked encoding with payload exceeding the 8-byte limit
  10552. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  10553. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  10554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10555. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10556. }
  10557. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  10558. // Test chunked encoding with payload within the 8-byte limit
  10559. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  10560. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  10561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10562. EXPECT_EQ(StatusCode::OK_200, res->status);
  10563. }
  10564. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  10565. // Test using send_request to send chunked data exceeding payload limit
  10566. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  10567. "Host: " +
  10568. std::string(HOST) + ":" + std::to_string(PORT) +
  10569. "\r\n"
  10570. "Transfer-Encoding: chunked\r\n"
  10571. "Connection: close\r\n"
  10572. "\r\n"
  10573. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  10574. "0123456789\r\n"
  10575. "0\r\n" // End chunk
  10576. "\r\n";
  10577. std::string response;
  10578. bool result = send_request(1, chunked_request, &response);
  10579. if (!result) {
  10580. // If send_request fails, it might be because the server closed the
  10581. // connection due to payload limit enforcement, which is acceptable
  10582. SUCCEED()
  10583. << "Server rejected oversized chunked request (connection closed)";
  10584. } else {
  10585. // If we got a response, check if it's an error response or connection was
  10586. // closed early Short response length indicates connection was closed due to
  10587. // payload limit
  10588. if (response.length() <= 10) {
  10589. SUCCEED() << "Server closed connection for oversized chunked request";
  10590. } else {
  10591. // Check for error status codes
  10592. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10593. response.find("Payload Too Large") != std::string::npos ||
  10594. response.find("400") != std::string::npos);
  10595. }
  10596. }
  10597. }
  10598. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  10599. // Test request without Content-Length header exceeding payload limit
  10600. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10601. "Host: " +
  10602. std::string(HOST) + ":" +
  10603. std::to_string(PORT) +
  10604. "\r\n"
  10605. "Connection: close\r\n"
  10606. "\r\n";
  10607. // Add payload exceeding the 8-byte limit
  10608. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  10609. request_without_content_length += large_payload;
  10610. std::string response;
  10611. bool result = send_request(1, request_without_content_length, &response);
  10612. if (!result) {
  10613. // If send_request fails, server likely closed connection due to payload
  10614. // limit
  10615. SUCCEED() << "Server rejected oversized request without Content-Length "
  10616. "(connection closed)";
  10617. } else {
  10618. // Check if server responded with error or closed connection early
  10619. if (response.length() <= 10) {
  10620. SUCCEED() << "Server closed connection for oversized request without "
  10621. "Content-Length";
  10622. } else {
  10623. // Check for error status codes
  10624. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10625. response.find("Payload Too Large") != std::string::npos ||
  10626. response.find("400") != std::string::npos);
  10627. }
  10628. }
  10629. }
  10630. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  10631. // Test request without Content-Length header within payload limit
  10632. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10633. "Host: " +
  10634. std::string(HOST) + ":" +
  10635. std::to_string(PORT) +
  10636. "\r\n"
  10637. "Connection: close\r\n"
  10638. "\r\n";
  10639. // Add payload within the 8-byte limit
  10640. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  10641. request_without_content_length += small_payload;
  10642. std::string response;
  10643. bool result = send_request(1, request_without_content_length, &response);
  10644. // For requests without Content-Length, the server may have different behavior
  10645. // The key is that it should not reject due to payload limit for small
  10646. // payloads
  10647. if (result) {
  10648. // Check for any HTTP response (success or error, but not connection closed)
  10649. if (response.length() > 10) {
  10650. SUCCEED()
  10651. << "Server processed request without Content-Length within limit";
  10652. } else {
  10653. // Short response might indicate connection closed, which is acceptable
  10654. SUCCEED() << "Server closed connection for request without "
  10655. "Content-Length (acceptable behavior)";
  10656. }
  10657. } else {
  10658. // Connection failure might be due to protocol requirements
  10659. SUCCEED() << "Connection issue with request without Content-Length "
  10660. "(environment-specific)";
  10661. }
  10662. }
  10663. class LargePayloadMaxLengthTest : public ::testing::Test {
  10664. protected:
  10665. LargePayloadMaxLengthTest()
  10666. : cli_(HOST, PORT)
  10667. #ifdef CPPHTTPLIB_SSL_ENABLED
  10668. ,
  10669. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10670. #endif
  10671. {
  10672. #ifdef CPPHTTPLIB_SSL_ENABLED
  10673. cli_.enable_server_certificate_verification(false);
  10674. #endif
  10675. }
  10676. virtual void SetUp() {
  10677. // Set 10MB payload limit
  10678. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  10679. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  10680. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10681. res.set_content("Large payload test", "text/plain");
  10682. });
  10683. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10684. svr_.wait_until_ready();
  10685. }
  10686. virtual void TearDown() {
  10687. svr_.stop();
  10688. t_.join();
  10689. }
  10690. #ifdef CPPHTTPLIB_SSL_ENABLED
  10691. SSLClient cli_;
  10692. SSLServer svr_;
  10693. #else
  10694. Client cli_;
  10695. Server svr_;
  10696. #endif
  10697. thread t_;
  10698. };
  10699. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  10700. // Test chunked encoding with payload within 10MB limit
  10701. std::string medium_payload(5 * 1024 * 1024,
  10702. 'A'); // 5MB payload, within 10MB limit
  10703. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  10704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10705. EXPECT_EQ(StatusCode::OK_200, res->status);
  10706. }
  10707. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  10708. // Test chunked encoding with payload exceeding 10MB limit
  10709. std::string large_payload(12 * 1024 * 1024,
  10710. 'B'); // 12MB payload, exceeds 10MB limit
  10711. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  10712. // Server may either return 413 or close the connection
  10713. if (res) {
  10714. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10715. } else {
  10716. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  10717. }
  10718. }
  10719. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  10720. // Test request without Content-Length header within 10MB limit
  10721. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10722. "Host: " +
  10723. std::string(HOST) + ":" +
  10724. std::to_string(PORT) +
  10725. "\r\n"
  10726. "Connection: close\r\n"
  10727. "\r\n";
  10728. // Add 1MB payload (within 10MB limit)
  10729. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  10730. request_without_content_length += medium_payload;
  10731. std::string response;
  10732. bool result = send_request(5, request_without_content_length, &response);
  10733. if (result) {
  10734. // Should get a proper HTTP response for payloads within limit
  10735. if (response.length() > 10) {
  10736. SUCCEED() << "Server processed 1MB request without Content-Length within "
  10737. "10MB limit";
  10738. } else {
  10739. SUCCEED() << "Server closed connection (acceptable behavior for no "
  10740. "Content-Length)";
  10741. }
  10742. } else {
  10743. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  10744. }
  10745. }
  10746. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  10747. // Test request without Content-Length header exceeding 10MB limit
  10748. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10749. "Host: " +
  10750. std::string(HOST) + ":" +
  10751. std::to_string(PORT) +
  10752. "\r\n"
  10753. "Connection: close\r\n"
  10754. "\r\n";
  10755. // Add 12MB payload (exceeds 10MB limit)
  10756. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  10757. request_without_content_length += large_payload;
  10758. std::string response;
  10759. bool result = send_request(10, request_without_content_length, &response);
  10760. if (!result) {
  10761. // Server should close connection due to payload limit
  10762. SUCCEED() << "Server rejected 12MB request without Content-Length "
  10763. "(connection closed)";
  10764. } else {
  10765. // Check for error response
  10766. if (response.length() <= 10) {
  10767. SUCCEED()
  10768. << "Server closed connection for 12MB request exceeding 10MB limit";
  10769. } else {
  10770. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10771. response.find("Payload Too Large") != std::string::npos ||
  10772. response.find("400") != std::string::npos);
  10773. }
  10774. }
  10775. }
  10776. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10777. // `payload_max_length` is not enforced on decompressed body in ContentReader
  10778. // path.
  10779. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  10780. Server svr;
  10781. const size_t LIMIT = 64 * 1024; // 64KB
  10782. svr.set_payload_max_length(LIMIT);
  10783. size_t total = 0;
  10784. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10785. const ContentReader &content_reader) {
  10786. content_reader([&](const char * /*data*/, size_t len) {
  10787. total += len;
  10788. return true;
  10789. });
  10790. res.status = 200;
  10791. res.set_content("stream_ok", "text/plain");
  10792. });
  10793. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10794. auto se = detail::scope_exit([&] {
  10795. svr.stop();
  10796. thread.join();
  10797. ASSERT_FALSE(svr.is_running());
  10798. });
  10799. svr.wait_until_ready();
  10800. // Prepare 256KB raw data and gzip-compress it
  10801. std::string raw(256 * 1024, 'A');
  10802. std::string gz;
  10803. {
  10804. z_stream zs{};
  10805. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  10806. Z_DEFAULT_STRATEGY);
  10807. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  10808. zs.avail_in = static_cast<uInt>(raw.size());
  10809. char outbuf[4096];
  10810. int ret;
  10811. do {
  10812. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  10813. zs.avail_out = sizeof(outbuf);
  10814. ret = deflate(&zs, Z_FINISH);
  10815. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  10816. } while (ret != Z_STREAM_END);
  10817. deflateEnd(&zs);
  10818. }
  10819. Client cli(HOST, PORT);
  10820. cli.set_connection_timeout(std::chrono::seconds(5));
  10821. Headers headers = {{"Content-Encoding", "gzip"}};
  10822. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  10823. "application/octet-stream");
  10824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10825. // Server must reject oversized decompressed payloads with 413.
  10826. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10827. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10828. EXPECT_LE(total, LIMIT);
  10829. }
  10830. #ifndef CPPHTTPLIB_SSL_ENABLED
  10831. // For a request with neither Content-Length nor Transfer-Encoding, the
  10832. // non-SSL raw-socket fallback in read_content_core() used to hand the
  10833. // compressed wire bytes straight to the ContentReader without ever routing
  10834. // them through the decompressor, so payload_max_length_ only bounded the
  10835. // compressed size on the wire, not the decompressed size.
  10836. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  10837. Server svr;
  10838. const size_t LIMIT = 64 * 1024; // 64KB
  10839. svr.set_payload_max_length(LIMIT);
  10840. size_t total = 0;
  10841. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10842. const ContentReader &content_reader) {
  10843. content_reader([&](const char * /*data*/, size_t len) {
  10844. total += len;
  10845. return true;
  10846. });
  10847. res.status = 200;
  10848. res.set_content("stream_ok", "text/plain");
  10849. });
  10850. auto port = svr.bind_to_any_port(HOST);
  10851. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10852. auto se = detail::scope_exit([&] {
  10853. svr.stop();
  10854. thread.join();
  10855. ASSERT_FALSE(svr.is_running());
  10856. });
  10857. svr.wait_until_ready();
  10858. // Prepare 256KB raw data and gzip-compress it, same payload as the
  10859. // StreamingGzipDecompression test above.
  10860. std::string raw(256 * 1024, 'A');
  10861. std::string gz;
  10862. {
  10863. httplib::detail::gzip_compressor compressor;
  10864. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  10865. [&](const char *chunk, size_t len) {
  10866. gz.append(chunk, len);
  10867. return true;
  10868. });
  10869. ASSERT_TRUE(result);
  10870. }
  10871. // Send the gzip body over raw TCP with neither Content-Length nor
  10872. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  10873. // kicks in.
  10874. std::string req = "POST /stream HTTP/1.1\r\n"
  10875. "Host: " +
  10876. std::string(HOST) + ":" + std::to_string(port) +
  10877. "\r\n"
  10878. "Content-Encoding: gzip\r\n"
  10879. "Connection: close\r\n"
  10880. "\r\n" +
  10881. gz;
  10882. std::string response;
  10883. ASSERT_TRUE(send_request(5, req, &response, port));
  10884. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10885. EXPECT_LE(total, LIMIT);
  10886. }
  10887. #endif
  10888. #endif
  10889. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  10890. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  10891. // the payload must be passed through untouched instead of being rejected.
  10892. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  10893. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10894. Server svr;
  10895. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  10896. res.set_content(body, "image/jpeg");
  10897. res.set_header("Content-Encoding", "UTF-8");
  10898. });
  10899. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  10900. res.set_content(body, "image/jpeg");
  10901. res.set_header("Content-Encoding", "identity");
  10902. });
  10903. svr.Post("/echo", [](const Request &req, Response &res) {
  10904. res.set_content(req.body, "image/jpeg");
  10905. });
  10906. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10907. auto se = detail::scope_exit([&] {
  10908. svr.stop();
  10909. t.join();
  10910. ASSERT_FALSE(svr.is_running());
  10911. });
  10912. svr.wait_until_ready();
  10913. Client cli(HOST, PORT);
  10914. {
  10915. auto res = cli.Get("/image");
  10916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10917. EXPECT_EQ(StatusCode::OK_200, res->status);
  10918. EXPECT_EQ(body, res->body);
  10919. }
  10920. {
  10921. auto res = cli.Get("/identity");
  10922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10923. EXPECT_EQ(StatusCode::OK_200, res->status);
  10924. EXPECT_EQ(body, res->body);
  10925. }
  10926. {
  10927. // The same applies to a request body reaching the server.
  10928. Headers headers = {{"Content-Encoding", "UTF-8"}};
  10929. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  10930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10931. EXPECT_EQ(StatusCode::OK_200, res->status);
  10932. EXPECT_EQ(body, res->body);
  10933. }
  10934. }
  10935. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  10936. // gzip-encoded response even when the build has no zlib support.
  10937. static const char GZIPPED_HELLO_WORLD[] = {
  10938. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  10939. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  10940. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  10941. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  10942. // A content coding is a whole token, not something the field value merely
  10943. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  10944. // as "fibre" look like Brotli, and turned a multi-coding value like
  10945. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  10946. // it was never meant to see.
  10947. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  10948. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10949. Server svr;
  10950. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  10951. res.set_content(body, "image/jpeg");
  10952. res.set_header("Content-Encoding", "fibre");
  10953. });
  10954. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  10955. res.set_content(body, "image/jpeg");
  10956. res.set_header("Content-Encoding", "gzip, br");
  10957. });
  10958. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  10959. res.set_content(body, "image/jpeg");
  10960. res.set_header("Content-Encoding", "x-zstd-ish");
  10961. });
  10962. auto port = svr.bind_to_any_port(HOST);
  10963. thread t = thread([&]() { svr.listen_after_bind(); });
  10964. auto se = detail::scope_exit([&] {
  10965. svr.stop();
  10966. t.join();
  10967. ASSERT_FALSE(svr.is_running());
  10968. });
  10969. svr.wait_until_ready();
  10970. Client cli(HOST, port);
  10971. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  10972. auto res = cli.Get(path);
  10973. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  10974. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10975. // Not a coding we recognize, so the payload comes back untouched
  10976. EXPECT_EQ(body, res->body) << path;
  10977. }
  10978. }
  10979. // A content coding cpp-httplib recognizes but was not built with must be
  10980. // reported as such. Handing the still-compressed payload back to the caller
  10981. // would silently corrupt it.
  10982. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  10983. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10984. Server svr;
  10985. // "image/jpeg" keeps the server from applying a content coding of its own,
  10986. // so the hand-crafted Content-Encoding below survives.
  10987. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  10988. res.set_content(gzipped, "image/jpeg");
  10989. res.set_header("Content-Encoding", "gzip");
  10990. });
  10991. // Content codings are case-insensitive (RFC 9110 8.4.1).
  10992. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  10993. res.set_content(gzipped, "image/jpeg");
  10994. res.set_header("Content-Encoding", "GZIP");
  10995. });
  10996. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10997. auto se = detail::scope_exit([&] {
  10998. svr.stop();
  10999. t.join();
  11000. ASSERT_FALSE(svr.is_running());
  11001. });
  11002. svr.wait_until_ready();
  11003. Client cli(HOST, PORT);
  11004. {
  11005. auto res = cli.Get("/gzipped");
  11006. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11008. EXPECT_EQ("Hello World!", res->body);
  11009. #else
  11010. ASSERT_FALSE(res);
  11011. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11012. #endif
  11013. }
  11014. {
  11015. // open_stream() must behave the same way.
  11016. auto handle = cli.open_stream("GET", "/gzipped");
  11017. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11018. ASSERT_TRUE(handle.is_valid());
  11019. std::string received;
  11020. char buf[256];
  11021. ssize_t n;
  11022. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11023. received.append(buf, static_cast<size_t>(n));
  11024. }
  11025. EXPECT_EQ("Hello World!", received);
  11026. #else
  11027. EXPECT_FALSE(handle.is_valid());
  11028. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  11029. #endif
  11030. }
  11031. {
  11032. // A differently-cased coding must not be mistaken for an unknown one, or
  11033. // the body would be handed back still compressed.
  11034. auto res = cli.Get("/gzipped-uppercase");
  11035. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11037. EXPECT_EQ("Hello World!", res->body);
  11038. #else
  11039. ASSERT_FALSE(res);
  11040. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11041. #endif
  11042. }
  11043. }
  11044. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11045. // A handler serving pre-compressed content (e.g. build-time gzipped static
  11046. // assets) sets Content-Encoding itself. The server used to pick a coding from
  11047. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  11048. // body a second time and appending a second Content-Encoding field line, so
  11049. // clients that decode one coding per listed value handed back raw gzip bytes.
  11050. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  11051. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11052. Server svr;
  11053. // text/plain is a compressible type, so only the pre-set Content-Encoding
  11054. // keeps the server from applying a coding of its own.
  11055. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11056. res.set_content(gzipped, "text/plain");
  11057. res.set_header("Content-Encoding", "gzip");
  11058. });
  11059. auto port = svr.bind_to_any_port(HOST);
  11060. thread t = thread([&]() { svr.listen_after_bind(); });
  11061. auto se = detail::scope_exit([&] {
  11062. svr.stop();
  11063. t.join();
  11064. ASSERT_FALSE(svr.is_running());
  11065. });
  11066. svr.wait_until_ready();
  11067. Client cli(HOST, port);
  11068. Headers headers = {{"Accept-Encoding", "gzip"}};
  11069. auto res = cli.Get("/pre-gzipped", headers);
  11070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11071. EXPECT_EQ(StatusCode::OK_200, res->status);
  11072. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11073. EXPECT_EQ("Hello World!", res->body);
  11074. }
  11075. // A chunked provider settles its coding where the headers are written and
  11076. // reuses it at write time. Both ends of that have to hold: a handler's own
  11077. // Content-Encoding suppresses the coding, and a response without one is still
  11078. // compressed as it always was.
  11079. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  11080. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11081. const std::string plain = "Hello World! Hello World! Hello World!";
  11082. Server svr;
  11083. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11084. res.set_header("Content-Encoding", "gzip");
  11085. res.set_chunked_content_provider(
  11086. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  11087. sink.write(gzipped.data(), gzipped.size());
  11088. sink.done();
  11089. return true;
  11090. });
  11091. });
  11092. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  11093. res.set_chunked_content_provider(
  11094. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  11095. sink.write(plain.data(), plain.size());
  11096. sink.done();
  11097. return true;
  11098. });
  11099. });
  11100. auto port = svr.bind_to_any_port(HOST);
  11101. thread t = thread([&]() { svr.listen_after_bind(); });
  11102. auto se = detail::scope_exit([&] {
  11103. svr.stop();
  11104. t.join();
  11105. ASSERT_FALSE(svr.is_running());
  11106. });
  11107. svr.wait_until_ready();
  11108. Client cli(HOST, port);
  11109. Headers headers = {{"Accept-Encoding", "gzip"}};
  11110. {
  11111. auto res = cli.Get("/pre-gzipped", headers);
  11112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11113. EXPECT_EQ(StatusCode::OK_200, res->status);
  11114. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11115. EXPECT_EQ("Hello World!", res->body);
  11116. }
  11117. {
  11118. auto res = cli.Get("/negotiated", headers);
  11119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11120. EXPECT_EQ(StatusCode::OK_200, res->status);
  11121. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  11122. EXPECT_EQ(plain, res->body);
  11123. }
  11124. }
  11125. #endif
  11126. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  11127. // the same message as the comma-joined one, so both have to be read the same
  11128. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  11129. // single gzip coding, and a body the sender says was encoded twice was handed
  11130. // back after one pass, still compressed but presented as decoded.
  11131. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  11132. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11133. Server svr;
  11134. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  11135. res.set_content(body, "image/jpeg");
  11136. res.headers.emplace("Content-Encoding", "gzip");
  11137. res.headers.emplace("Content-Encoding", "gzip");
  11138. });
  11139. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  11140. res.set_content(body, "image/jpeg");
  11141. res.set_header("Content-Encoding", "gzip, gzip");
  11142. });
  11143. auto port = svr.bind_to_any_port(HOST);
  11144. thread t = thread([&]() { svr.listen_after_bind(); });
  11145. auto se = detail::scope_exit([&] {
  11146. svr.stop();
  11147. t.join();
  11148. ASSERT_FALSE(svr.is_running());
  11149. });
  11150. svr.wait_until_ready();
  11151. Client cli(HOST, port);
  11152. // Two codings is not something cpp-httplib decodes, so both representations
  11153. // take the pass-through path rather than one of them being gunzipped once.
  11154. for (const char *path : {"/split", "/joined"}) {
  11155. auto res = cli.Get(path);
  11156. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11157. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11158. EXPECT_EQ(body, res->body) << path;
  11159. }
  11160. }
  11161. // Regression test for DoS vulnerability: a malicious server sending a response
  11162. // without Content-Length header must not cause unbounded memory consumption on
  11163. // the client side. The client should stop reading after a reasonable limit,
  11164. // similar to the server-side set_payload_max_length protection.
  11165. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  11166. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11167. #ifndef _WIN32
  11168. signal(SIGPIPE, SIG_IGN);
  11169. #endif
  11170. auto server_thread = std::thread([] {
  11171. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  11172. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11173. default_socket_options(srv);
  11174. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11175. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11176. sockaddr_in addr{};
  11177. addr.sin_family = AF_INET;
  11178. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11179. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11180. int opt = 1;
  11181. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11182. #ifdef _WIN32
  11183. reinterpret_cast<const char *>(&opt),
  11184. #else
  11185. &opt,
  11186. #endif
  11187. sizeof(opt));
  11188. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11189. ::listen(srv, 1);
  11190. sockaddr_in cli_addr{};
  11191. socklen_t cli_len = sizeof(cli_addr);
  11192. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11193. if (cli != INVALID_SOCKET) {
  11194. char buf[4096];
  11195. ::recv(cli, buf, sizeof(buf), 0);
  11196. // Malicious response: no Content-Length, no chunked encoding
  11197. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11198. "Connection: close\r\n"
  11199. "\r\n";
  11200. ::send(cli,
  11201. #ifdef _WIN32
  11202. static_cast<const char *>(response_header.c_str()),
  11203. static_cast<int>(response_header.size()),
  11204. #else
  11205. response_header.c_str(), response_header.size(),
  11206. #endif
  11207. 0);
  11208. // Send 10MB of data
  11209. std::string chunk(64 * 1024, 'A');
  11210. size_t total_sent = 0;
  11211. while (total_sent < MALICIOUS_DATA_SIZE) {
  11212. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  11213. auto sent = ::send(cli,
  11214. #ifdef _WIN32
  11215. static_cast<const char *>(chunk.c_str()),
  11216. static_cast<int>(to_send),
  11217. #else
  11218. chunk.c_str(), to_send,
  11219. #endif
  11220. 0);
  11221. if (sent <= 0) break;
  11222. total_sent += static_cast<size_t>(sent);
  11223. }
  11224. detail::close_socket(cli);
  11225. }
  11226. detail::close_socket(srv);
  11227. });
  11228. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11229. size_t total_read = 0;
  11230. {
  11231. Client cli("127.0.0.1", PORT + 2);
  11232. cli.set_read_timeout(5, 0);
  11233. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11234. auto stream = cli.open_stream("GET", "/malicious");
  11235. ASSERT_TRUE(stream.is_valid());
  11236. char buffer[64 * 1024];
  11237. ssize_t n;
  11238. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11239. total_read += static_cast<size_t>(n);
  11240. }
  11241. } // StreamHandle and Client destroyed here, closing the socket
  11242. server_thread.join();
  11243. // With set_payload_max_length, the client must stop reading before consuming
  11244. // all 10MB. The read loop should be cut off at or near the configured limit.
  11245. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  11246. << "Client read " << total_read << " bytes, exceeding the configured "
  11247. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  11248. }
  11249. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  11250. // the entire response body without truncation.
  11251. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  11252. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  11253. #ifndef _WIN32
  11254. signal(SIGPIPE, SIG_IGN);
  11255. #endif
  11256. auto server_thread = std::thread([] {
  11257. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11258. default_socket_options(srv);
  11259. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11260. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11261. sockaddr_in addr{};
  11262. addr.sin_family = AF_INET;
  11263. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11264. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11265. int opt = 1;
  11266. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11267. #ifdef _WIN32
  11268. reinterpret_cast<const char *>(&opt),
  11269. #else
  11270. &opt,
  11271. #endif
  11272. sizeof(opt));
  11273. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11274. ::listen(srv, 1);
  11275. sockaddr_in cli_addr{};
  11276. socklen_t cli_len = sizeof(cli_addr);
  11277. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11278. if (cli != INVALID_SOCKET) {
  11279. char buf[4096];
  11280. ::recv(cli, buf, sizeof(buf), 0);
  11281. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11282. "Connection: close\r\n"
  11283. "\r\n";
  11284. ::send(cli,
  11285. #ifdef _WIN32
  11286. static_cast<const char *>(response_header.c_str()),
  11287. static_cast<int>(response_header.size()),
  11288. #else
  11289. response_header.c_str(), response_header.size(),
  11290. #endif
  11291. 0);
  11292. std::string chunk(64 * 1024, 'A');
  11293. size_t total_sent = 0;
  11294. while (total_sent < DATA_SIZE) {
  11295. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11296. auto sent = ::send(cli,
  11297. #ifdef _WIN32
  11298. static_cast<const char *>(chunk.c_str()),
  11299. static_cast<int>(to_send),
  11300. #else
  11301. chunk.c_str(), to_send,
  11302. #endif
  11303. 0);
  11304. if (sent <= 0) break;
  11305. total_sent += static_cast<size_t>(sent);
  11306. }
  11307. #ifdef _WIN32
  11308. ::shutdown(cli, SD_SEND);
  11309. #else
  11310. ::shutdown(cli, SHUT_WR);
  11311. #endif
  11312. // Drain until the client closes its end, ensuring all data is delivered
  11313. char drain[1024];
  11314. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11315. detail::close_socket(cli);
  11316. }
  11317. detail::close_socket(srv);
  11318. });
  11319. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11320. size_t total_read = 0;
  11321. {
  11322. Client cli("127.0.0.1", PORT + 2);
  11323. cli.set_read_timeout(5, 0);
  11324. cli.set_payload_max_length(0); // 0 means no limit
  11325. auto stream = cli.open_stream("GET", "/data");
  11326. ASSERT_TRUE(stream.is_valid());
  11327. char buffer[64 * 1024];
  11328. ssize_t n;
  11329. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11330. total_read += static_cast<size_t>(n);
  11331. }
  11332. }
  11333. server_thread.join();
  11334. EXPECT_EQ(total_read, DATA_SIZE)
  11335. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  11336. << " bytes without truncation, but only read " << total_read << " bytes.";
  11337. }
  11338. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  11339. // enormous Content-Length must not cause the client to pre-allocate a huge
  11340. // response body buffer. The reservation is capped at payload_max_length_, and
  11341. // the read itself fails when the body exceeds the limit.
  11342. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  11343. #ifndef _WIN32
  11344. signal(SIGPIPE, SIG_IGN);
  11345. #endif
  11346. auto server_thread = std::thread([] {
  11347. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11348. default_socket_options(srv);
  11349. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11350. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11351. sockaddr_in addr{};
  11352. addr.sin_family = AF_INET;
  11353. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11354. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11355. int opt = 1;
  11356. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11357. #ifdef _WIN32
  11358. reinterpret_cast<const char *>(&opt),
  11359. #else
  11360. &opt,
  11361. #endif
  11362. sizeof(opt));
  11363. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11364. ::listen(srv, 1);
  11365. sockaddr_in cli_addr{};
  11366. socklen_t cli_len = sizeof(cli_addr);
  11367. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11368. if (cli != INVALID_SOCKET) {
  11369. char buf[4096];
  11370. ::recv(cli, buf, sizeof(buf), 0);
  11371. // Malicious response: claim a 20GB body but send only a tiny payload.
  11372. std::string response = "HTTP/1.1 200 OK\r\n"
  11373. "Content-Length: 20000000000\r\n"
  11374. "\r\n"
  11375. "abc";
  11376. ::send(cli,
  11377. #ifdef _WIN32
  11378. static_cast<const char *>(response.c_str()),
  11379. static_cast<int>(response.size()),
  11380. #else
  11381. response.c_str(), response.size(),
  11382. #endif
  11383. 0);
  11384. detail::close_socket(cli);
  11385. }
  11386. detail::close_socket(srv);
  11387. });
  11388. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11389. {
  11390. Client cli("127.0.0.1", PORT + 2);
  11391. cli.set_read_timeout(5, 0);
  11392. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  11393. // result in a 20GB pre-allocation. The Get() call is expected to fail
  11394. // (server claims more bytes than payload_max_length permits), but it must
  11395. // not exhaust memory before getting there.
  11396. auto res = cli.Get("/malicious");
  11397. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  11398. }
  11399. server_thread.join();
  11400. }
  11401. // Verify that content_receiver bypasses the default payload_max_length,
  11402. // allowing streaming downloads larger than 100MB without requiring an explicit
  11403. // set_payload_max_length call.
  11404. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  11405. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11406. #ifndef _WIN32
  11407. signal(SIGPIPE, SIG_IGN);
  11408. #endif
  11409. auto server_thread = std::thread([] {
  11410. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11411. default_socket_options(srv);
  11412. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11413. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11414. sockaddr_in addr{};
  11415. addr.sin_family = AF_INET;
  11416. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11417. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11418. int opt = 1;
  11419. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11420. #ifdef _WIN32
  11421. reinterpret_cast<const char *>(&opt),
  11422. #else
  11423. &opt,
  11424. #endif
  11425. sizeof(opt));
  11426. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11427. ::listen(srv, 1);
  11428. sockaddr_in cli_addr{};
  11429. socklen_t cli_len = sizeof(cli_addr);
  11430. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11431. if (cli != INVALID_SOCKET) {
  11432. char buf[4096];
  11433. ::recv(cli, buf, sizeof(buf), 0);
  11434. // Response with Content-Length larger than default 100MB limit
  11435. auto content_length = std::to_string(DATA_SIZE);
  11436. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11437. "Content-Length: " +
  11438. content_length +
  11439. "\r\n"
  11440. "Connection: close\r\n"
  11441. "\r\n";
  11442. ::send(cli,
  11443. #ifdef _WIN32
  11444. static_cast<const char *>(response_header.c_str()),
  11445. static_cast<int>(response_header.size()),
  11446. #else
  11447. response_header.c_str(), response_header.size(),
  11448. #endif
  11449. 0);
  11450. std::string chunk(64 * 1024, 'A');
  11451. size_t total_sent = 0;
  11452. while (total_sent < DATA_SIZE) {
  11453. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11454. auto sent = ::send(cli,
  11455. #ifdef _WIN32
  11456. static_cast<const char *>(chunk.c_str()),
  11457. static_cast<int>(to_send),
  11458. #else
  11459. chunk.c_str(), to_send,
  11460. #endif
  11461. 0);
  11462. if (sent <= 0) break;
  11463. total_sent += static_cast<size_t>(sent);
  11464. }
  11465. detail::close_socket(cli);
  11466. }
  11467. detail::close_socket(srv);
  11468. });
  11469. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11470. size_t total_received = 0;
  11471. {
  11472. Client cli("127.0.0.1", PORT + 2);
  11473. cli.set_read_timeout(10, 0);
  11474. // Do NOT call set_payload_max_length — use the default 100MB limit
  11475. auto res =
  11476. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11477. total_received += data_length;
  11478. return true;
  11479. });
  11480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11481. EXPECT_EQ(StatusCode::OK_200, res->status);
  11482. }
  11483. server_thread.join();
  11484. EXPECT_EQ(total_received, DATA_SIZE)
  11485. << "With content_receiver, the client should read all " << DATA_SIZE
  11486. << " bytes despite the default 100MB payload_max_length, but only read "
  11487. << total_received << " bytes.";
  11488. }
  11489. // Verify that an explicit set_payload_max_length smaller than the response is
  11490. // enforced even when a content_receiver is used.
  11491. TEST(ClientVulnerabilityTest,
  11492. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  11493. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11494. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  11495. #ifndef _WIN32
  11496. signal(SIGPIPE, SIG_IGN);
  11497. #endif
  11498. auto server_thread = std::thread([] {
  11499. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11500. default_socket_options(srv);
  11501. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11502. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11503. sockaddr_in addr{};
  11504. addr.sin_family = AF_INET;
  11505. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11506. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11507. int opt = 1;
  11508. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11509. #ifdef _WIN32
  11510. reinterpret_cast<const char *>(&opt),
  11511. #else
  11512. &opt,
  11513. #endif
  11514. sizeof(opt));
  11515. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11516. ::listen(srv, 1);
  11517. sockaddr_in cli_addr{};
  11518. socklen_t cli_len = sizeof(cli_addr);
  11519. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11520. if (cli != INVALID_SOCKET) {
  11521. char buf[4096];
  11522. ::recv(cli, buf, sizeof(buf), 0);
  11523. auto content_length = std::to_string(DATA_SIZE);
  11524. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11525. "Content-Length: " +
  11526. content_length +
  11527. "\r\n"
  11528. "Connection: close\r\n"
  11529. "\r\n";
  11530. ::send(cli,
  11531. #ifdef _WIN32
  11532. static_cast<const char *>(response_header.c_str()),
  11533. static_cast<int>(response_header.size()),
  11534. #else
  11535. response_header.c_str(), response_header.size(),
  11536. #endif
  11537. 0);
  11538. std::string chunk(64 * 1024, 'A');
  11539. size_t total_sent = 0;
  11540. while (total_sent < DATA_SIZE) {
  11541. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11542. auto sent = ::send(cli,
  11543. #ifdef _WIN32
  11544. static_cast<const char *>(chunk.c_str()),
  11545. static_cast<int>(to_send),
  11546. #else
  11547. chunk.c_str(), to_send,
  11548. #endif
  11549. 0);
  11550. if (sent <= 0) break;
  11551. total_sent += static_cast<size_t>(sent);
  11552. }
  11553. detail::close_socket(cli);
  11554. }
  11555. detail::close_socket(srv);
  11556. });
  11557. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11558. size_t total_received = 0;
  11559. {
  11560. Client cli("127.0.0.1", PORT + 2);
  11561. cli.set_read_timeout(10, 0);
  11562. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  11563. auto res =
  11564. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11565. total_received += data_length;
  11566. return true;
  11567. });
  11568. // Should fail because 200MB exceeds the explicit 150MB limit
  11569. EXPECT_FALSE(res);
  11570. }
  11571. server_thread.join();
  11572. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  11573. << "Client with content_receiver should respect the explicit "
  11574. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  11575. << total_received << " bytes.";
  11576. }
  11577. // Verify that an explicit set_payload_max_length larger than the response
  11578. // allows the content_receiver to read all data successfully.
  11579. TEST(ClientVulnerabilityTest,
  11580. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  11581. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11582. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  11583. #ifndef _WIN32
  11584. signal(SIGPIPE, SIG_IGN);
  11585. #endif
  11586. auto server_thread = std::thread([] {
  11587. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11588. default_socket_options(srv);
  11589. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11590. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11591. sockaddr_in addr{};
  11592. addr.sin_family = AF_INET;
  11593. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11594. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11595. int opt = 1;
  11596. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11597. #ifdef _WIN32
  11598. reinterpret_cast<const char *>(&opt),
  11599. #else
  11600. &opt,
  11601. #endif
  11602. sizeof(opt));
  11603. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11604. ::listen(srv, 1);
  11605. sockaddr_in cli_addr{};
  11606. socklen_t cli_len = sizeof(cli_addr);
  11607. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11608. if (cli != INVALID_SOCKET) {
  11609. char buf[4096];
  11610. ::recv(cli, buf, sizeof(buf), 0);
  11611. auto content_length = std::to_string(DATA_SIZE);
  11612. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11613. "Content-Length: " +
  11614. content_length +
  11615. "\r\n"
  11616. "Connection: close\r\n"
  11617. "\r\n";
  11618. ::send(cli,
  11619. #ifdef _WIN32
  11620. static_cast<const char *>(response_header.c_str()),
  11621. static_cast<int>(response_header.size()),
  11622. #else
  11623. response_header.c_str(), response_header.size(),
  11624. #endif
  11625. 0);
  11626. std::string chunk(64 * 1024, 'A');
  11627. size_t total_sent = 0;
  11628. while (total_sent < DATA_SIZE) {
  11629. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11630. auto sent = ::send(cli,
  11631. #ifdef _WIN32
  11632. static_cast<const char *>(chunk.c_str()),
  11633. static_cast<int>(to_send),
  11634. #else
  11635. chunk.c_str(), to_send,
  11636. #endif
  11637. 0);
  11638. if (sent <= 0) break;
  11639. total_sent += static_cast<size_t>(sent);
  11640. }
  11641. #ifdef _WIN32
  11642. ::shutdown(cli, SD_SEND);
  11643. #else
  11644. ::shutdown(cli, SHUT_WR);
  11645. #endif
  11646. char drain[1024];
  11647. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11648. detail::close_socket(cli);
  11649. }
  11650. detail::close_socket(srv);
  11651. });
  11652. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11653. size_t total_received = 0;
  11654. {
  11655. Client cli("127.0.0.1", PORT + 2);
  11656. cli.set_read_timeout(10, 0);
  11657. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  11658. auto res =
  11659. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11660. total_received += data_length;
  11661. return true;
  11662. });
  11663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11664. EXPECT_EQ(StatusCode::OK_200, res->status);
  11665. }
  11666. server_thread.join();
  11667. EXPECT_EQ(total_received, DATA_SIZE)
  11668. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  11669. << " bytes (larger than " << DATA_SIZE
  11670. << " bytes response), content_receiver should read all data, but only "
  11671. "read "
  11672. << total_received << " bytes.";
  11673. }
  11674. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  11675. // Regression test for "zip bomb" attack on the client side: a malicious server
  11676. // sends a small gzip-compressed response that decompresses to a huge payload.
  11677. // The client must enforce payload_max_length on the decompressed size.
  11678. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  11679. constexpr size_t DECOMPRESSED_SIZE =
  11680. 10 * 1024 * 1024; // 10MB after decompression
  11681. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11682. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  11683. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  11684. std::string compressed;
  11685. {
  11686. httplib::detail::gzip_compressor compressor;
  11687. bool ok =
  11688. compressor.compress(uncompressed.data(), uncompressed.size(),
  11689. /*last=*/true, [&](const char *buf, size_t len) {
  11690. compressed.append(buf, len);
  11691. return true;
  11692. });
  11693. ASSERT_TRUE(ok);
  11694. }
  11695. // Sanity: compressed data should be much smaller than the decompressed size
  11696. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  11697. #ifndef _WIN32
  11698. signal(SIGPIPE, SIG_IGN);
  11699. #endif
  11700. // Set up the listening socket in the main thread so the server is guaranteed
  11701. // to be ready before the client connects (eliminates race condition).
  11702. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11703. default_socket_options(srv);
  11704. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11705. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11706. sockaddr_in addr{};
  11707. addr.sin_family = AF_INET;
  11708. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  11709. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11710. int opt = 1;
  11711. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11712. #ifdef _WIN32
  11713. reinterpret_cast<const char *>(&opt),
  11714. #else
  11715. &opt,
  11716. #endif
  11717. sizeof(opt));
  11718. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11719. ASSERT_EQ(0, ::listen(srv, 1));
  11720. auto server_thread = std::thread([&compressed, srv] {
  11721. sockaddr_in cli_addr{};
  11722. socklen_t cli_len = sizeof(cli_addr);
  11723. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11724. if (cli != INVALID_SOCKET) {
  11725. // Read the full HTTP request (until \r\n\r\n)
  11726. char buf[4096];
  11727. size_t total = 0;
  11728. while (total < sizeof(buf)) {
  11729. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  11730. if (n <= 0) break;
  11731. total += static_cast<size_t>(n);
  11732. // Check for end of headers
  11733. if (total >= 4) {
  11734. std::string req(buf, total);
  11735. if (req.find("\r\n\r\n") != std::string::npos) break;
  11736. }
  11737. }
  11738. // Malicious response: gzip-compressed body, no Content-Length
  11739. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11740. "Content-Encoding: gzip\r\n"
  11741. "Connection: close\r\n"
  11742. "\r\n";
  11743. ::send(cli,
  11744. #ifdef _WIN32
  11745. static_cast<const char *>(response_header.c_str()),
  11746. static_cast<int>(response_header.size()),
  11747. #else
  11748. response_header.c_str(), response_header.size(),
  11749. #endif
  11750. 0);
  11751. // Send the compressed payload (small on the wire, huge when decompressed)
  11752. size_t total_sent = 0;
  11753. while (total_sent < compressed.size()) {
  11754. auto to_send = std::min(compressed.size() - total_sent,
  11755. static_cast<size_t>(64 * 1024));
  11756. auto sent =
  11757. ::send(cli,
  11758. #ifdef _WIN32
  11759. static_cast<const char *>(compressed.c_str() + total_sent),
  11760. static_cast<int>(to_send),
  11761. #else
  11762. compressed.c_str() + total_sent, to_send,
  11763. #endif
  11764. 0);
  11765. if (sent <= 0) break;
  11766. total_sent += static_cast<size_t>(sent);
  11767. }
  11768. detail::close_socket(cli);
  11769. }
  11770. });
  11771. auto se = detail::scope_exit([&] {
  11772. detail::close_socket(srv);
  11773. server_thread.join();
  11774. });
  11775. size_t total_decompressed = 0;
  11776. {
  11777. Client cli("127.0.0.1", PORT + 3);
  11778. cli.set_read_timeout(5, 0);
  11779. cli.set_decompress(true);
  11780. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11781. auto stream = cli.open_stream("GET", "/zipbomb");
  11782. ASSERT_TRUE(stream.is_valid());
  11783. char buffer[64 * 1024];
  11784. ssize_t n;
  11785. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11786. total_decompressed += static_cast<size_t>(n);
  11787. }
  11788. }
  11789. // The decompressed size must be capped by payload_max_length. Without
  11790. // protection, the client would decompress the full 10MB from a tiny
  11791. // compressed payload, enabling a zip bomb DoS attack.
  11792. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  11793. << "Client decompressed " << total_decompressed
  11794. << " bytes from a gzip response. The decompressed size should be "
  11795. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  11796. }
  11797. #endif
  11798. TEST(HostAndPortPropertiesTest, NoSSL) {
  11799. httplib::Client cli("www.google.com", 1234);
  11800. ASSERT_EQ("www.google.com", cli.host());
  11801. ASSERT_EQ(1234, cli.port());
  11802. }
  11803. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  11804. httplib::Client cli("www.google.com:1234");
  11805. ASSERT_EQ("www.google.com", cli.host());
  11806. ASSERT_EQ(1234, cli.port());
  11807. }
  11808. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  11809. // Port number that overflows int — should not crash, client becomes invalid
  11810. httplib::Client cli("http://www.google.com:99999999999999999999");
  11811. ASSERT_FALSE(cli.is_valid());
  11812. }
  11813. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  11814. // Port 99999 exceeds valid range (1-65535) — should not crash
  11815. httplib::Client cli("http://www.google.com:99999");
  11816. ASSERT_FALSE(cli.is_valid());
  11817. }
  11818. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  11819. httplib::Client cli("http://www.google.com:80abc");
  11820. ASSERT_FALSE(cli.is_valid());
  11821. }
  11822. #ifdef CPPHTTPLIB_SSL_ENABLED
  11823. TEST(HostAndPortPropertiesTest, SSL) {
  11824. httplib::SSLClient cli("www.google.com");
  11825. ASSERT_EQ("www.google.com", cli.host());
  11826. ASSERT_EQ(443, cli.port());
  11827. }
  11828. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  11829. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  11830. std::string cert;
  11831. read_file(CA_CERT_FILE, cert);
  11832. httplib::SSLClient httplib_client("www.google.com");
  11833. // Load CA store first time
  11834. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11835. // Load CA store second time (update)
  11836. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11837. // Verify client is still valid and can make connections
  11838. httplib_client.enable_server_certificate_verification(true);
  11839. auto res = httplib_client.Get("/");
  11840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11841. // Google may return 200 or 301 depending on various factors
  11842. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  11843. res->status == StatusCode::MovedPermanently_301);
  11844. }
  11845. TEST(SSLClientTest, ServerNameIndication_Online) {
  11846. auto host = "httpbingo.org";
  11847. auto path = std::string{"/get"};
  11848. SSLClient cli(host, 443);
  11849. auto res = cli.Get(path);
  11850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11851. ASSERT_EQ(StatusCode::OK_200, res->status);
  11852. }
  11853. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  11854. // Use a site that will cause SSL verification failure due to self-signed cert
  11855. SSLClient cli("self-signed.badssl.com", 443);
  11856. cli.enable_server_certificate_verification(true);
  11857. auto res = cli.Get("/");
  11858. ASSERT_TRUE(!res);
  11859. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11860. // Verify backend error is captured for SSLServerVerification
  11861. // This occurs when certificate verification fails
  11862. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  11863. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  11864. EXPECT_NE(0UL, res.ssl_backend_error());
  11865. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11866. // For OpenSSL, ssl_error is 0 for verification errors
  11867. EXPECT_EQ(0, res.ssl_error());
  11868. #if !defined(_WIN32) || \
  11869. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11870. // On non-Windows or when Windows Schannel is disabled, the error comes
  11871. // from OpenSSL's verification
  11872. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  11873. res.ssl_backend_error());
  11874. #endif
  11875. #endif
  11876. }
  11877. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  11878. // Use a site where hostname doesn't match the certificate
  11879. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  11880. SSLClient cli("wrong.host.badssl.com", 443);
  11881. cli.enable_server_certificate_verification(true);
  11882. cli.enable_server_hostname_verification(true);
  11883. auto res = cli.Get("/");
  11884. ASSERT_TRUE(!res);
  11885. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  11886. // Verify backend error is captured for hostname verification failure
  11887. EXPECT_NE(0UL, res.ssl_backend_error());
  11888. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11889. // For OpenSSL, ssl_error is 0 for verification errors
  11890. EXPECT_EQ(0, res.ssl_error());
  11891. #if !defined(_WIN32) || \
  11892. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11893. // On non-Windows or when Windows Schannel is disabled, the error comes
  11894. // from OpenSSL's hostname verification
  11895. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  11896. res.ssl_backend_error());
  11897. #endif
  11898. #endif
  11899. }
  11900. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  11901. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11902. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  11903. SSLClient cli("www.google.com", 443);
  11904. cli.enable_server_certificate_verification(true);
  11905. auto res = cli.Get("/");
  11906. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11907. }
  11908. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  11909. SSLClient cli("www.google.com", 443);
  11910. cli.enable_server_certificate_verification(true);
  11911. cli.enable_windows_certificate_verification(false);
  11912. auto res = cli.Get("/");
  11913. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11914. }
  11915. // The server sends an intermediate cross-signed by a root Windows trusts,
  11916. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  11917. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  11918. SSLClient cli("accounts.spotify.com", 443);
  11919. auto res = cli.Get("/");
  11920. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  11921. << " ssl_backend_error=" << res.ssl_backend_error();
  11922. }
  11923. // Windows, not the backend, decides on the chain: the error carries a
  11924. // CryptoAPI trust status, which no backend error for a self-signed
  11925. // certificate has.
  11926. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  11927. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11928. ASSERT_TRUE(svr.is_valid());
  11929. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11930. auto se = detail::scope_exit([&] {
  11931. svr.stop();
  11932. t.join();
  11933. ASSERT_FALSE(svr.is_running());
  11934. });
  11935. svr.wait_until_ready();
  11936. SSLClient cli("127.0.0.1", PORT);
  11937. cli.set_connection_timeout(30);
  11938. auto res = cli.Get("/");
  11939. ASSERT_FALSE(res);
  11940. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11941. EXPECT_NE(0u, res.ssl_backend_error() & CERT_TRUST_IS_UNTRUSTED_ROOT)
  11942. << "ssl_backend_error=" << res.ssl_backend_error();
  11943. }
  11944. #endif
  11945. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  11946. Client cli("https://google.com");
  11947. auto res = cli.Get("/");
  11948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11949. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11950. }
  11951. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  11952. SSLClient cli("google.com");
  11953. cli.set_ca_cert_path(CA_CERT_FILE);
  11954. auto res = cli.Get("/");
  11955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11956. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11957. }
  11958. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  11959. SSLClient cli("google.com");
  11960. cli.enable_server_certificate_verification(true);
  11961. cli.set_ca_cert_path("hello");
  11962. auto res = cli.Get("/");
  11963. ASSERT_TRUE(!res);
  11964. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  11965. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  11966. // should be set
  11967. EXPECT_EQ(0, res.ssl_error());
  11968. // Verify backend error is captured for SSLLoadingCerts
  11969. // This error occurs when loading CA certificates fails
  11970. EXPECT_NE(0UL, res.ssl_backend_error());
  11971. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11972. // OpenSSL specific error codes:
  11973. // > openssl errstr 0x80000002
  11974. // error:80000002:system library::No such file or directory
  11975. // > openssl errstr 0xA000126
  11976. // error:0A000126:SSL routines::unexpected eof while reading
  11977. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  11978. res.ssl_backend_error() == 0xA000126);
  11979. #endif
  11980. }
  11981. TEST(SSLClientTest, ServerCertificateVerification4) {
  11982. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11983. ASSERT_TRUE(svr.is_valid());
  11984. svr.Get("/test", [&](const Request &, Response &res) {
  11985. res.set_content("test", "text/plain");
  11986. svr.stop();
  11987. ASSERT_TRUE(true);
  11988. });
  11989. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11990. auto se = detail::scope_exit([&] {
  11991. t.join();
  11992. ASSERT_FALSE(svr.is_running());
  11993. });
  11994. svr.wait_until_ready();
  11995. SSLClient cli("127.0.0.1", PORT);
  11996. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  11997. cli.enable_server_certificate_verification(true);
  11998. cli.set_connection_timeout(30);
  11999. auto res = cli.Get("/test");
  12000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12001. ASSERT_EQ(StatusCode::OK_200, res->status);
  12002. }
  12003. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  12004. std::string cert;
  12005. read_file(CA_CERT_FILE, cert);
  12006. SSLClient cli("google.com");
  12007. cli.load_ca_cert_store(cert.data(), cert.size());
  12008. const auto res = cli.Get("/");
  12009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12010. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12011. }
  12012. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  12013. // clang-format off
  12014. static constexpr char cert[] =
  12015. "GlobalSign Root CA\n"
  12016. "==================\n"
  12017. "-----BEGIN CERTIFICATE-----\n"
  12018. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  12019. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  12020. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  12021. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  12022. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  12023. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  12024. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  12025. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  12026. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  12027. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  12028. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  12029. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  12030. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  12031. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  12032. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  12033. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  12034. "-----END CERTIFICATE-----\n";
  12035. // clang-format on
  12036. SSLClient cli("google.com");
  12037. cli.load_ca_cert_store(cert, sizeof(cert));
  12038. const auto res = cli.Get("/");
  12039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12040. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12041. }
  12042. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  12043. SSLClient cli("www.youtube.com");
  12044. cli.set_ca_cert_path(CA_CERT_FILE);
  12045. cli.enable_server_certificate_verification(true);
  12046. cli.set_follow_location(true);
  12047. auto res = cli.Get("/");
  12048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12049. ASSERT_EQ(StatusCode::OK_200, res->status);
  12050. }
  12051. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  12052. SSLClient cli("wWw.YouTube.Com");
  12053. cli.set_ca_cert_path(CA_CERT_FILE);
  12054. cli.enable_server_certificate_verification(true);
  12055. cli.enable_server_hostname_verification(true);
  12056. cli.set_follow_location(true);
  12057. auto res = cli.Get("/");
  12058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12059. ASSERT_EQ(StatusCode::OK_200, res->status);
  12060. }
  12061. TEST(SSLClientTest, HostNameMatchCase_Online) {
  12062. SSLClient cli("gOoGlE.COm");
  12063. cli.enable_server_certificate_verification(true);
  12064. cli.enable_server_hostname_verification(true);
  12065. cli.set_follow_location(true);
  12066. auto res = cli.Get("/");
  12067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12068. ASSERT_EQ(StatusCode::OK_200, res->status);
  12069. }
  12070. TEST(SSLClientTest, Issue2004_Online) {
  12071. Client client("https://google.com");
  12072. client.set_follow_location(true);
  12073. auto res = client.Get("/");
  12074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12075. ASSERT_EQ(StatusCode::OK_200, res->status);
  12076. auto body = res->body;
  12077. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  12078. }
  12079. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  12080. // Create SSLClient with invalid cert/key to make is_valid() return false
  12081. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  12082. "nonexistent_key.pem");
  12083. // is_valid() should be false due to cert loading failure
  12084. ASSERT_FALSE(cli.is_valid());
  12085. auto res = cli.Get("/");
  12086. ASSERT_FALSE(res);
  12087. EXPECT_EQ(Error::SSLConnection, res.error());
  12088. }
  12089. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  12090. // Test for Issue #2251: SSL error not properly reported when client cert
  12091. // and key paths are swapped or mismatched
  12092. // This simulates the scenario where user accidentally swaps the cert and key
  12093. // files
  12094. // Using client cert file as private key and vice versa (completely wrong)
  12095. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  12096. // Should fail validation due to cert/key mismatch
  12097. ASSERT_FALSE(cli.is_valid());
  12098. // Attempt to make a request should fail with proper error
  12099. auto res = cli.Get("/");
  12100. ASSERT_FALSE(res);
  12101. EXPECT_EQ(Error::SSLConnection, res.error());
  12102. // SSL error should be recorded in the Result object (this is the key fix for
  12103. // Issue #2251)
  12104. auto backend_error = res.ssl_backend_error();
  12105. EXPECT_NE(0u, backend_error);
  12106. }
  12107. // Tests cert/key mismatch detection at the TLS context level
  12108. TEST(TlsApiTest, ClientCertKeyMismatch) {
  12109. // Test that using mismatched cert/key causes connection failure.
  12110. // We verify this at the SSLClient level rather than through internal
  12111. // TLS API functions.
  12112. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  12113. cli.enable_server_certificate_verification(false);
  12114. cli.set_connection_timeout(2);
  12115. // The mismatch should cause a connection or handshake error
  12116. auto res = cli.Get("/test");
  12117. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  12118. // Either way, the request should fail
  12119. EXPECT_FALSE(res);
  12120. }
  12121. #endif
  12122. #if 0
  12123. TEST(SSLClientTest, SetInterfaceWithINET6) {
  12124. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  12125. ASSERT_TRUE(cli != nullptr);
  12126. cli->set_address_family(AF_INET6);
  12127. cli->set_interface("en0");
  12128. auto res = cli->Get("/get");
  12129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12130. ASSERT_EQ(StatusCode::OK_200, res->status);
  12131. }
  12132. #endif
  12133. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  12134. #ifdef CPPHTTPLIB_SSL_ENABLED
  12135. void ClientCertPresent(
  12136. const std::string &client_cert_file,
  12137. const std::string &client_private_key_file,
  12138. const std::string &client_encrypted_private_key_pass = std::string()) {
  12139. using namespace httplib::tls;
  12140. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12141. CLIENT_CA_CERT_DIR);
  12142. ASSERT_TRUE(svr.is_valid());
  12143. svr.Get("/test", [&](const Request &req, Response &res) {
  12144. res.set_content("test", "text/plain");
  12145. auto cert = req.peer_cert();
  12146. ASSERT_TRUE(static_cast<bool>(cert));
  12147. std::string common_name = cert.subject_cn();
  12148. EXPECT_EQ("Common Name", common_name);
  12149. });
  12150. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12151. auto se = detail::scope_exit([&] {
  12152. svr.stop();
  12153. t.join();
  12154. ASSERT_FALSE(svr.is_running());
  12155. });
  12156. svr.wait_until_ready();
  12157. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  12158. client_encrypted_private_key_pass);
  12159. cli.enable_server_certificate_verification(false);
  12160. cli.set_connection_timeout(30);
  12161. auto res = cli.Get("/test");
  12162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12163. ASSERT_EQ(StatusCode::OK_200, res->status);
  12164. }
  12165. TEST(SSLClientServerTest, ClientCertPresent) {
  12166. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12167. }
  12168. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  12169. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12170. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12171. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12172. }
  12173. // PEM memory-based constructor tests (works with all TLS backends)
  12174. void PemMemoryClientCertPresent(
  12175. const std::string &client_cert_file,
  12176. const std::string &client_private_key_file,
  12177. const std::string &client_encrypted_private_key_pass = std::string()) {
  12178. // Read PEM files into memory
  12179. std::string server_cert_pem, server_key_pem;
  12180. std::string client_ca_pem;
  12181. std::string client_cert_pem, client_key_pem;
  12182. read_file(SERVER_CERT_FILE, server_cert_pem);
  12183. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12184. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12185. read_file(client_cert_file, client_cert_pem);
  12186. read_file(client_private_key_file, client_key_pem);
  12187. // Create server with PEM memory
  12188. SSLServer::PemMemory server_pem = {
  12189. server_cert_pem.c_str(),
  12190. server_cert_pem.size(),
  12191. server_key_pem.c_str(),
  12192. server_key_pem.size(),
  12193. client_ca_pem.c_str(),
  12194. client_ca_pem.size(),
  12195. nullptr // no password for server key
  12196. };
  12197. SSLServer svr(server_pem);
  12198. ASSERT_TRUE(svr.is_valid());
  12199. svr.Get("/test", [&](const Request &, Response &res) {
  12200. res.set_content("test", "text/plain");
  12201. });
  12202. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12203. auto se = detail::scope_exit([&] {
  12204. svr.stop();
  12205. t.join();
  12206. ASSERT_FALSE(svr.is_running());
  12207. });
  12208. svr.wait_until_ready();
  12209. // Create client with PEM memory
  12210. const char *password = client_encrypted_private_key_pass.empty()
  12211. ? nullptr
  12212. : client_encrypted_private_key_pass.c_str();
  12213. SSLClient::PemMemory client_pem = {
  12214. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  12215. client_key_pem.size(), password};
  12216. SSLClient cli(HOST, PORT, client_pem);
  12217. cli.enable_server_certificate_verification(false);
  12218. cli.set_connection_timeout(30);
  12219. auto res = cli.Get("/test");
  12220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12221. ASSERT_EQ(StatusCode::OK_200, res->status);
  12222. }
  12223. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  12224. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12225. }
  12226. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  12227. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12228. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12229. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12230. }
  12231. TEST(SSLClientServerTest, ClientCertMissing) {
  12232. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12233. CLIENT_CA_CERT_DIR);
  12234. ASSERT_TRUE(svr.is_valid());
  12235. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  12236. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12237. auto se = detail::scope_exit([&] {
  12238. svr.stop();
  12239. t.join();
  12240. ASSERT_FALSE(svr.is_running());
  12241. });
  12242. svr.wait_until_ready();
  12243. SSLClient cli(HOST, PORT);
  12244. cli.set_connection_timeout(30);
  12245. // cert.pem does not match HOST. Skip the hostname check, which runs before
  12246. // the chain check on Windows, so the result does not depend on the order.
  12247. cli.enable_server_hostname_verification(false);
  12248. auto res = cli.Get("/test");
  12249. ASSERT_TRUE(!res);
  12250. // When client cert is missing and server requires it, connection fails
  12251. // Error type depends on backend implementation
  12252. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12253. res.error() == Error::SSLConnection);
  12254. // Verify backend error is captured
  12255. // Note: This test may have different error codes depending on the exact
  12256. // verification failure
  12257. EXPECT_NE(0UL, res.ssl_backend_error());
  12258. }
  12259. TEST(SSLClientServerTest, TrustDirOptional) {
  12260. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12261. ASSERT_TRUE(svr.is_valid());
  12262. svr.Get("/test", [&](const Request &, Response &res) {
  12263. res.set_content("test", "text/plain");
  12264. });
  12265. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12266. auto se = detail::scope_exit([&] {
  12267. svr.stop();
  12268. t.join();
  12269. ASSERT_FALSE(svr.is_running());
  12270. });
  12271. svr.wait_until_ready();
  12272. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12273. cli.enable_server_certificate_verification(false);
  12274. cli.set_connection_timeout(30);
  12275. auto res = cli.Get("/test");
  12276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12277. ASSERT_EQ(StatusCode::OK_200, res->status);
  12278. }
  12279. TEST(SSLClientServerTest, SSLConnectTimeout) {
  12280. class NoListenSSLServer : public SSLServer {
  12281. public:
  12282. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  12283. const char *client_ca_cert_file_path,
  12284. const char *client_ca_cert_dir_path = nullptr)
  12285. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  12286. client_ca_cert_dir_path),
  12287. stop_(false) {}
  12288. std::atomic_bool stop_;
  12289. private:
  12290. bool process_and_close_socket(socket_t /*sock*/) override {
  12291. // Don't create SSL context
  12292. while (!stop_.load()) {
  12293. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  12294. }
  12295. return true;
  12296. }
  12297. };
  12298. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12299. CLIENT_CA_CERT_FILE);
  12300. ASSERT_TRUE(svr.is_valid());
  12301. svr.Get("/test", [&](const Request &, Response &res) {
  12302. res.set_content("test", "text/plain");
  12303. });
  12304. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12305. auto se = detail::scope_exit([&] {
  12306. svr.stop_ = true;
  12307. svr.stop();
  12308. t.join();
  12309. ASSERT_FALSE(svr.is_running());
  12310. });
  12311. svr.wait_until_ready();
  12312. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12313. cli.enable_server_certificate_verification(false);
  12314. cli.set_connection_timeout(1);
  12315. auto res = cli.Get("/test");
  12316. ASSERT_TRUE(!res);
  12317. EXPECT_EQ(Error::SSLConnection, res.error());
  12318. // Timeout results in WantRead error code (maps to backend-specific value)
  12319. EXPECT_NE(0, res.ssl_error());
  12320. }
  12321. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  12322. // Test SSLServer with client certificate verification using the standard
  12323. // constructor (ContextSetupCallback is tested by backend-specific tests)
  12324. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12325. CLIENT_CA_CERT_DIR);
  12326. ASSERT_TRUE(svr.is_valid());
  12327. svr.Get("/test", [&](const Request &req, Response &res) {
  12328. res.set_content("test", "text/plain");
  12329. auto cert = req.peer_cert();
  12330. ASSERT_TRUE(static_cast<bool>(cert));
  12331. auto common_name = cert.subject_cn();
  12332. EXPECT_EQ("Common Name", common_name);
  12333. });
  12334. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12335. auto se = detail::scope_exit([&] {
  12336. svr.stop();
  12337. t.join();
  12338. ASSERT_FALSE(svr.is_running());
  12339. });
  12340. svr.wait_until_ready();
  12341. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12342. cli.enable_server_certificate_verification(false);
  12343. cli.set_connection_timeout(30);
  12344. auto res = cli.Get("/test");
  12345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12346. ASSERT_EQ(StatusCode::OK_200, res->status);
  12347. }
  12348. // Test verify_hostname for both OpenSSL and MbedTLS backends
  12349. // Verifies that wildcard matching and exact matching work consistently
  12350. TEST(SSLClientServerTest, TlsVerifyHostname) {
  12351. using namespace httplib::tls;
  12352. // We need a running server to test against
  12353. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12354. ASSERT_TRUE(svr.is_valid());
  12355. svr.Get("/test", [](const Request &, Response &res) {
  12356. res.set_content("ok", "text/plain");
  12357. });
  12358. thread t([&]() { svr.listen(HOST, PORT); });
  12359. auto se = detail::scope_exit([&] {
  12360. svr.stop();
  12361. t.join();
  12362. });
  12363. svr.wait_until_ready();
  12364. bool verify_callback_called = false;
  12365. bool verify_result_wrong = false;
  12366. SSLClient cli(HOST, PORT);
  12367. cli.enable_server_certificate_verification(true);
  12368. cli.set_ca_cert_path(CA_CERT_FILE);
  12369. cli.set_connection_timeout(5);
  12370. // Note: Test certificate has CN="Common Name", not "localhost"
  12371. bool verify_result_cn = false;
  12372. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12373. verify_callback_called = true;
  12374. if (!ctx.cert) return false;
  12375. // Test 1: "Common Name" should match (our test server cert CN)
  12376. verify_result_cn = ctx.check_hostname("Common Name");
  12377. // Test 2: wrong hostname should not match
  12378. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  12379. return true; // Accept for the purpose of this test
  12380. });
  12381. auto res = cli.Get("/test");
  12382. // The request may succeed or fail depending on cert configuration
  12383. // but the callback should have been called
  12384. ASSERT_TRUE(verify_callback_called)
  12385. << "Verify callback should have been called";
  12386. // CN="Common Name" should match our test certificate
  12387. //
  12388. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  12389. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  12390. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  12391. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  12392. // <openssl/base.h>, which is included transitively when
  12393. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  12394. #if defined(OPENSSL_IS_BORINGSSL)
  12395. EXPECT_FALSE(verify_result_cn)
  12396. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  12397. #else
  12398. EXPECT_TRUE(verify_result_cn)
  12399. << "verify_hostname should match 'Common Name' (certificate CN)";
  12400. #endif
  12401. // Wrong hostname should not match
  12402. EXPECT_FALSE(verify_result_wrong)
  12403. << "verify_hostname should not match 'wronghost.example.com'";
  12404. }
  12405. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  12406. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  12407. // X509_check_ip behavior and must hold for every backend.
  12408. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  12409. using namespace httplib::tls;
  12410. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  12411. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  12412. ASSERT_TRUE(svr.is_valid());
  12413. svr.Get("/test", [](const Request &, Response &res) {
  12414. res.set_content("ok", "text/plain");
  12415. });
  12416. thread t([&]() { svr.listen(HOST, PORT); });
  12417. auto se = detail::scope_exit([&] {
  12418. svr.stop();
  12419. t.join();
  12420. });
  12421. svr.wait_until_ready();
  12422. bool verify_callback_called = false;
  12423. bool ip_matched_via_cn = true;
  12424. SSLClient cli(HOST, PORT);
  12425. cli.enable_server_certificate_verification(true);
  12426. cli.set_ca_cert_path(CA_CERT_FILE);
  12427. cli.set_connection_timeout(5);
  12428. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12429. verify_callback_called = true;
  12430. if (!ctx.cert) return false;
  12431. // The IP appears only in the CN, so it must NOT be accepted.
  12432. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  12433. return true; // Accept for the purpose of this test
  12434. });
  12435. cli.Get("/test");
  12436. ASSERT_TRUE(verify_callback_called)
  12437. << "Verify callback should have been called";
  12438. EXPECT_FALSE(ip_matched_via_cn)
  12439. << "An IP host must not be authenticated via the certificate CN";
  12440. }
  12441. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  12442. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  12443. using namespace httplib::tls;
  12444. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  12445. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  12446. ASSERT_TRUE(svr.is_valid());
  12447. svr.Get("/test", [](const Request &, Response &res) {
  12448. res.set_content("ok", "text/plain");
  12449. });
  12450. thread t([&]() { svr.listen(HOST, PORT); });
  12451. auto se = detail::scope_exit([&] {
  12452. svr.stop();
  12453. t.join();
  12454. });
  12455. svr.wait_until_ready();
  12456. bool verify_callback_called = false;
  12457. bool san_matched = false;
  12458. bool wrong_ipv6_matched = true;
  12459. bool cn_ipv6_matched = true;
  12460. SSLClient cli(HOST, PORT);
  12461. cli.enable_server_certificate_verification(true);
  12462. cli.set_ca_cert_path(CA_CERT_FILE);
  12463. cli.set_connection_timeout(5);
  12464. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12465. verify_callback_called = true;
  12466. if (!ctx.cert) return false;
  12467. // Matches the IPv6 iPAddress SAN.
  12468. san_matched = ctx.check_hostname("2001:db8::1");
  12469. // A different IPv6 address must not match.
  12470. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  12471. // "::1" lives only in the CN, so it must not be accepted.
  12472. cn_ipv6_matched = ctx.check_hostname("::1");
  12473. return true; // Accept for the purpose of this test
  12474. });
  12475. cli.Get("/test");
  12476. ASSERT_TRUE(verify_callback_called)
  12477. << "Verify callback should have been called";
  12478. EXPECT_TRUE(san_matched)
  12479. << "verify_hostname should match an IPv6 iPAddress SAN";
  12480. EXPECT_FALSE(wrong_ipv6_matched)
  12481. << "verify_hostname should not match a non-matching IPv6 address";
  12482. EXPECT_FALSE(cn_ipv6_matched)
  12483. << "An IPv6 host must not be authenticated via the certificate CN";
  12484. }
  12485. #endif
  12486. // mbedTLS-specific callback constructor test
  12487. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  12488. #ifdef CPPHTTPLIB_SSL_ENABLED
  12489. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  12490. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12491. ASSERT_TRUE(svr.is_valid());
  12492. // Set up a handler to verify client certificate is present
  12493. bool client_cert_verified = false;
  12494. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12495. // Verify that client certificate was provided
  12496. client_cert_verified = true;
  12497. res.set_content("success", "text/plain");
  12498. });
  12499. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12500. auto se = detail::scope_exit([&] {
  12501. svr.stop();
  12502. t.join();
  12503. ASSERT_FALSE(svr.is_running());
  12504. });
  12505. svr.wait_until_ready();
  12506. // Client with certificate
  12507. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12508. cli.enable_server_certificate_verification(false);
  12509. cli.set_connection_timeout(30);
  12510. auto res = cli.Get("/test");
  12511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12512. ASSERT_EQ(StatusCode::OK_200, res->status);
  12513. ASSERT_TRUE(client_cert_verified);
  12514. EXPECT_EQ("success", res->body);
  12515. }
  12516. #endif
  12517. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  12518. // backends
  12519. #ifdef CPPHTTPLIB_SSL_ENABLED
  12520. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  12521. using namespace httplib::tls;
  12522. // Test that when client CA cert file is provided,
  12523. // the server properly requests and validates client certificates
  12524. // Create a server with client authentication
  12525. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12526. ASSERT_TRUE(svr.is_valid());
  12527. bool handler_called = false;
  12528. svr.Get("/test", [&](const Request &req, Response &res) {
  12529. handler_called = true;
  12530. // Verify that a client certificate was provided
  12531. auto cert = req.peer_cert();
  12532. ASSERT_TRUE(static_cast<bool>(cert));
  12533. // Get the issuer name
  12534. std::string issuer_str = cert.issuer_name();
  12535. ASSERT_FALSE(issuer_str.empty());
  12536. // The client certificate should be issued by our test CA
  12537. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  12538. res.set_content("authenticated", "text/plain");
  12539. });
  12540. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12541. auto se = detail::scope_exit([&] {
  12542. svr.stop();
  12543. t.join();
  12544. ASSERT_FALSE(svr.is_running());
  12545. });
  12546. svr.wait_until_ready();
  12547. // Connect with a client certificate issued by the CA
  12548. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12549. cli.enable_server_certificate_verification(false);
  12550. cli.set_connection_timeout(30);
  12551. auto res = cli.Get("/test");
  12552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12553. ASSERT_EQ(StatusCode::OK_200, res->status);
  12554. ASSERT_TRUE(handler_called);
  12555. EXPECT_EQ("authenticated", res->body);
  12556. }
  12557. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  12558. using namespace httplib::tls;
  12559. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12560. ASSERT_TRUE(svr.is_valid());
  12561. svr.Get("/test", [](const Request &, Response &res) {
  12562. res.set_content("ok", "text/plain");
  12563. });
  12564. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12565. auto se = detail::scope_exit([&] {
  12566. svr.stop();
  12567. t.join();
  12568. });
  12569. svr.wait_until_ready();
  12570. SSLClient cli(HOST, PORT);
  12571. cli.enable_server_certificate_verification(false);
  12572. cli.set_connection_timeout(30);
  12573. bool cert_checked = false;
  12574. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12575. if (ctx.cert) {
  12576. auto sans = ctx.sans();
  12577. // Test certificate may or may not have SANs - just verify the API
  12578. // works If SANs exist, verify the types are valid
  12579. for (const auto &san : sans) {
  12580. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  12581. san.type == SanType::EMAIL || san.type == SanType::URI ||
  12582. san.type == SanType::OTHER);
  12583. EXPECT_FALSE(san.value.empty());
  12584. }
  12585. cert_checked = true;
  12586. }
  12587. return true;
  12588. });
  12589. auto res = cli.Get("/test");
  12590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12591. EXPECT_TRUE(cert_checked);
  12592. }
  12593. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  12594. using namespace httplib::tls;
  12595. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12596. ASSERT_TRUE(svr.is_valid());
  12597. svr.Get("/test", [](const Request &, Response &res) {
  12598. res.set_content("ok", "text/plain");
  12599. });
  12600. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12601. auto se = detail::scope_exit([&] {
  12602. svr.stop();
  12603. t.join();
  12604. });
  12605. svr.wait_until_ready();
  12606. SSLClient cli(HOST, PORT);
  12607. cli.enable_server_certificate_verification(false);
  12608. cli.set_connection_timeout(30);
  12609. bool validity_checked = false;
  12610. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12611. if (ctx.cert) {
  12612. time_t not_before = 0, not_after = 0;
  12613. bool result = ctx.validity(not_before, not_after);
  12614. EXPECT_TRUE(result);
  12615. // Verify that not_before < now < not_after for a valid cert
  12616. time_t now = time(nullptr);
  12617. EXPECT_LT(not_before, now);
  12618. EXPECT_GT(not_after, now);
  12619. validity_checked = true;
  12620. }
  12621. return true;
  12622. });
  12623. auto res = cli.Get("/test");
  12624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12625. EXPECT_TRUE(validity_checked);
  12626. }
  12627. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  12628. using namespace httplib::tls;
  12629. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12630. ASSERT_TRUE(svr.is_valid());
  12631. svr.Get("/test", [](const Request &, Response &res) {
  12632. res.set_content("ok", "text/plain");
  12633. });
  12634. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12635. auto se = detail::scope_exit([&] {
  12636. svr.stop();
  12637. t.join();
  12638. });
  12639. svr.wait_until_ready();
  12640. SSLClient cli(HOST, PORT);
  12641. cli.enable_server_certificate_verification(false);
  12642. cli.set_connection_timeout(30);
  12643. bool serial_checked = false;
  12644. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12645. if (ctx.cert) {
  12646. std::string serial = ctx.serial();
  12647. EXPECT_FALSE(serial.empty());
  12648. // Serial should be a hex string
  12649. for (char c : serial) {
  12650. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  12651. (c >= 'a' && c <= 'f'));
  12652. }
  12653. serial_checked = true;
  12654. }
  12655. return true;
  12656. });
  12657. auto res = cli.Get("/test");
  12658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12659. EXPECT_TRUE(serial_checked);
  12660. }
  12661. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  12662. // Test 1: Valid CA file - no error should be recorded
  12663. {
  12664. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12665. CLIENT_CA_CERT_FILE);
  12666. ASSERT_TRUE(svr.is_valid());
  12667. // With valid setup, last_ssl_error should be 0
  12668. EXPECT_EQ(0, svr.ssl_last_error());
  12669. }
  12670. // Test 2: Invalid CA file content
  12671. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  12672. {
  12673. // Create a temporary file with completely invalid content
  12674. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  12675. {
  12676. std::ofstream ofs(temp_invalid_ca);
  12677. ofs << "This is not a certificate file at all\n";
  12678. ofs << "Just plain text content\n";
  12679. }
  12680. // Create server with invalid CA file
  12681. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  12682. // Clean up temporary file
  12683. std::remove(temp_invalid_ca);
  12684. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  12685. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  12686. // Note: SSL_CTX_load_verify_locations typically fails first,
  12687. // but our error handling code path is still exercised
  12688. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  12689. }
  12690. }
  12691. TEST(VerifyCallbackTest, VerifyContextFields) {
  12692. using namespace httplib::tls;
  12693. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12694. ASSERT_TRUE(svr.is_valid());
  12695. svr.Get("/test", [](const Request &, Response &res) {
  12696. res.set_content("ok", "text/plain");
  12697. });
  12698. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12699. auto se = detail::scope_exit([&] {
  12700. svr.stop();
  12701. t.join();
  12702. });
  12703. svr.wait_until_ready();
  12704. SSLClient cli(HOST, PORT);
  12705. cli.enable_server_certificate_verification(false);
  12706. cli.set_connection_timeout(30);
  12707. int callback_count = 0;
  12708. bool saw_leaf_cert = false;
  12709. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12710. if (ctx.cert) {
  12711. callback_count++;
  12712. // We should see at least one certificate (the leaf)
  12713. std::string cn = ctx.subject_cn();
  12714. if (!cn.empty()) { saw_leaf_cert = true; }
  12715. // Verify context fields are populated
  12716. EXPECT_NE(ctx.session, nullptr);
  12717. EXPECT_GE(ctx.depth, 0);
  12718. }
  12719. return true;
  12720. });
  12721. auto res = cli.Get("/test");
  12722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12723. EXPECT_GT(callback_count, 0);
  12724. EXPECT_TRUE(saw_leaf_cert);
  12725. }
  12726. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  12727. using httplib::tls::TlsError;
  12728. // Test that verify_error_to_string returns empty for success
  12729. std::string success_str = TlsError::verify_error_to_string(0);
  12730. EXPECT_TRUE(success_str.empty());
  12731. // Test that verify_error_to_string returns non-empty for error codes
  12732. // Using a common error code (certificate expired)
  12733. std::string error_str =
  12734. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  12735. EXPECT_FALSE(error_str.empty());
  12736. }
  12737. TEST(SessionVerifierTest, CertificateAccepted) {
  12738. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12739. ASSERT_TRUE(svr.is_valid());
  12740. svr.Get("/test", [](const Request &, Response &res) {
  12741. res.set_content("ok", "text/plain");
  12742. });
  12743. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12744. auto se = detail::scope_exit([&] {
  12745. svr.stop();
  12746. t.join();
  12747. });
  12748. svr.wait_until_ready();
  12749. SSLClient cli(HOST, PORT);
  12750. cli.enable_server_certificate_verification(false);
  12751. cli.set_connection_timeout(30);
  12752. bool callback_called = false;
  12753. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12754. EXPECT_NE(session, nullptr);
  12755. callback_called = true;
  12756. return SSLVerifierResponse::CertificateAccepted;
  12757. });
  12758. auto res = cli.Get("/test");
  12759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12760. EXPECT_EQ(200, res->status);
  12761. EXPECT_TRUE(callback_called);
  12762. }
  12763. TEST(SessionVerifierTest, CertificateRejected) {
  12764. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12765. ASSERT_TRUE(svr.is_valid());
  12766. svr.Get("/test", [](const Request &, Response &res) {
  12767. res.set_content("ok", "text/plain");
  12768. });
  12769. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12770. auto se = detail::scope_exit([&] {
  12771. svr.stop();
  12772. t.join();
  12773. });
  12774. svr.wait_until_ready();
  12775. SSLClient cli(HOST, PORT);
  12776. cli.enable_server_certificate_verification(false);
  12777. cli.set_connection_timeout(30);
  12778. bool callback_called = false;
  12779. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12780. EXPECT_NE(session, nullptr);
  12781. callback_called = true;
  12782. return SSLVerifierResponse::CertificateRejected;
  12783. });
  12784. auto res = cli.Get("/test");
  12785. EXPECT_FALSE(res);
  12786. EXPECT_TRUE(callback_called);
  12787. }
  12788. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  12789. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12790. ASSERT_TRUE(svr.is_valid());
  12791. svr.Get("/test", [](const Request &, Response &res) {
  12792. res.set_content("ok", "text/plain");
  12793. });
  12794. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12795. auto se = detail::scope_exit([&] {
  12796. svr.stop();
  12797. t.join();
  12798. });
  12799. svr.wait_until_ready();
  12800. // NoDecisionMade with verification disabled should succeed (no default check)
  12801. SSLClient cli(HOST, PORT);
  12802. cli.enable_server_certificate_verification(false);
  12803. cli.set_connection_timeout(30);
  12804. bool callback_called = false;
  12805. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12806. EXPECT_NE(session, nullptr);
  12807. callback_called = true;
  12808. return SSLVerifierResponse::NoDecisionMade;
  12809. });
  12810. auto res = cli.Get("/test");
  12811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12812. EXPECT_EQ(200, res->status);
  12813. EXPECT_TRUE(callback_called);
  12814. }
  12815. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  12816. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12817. ASSERT_TRUE(svr.is_valid());
  12818. svr.Get("/test", [](const Request &, Response &res) {
  12819. res.set_content("ok", "text/plain");
  12820. });
  12821. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12822. auto se = detail::scope_exit([&] {
  12823. svr.stop();
  12824. t.join();
  12825. });
  12826. svr.wait_until_ready();
  12827. // NoDecisionMade with verification enabled should fail (self-signed cert).
  12828. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  12829. // so we only check that the request fails, not whether the callback was
  12830. // called.
  12831. SSLClient cli(HOST, PORT);
  12832. cli.enable_server_certificate_verification(true);
  12833. cli.set_connection_timeout(30);
  12834. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12835. EXPECT_NE(session, nullptr);
  12836. return SSLVerifierResponse::NoDecisionMade;
  12837. });
  12838. auto res = cli.Get("/test");
  12839. EXPECT_FALSE(res);
  12840. }
  12841. TEST(SSLClientServerTest, ClientCAListFromPem) {
  12842. // Test SSL server using PemMemory constructor with client CA certificates
  12843. // Read PEM files
  12844. std::string server_cert_pem, server_key_pem, client_ca_pem;
  12845. read_file(SERVER_CERT_FILE, server_cert_pem);
  12846. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12847. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12848. // Create SSLServer with PemMemory constructor including client CA
  12849. SSLServer::PemMemory server_pem = {
  12850. server_cert_pem.c_str(),
  12851. server_cert_pem.size(),
  12852. server_key_pem.c_str(),
  12853. server_key_pem.size(),
  12854. client_ca_pem.c_str(),
  12855. client_ca_pem.size(),
  12856. nullptr // no password for server key
  12857. };
  12858. SSLServer svr(server_pem);
  12859. ASSERT_TRUE(svr.is_valid());
  12860. // No SSL error should be recorded for valid setup
  12861. EXPECT_EQ(0, svr.ssl_last_error());
  12862. // Set up server endpoints
  12863. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  12864. res.set_content("ok", "text/plain");
  12865. });
  12866. // Start server in a thread
  12867. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  12868. svr.wait_until_ready();
  12869. // Connect with client certificate (using constructor with paths)
  12870. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12871. cli.enable_server_certificate_verification(false);
  12872. auto res = cli.Get("/test-pem-ca");
  12873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12874. EXPECT_EQ(200, res->status);
  12875. EXPECT_EQ("ok", res->body);
  12876. svr.stop();
  12877. server_thread.join();
  12878. }
  12879. #endif
  12880. #ifdef _WIN32
  12881. TEST(CleanupTest, WSACleanup) {
  12882. int ret = WSACleanup();
  12883. ASSERT_EQ(0, ret);
  12884. }
  12885. #endif
  12886. #ifndef CPPHTTPLIB_SSL_ENABLED
  12887. TEST(NoSSLSupport, SimpleInterface) {
  12888. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  12889. }
  12890. #endif
  12891. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12892. TEST(InvalidScheme, SimpleInterface) {
  12893. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  12894. }
  12895. #endif
  12896. TEST(NoScheme, SimpleInterface) {
  12897. Client cli("yahoo.com:80");
  12898. ASSERT_TRUE(cli.is_valid());
  12899. }
  12900. TEST(SendAPI, SimpleInterface_Online) {
  12901. Client cli("http://yahoo.com");
  12902. Request req;
  12903. req.method = "GET";
  12904. req.path = "/";
  12905. auto res = cli.send(req);
  12906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12907. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12908. }
  12909. TEST(SendAPI, WithParamsInRequest) {
  12910. Server svr;
  12911. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  12912. EXPECT_TRUE(req.has_param("test"));
  12913. EXPECT_EQ("test_value", req.get_param_value("test"));
  12914. });
  12915. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12916. auto se = detail::scope_exit([&] {
  12917. svr.stop();
  12918. t.join();
  12919. ASSERT_FALSE(svr.is_running());
  12920. });
  12921. svr.wait_until_ready();
  12922. Client cli(HOST, PORT);
  12923. {
  12924. Request req;
  12925. req.method = "GET";
  12926. req.path = "/";
  12927. req.params.emplace("test", "test_value");
  12928. auto res = cli.send(req);
  12929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12930. }
  12931. {
  12932. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  12933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12934. }
  12935. }
  12936. TEST(ClientImplMethods, GetSocketTest) {
  12937. httplib::Server svr;
  12938. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  12939. res.status = StatusCode::OK_200;
  12940. });
  12941. auto port = svr.bind_to_any_port("127.0.0.1");
  12942. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12943. auto se = detail::scope_exit([&] {
  12944. svr.stop();
  12945. thread.join();
  12946. ASSERT_FALSE(svr.is_running());
  12947. });
  12948. svr.wait_until_ready();
  12949. {
  12950. httplib::Client cli("127.0.0.1", port);
  12951. cli.set_keep_alive(true);
  12952. // Use the behavior of cpp-httplib of opening the connection
  12953. // only when the first request happens. If that changes,
  12954. // this test would be obsolete.
  12955. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  12956. // This also implicitly tests the server. But other tests would fail much
  12957. // earlier than this one to be considered.
  12958. auto res = cli.Get("/");
  12959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12960. EXPECT_EQ(StatusCode::OK_200, res->status);
  12961. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  12962. }
  12963. }
  12964. #ifdef CPPHTTPLIB_SSL_ENABLED
  12965. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  12966. Client cli("http://yahoo.com");
  12967. auto res = cli.Get("/");
  12968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12969. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12970. cli.set_follow_location(true);
  12971. res = cli.Get("/");
  12972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12973. EXPECT_EQ(StatusCode::OK_200, res->status);
  12974. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12975. }
  12976. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  12977. Client cli("https://yahoo.com");
  12978. auto res = cli.Get("/");
  12979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12980. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12981. cli.set_follow_location(true);
  12982. res = cli.Get("/");
  12983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12984. EXPECT_EQ(StatusCode::OK_200, res->status);
  12985. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12986. }
  12987. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  12988. Client cli("https://yahoo.com");
  12989. auto res = cli.Get("/");
  12990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12991. ASSERT_FALSE(!res);
  12992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12993. ASSERT_FALSE(res == nullptr);
  12994. ASSERT_TRUE(res != nullptr);
  12995. EXPECT_EQ(Error::Success, res.error());
  12996. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  12997. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  12998. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12999. cli.set_follow_location(true);
  13000. res = cli.Get("/");
  13001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13002. EXPECT_EQ(Error::Success, res.error());
  13003. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  13004. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  13005. EXPECT_EQ(StatusCode::OK_200, res->status);
  13006. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13007. }
  13008. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13009. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  13010. Client cli("https://cdnjs.cloudflare.com");
  13011. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  13012. Headers{{"Accept-Encoding", "br"}});
  13013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13014. EXPECT_EQ(StatusCode::OK_200, res->status);
  13015. EXPECT_EQ(287630U, res->body.size());
  13016. EXPECT_EQ("application/javascript; charset=utf-8",
  13017. res->get_header_value("Content-Type"));
  13018. }
  13019. #endif
  13020. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  13021. #undef REDIR_HOST // Silence compiler warning
  13022. #define REDIR_HOST "https://httpbingo.org"
  13023. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  13024. Client cli(REDIR_HOST);
  13025. cli.set_follow_location(true);
  13026. auto res =
  13027. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  13028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13029. EXPECT_EQ(StatusCode::OK_200, res->status);
  13030. }
  13031. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  13032. Client cli(REDIR_HOST);
  13033. cli.set_follow_location(true);
  13034. Params params;
  13035. params.emplace("url", "http://example.com");
  13036. params.emplace("status_code", "302");
  13037. auto res = cli.Get(REDIR_PATH, params, Headers{});
  13038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13039. EXPECT_EQ(StatusCode::OK_200, res->status);
  13040. }
  13041. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  13042. Client cli(REDIR_HOST);
  13043. cli.set_follow_location(true);
  13044. Params params;
  13045. params.emplace("url", "http://example.com");
  13046. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  13047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13048. EXPECT_EQ(StatusCode::OK_200, res->status);
  13049. }
  13050. TEST(HttpToHttpsRedirectTest, CertFile) {
  13051. auto ssl_port = PORT + 1;
  13052. Server svr;
  13053. ASSERT_TRUE(svr.is_valid());
  13054. svr.Get("/index", [&](const Request &, Response &res) {
  13055. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13056. "/index");
  13057. svr.stop();
  13058. });
  13059. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13060. ASSERT_TRUE(ssl_svr.is_valid());
  13061. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  13062. res.set_content("test", "text/plain");
  13063. ssl_svr.stop();
  13064. });
  13065. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13066. thread t2 =
  13067. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  13068. auto se = detail::scope_exit([&] {
  13069. t2.join();
  13070. t.join();
  13071. ASSERT_FALSE(svr.is_running());
  13072. });
  13073. svr.wait_until_ready();
  13074. ssl_svr.wait_until_ready();
  13075. Client cli("127.0.0.1", PORT);
  13076. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13077. cli.enable_server_certificate_verification(true);
  13078. cli.set_follow_location(true);
  13079. cli.set_connection_timeout(30);
  13080. auto res = cli.Get("/index");
  13081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13082. ASSERT_EQ(StatusCode::OK_200, res->status);
  13083. }
  13084. TEST(SSLClientRedirectTest, CertFile) {
  13085. auto ssl_port = PORT + 1;
  13086. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13087. ASSERT_TRUE(ssl_svr1.is_valid());
  13088. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13089. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13090. "/index");
  13091. ssl_svr1.stop();
  13092. });
  13093. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13094. ASSERT_TRUE(ssl_svr2.is_valid());
  13095. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13096. res.set_content("test", "text/plain");
  13097. ssl_svr2.stop();
  13098. });
  13099. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13100. thread t2 =
  13101. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13102. auto se = detail::scope_exit([&] {
  13103. t2.join();
  13104. t.join();
  13105. ASSERT_FALSE(ssl_svr1.is_running());
  13106. });
  13107. ssl_svr1.wait_until_ready();
  13108. ssl_svr2.wait_until_ready();
  13109. SSLClient cli("127.0.0.1", PORT);
  13110. std::string cert;
  13111. read_file(SERVER_CERT2_FILE, cert);
  13112. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13113. cli.enable_server_certificate_verification(true);
  13114. cli.set_follow_location(true);
  13115. cli.set_connection_timeout(30);
  13116. auto res = cli.Get("/index");
  13117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13118. ASSERT_EQ(StatusCode::OK_200, res->status);
  13119. }
  13120. #endif
  13121. #ifdef CPPHTTPLIB_SSL_ENABLED
  13122. // Test that set_ca_cert_store() skips system certs (consistent with
  13123. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  13124. // should be trusted - system certs should NOT be loaded.
  13125. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  13126. // Load a specific cert that is NOT a system CA cert
  13127. std::string cert;
  13128. read_file(SERVER_CERT2_FILE, cert);
  13129. SSLClient cli("google.com");
  13130. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13131. cli.enable_server_certificate_verification(true);
  13132. // This should FAIL because:
  13133. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  13134. // 2. System certs should NOT be loaded when custom store is set
  13135. // If system certs WERE loaded, this would succeed
  13136. auto res = cli.Get("/");
  13137. ASSERT_FALSE(res);
  13138. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13139. }
  13140. // Same as above, but through the native store handle path. Regression test:
  13141. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  13142. // merged system certs into the user-provided store.
  13143. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  13144. std::string cert;
  13145. read_file(SERVER_CERT2_FILE, cert);
  13146. SSLClient cli("google.com");
  13147. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13148. cli.enable_server_certificate_verification(true);
  13149. auto res = cli.Get("/");
  13150. ASSERT_FALSE(res);
  13151. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13152. }
  13153. // A custom store set via the native handle must still verify a server whose
  13154. // cert it does contain.
  13155. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  13156. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13157. ASSERT_TRUE(svr.is_valid());
  13158. svr.Get("/test", [&](const Request &, Response &res) {
  13159. res.set_content("test", "text/plain");
  13160. });
  13161. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13162. auto se = detail::scope_exit([&] {
  13163. svr.stop();
  13164. t.join();
  13165. ASSERT_FALSE(svr.is_running());
  13166. });
  13167. svr.wait_until_ready();
  13168. SSLClient cli("127.0.0.1", PORT);
  13169. std::string cert;
  13170. read_file(SERVER_CERT2_FILE, cert);
  13171. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13172. cli.enable_server_certificate_verification(true);
  13173. cli.set_connection_timeout(30);
  13174. auto res = cli.Get("/test");
  13175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13176. ASSERT_EQ(StatusCode::OK_200, res->status);
  13177. }
  13178. // CA certs loaded through the universal Client must be transferred to the
  13179. // client created internally for following an HTTPS redirect. Regression test:
  13180. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  13181. // the CA data for redirect transfer.
  13182. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  13183. auto ssl_port = PORT + 1;
  13184. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13185. ASSERT_TRUE(ssl_svr1.is_valid());
  13186. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13187. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13188. "/index");
  13189. });
  13190. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13191. ASSERT_TRUE(ssl_svr2.is_valid());
  13192. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13193. res.set_content("test", "text/plain");
  13194. });
  13195. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13196. thread t2 =
  13197. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13198. auto se = detail::scope_exit([&] {
  13199. ssl_svr2.stop();
  13200. ssl_svr1.stop();
  13201. t2.join();
  13202. t.join();
  13203. ASSERT_FALSE(ssl_svr1.is_running());
  13204. });
  13205. ssl_svr1.wait_until_ready();
  13206. ssl_svr2.wait_until_ready();
  13207. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13208. std::string cert;
  13209. read_file(SERVER_CERT2_FILE, cert);
  13210. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13211. cli.enable_server_certificate_verification(true);
  13212. cli.set_follow_location(true);
  13213. cli.set_connection_timeout(30);
  13214. auto res = cli.Get("/index");
  13215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13216. ASSERT_EQ(StatusCode::OK_200, res->status);
  13217. }
  13218. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  13219. // so a host signed by a system CA verifies even though a custom CA is set
  13220. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  13221. std::string cert;
  13222. read_file(SERVER_CERT2_FILE, cert);
  13223. SSLClient cli("google.com");
  13224. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13225. cli.enable_system_ca(true);
  13226. cli.enable_server_certificate_verification(true);
  13227. auto res = cli.Get("/");
  13228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13229. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13230. }
  13231. // The custom CA remains effective when combined with the system CA
  13232. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  13233. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13234. ASSERT_TRUE(svr.is_valid());
  13235. svr.Get("/test", [&](const Request &, Response &res) {
  13236. res.set_content("test", "text/plain");
  13237. });
  13238. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13239. auto se = detail::scope_exit([&] {
  13240. svr.stop();
  13241. t.join();
  13242. ASSERT_FALSE(svr.is_running());
  13243. });
  13244. svr.wait_until_ready();
  13245. SSLClient cli("127.0.0.1", PORT);
  13246. std::string cert;
  13247. read_file(SERVER_CERT2_FILE, cert);
  13248. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13249. cli.enable_system_ca(true);
  13250. cli.enable_server_certificate_verification(true);
  13251. cli.set_connection_timeout(30);
  13252. auto res = cli.Get("/test");
  13253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13254. ASSERT_EQ(StatusCode::OK_200, res->status);
  13255. }
  13256. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  13257. // skip chain verification entirely (only the certificate identity was
  13258. // checked), so a server presenting an untrusted certificate with a matching
  13259. // IP SAN was accepted. The chain must be validated for IP hosts too.
  13260. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  13261. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13262. ASSERT_TRUE(svr.is_valid());
  13263. svr.Get("/test", [&](const Request &, Response &res) {
  13264. res.set_content("test", "text/plain");
  13265. });
  13266. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13267. auto se = detail::scope_exit([&] {
  13268. svr.stop();
  13269. t.join();
  13270. ASSERT_FALSE(svr.is_running());
  13271. });
  13272. svr.wait_until_ready();
  13273. SSLClient cli("127.0.0.1", PORT);
  13274. std::string cert;
  13275. // A trusted CA that did not sign the server certificate. The server cert
  13276. // (cert2) carries the matching IP SAN, so only chain validation can reject
  13277. // this connection.
  13278. read_file(CLIENT_CA_CERT_FILE, cert);
  13279. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13280. cli.enable_server_certificate_verification(true);
  13281. cli.set_connection_timeout(30);
  13282. auto res = cli.Get("/test");
  13283. ASSERT_FALSE(res);
  13284. }
  13285. // enable_system_ca(false) prevents system CA loading entirely
  13286. TEST(SSLClientTest, DisableSystemCa_Online) {
  13287. SSLClient cli("google.com");
  13288. cli.enable_system_ca(false);
  13289. cli.enable_server_certificate_verification(true);
  13290. auto res = cli.Get("/");
  13291. ASSERT_FALSE(res);
  13292. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  13293. // itself when the CA chain is empty
  13294. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13295. res.error() == Error::SSLConnection);
  13296. }
  13297. // The universal Client forwards enable_system_ca()
  13298. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  13299. std::string cert;
  13300. read_file(SERVER_CERT2_FILE, cert);
  13301. Client cli("https://google.com");
  13302. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13303. cli.enable_system_ca(true);
  13304. cli.enable_server_certificate_verification(true);
  13305. auto res = cli.Get("/");
  13306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13307. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13308. }
  13309. // The system CA policy must carry over to the client created internally for
  13310. // following a cross-host HTTPS redirect
  13311. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  13312. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13313. ASSERT_TRUE(svr.is_valid());
  13314. svr.Get("/index", [&](const Request &, Response &res) {
  13315. res.set_redirect("https://www.google.com/");
  13316. });
  13317. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13318. auto se = detail::scope_exit([&] {
  13319. svr.stop();
  13320. t.join();
  13321. ASSERT_FALSE(svr.is_running());
  13322. });
  13323. svr.wait_until_ready();
  13324. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13325. std::string cert;
  13326. read_file(SERVER_CERT2_FILE, cert);
  13327. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13328. cli.enable_system_ca(true);
  13329. cli.enable_server_certificate_verification(true);
  13330. cli.set_follow_location(true);
  13331. cli.set_connection_timeout(30);
  13332. // Receiving any response proves the redirect client completed the TLS
  13333. // handshake with a system-CA-signed host
  13334. auto res = cli.Get("/index");
  13335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13336. }
  13337. TEST(MultipartFormDataTest, LargeData) {
  13338. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13339. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  13340. const ContentReader &content_reader) {
  13341. if (req.is_multipart_form_data()) {
  13342. std::vector<FormData> items;
  13343. content_reader(
  13344. [&](const FormData &file) {
  13345. items.push_back(file);
  13346. return true;
  13347. },
  13348. [&](const char *data, size_t data_length) {
  13349. items.back().content.append(data, data_length);
  13350. return true;
  13351. });
  13352. EXPECT_TRUE(std::string(items[0].name) == "document");
  13353. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13354. EXPECT_TRUE(items[0].filename == "2MB_data");
  13355. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13356. EXPECT_TRUE(items[1].name == "hello");
  13357. EXPECT_TRUE(items[1].content == "world");
  13358. EXPECT_TRUE(items[1].filename == "");
  13359. EXPECT_TRUE(items[1].content_type == "");
  13360. } else {
  13361. std::string body;
  13362. content_reader([&](const char *data, size_t data_length) {
  13363. body.append(data, data_length);
  13364. return true;
  13365. });
  13366. }
  13367. });
  13368. auto port = svr.bind_to_any_port(HOST);
  13369. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13370. auto se = detail::scope_exit([&] {
  13371. svr.stop();
  13372. t.join();
  13373. ASSERT_FALSE(svr.is_running());
  13374. });
  13375. svr.wait_until_ready();
  13376. {
  13377. std::string data(1024 * 1024 * 2, '.');
  13378. std::stringstream buffer;
  13379. buffer << data;
  13380. SSLClient cli(HOST, port);
  13381. cli.enable_server_certificate_verification(false);
  13382. UploadFormDataItems items{
  13383. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13384. {"hello", "world", "", ""},
  13385. };
  13386. auto res = cli.Post("/post", items);
  13387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13388. ASSERT_EQ(StatusCode::OK_200, res->status);
  13389. }
  13390. }
  13391. TEST(MultipartFormDataTest, DataProviderItems) {
  13392. std::random_device seed_gen;
  13393. std::mt19937 random(seed_gen());
  13394. std::string rand1;
  13395. rand1.resize(1000);
  13396. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  13397. std::string rand2;
  13398. rand2.resize(3000);
  13399. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  13400. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13401. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  13402. const ContentReader &content_reader) {
  13403. ASSERT_FALSE(req.is_multipart_form_data());
  13404. std::string body;
  13405. content_reader([&](const char *data, size_t data_length) {
  13406. body.append(data, data_length);
  13407. return true;
  13408. });
  13409. EXPECT_EQ(body, "");
  13410. });
  13411. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  13412. const ContentReader &content_reader) {
  13413. ASSERT_TRUE(req.is_multipart_form_data());
  13414. std::vector<FormData> items;
  13415. content_reader(
  13416. [&](const FormData &file) {
  13417. items.push_back(file);
  13418. return true;
  13419. },
  13420. [&](const char *data, size_t data_length) {
  13421. items.back().content.append(data, data_length);
  13422. return true;
  13423. });
  13424. ASSERT_TRUE(items.size() == 2);
  13425. EXPECT_EQ(std::string(items[0].name), "name1");
  13426. EXPECT_EQ(items[0].content, "Testing123");
  13427. EXPECT_EQ(items[0].filename, "filename1");
  13428. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13429. EXPECT_EQ(items[1].name, "name2");
  13430. EXPECT_EQ(items[1].content, "Testing456");
  13431. EXPECT_EQ(items[1].filename, "");
  13432. EXPECT_EQ(items[1].content_type, "");
  13433. });
  13434. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  13435. const ContentReader &content_reader) {
  13436. ASSERT_TRUE(req.is_multipart_form_data());
  13437. std::vector<FormData> items;
  13438. content_reader(
  13439. [&](const FormData &file) {
  13440. items.push_back(file);
  13441. return true;
  13442. },
  13443. [&](const char *data, size_t data_length) {
  13444. items.back().content.append(data, data_length);
  13445. return true;
  13446. });
  13447. ASSERT_TRUE(items.size() == 2);
  13448. EXPECT_EQ(items[0].name, "name3");
  13449. EXPECT_EQ(items[0].content, rand1);
  13450. EXPECT_EQ(items[0].filename, "filename3");
  13451. EXPECT_EQ(items[0].content_type, "");
  13452. EXPECT_EQ(items[1].name, "name4");
  13453. EXPECT_EQ(items[1].content, rand2);
  13454. EXPECT_EQ(items[1].filename, "filename4");
  13455. EXPECT_EQ(items[1].content_type, "");
  13456. });
  13457. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  13458. const ContentReader &content_reader) {
  13459. ASSERT_TRUE(req.is_multipart_form_data());
  13460. std::vector<FormData> items;
  13461. content_reader(
  13462. [&](const FormData &file) {
  13463. items.push_back(file);
  13464. return true;
  13465. },
  13466. [&](const char *data, size_t data_length) {
  13467. items.back().content.append(data, data_length);
  13468. return true;
  13469. });
  13470. ASSERT_TRUE(items.size() == 4);
  13471. EXPECT_EQ(std::string(items[0].name), "name1");
  13472. EXPECT_EQ(items[0].content, "Testing123");
  13473. EXPECT_EQ(items[0].filename, "filename1");
  13474. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13475. EXPECT_EQ(items[1].name, "name2");
  13476. EXPECT_EQ(items[1].content, "Testing456");
  13477. EXPECT_EQ(items[1].filename, "");
  13478. EXPECT_EQ(items[1].content_type, "");
  13479. EXPECT_EQ(items[2].name, "name3");
  13480. EXPECT_EQ(items[2].content, rand1);
  13481. EXPECT_EQ(items[2].filename, "filename3");
  13482. EXPECT_EQ(items[2].content_type, "");
  13483. EXPECT_EQ(items[3].name, "name4");
  13484. EXPECT_EQ(items[3].content, rand2);
  13485. EXPECT_EQ(items[3].filename, "filename4");
  13486. EXPECT_EQ(items[3].content_type, "");
  13487. });
  13488. auto port = svr.bind_to_any_port("localhost");
  13489. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13490. auto se = detail::scope_exit([&] {
  13491. svr.stop();
  13492. t.join();
  13493. ASSERT_FALSE(svr.is_running());
  13494. });
  13495. svr.wait_until_ready();
  13496. {
  13497. SSLClient cli("localhost", port);
  13498. cli.enable_server_certificate_verification(false);
  13499. UploadFormDataItems items{
  13500. {"name1", "Testing123", "filename1", "application/octet-stream"},
  13501. {"name2", "Testing456", "", ""}, // not a file
  13502. };
  13503. {
  13504. auto res = cli.Post("/post-none", {}, {}, {});
  13505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13506. ASSERT_EQ(StatusCode::OK_200, res->status);
  13507. }
  13508. FormDataProviderItems providers;
  13509. {
  13510. auto res =
  13511. cli.Post("/post-items", {}, items, providers); // empty providers
  13512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13513. ASSERT_EQ(StatusCode::OK_200, res->status);
  13514. }
  13515. providers.push_back({"name3",
  13516. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13517. // test the offset is given correctly at each step
  13518. if (!offset)
  13519. sink.os.write(rand1.data(), 30);
  13520. else if (offset == 30)
  13521. sink.os.write(rand1.data() + 30, 300);
  13522. else if (offset == 330)
  13523. sink.os.write(rand1.data() + 330, 670);
  13524. else if (offset == rand1.size())
  13525. sink.done();
  13526. return true;
  13527. },
  13528. "filename3",
  13529. {}});
  13530. providers.push_back({"name4",
  13531. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13532. // test the offset is given correctly at each step
  13533. if (!offset)
  13534. sink.os.write(rand2.data(), 2000);
  13535. else if (offset == 2000)
  13536. sink.os.write(rand2.data() + 2000, 1);
  13537. else if (offset == 2001)
  13538. sink.os.write(rand2.data() + 2001, 999);
  13539. else if (offset == rand2.size())
  13540. sink.done();
  13541. return true;
  13542. },
  13543. "filename4",
  13544. {}});
  13545. {
  13546. auto res = cli.Post("/post-providers", {}, {}, providers);
  13547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13548. ASSERT_EQ(StatusCode::OK_200, res->status);
  13549. }
  13550. {
  13551. auto res = cli.Post("/post-both", {}, items, providers);
  13552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13553. ASSERT_EQ(StatusCode::OK_200, res->status);
  13554. }
  13555. }
  13556. }
  13557. TEST(MultipartFormDataTest, BadHeader) {
  13558. Server svr;
  13559. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13560. res.set_content("ok", "text/plain");
  13561. });
  13562. thread t = thread([&] { svr.listen(HOST, PORT); });
  13563. auto se = detail::scope_exit([&] {
  13564. svr.stop();
  13565. t.join();
  13566. ASSERT_FALSE(svr.is_running());
  13567. });
  13568. svr.wait_until_ready();
  13569. const std::string body =
  13570. "This is the preamble. It is to be ignored, though it\r\n"
  13571. "is a handy place for composition agents to include an\r\n"
  13572. "explanatory note to non-MIME conformant readers.\r\n"
  13573. "\r\n"
  13574. "\r\n"
  13575. "--simple boundary\r\n"
  13576. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13577. ": BAD...\r\n"
  13578. "\r\n"
  13579. "value1\r\n"
  13580. "--simple boundary\r\n"
  13581. "Content-Disposition: form-data; name=\"field2\"; "
  13582. "filename=\"example.txt\"\r\n"
  13583. "\r\n"
  13584. "value2\r\n"
  13585. "--simple boundary--\r\n"
  13586. "This is the epilogue. It is also to be ignored.\r\n";
  13587. std::string content_type =
  13588. R"(multipart/form-data; boundary="simple boundary")";
  13589. Client cli(HOST, PORT);
  13590. auto res = cli.Post("/post", body, content_type.c_str());
  13591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13592. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13593. }
  13594. TEST(MultipartFormDataTest, WithPreamble) {
  13595. Server svr;
  13596. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13597. res.set_content("ok", "text/plain");
  13598. });
  13599. thread t = thread([&] { svr.listen(HOST, PORT); });
  13600. auto se = detail::scope_exit([&] {
  13601. svr.stop();
  13602. t.join();
  13603. ASSERT_FALSE(svr.is_running());
  13604. });
  13605. svr.wait_until_ready();
  13606. const std::string body =
  13607. "This is the preamble. It is to be ignored, though it\r\n"
  13608. "is a handy place for composition agents to include an\r\n"
  13609. "explanatory note to non-MIME conformant readers.\r\n"
  13610. "\r\n"
  13611. "\r\n"
  13612. "--simple boundary\r\n"
  13613. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13614. "\r\n"
  13615. "value1\r\n"
  13616. "--simple boundary\r\n"
  13617. "Content-Disposition: form-data; name=\"field2\"; "
  13618. "filename=\"example.txt\"\r\n"
  13619. "\r\n"
  13620. "value2\r\n"
  13621. "--simple boundary--\r\n"
  13622. "This is the epilogue. It is also to be ignored.\r\n";
  13623. std::string content_type =
  13624. R"(multipart/form-data; boundary="simple boundary")";
  13625. Client cli(HOST, PORT);
  13626. auto res = cli.Post("/post", body, content_type.c_str());
  13627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13628. EXPECT_EQ(StatusCode::OK_200, res->status);
  13629. }
  13630. TEST(MultipartFormDataTest, PostCustomBoundary) {
  13631. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13632. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  13633. const ContentReader &content_reader) {
  13634. if (req.is_multipart_form_data()) {
  13635. std::vector<FormData> items;
  13636. content_reader(
  13637. [&](const FormData &file) {
  13638. items.push_back(file);
  13639. return true;
  13640. },
  13641. [&](const char *data, size_t data_length) {
  13642. items.back().content.append(data, data_length);
  13643. return true;
  13644. });
  13645. EXPECT_TRUE(std::string(items[0].name) == "document");
  13646. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13647. EXPECT_TRUE(items[0].filename == "2MB_data");
  13648. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13649. EXPECT_TRUE(items[1].name == "hello");
  13650. EXPECT_TRUE(items[1].content == "world");
  13651. EXPECT_TRUE(items[1].filename == "");
  13652. EXPECT_TRUE(items[1].content_type == "");
  13653. } else {
  13654. std::string body;
  13655. content_reader([&](const char *data, size_t data_length) {
  13656. body.append(data, data_length);
  13657. return true;
  13658. });
  13659. }
  13660. });
  13661. auto port = svr.bind_to_any_port("localhost");
  13662. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13663. auto se = detail::scope_exit([&] {
  13664. svr.stop();
  13665. t.join();
  13666. ASSERT_FALSE(svr.is_running());
  13667. });
  13668. svr.wait_until_ready();
  13669. {
  13670. std::string data(1024 * 1024 * 2, '.');
  13671. std::stringstream buffer;
  13672. buffer << data;
  13673. SSLClient cli("localhost", port);
  13674. cli.enable_server_certificate_verification(false);
  13675. UploadFormDataItems items{
  13676. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13677. {"hello", "world", "", ""},
  13678. };
  13679. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  13680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13681. ASSERT_EQ(StatusCode::OK_200, res->status);
  13682. }
  13683. }
  13684. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  13685. std::string data(1024 * 1024 * 2, '&');
  13686. std::stringstream buffer;
  13687. buffer << data;
  13688. Client cli("https://localhost:8080");
  13689. UploadFormDataItems items{
  13690. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13691. {"hello", "world", "", ""},
  13692. };
  13693. for (const char &c : " \t\r\n") {
  13694. auto res =
  13695. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  13696. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13697. ASSERT_FALSE(res);
  13698. }
  13699. }
  13700. TEST(MultipartFormDataTest, PutFormData) {
  13701. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13702. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  13703. const ContentReader &content_reader) {
  13704. if (req.is_multipart_form_data()) {
  13705. std::vector<FormData> items;
  13706. content_reader(
  13707. [&](const FormData &file) {
  13708. items.push_back(file);
  13709. return true;
  13710. },
  13711. [&](const char *data, size_t data_length) {
  13712. items.back().content.append(data, data_length);
  13713. return true;
  13714. });
  13715. EXPECT_TRUE(std::string(items[0].name) == "document");
  13716. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13717. EXPECT_TRUE(items[0].filename == "2MB_data");
  13718. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13719. EXPECT_TRUE(items[1].name == "hello");
  13720. EXPECT_TRUE(items[1].content == "world");
  13721. EXPECT_TRUE(items[1].filename == "");
  13722. EXPECT_TRUE(items[1].content_type == "");
  13723. } else {
  13724. std::string body;
  13725. content_reader([&](const char *data, size_t data_length) {
  13726. body.append(data, data_length);
  13727. return true;
  13728. });
  13729. }
  13730. });
  13731. auto port = svr.bind_to_any_port("localhost");
  13732. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13733. auto se = detail::scope_exit([&] {
  13734. svr.stop();
  13735. t.join();
  13736. ASSERT_FALSE(svr.is_running());
  13737. });
  13738. svr.wait_until_ready();
  13739. {
  13740. std::string data(1024 * 1024 * 2, '&');
  13741. std::stringstream buffer;
  13742. buffer << data;
  13743. SSLClient cli("localhost", port);
  13744. cli.enable_server_certificate_verification(false);
  13745. UploadFormDataItems items{
  13746. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13747. {"hello", "world", "", ""},
  13748. };
  13749. auto res = cli.Put("/put", items);
  13750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13751. ASSERT_EQ(StatusCode::OK_200, res->status);
  13752. }
  13753. }
  13754. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  13755. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13756. svr.Put("/put_customboundary",
  13757. [&](const Request &req, const Response & /*res*/,
  13758. const ContentReader &content_reader) {
  13759. if (req.is_multipart_form_data()) {
  13760. std::vector<FormData> items;
  13761. content_reader(
  13762. [&](const FormData &file) {
  13763. items.push_back(file);
  13764. return true;
  13765. },
  13766. [&](const char *data, size_t data_length) {
  13767. items.back().content.append(data, data_length);
  13768. return true;
  13769. });
  13770. EXPECT_TRUE(std::string(items[0].name) == "document");
  13771. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13772. EXPECT_TRUE(items[0].filename == "2MB_data");
  13773. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13774. EXPECT_TRUE(items[1].name == "hello");
  13775. EXPECT_TRUE(items[1].content == "world");
  13776. EXPECT_TRUE(items[1].filename == "");
  13777. EXPECT_TRUE(items[1].content_type == "");
  13778. } else {
  13779. std::string body;
  13780. content_reader([&](const char *data, size_t data_length) {
  13781. body.append(data, data_length);
  13782. return true;
  13783. });
  13784. }
  13785. });
  13786. auto port = svr.bind_to_any_port("localhost");
  13787. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13788. auto se = detail::scope_exit([&] {
  13789. svr.stop();
  13790. t.join();
  13791. ASSERT_FALSE(svr.is_running());
  13792. });
  13793. svr.wait_until_ready();
  13794. {
  13795. std::string data(1024 * 1024 * 2, '&');
  13796. std::stringstream buffer;
  13797. buffer << data;
  13798. SSLClient cli("localhost", port);
  13799. cli.enable_server_certificate_verification(false);
  13800. UploadFormDataItems items{
  13801. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13802. {"hello", "world", "", ""},
  13803. };
  13804. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  13805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13806. ASSERT_EQ(StatusCode::OK_200, res->status);
  13807. }
  13808. }
  13809. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  13810. std::string data(1024 * 1024 * 2, '&');
  13811. std::stringstream buffer;
  13812. buffer << data;
  13813. Client cli("https://localhost:8080");
  13814. cli.enable_server_certificate_verification(false);
  13815. UploadFormDataItems items{
  13816. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13817. {"hello", "world", "", ""},
  13818. };
  13819. for (const char &c : " \t\r\n") {
  13820. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  13821. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13822. ASSERT_FALSE(res);
  13823. }
  13824. }
  13825. TEST(MultipartFormDataTest, AlternateFilename) {
  13826. auto handled = false;
  13827. Server svr;
  13828. svr.Post("/test", [&](const Request &req, Response &res) {
  13829. ASSERT_EQ(2u, req.form.files.size());
  13830. ASSERT_EQ(1u, req.form.fields.size());
  13831. // Test files
  13832. const auto &file1 = req.form.get_file("file1");
  13833. ASSERT_EQ("file1", file1.name);
  13834. ASSERT_EQ("A.txt", file1.filename);
  13835. ASSERT_EQ("text/plain", file1.content_type);
  13836. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  13837. const auto &file2 = req.form.get_file("file2");
  13838. ASSERT_EQ("file2", file2.name);
  13839. ASSERT_EQ("a.html", file2.filename);
  13840. ASSERT_EQ("text/html", file2.content_type);
  13841. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  13842. file2.content);
  13843. // Test text field
  13844. const auto &text = req.form.get_field("text");
  13845. ASSERT_EQ("text default", text);
  13846. res.set_content("ok", "text/plain");
  13847. handled = true;
  13848. });
  13849. thread t = thread([&] { svr.listen(HOST, PORT); });
  13850. auto se = detail::scope_exit([&] {
  13851. svr.stop();
  13852. t.join();
  13853. ASSERT_FALSE(svr.is_running());
  13854. ASSERT_TRUE(handled);
  13855. });
  13856. svr.wait_until_ready();
  13857. auto req = "POST /test HTTP/1.1\r\n"
  13858. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13859. "Content-Length: 399\r\n"
  13860. "\r\n"
  13861. "----------\r\n"
  13862. "Content-Disposition: form-data; name=\"text\"\r\n"
  13863. "\r\n"
  13864. "text default\r\n"
  13865. "----------\r\n"
  13866. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  13867. "filename=\"a.txt\"; name=\"file1\"\r\n"
  13868. "Content-Type: text/plain\r\n"
  13869. "\r\n"
  13870. "Content of a.txt.\r\n"
  13871. "\r\n"
  13872. "----------\r\n"
  13873. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  13874. "\"a.html\"\r\n"
  13875. "Content-Type: text/html\r\n"
  13876. "\r\n"
  13877. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  13878. "\r\n"
  13879. "------------\r\n";
  13880. ASSERT_TRUE(send_request(1, req));
  13881. }
  13882. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  13883. auto handled = false;
  13884. Server svr;
  13885. svr.Post("/test", [&](const Request &req, Response &res) {
  13886. // Case-insensitive "utf-8''" prefix with a long value
  13887. const auto &file = req.form.get_file("file1");
  13888. ASSERT_EQ("file1", file.name);
  13889. // 8000 chars exercises both the Content-Disposition parser and the
  13890. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  13891. // Prior to the fix, std::regex_match on this header would cause O(N)
  13892. // stack recursion in libstdc++, leading to SIGSEGV.
  13893. std::string expected_filename(8000, 'A');
  13894. ASSERT_EQ(expected_filename, file.filename);
  13895. res.set_content("ok", "text/plain");
  13896. handled = true;
  13897. });
  13898. thread t = thread([&] { svr.listen(HOST, PORT); });
  13899. auto se = detail::scope_exit([&] {
  13900. svr.stop();
  13901. t.join();
  13902. ASSERT_FALSE(svr.is_running());
  13903. ASSERT_TRUE(handled);
  13904. });
  13905. svr.wait_until_ready();
  13906. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  13907. // Regression test for GHSA-qq6v-r583-3h69
  13908. std::string long_filename(8000, 'A');
  13909. std::string body = "----------\r\n"
  13910. "Content-Disposition: form-data; name=\"file1\"; "
  13911. "filename*=\"Utf-8''" +
  13912. long_filename +
  13913. "\"\r\n"
  13914. "\r\n"
  13915. "hello\r\n"
  13916. "------------\r\n";
  13917. auto req = "POST /test HTTP/1.1\r\n"
  13918. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13919. "Content-Length: " +
  13920. std::to_string(body.size()) + "\r\n\r\n" + body;
  13921. ASSERT_TRUE(send_request(1, req));
  13922. }
  13923. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  13924. auto handled = false;
  13925. Server svr;
  13926. svr.Post("/test", [&](const Request &req, Response &) {
  13927. ASSERT_EQ(2u, req.form.fields.size());
  13928. const auto &text1 = req.form.get_field("text1");
  13929. ASSERT_EQ("text1", text1);
  13930. const auto &text2 = req.form.get_field("text2");
  13931. ASSERT_EQ("text2", text2);
  13932. handled = true;
  13933. });
  13934. thread t = thread([&] { svr.listen(HOST, PORT); });
  13935. auto se = detail::scope_exit([&] {
  13936. svr.stop();
  13937. t.join();
  13938. ASSERT_FALSE(svr.is_running());
  13939. ASSERT_TRUE(handled);
  13940. });
  13941. svr.wait_until_ready();
  13942. auto req = "POST /test HTTP/1.1\r\n"
  13943. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13944. "Content-Length: 146\r\n"
  13945. "\r\n----------\r\n"
  13946. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13947. "\r\n"
  13948. "text1"
  13949. "\r\n----------\r\n"
  13950. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13951. "\r\n"
  13952. "text2"
  13953. "\r\n------------";
  13954. std::string response;
  13955. ASSERT_TRUE(send_request(1, req, &response));
  13956. ASSERT_EQ("200", response.substr(9, 3));
  13957. }
  13958. TEST(MultipartFormDataTest, ContentLength) {
  13959. auto handled = false;
  13960. Server svr;
  13961. svr.Post("/test", [&](const Request &req, Response &) {
  13962. ASSERT_EQ(2u, req.form.fields.size());
  13963. const auto &text1 = req.form.get_field("text1");
  13964. ASSERT_EQ("text1", text1);
  13965. const auto &text2 = req.form.get_field("text2");
  13966. ASSERT_EQ("text2", text2);
  13967. handled = true;
  13968. });
  13969. thread t = thread([&] { svr.listen(HOST, PORT); });
  13970. auto se = detail::scope_exit([&] {
  13971. svr.stop();
  13972. t.join();
  13973. ASSERT_FALSE(svr.is_running());
  13974. ASSERT_TRUE(handled);
  13975. });
  13976. svr.wait_until_ready();
  13977. auto req = "POST /test HTTP/1.1\r\n"
  13978. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13979. "Content-Length: 167\r\n"
  13980. "\r\n----------\r\n"
  13981. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13982. "Content-Length: 5\r\n"
  13983. "\r\n"
  13984. "text1"
  13985. "\r\n----------\r\n"
  13986. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13987. "\r\n"
  13988. "text2"
  13989. "\r\n------------\r\n";
  13990. std::string response;
  13991. ASSERT_TRUE(send_request(1, req, &response));
  13992. ASSERT_EQ("200", response.substr(9, 3));
  13993. }
  13994. TEST(MultipartFormDataTest, AccessPartHeaders) {
  13995. auto handled = false;
  13996. Server svr;
  13997. svr.Post("/test", [&](const Request &req, Response &) {
  13998. ASSERT_EQ(2u, req.form.fields.size());
  13999. const auto &text1 = req.form.get_field("text1");
  14000. ASSERT_EQ("text1", text1);
  14001. // TODO: Add header access for text fields if needed
  14002. const auto &text2 = req.form.get_field("text2");
  14003. ASSERT_EQ("text2", text2);
  14004. // TODO: Header access for text fields needs to be implemented
  14005. // auto &headers = it->second.headers;
  14006. // ASSERT_EQ(3U, headers.size());
  14007. // auto custom_header = headers.find("x-whatever");
  14008. // ASSERT_TRUE(custom_header != headers.end());
  14009. // ASSERT_NE("customvalue", custom_header->second);
  14010. // ASSERT_EQ("CustomValue", custom_header->second);
  14011. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  14012. handled = true;
  14013. });
  14014. thread t = thread([&] { svr.listen(HOST, PORT); });
  14015. auto se = detail::scope_exit([&] {
  14016. svr.stop();
  14017. t.join();
  14018. ASSERT_FALSE(svr.is_running());
  14019. ASSERT_TRUE(handled);
  14020. });
  14021. svr.wait_until_ready();
  14022. auto req = "POST /test HTTP/1.1\r\n"
  14023. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14024. "Content-Length: 232\r\n"
  14025. "\r\n----------\r\n"
  14026. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14027. "Content-Length: 5\r\n"
  14028. "X-Test: 1\r\n"
  14029. "\r\n"
  14030. "text1"
  14031. "\r\n----------\r\n"
  14032. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14033. "Content-Type: text/plain\r\n"
  14034. "X-Whatever: CustomValue\r\n"
  14035. "\r\n"
  14036. "text2"
  14037. "\r\n------------\r\n"
  14038. "That should be disregarded. Not even read";
  14039. std::string response;
  14040. ASSERT_TRUE(send_request(1, req, &response));
  14041. ASSERT_EQ("200", response.substr(9, 3));
  14042. }
  14043. TEST(MultipartFormDataTest, LargeHeader) {
  14044. auto handled = false;
  14045. Server svr;
  14046. svr.Post("/test", [&](const Request &req, Response &) {
  14047. ASSERT_EQ(1u, req.form.fields.size());
  14048. const auto &text = req.form.get_field("name1");
  14049. ASSERT_EQ("text1", text);
  14050. handled = true;
  14051. });
  14052. thread t = thread([&] { svr.listen(HOST, PORT); });
  14053. auto se = detail::scope_exit([&] {
  14054. svr.stop();
  14055. t.join();
  14056. ASSERT_FALSE(svr.is_running());
  14057. ASSERT_TRUE(handled);
  14058. });
  14059. svr.wait_until_ready();
  14060. auto boundary = std::string("cpp-httplib-multipart-data");
  14061. std::string content = "--" + boundary +
  14062. "\r\n"
  14063. "Content-Disposition: form-data; name=\"name1\"\r\n"
  14064. "\r\n"
  14065. "text1\r\n"
  14066. "--" +
  14067. boundary + "--\r\n";
  14068. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  14069. "Content-Type: multipart/form-data;boundary=" +
  14070. boundary +
  14071. "\r\n"
  14072. "Content-Length: " +
  14073. std::to_string(content.size()) +
  14074. "\r\n"
  14075. "Dummy-Header: ";
  14076. std::string header_suffix = "\r\n"
  14077. "\r\n";
  14078. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  14079. size_t header_dummy_size =
  14080. read_buff_size -
  14081. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  14082. auto header_dummy = std::string(header_dummy_size, '@');
  14083. auto req = header_prefix + header_dummy + header_suffix + content;
  14084. std::string response;
  14085. ASSERT_TRUE(send_request(1, req, &response));
  14086. ASSERT_EQ("200", response.substr(9, 3));
  14087. }
  14088. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  14089. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  14090. // (not chunked Transfer-Encoding) after the streaming refactor.
  14091. auto handled = false;
  14092. Server svr;
  14093. svr.Post("/upload", [&](const Request &req, Response &res) {
  14094. auto cl_it = req.headers.find("Content-Length");
  14095. EXPECT_TRUE(cl_it != req.headers.end());
  14096. auto te_it = req.headers.find("Transfer-Encoding");
  14097. EXPECT_TRUE(te_it == req.headers.end());
  14098. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  14099. res.set_content("ok", "text/plain");
  14100. handled = true;
  14101. });
  14102. auto port = svr.bind_to_any_port(HOST);
  14103. auto t = thread([&] { svr.listen_after_bind(); });
  14104. auto se = detail::scope_exit([&] {
  14105. svr.stop();
  14106. t.join();
  14107. ASSERT_FALSE(svr.is_running());
  14108. ASSERT_TRUE(handled);
  14109. });
  14110. svr.wait_until_ready();
  14111. UploadFormDataItems items = {
  14112. {"field1", "hello", "", "text/plain"},
  14113. {"file1", "world", "test.txt", "application/octet-stream"},
  14114. };
  14115. Client cli(HOST, port);
  14116. auto res = cli.Post("/upload", {}, items);
  14117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14118. EXPECT_EQ(StatusCode::OK_200, res->status);
  14119. }
  14120. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  14121. // Verify that make_multipart_content_provider coalesces many small segments
  14122. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  14123. constexpr size_t kItemCount = 1000;
  14124. UploadFormDataItems items;
  14125. items.reserve(kItemCount);
  14126. for (size_t i = 0; i < kItemCount; i++) {
  14127. items.push_back(
  14128. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14129. }
  14130. const std::string boundary = "----test-boundary";
  14131. auto content_length = detail::get_multipart_content_length(items, boundary);
  14132. auto provider = detail::make_multipart_content_provider(items, boundary);
  14133. // Drive the provider the same way write_content_with_progress does
  14134. size_t write_count = 0;
  14135. size_t total_bytes = 0;
  14136. DataSink sink;
  14137. size_t offset = 0;
  14138. sink.write = [&](const char *d, size_t l) -> bool {
  14139. (void)d;
  14140. write_count++;
  14141. total_bytes += l;
  14142. offset += l;
  14143. return true;
  14144. };
  14145. sink.is_writable = []() -> bool { return true; };
  14146. while (offset < content_length) {
  14147. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  14148. }
  14149. EXPECT_EQ(content_length, total_bytes);
  14150. // The total number of segments is 3 * kItemCount + 1 = 3001.
  14151. // With buffering into 64KB blocks, write_count should be much smaller.
  14152. auto segment_count = 3 * kItemCount + 1;
  14153. EXPECT_LT(write_count, segment_count / 10);
  14154. }
  14155. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  14156. // Integration test: send many UploadFormDataItems and verify the server
  14157. // receives all of them correctly (#2410).
  14158. constexpr size_t kItemCount = 500;
  14159. auto handled = false;
  14160. Server svr;
  14161. svr.Post("/upload", [&](const Request &req, Response &res) {
  14162. EXPECT_EQ(kItemCount, req.form.fields.size());
  14163. for (size_t i = 0; i < kItemCount; i++) {
  14164. auto key = "field" + std::to_string(i);
  14165. auto val = "value" + std::to_string(i);
  14166. auto it = req.form.fields.find(key);
  14167. if (it != req.form.fields.end()) {
  14168. EXPECT_EQ(val, it->second.content);
  14169. } else {
  14170. ADD_FAILURE() << "Missing field: " << key;
  14171. }
  14172. }
  14173. res.set_content("ok", "text/plain");
  14174. handled = true;
  14175. });
  14176. auto port = svr.bind_to_any_port(HOST);
  14177. auto t = thread([&] { svr.listen_after_bind(); });
  14178. auto se = detail::scope_exit([&] {
  14179. svr.stop();
  14180. t.join();
  14181. ASSERT_FALSE(svr.is_running());
  14182. ASSERT_TRUE(handled);
  14183. });
  14184. svr.wait_until_ready();
  14185. UploadFormDataItems items;
  14186. items.reserve(kItemCount);
  14187. for (size_t i = 0; i < kItemCount; i++) {
  14188. items.push_back(
  14189. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14190. }
  14191. Client cli(HOST, port);
  14192. auto res = cli.Post("/upload", items);
  14193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14194. EXPECT_EQ(StatusCode::OK_200, res->status);
  14195. }
  14196. TEST(MultipartFormDataTest, MakeFileProvider) {
  14197. // Verify make_file_provider sends a file's contents correctly.
  14198. const std::string file_content(4096, 'Z');
  14199. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  14200. {
  14201. std::ofstream ofs(tmp_path, std::ios::binary);
  14202. ofs.write(file_content.data(),
  14203. static_cast<std::streamsize>(file_content.size()));
  14204. }
  14205. auto handled = false;
  14206. Server svr;
  14207. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  14208. const ContentReader &content_reader) {
  14209. ASSERT_TRUE(req.is_multipart_form_data());
  14210. std::vector<FormData> items;
  14211. content_reader(
  14212. [&](const FormData &file) {
  14213. items.push_back(file);
  14214. return true;
  14215. },
  14216. [&](const char *data, size_t data_length) {
  14217. items.back().content.append(data, data_length);
  14218. return true;
  14219. });
  14220. ASSERT_EQ(1u, items.size());
  14221. EXPECT_EQ("myfile", items[0].name);
  14222. EXPECT_EQ("data.bin", items[0].filename);
  14223. EXPECT_EQ("application/octet-stream", items[0].content_type);
  14224. EXPECT_EQ(file_content, items[0].content);
  14225. handled = true;
  14226. });
  14227. auto port = svr.bind_to_any_port(HOST);
  14228. auto t = thread([&] { svr.listen_after_bind(); });
  14229. auto se = detail::scope_exit([&] {
  14230. svr.stop();
  14231. t.join();
  14232. ASSERT_FALSE(svr.is_running());
  14233. ASSERT_TRUE(handled);
  14234. std::remove(tmp_path.c_str());
  14235. });
  14236. svr.wait_until_ready();
  14237. FormDataProviderItems providers;
  14238. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  14239. "application/octet-stream"));
  14240. Client cli(HOST, port);
  14241. auto res = cli.Post("/upload", {}, {}, providers);
  14242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14243. EXPECT_EQ(StatusCode::OK_200, res->status);
  14244. }
  14245. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  14246. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  14247. // (100) headers is rejected with a 400 Bad Request response.
  14248. Server svr;
  14249. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14250. res.set_content("ok", "text/plain");
  14251. });
  14252. thread t = thread([&] { svr.listen(HOST, PORT); });
  14253. auto se = detail::scope_exit([&] {
  14254. svr.stop();
  14255. t.join();
  14256. ASSERT_FALSE(svr.is_running());
  14257. });
  14258. svr.wait_until_ready();
  14259. // Build a multipart part with 101 custom headers (exceeding
  14260. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  14261. std::stringstream body;
  14262. body << "--simpleboundary\r\n"
  14263. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  14264. for (int i = 0; i < 101; i++) {
  14265. body << "X-Custom-Header-" << i << ": value\r\n";
  14266. }
  14267. body << "\r\n"
  14268. << "value1\r\n"
  14269. << "--simpleboundary--\r\n";
  14270. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  14271. Client cli(HOST, PORT);
  14272. auto res = cli.Post("/post", body.str(), content_type.c_str());
  14273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14274. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14275. }
  14276. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  14277. // A body that never contains the declared boundary must not be accumulated
  14278. // while the parser waits for it. Buffering it would also make every read
  14279. // rescan everything seen so far, which is quadratic in the body size.
  14280. Server svr;
  14281. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14282. res.set_content("ok", "text/plain");
  14283. });
  14284. auto port = svr.bind_to_any_port(HOST);
  14285. thread t = thread([&] { svr.listen_after_bind(); });
  14286. auto se = detail::scope_exit([&] {
  14287. svr.stop();
  14288. t.join();
  14289. ASSERT_FALSE(svr.is_running());
  14290. });
  14291. svr.wait_until_ready();
  14292. Client cli(HOST, port);
  14293. cli.set_read_timeout(60, 0);
  14294. cli.set_write_timeout(60, 0);
  14295. // '-' is the worst case: it matches the first character of the boundary, so
  14296. // every position has to be checked against it.
  14297. auto post_dashes = [&](size_t size) {
  14298. const std::string body(size, '-');
  14299. auto start = std::chrono::steady_clock::now();
  14300. auto res =
  14301. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  14302. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  14303. std::chrono::steady_clock::now() - start)
  14304. .count();
  14305. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14306. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  14307. return ms;
  14308. };
  14309. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  14310. // Windows.
  14311. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  14312. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  14313. // Comparing the two sizes rather than checking an absolute duration keeps
  14314. // this meaningful across build types and CI load, both of which move the
  14315. // absolute numbers by more than an order of magnitude. Four times the bytes
  14316. // costs about four times the time when parsing is linear, and about sixteen
  14317. // times when the body is buffered and rescanned.
  14318. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  14319. EXPECT_LT(ms_16mb, ms_4mb * 10)
  14320. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  14321. << "ms, which suggests the body is being buffered and rescanned";
  14322. }
  14323. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  14324. // A boundary can only be followed by CRLF or by "--", so anything else is
  14325. // malformed no matter what comes next. The parser must say so right away
  14326. // instead of buffering the rest of the declared body.
  14327. Server svr;
  14328. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14329. res.set_content("ok", "text/plain");
  14330. });
  14331. auto port = svr.bind_to_any_port(HOST);
  14332. thread t = thread([&] { svr.listen_after_bind(); });
  14333. auto se = detail::scope_exit([&] {
  14334. svr.stop();
  14335. t.join();
  14336. ASSERT_FALSE(svr.is_running());
  14337. });
  14338. svr.wait_until_ready();
  14339. // Announce a 1 MB body but send only the malformed prefix. A parser that
  14340. // buffers instead of failing would still be waiting for the remaining bytes.
  14341. const std::string body = "--zzzz\r\n"
  14342. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14343. "\r\n"
  14344. "text1"
  14345. "\r\n--zzzzXX";
  14346. const std::string req = "POST /post HTTP/1.1\r\n"
  14347. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14348. "Content-Length: 1048576\r\n"
  14349. "\r\n" +
  14350. body;
  14351. std::string response;
  14352. ASSERT_TRUE(send_request(3, req, &response, port));
  14353. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  14354. EXPECT_EQ("400", response.substr(9, 3));
  14355. }
  14356. // Posts a multipart body split into two writes, so that the server sees the
  14357. // split at whatever offset the caller chose, and expects the single "text1"
  14358. // field to come through.
  14359. static void expect_split_multipart_ok(const std::string &body1,
  14360. const std::string &body2) {
  14361. auto handled = false;
  14362. Server svr;
  14363. svr.Post("/post", [&](const Request &req, Response &) {
  14364. EXPECT_EQ(1u, req.form.fields.size());
  14365. EXPECT_EQ("text1", req.form.get_field("text1"));
  14366. handled = true;
  14367. });
  14368. auto port = svr.bind_to_any_port(HOST);
  14369. thread t = thread([&] { svr.listen_after_bind(); });
  14370. auto se = detail::scope_exit([&] {
  14371. svr.stop();
  14372. t.join();
  14373. ASSERT_FALSE(svr.is_running());
  14374. ASSERT_TRUE(handled);
  14375. });
  14376. svr.wait_until_ready();
  14377. // "Connection: close" makes the server close once it has answered, so the
  14378. // response drain ends immediately instead of idling until the read timeout.
  14379. const std::string head =
  14380. "POST /post HTTP/1.1\r\n"
  14381. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14382. "Connection: close\r\n"
  14383. "Content-Length: " +
  14384. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  14385. std::string response;
  14386. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  14387. ASSERT_GE(response.size(), 12u) << "no response";
  14388. EXPECT_EQ("200", response.substr(9, 3));
  14389. }
  14390. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  14391. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  14392. // ignored, including when it does not arrive in the same read as the
  14393. // close-delimiter itself.
  14394. expect_split_multipart_ok("--zzzz\r\n"
  14395. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14396. "\r\n"
  14397. "text1"
  14398. "\r\n--zzzz--",
  14399. "\r\nthis epilogue must be ignored\r\n");
  14400. }
  14401. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  14402. // The initial boundary may be preceded by a preamble of any length and may
  14403. // straddle a read boundary. Discarding data while waiting for it must not
  14404. // throw away a partial boundary sitting at the end of the buffer.
  14405. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  14406. "zz\r\n"
  14407. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14408. "\r\n"
  14409. "text1"
  14410. "\r\n--zzzz--\r\n");
  14411. }
  14412. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  14413. // The received boundary was only checked for being non-empty, so it could be
  14414. // as long as a header is allowed to be. The parser scans the body for
  14415. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  14416. // costs a nearly full comparison at nearly every position, making the
  14417. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  14418. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  14419. Server svr;
  14420. svr.Post("/post", [](const Request &req, Response &res) {
  14421. EXPECT_EQ(1u, req.form.fields.size());
  14422. EXPECT_EQ("text1", req.form.get_field("text1"));
  14423. res.set_content("ok", "text/plain");
  14424. });
  14425. auto port = svr.bind_to_any_port(HOST);
  14426. thread t = thread([&] { svr.listen_after_bind(); });
  14427. auto se = detail::scope_exit([&] {
  14428. svr.stop();
  14429. t.join();
  14430. ASSERT_FALSE(svr.is_running());
  14431. });
  14432. svr.wait_until_ready();
  14433. Client cli(HOST, port);
  14434. auto post_with_boundary_of_length = [&](size_t len) {
  14435. const std::string boundary(len, 'a');
  14436. const std::string body =
  14437. "--" + boundary +
  14438. "\r\n"
  14439. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14440. "\r\n"
  14441. "text1"
  14442. "\r\n--" +
  14443. boundary + "--\r\n";
  14444. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  14445. };
  14446. auto res = post_with_boundary_of_length(70);
  14447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14448. EXPECT_EQ(StatusCode::OK_200, res->status);
  14449. res = post_with_boundary_of_length(71);
  14450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14451. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14452. }
  14453. TEST(MakeFileBodyTest, Basic) {
  14454. const std::string file_content(4096, 'Z');
  14455. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  14456. {
  14457. std::ofstream ofs(tmp_path, std::ios::binary);
  14458. ofs.write(file_content.data(),
  14459. static_cast<std::streamsize>(file_content.size()));
  14460. }
  14461. auto handled = false;
  14462. Server svr;
  14463. svr.Post("/upload", [&](const Request &req, Response &res) {
  14464. EXPECT_EQ(file_content, req.body);
  14465. handled = true;
  14466. res.status = StatusCode::OK_200;
  14467. });
  14468. auto port = svr.bind_to_any_port(HOST);
  14469. auto t = thread([&] { svr.listen_after_bind(); });
  14470. auto se = detail::scope_exit([&] {
  14471. svr.stop();
  14472. t.join();
  14473. ASSERT_FALSE(svr.is_running());
  14474. ASSERT_TRUE(handled);
  14475. std::remove(tmp_path.c_str());
  14476. });
  14477. svr.wait_until_ready();
  14478. auto fb = make_file_body(tmp_path);
  14479. ASSERT_GT(fb.first, 0u);
  14480. Client cli(HOST, port);
  14481. auto res =
  14482. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  14483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14484. EXPECT_EQ(StatusCode::OK_200, res->status);
  14485. }
  14486. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  14487. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  14488. {
  14489. std::ofstream ofs(path, std::ios::binary);
  14490. const std::string content(100, 'A');
  14491. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14492. }
  14493. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14494. auto body = make_file_body(path);
  14495. ASSERT_EQ(100u, body.first);
  14496. ASSERT_TRUE(static_cast<bool>(body.second));
  14497. // Rewritten shorter after its length was measured - and, on a server, after
  14498. // that length has already gone out as Content-Length.
  14499. {
  14500. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  14501. const std::string content(10, 'A');
  14502. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14503. }
  14504. std::string written;
  14505. DataSink sink;
  14506. sink.write = [&](const char *d, size_t l) {
  14507. written.append(d, l);
  14508. return true;
  14509. };
  14510. // The provider has to report failure. write_content_with_progress() advances
  14511. // its offset only by what was written, so a provider that returns true
  14512. // without completing the length it promised is called again straight away,
  14513. // and again.
  14514. EXPECT_FALSE(body.second(0, body.first, sink));
  14515. EXPECT_EQ(std::string(10, 'A'), written);
  14516. }
  14517. TEST(MakeFileBodyTest, WholeFileIsSent) {
  14518. const std::string path = "./httplib_test_make_file_body_whole.bin";
  14519. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  14520. {
  14521. std::ofstream ofs(path, std::ios::binary);
  14522. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14523. }
  14524. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14525. auto body = make_file_body(path);
  14526. ASSERT_EQ(content.size(), body.first);
  14527. ASSERT_TRUE(static_cast<bool>(body.second));
  14528. std::string written;
  14529. DataSink sink;
  14530. sink.write = [&](const char *d, size_t l) {
  14531. written.append(d, l);
  14532. return true;
  14533. };
  14534. EXPECT_TRUE(body.second(0, body.first, sink));
  14535. EXPECT_EQ(content, written);
  14536. }
  14537. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  14538. static constexpr unsigned int number_of_tasks{1000000};
  14539. std::atomic_uint count{0};
  14540. std::unique_ptr<TaskQueue> task_queue{
  14541. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  14542. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14543. auto queued = task_queue->enqueue(
  14544. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  14545. EXPECT_TRUE(queued);
  14546. }
  14547. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14548. task_queue->shutdown();
  14549. #else
  14550. EXPECT_NO_THROW(task_queue->shutdown());
  14551. #endif
  14552. EXPECT_EQ(number_of_tasks, count.load());
  14553. }
  14554. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  14555. static constexpr unsigned int number_of_tasks{1000000};
  14556. static constexpr unsigned int qlimit{2};
  14557. unsigned int queued_count{0};
  14558. std::atomic_uint count{0};
  14559. std::unique_ptr<TaskQueue> task_queue{
  14560. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  14561. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14562. if (task_queue->enqueue(
  14563. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  14564. queued_count++;
  14565. }
  14566. }
  14567. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14568. task_queue->shutdown();
  14569. #else
  14570. EXPECT_NO_THROW(task_queue->shutdown());
  14571. #endif
  14572. EXPECT_EQ(queued_count, count.load());
  14573. EXPECT_TRUE(queued_count <= number_of_tasks);
  14574. EXPECT_TRUE(queued_count >= qlimit);
  14575. }
  14576. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  14577. // Use a short idle timeout so a dynamic thread spawns, times out and
  14578. // exits during the test, and the pool keeps working afterwards.
  14579. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  14580. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  14581. /*idle_timeout_sec=*/1}};
  14582. std::atomic_uint count{0};
  14583. std::condition_variable cv;
  14584. std::mutex mtx;
  14585. bool release = false;
  14586. // Block the base thread so the second task spawns a dynamic thread.
  14587. EXPECT_TRUE(task_queue->enqueue([&] {
  14588. std::unique_lock<std::mutex> lock(mtx);
  14589. while (!release) {
  14590. cv.wait(lock);
  14591. }
  14592. count++;
  14593. }));
  14594. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14595. // Let the dynamic thread finish its task and exceed the idle timeout.
  14596. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  14597. {
  14598. std::unique_lock<std::mutex> lock(mtx);
  14599. release = true;
  14600. }
  14601. cv.notify_all();
  14602. // The pool must still accept and run tasks after the dynamic thread exited.
  14603. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14604. task_queue->shutdown();
  14605. EXPECT_EQ(3u, count.load());
  14606. }
  14607. TEST(TaskQueueTest, MaxQueuedRequests) {
  14608. static constexpr unsigned int qlimit{3};
  14609. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  14610. std::condition_variable sem_cv;
  14611. std::mutex sem_mtx;
  14612. int credits = 0;
  14613. bool queued;
  14614. /* Fill up the queue with tasks that will block until we give them credits to
  14615. * complete. */
  14616. for (unsigned int n = 0; n <= qlimit;) {
  14617. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  14618. std::unique_lock<std::mutex> lock(sem_mtx);
  14619. while (credits <= 0) {
  14620. sem_cv.wait(lock);
  14621. }
  14622. /* Consume the credit and signal the test code if they are all gone. */
  14623. if (--credits == 0) { sem_cv.notify_one(); }
  14624. });
  14625. if (n < qlimit) {
  14626. /* The first qlimit enqueues must succeed. */
  14627. EXPECT_TRUE(queued);
  14628. } else {
  14629. /* The last one will succeed only when the worker thread
  14630. * starts and dequeues the first blocking task. Although
  14631. * not necessary for the correctness of this test, we sleep for
  14632. * a short while to avoid busy waiting. */
  14633. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14634. }
  14635. if (queued) { n++; }
  14636. }
  14637. /* Further enqueues must fail since the queue is full. */
  14638. for (auto i = 0; i < 4; i++) {
  14639. queued = task_queue->enqueue([] {});
  14640. EXPECT_FALSE(queued);
  14641. }
  14642. /* Give the credits to allow the previous tasks to complete. */
  14643. {
  14644. std::unique_lock<std::mutex> lock(sem_mtx);
  14645. credits += qlimit + 1;
  14646. }
  14647. sem_cv.notify_all();
  14648. /* Wait for all the credits to be consumed. */
  14649. {
  14650. std::unique_lock<std::mutex> lock(sem_mtx);
  14651. while (credits > 0) {
  14652. sem_cv.wait(lock);
  14653. }
  14654. }
  14655. /* Check that we are able again to enqueue at least qlimit tasks. */
  14656. for (unsigned int i = 0; i < qlimit; i++) {
  14657. queued = task_queue->enqueue([] {});
  14658. EXPECT_TRUE(queued);
  14659. }
  14660. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14661. task_queue->shutdown();
  14662. #else
  14663. EXPECT_NO_THROW(task_queue->shutdown());
  14664. #endif
  14665. }
  14666. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  14667. Server svr;
  14668. std::string method;
  14669. std::string body;
  14670. auto has_content_length = false;
  14671. auto has_transfer_encoding = false;
  14672. std::atomic<int> bad_requests{0};
  14673. // Leftover body bytes get parsed as a malformed request and answered with
  14674. // 400
  14675. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  14676. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  14677. });
  14678. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  14679. res.set_redirect("/down", StatusCode::SeeOther_303);
  14680. });
  14681. svr.Get("/down", [&](const Request &req, Response &res) {
  14682. method = req.method;
  14683. body = req.body;
  14684. has_content_length = req.has_header("Content-Length");
  14685. has_transfer_encoding = req.has_header("Transfer-Encoding");
  14686. res.set_content("ok", "text/plain");
  14687. });
  14688. auto port = svr.bind_to_any_port(HOST);
  14689. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14690. auto se = detail::scope_exit([&] {
  14691. svr.stop();
  14692. thread.join();
  14693. ASSERT_FALSE(svr.is_running());
  14694. });
  14695. svr.wait_until_ready();
  14696. const std::string payload = "SECRET-BODY";
  14697. auto check = [&](Client &cli, const Result &res) {
  14698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14699. EXPECT_EQ(StatusCode::OK_200, res->status);
  14700. EXPECT_EQ("ok", res->body);
  14701. EXPECT_EQ("GET", method);
  14702. EXPECT_TRUE(body.empty());
  14703. EXPECT_FALSE(has_content_length);
  14704. EXPECT_FALSE(has_transfer_encoding);
  14705. // Nothing of the original body may be left on the connection
  14706. auto res2 = cli.Get("/down");
  14707. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  14708. EXPECT_EQ(StatusCode::OK_200, res2->status);
  14709. EXPECT_EQ("ok", res2->body);
  14710. EXPECT_EQ(0, bad_requests);
  14711. };
  14712. // With content length
  14713. {
  14714. Client cli(HOST, port);
  14715. cli.set_keep_alive(true);
  14716. cli.set_follow_location(true);
  14717. auto res = cli.Post(
  14718. "/up", payload.size(),
  14719. [&](size_t offset, size_t length, DataSink &sink) {
  14720. return sink.write(payload.data() + offset, length);
  14721. },
  14722. "text/plain");
  14723. check(cli, res);
  14724. }
  14725. // Without content length (chunked)
  14726. {
  14727. Client cli(HOST, port);
  14728. cli.set_keep_alive(true);
  14729. cli.set_follow_location(true);
  14730. auto res = cli.Post(
  14731. "/up",
  14732. [&](size_t /*offset*/, DataSink &sink) {
  14733. sink.write(payload.data(), payload.size());
  14734. sink.done();
  14735. return true;
  14736. },
  14737. "text/plain");
  14738. check(cli, res);
  14739. }
  14740. }
  14741. TEST(RedirectTest, LocationPathIsNotDecoded) {
  14742. Server svr;
  14743. std::string target;
  14744. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  14745. // Echo the still-encoded name back in the Location
  14746. const std::string prefix = "/start/";
  14747. res.status = StatusCode::Found_302;
  14748. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  14749. });
  14750. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  14751. target = req.target;
  14752. res.set_content("ok", "text/plain");
  14753. });
  14754. auto port = svr.bind_to_any_port(HOST);
  14755. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14756. auto se = detail::scope_exit([&] {
  14757. svr.stop();
  14758. thread.join();
  14759. ASSERT_FALSE(svr.is_running());
  14760. });
  14761. svr.wait_until_ready();
  14762. // Decoding the Location path would turn the first four into a path
  14763. // separator, a query delimiter, a fragment delimiter and a different
  14764. // percent-encoded octet. The rest must keep reaching the server as they are.
  14765. const std::vector<std::string> names = {
  14766. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  14767. };
  14768. for (auto path_encode : {true, false}) {
  14769. Client cli(HOST, port);
  14770. cli.set_follow_location(true);
  14771. cli.set_path_encode(path_encode);
  14772. for (const auto &name : names) {
  14773. target.clear();
  14774. auto res = cli.Get("/start/" + name);
  14775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14776. EXPECT_EQ(StatusCode::OK_200, res->status);
  14777. EXPECT_EQ("/dest/" + name, target);
  14778. }
  14779. }
  14780. }
  14781. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  14782. Server svr;
  14783. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14784. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  14785. });
  14786. svr.Get("/hello", [](const Request &req, Response &res) {
  14787. res.set_content(req.get_param_value("key"), "text/plain");
  14788. });
  14789. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14790. auto se = detail::scope_exit([&] {
  14791. svr.stop();
  14792. thread.join();
  14793. ASSERT_FALSE(svr.is_running());
  14794. });
  14795. svr.wait_until_ready();
  14796. {
  14797. Client cli(HOST, PORT);
  14798. cli.set_follow_location(true);
  14799. auto res = cli.Get("/");
  14800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14801. EXPECT_EQ(StatusCode::OK_200, res->status);
  14802. EXPECT_EQ("val&key2=val2", res->body);
  14803. }
  14804. }
  14805. #endif
  14806. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  14807. Server svr;
  14808. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14809. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  14810. });
  14811. svr.Get("/hello", [](const Request &req, Response &res) {
  14812. res.set_content(req.get_param_value("key"), "text/plain");
  14813. });
  14814. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14815. auto se = detail::scope_exit([&] {
  14816. svr.stop();
  14817. thread.join();
  14818. ASSERT_FALSE(svr.is_running());
  14819. });
  14820. svr.wait_until_ready();
  14821. {
  14822. Client cli(HOST, PORT);
  14823. cli.set_follow_location(true);
  14824. auto res = cli.Get("/");
  14825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14826. EXPECT_EQ(StatusCode::OK_200, res->status);
  14827. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  14828. }
  14829. }
  14830. TEST(RedirectTest, RedirectWithPlusInPath) {
  14831. Server svr;
  14832. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14833. res.set_redirect("/a+b");
  14834. });
  14835. // Route pattern uses regex; escape + as \\+
  14836. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  14837. res.set_content(req.path, "text/plain");
  14838. });
  14839. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14840. auto se = detail::scope_exit([&] {
  14841. svr.stop();
  14842. thread.join();
  14843. ASSERT_FALSE(svr.is_running());
  14844. });
  14845. svr.wait_until_ready();
  14846. {
  14847. Client cli(HOST, PORT);
  14848. cli.set_follow_location(true);
  14849. auto res = cli.Get("/");
  14850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14851. EXPECT_EQ(StatusCode::OK_200, res->status);
  14852. EXPECT_EQ("/a+b", res->body);
  14853. }
  14854. }
  14855. TEST(RedirectTest, ResolveRelativeLocation) {
  14856. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  14857. const std::vector<std::pair<std::string, std::string>> cases = {
  14858. {"g", "/b/c/g"},
  14859. {"./g", "/b/c/g"},
  14860. {"g/", "/b/c/g/"},
  14861. {"?y", "/b/c/d;p?y"},
  14862. {"g?y", "/b/c/g?y"},
  14863. {"#s", "/b/c/d;p?q#s"},
  14864. {"g#s", "/b/c/g#s"},
  14865. {"g?y#s", "/b/c/g?y#s"},
  14866. {";x", "/b/c/;x"},
  14867. {"g;x", "/b/c/g;x"},
  14868. {".", "/b/c/"},
  14869. {"./", "/b/c/"},
  14870. {"..", "/b/"},
  14871. {"../", "/b/"},
  14872. {"../g", "/b/g"},
  14873. {"../..", "/"},
  14874. {"../../", "/"},
  14875. {"../../g", "/g"},
  14876. {"../../../g", "/g"},
  14877. {"g.", "/b/c/g."},
  14878. {".g", "/b/c/.g"},
  14879. {"g..", "/b/c/g.."},
  14880. {"..g", "/b/c/..g"},
  14881. {"./../g", "/b/g"},
  14882. {"./g/.", "/b/c/g/"},
  14883. {"g/./h", "/b/c/g/h"},
  14884. {"g/../h", "/b/c/h"},
  14885. {"g;x=1/./y", "/b/c/g;x=1/y"},
  14886. {"g;x=1/../y", "/b/c/y"},
  14887. {"g?y/./x", "/b/c/g?y/./x"},
  14888. {"g#s/../x", "/b/c/g#s/../x"},
  14889. // Not relative-path references, so left for parse_url.
  14890. {"/g", "/g"},
  14891. {"//g", "//g"},
  14892. {"http://g/x", "http://g/x"},
  14893. {"g:h", "g:h"},
  14894. };
  14895. for (const auto &c : cases) {
  14896. EXPECT_EQ(c.second,
  14897. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  14898. << c.first;
  14899. }
  14900. }
  14901. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  14902. Server svr;
  14903. svr.Get("/dir/page", [](const Request &req, Response &res) {
  14904. res.set_redirect(req.get_param_value("to"));
  14905. });
  14906. svr.Get("/dir/next", [](const Request &req, Response &res) {
  14907. res.set_content(req.target, "text/plain");
  14908. });
  14909. svr.Get("/other", [](const Request &req, Response &res) {
  14910. res.set_content(req.target, "text/plain");
  14911. });
  14912. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14913. auto se = detail::scope_exit([&] {
  14914. svr.stop();
  14915. thread.join();
  14916. ASSERT_FALSE(svr.is_running());
  14917. });
  14918. svr.wait_until_ready();
  14919. const std::vector<std::pair<std::string, std::string>> cases = {
  14920. {"next", "/dir/next"},
  14921. {"./next?x=1", "/dir/next?x=1"},
  14922. {"../other", "/other"},
  14923. };
  14924. for (const auto &c : cases) {
  14925. Client cli(HOST, PORT);
  14926. cli.set_follow_location(true);
  14927. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  14928. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  14929. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  14930. EXPECT_EQ(c.second, res->body) << c.first;
  14931. }
  14932. }
  14933. #ifdef CPPHTTPLIB_SSL_ENABLED
  14934. TEST(RedirectTest, Issue2185_Online) {
  14935. SSLClient client("github.com");
  14936. client.set_follow_location(true);
  14937. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  14938. "Coollab-Windows.zip");
  14939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14940. EXPECT_EQ(StatusCode::OK_200, res->status);
  14941. EXPECT_EQ(9920427U, res->body.size());
  14942. }
  14943. #endif
  14944. TEST(VulnerabilityTest, CRLFInjection) {
  14945. Server svr;
  14946. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  14947. res.set_content("Hello 1", "text/plain");
  14948. });
  14949. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  14950. res.set_content("Hello 2", "text/plain");
  14951. });
  14952. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  14953. res.set_content("Hello 3", "text/plain");
  14954. });
  14955. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  14956. res.set_content("Hello 4", "text/plain");
  14957. });
  14958. svr.set_logger([](const Request &req, const Response & /*res*/) {
  14959. for (const auto &x : req.headers) {
  14960. auto key = x.first;
  14961. EXPECT_STRNE("evil", key.c_str());
  14962. }
  14963. });
  14964. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14965. auto se = detail::scope_exit([&] {
  14966. svr.stop();
  14967. thread.join();
  14968. ASSERT_FALSE(svr.is_running());
  14969. });
  14970. svr.wait_until_ready();
  14971. {
  14972. Client cli(HOST, PORT);
  14973. cli.Post("/test1", "A=B",
  14974. "application/x-www-form-urlencoded\r\nevil: hello1");
  14975. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  14976. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  14977. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  14978. }
  14979. }
  14980. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  14981. auto server_thread = std::thread([] {
  14982. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14983. default_socket_options(srv);
  14984. sockaddr_in addr{};
  14985. addr.sin_family = AF_INET;
  14986. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  14987. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14988. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  14989. ::listen(srv, 1);
  14990. sockaddr_in cli_addr{};
  14991. socklen_t cli_len = sizeof(cli_addr);
  14992. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14993. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  14994. std::string buf_all;
  14995. char buf[2048];
  14996. ssize_t n;
  14997. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  14998. buf_all.append(buf, static_cast<size_t>(n));
  14999. size_t pos;
  15000. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  15001. auto request_block = buf_all.substr(0, pos + 4); // include separator
  15002. auto e = request_block.find("\r\n");
  15003. if (e != std::string::npos) {
  15004. auto request_line = request_block.substr(0, e);
  15005. std::string msg =
  15006. "CRLF injection detected in request line: '" + request_line + "'";
  15007. EXPECT_FALSE(true) << msg;
  15008. }
  15009. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  15010. ::send(cli,
  15011. #ifdef _WIN32
  15012. static_cast<const char *>(resp.c_str()),
  15013. static_cast<int>(resp.size()),
  15014. #else
  15015. resp.c_str(), resp.size(),
  15016. #endif
  15017. 0);
  15018. buf_all.erase(0, pos + 4);
  15019. }
  15020. }
  15021. detail::close_socket(cli);
  15022. detail::close_socket(srv);
  15023. });
  15024. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15025. auto cli = Client("127.0.0.1", PORT + 1);
  15026. auto headers = Headers{
  15027. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  15028. {"Connection", "keep-alive"}};
  15029. auto res = cli.Get("/hi", headers);
  15030. EXPECT_FALSE(res);
  15031. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15032. server_thread.join();
  15033. }
  15034. // A request rejected before any byte reaches the socket must fail right away
  15035. // instead of waiting for a response the server will never send.
  15036. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  15037. // The kernel completes the TCP handshake from the listen backlog, so the
  15038. // client connects, but nothing ever reads, responds or closes.
  15039. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15040. default_socket_options(srv);
  15041. sockaddr_in addr{};
  15042. addr.sin_family = AF_INET;
  15043. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15044. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15045. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15046. ASSERT_EQ(0, ::listen(srv, 8));
  15047. auto cli = Client("127.0.0.1", PORT + 1);
  15048. cli.set_read_timeout(10, 0);
  15049. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  15050. return std::chrono::duration_cast<std::chrono::milliseconds>(
  15051. std::chrono::steady_clock::now() - start)
  15052. .count();
  15053. };
  15054. {
  15055. Request req;
  15056. req.method = "GE T";
  15057. req.path = "/";
  15058. auto start = std::chrono::steady_clock::now();
  15059. auto res = cli.send(req);
  15060. EXPECT_FALSE(res);
  15061. EXPECT_EQ(Error::Write, res.error());
  15062. EXPECT_LT(elapsed_ms(start), 1000);
  15063. }
  15064. {
  15065. auto start = std::chrono::steady_clock::now();
  15066. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  15067. EXPECT_FALSE(res);
  15068. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15069. EXPECT_LT(elapsed_ms(start), 1000);
  15070. }
  15071. EXPECT_FALSE(cli.is_socket_open());
  15072. detail::close_socket(srv);
  15073. }
  15074. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  15075. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15076. default_socket_options(srv);
  15077. sockaddr_in addr{};
  15078. addr.sin_family = AF_INET;
  15079. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15080. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15081. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15082. ASSERT_EQ(0, ::listen(srv, 1));
  15083. std::string received;
  15084. auto server_thread = std::thread([&] {
  15085. auto sock = ::accept(srv, nullptr, nullptr);
  15086. if (sock == INVALID_SOCKET) { return; }
  15087. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  15088. char buf[2048];
  15089. ssize_t n;
  15090. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  15091. received.append(buf, static_cast<size_t>(n));
  15092. }
  15093. detail::close_socket(sock);
  15094. });
  15095. {
  15096. auto cli = Client("127.0.0.1", PORT + 1);
  15097. // "Z" sorts after the default headers, so writing straight to the socket
  15098. // would have sent the request line and those headers before the rejection.
  15099. auto handle =
  15100. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  15101. EXPECT_FALSE(handle.is_valid());
  15102. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  15103. }
  15104. server_thread.join();
  15105. detail::close_socket(srv);
  15106. EXPECT_TRUE(received.empty()) << received;
  15107. }
  15108. TEST(PathParamsTest, StaticMatch) {
  15109. const auto pattern = "/users/all";
  15110. detail::PathParamsMatcher matcher(pattern);
  15111. Request request;
  15112. request.path = "/users/all";
  15113. ASSERT_TRUE(matcher.match(request));
  15114. std::unordered_map<std::string, std::string> expected_params = {};
  15115. EXPECT_EQ(request.path_params, expected_params);
  15116. }
  15117. TEST(PathParamsTest, StaticMismatch) {
  15118. const auto pattern = "/users/all";
  15119. detail::PathParamsMatcher matcher(pattern);
  15120. Request request;
  15121. request.path = "/users/1";
  15122. ASSERT_FALSE(matcher.match(request));
  15123. }
  15124. TEST(PathParamsTest, SingleParamInTheMiddle) {
  15125. const auto pattern = "/users/:id/subscriptions";
  15126. detail::PathParamsMatcher matcher(pattern);
  15127. Request request;
  15128. request.path = "/users/42/subscriptions";
  15129. ASSERT_TRUE(matcher.match(request));
  15130. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15131. EXPECT_EQ(request.path_params, expected_params);
  15132. }
  15133. TEST(PathParamsTest, SingleParamInTheEnd) {
  15134. const auto pattern = "/users/:id";
  15135. detail::PathParamsMatcher matcher(pattern);
  15136. Request request;
  15137. request.path = "/users/24";
  15138. ASSERT_TRUE(matcher.match(request));
  15139. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  15140. EXPECT_EQ(request.path_params, expected_params);
  15141. }
  15142. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  15143. const auto pattern = "/users/:id/";
  15144. detail::PathParamsMatcher matcher(pattern);
  15145. Request request;
  15146. request.path = "/users/42/";
  15147. ASSERT_TRUE(matcher.match(request));
  15148. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15149. EXPECT_EQ(request.path_params, expected_params);
  15150. }
  15151. TEST(PathParamsTest, EmptyParam) {
  15152. const auto pattern = "/users/:id/";
  15153. detail::PathParamsMatcher matcher(pattern);
  15154. Request request;
  15155. request.path = "/users//";
  15156. ASSERT_TRUE(matcher.match(request));
  15157. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  15158. EXPECT_EQ(request.path_params, expected_params);
  15159. }
  15160. TEST(PathParamsTest, FragmentMismatch) {
  15161. const auto pattern = "/users/:id/";
  15162. detail::PathParamsMatcher matcher(pattern);
  15163. Request request;
  15164. request.path = "/admins/24/";
  15165. ASSERT_FALSE(matcher.match(request));
  15166. }
  15167. TEST(PathParamsTest, ExtraFragments) {
  15168. const auto pattern = "/users/:id";
  15169. detail::PathParamsMatcher matcher(pattern);
  15170. Request request;
  15171. request.path = "/users/42/subscriptions";
  15172. ASSERT_FALSE(matcher.match(request));
  15173. }
  15174. TEST(PathParamsTest, MissingTrailingParam) {
  15175. const auto pattern = "/users/:id";
  15176. detail::PathParamsMatcher matcher(pattern);
  15177. Request request;
  15178. request.path = "/users";
  15179. ASSERT_FALSE(matcher.match(request));
  15180. }
  15181. TEST(PathParamsTest, MissingParamInTheMiddle) {
  15182. const auto pattern = "/users/:id/subscriptions";
  15183. detail::PathParamsMatcher matcher(pattern);
  15184. Request request;
  15185. request.path = "/users/subscriptions";
  15186. ASSERT_FALSE(matcher.match(request));
  15187. }
  15188. TEST(PathParamsTest, MultipleParams) {
  15189. const auto pattern = "/users/:userid/subscriptions/:subid";
  15190. detail::PathParamsMatcher matcher(pattern);
  15191. Request request;
  15192. request.path = "/users/42/subscriptions/2";
  15193. ASSERT_TRUE(matcher.match(request));
  15194. std::unordered_map<std::string, std::string> expected_params = {
  15195. {"userid", "42"}, {"subid", "2"}};
  15196. EXPECT_EQ(request.path_params, expected_params);
  15197. }
  15198. TEST(PathParamsTest, SequenceOfParams) {
  15199. const auto pattern = "/values/:x/:y/:z";
  15200. detail::PathParamsMatcher matcher(pattern);
  15201. Request request;
  15202. request.path = "/values/1/2/3";
  15203. ASSERT_TRUE(matcher.match(request));
  15204. std::unordered_map<std::string, std::string> expected_params = {
  15205. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  15206. EXPECT_EQ(request.path_params, expected_params);
  15207. }
  15208. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  15209. const auto pattern = "/prefix:suffix";
  15210. detail::PathParamsMatcher matcher(pattern);
  15211. Request request;
  15212. request.path = "/prefix:suffix";
  15213. ASSERT_TRUE(matcher.match(request));
  15214. const std::unordered_map<std::string, std::string> expected_params = {};
  15215. EXPECT_EQ(request.path_params, expected_params);
  15216. }
  15217. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  15218. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  15219. // calling thread's stack on a long enough path for a quantified pattern;
  15220. // RegexMatcher must refuse to run regex matching on paths beyond
  15221. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  15222. detail::RegexMatcher matcher("/files/(.*)");
  15223. Request within_limit;
  15224. within_limit.path = "/files/" + std::string(10, 'A');
  15225. EXPECT_TRUE(matcher.match(within_limit));
  15226. Request over_limit;
  15227. over_limit.path =
  15228. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  15229. EXPECT_FALSE(matcher.match(over_limit));
  15230. }
  15231. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  15232. Server svr;
  15233. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  15234. res.set_content("ok", "text/plain");
  15235. });
  15236. auto port = svr.bind_to_any_port(HOST);
  15237. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15238. auto se = detail::scope_exit([&] {
  15239. svr.stop();
  15240. thread.join();
  15241. ASSERT_FALSE(svr.is_running());
  15242. });
  15243. svr.wait_until_ready();
  15244. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  15245. // request URI limit; this used to be able to crash the process.
  15246. std::string path =
  15247. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  15248. std::string req = "GET " + path +
  15249. " HTTP/1.1\r\n"
  15250. "Host: " +
  15251. std::string(HOST) + ":" + std::to_string(port) +
  15252. "\r\n"
  15253. "Connection: close\r\n"
  15254. "\r\n";
  15255. std::string response;
  15256. ASSERT_TRUE(send_request(5, req, &response, port));
  15257. EXPECT_NE(std::string::npos, response.find("404"));
  15258. }
  15259. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  15260. Server svr;
  15261. auto handler = [](const Request & /*req*/, Response &res) {
  15262. res.set_content("hit", "text/plain");
  15263. };
  15264. // No regex metacharacter, so this one is compared literally
  15265. svr.Get("/literal/route", handler);
  15266. // '.' is a regex metacharacter, so this one must keep regex semantics
  15267. svr.Get("/a.c", handler);
  15268. auto port = svr.bind_to_any_port(HOST);
  15269. std::thread t([&]() { svr.listen_after_bind(); });
  15270. auto se = detail::scope_exit([&] {
  15271. svr.stop();
  15272. t.join();
  15273. ASSERT_FALSE(svr.is_running());
  15274. });
  15275. svr.wait_until_ready();
  15276. Client cli(HOST, port);
  15277. struct {
  15278. const char *path;
  15279. int status;
  15280. } cases[] = {
  15281. {"/literal/route", StatusCode::OK_200},
  15282. {"/literal/routes", StatusCode::NotFound_404},
  15283. {"/literal/rout", StatusCode::NotFound_404},
  15284. {"/abc", StatusCode::OK_200},
  15285. {"/a.c", StatusCode::OK_200},
  15286. };
  15287. for (const auto &x : cases) {
  15288. auto res = cli.Get(x.path);
  15289. ASSERT_TRUE(res) << x.path;
  15290. EXPECT_EQ(x.status, res->status) << x.path;
  15291. }
  15292. }
  15293. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  15294. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  15295. // from exhausting the stack, so it must only constrain routes that actually
  15296. // run a regular expression. A literal route is matched by comparison and
  15297. // stays usable at any length.
  15298. Server svr;
  15299. const std::string pattern =
  15300. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  15301. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  15302. res.set_content("hit", "text/plain");
  15303. });
  15304. auto port = svr.bind_to_any_port(HOST);
  15305. std::thread t([&]() { svr.listen_after_bind(); });
  15306. auto se = detail::scope_exit([&] {
  15307. svr.stop();
  15308. t.join();
  15309. ASSERT_FALSE(svr.is_running());
  15310. });
  15311. svr.wait_until_ready();
  15312. Client cli(HOST, port);
  15313. auto res = cli.Get(pattern);
  15314. ASSERT_TRUE(res);
  15315. EXPECT_EQ(StatusCode::OK_200, res->status);
  15316. }
  15317. TEST(ParseUrlTest, VariousPatterns) {
  15318. {
  15319. detail::UrlComponents uc;
  15320. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  15321. EXPECT_EQ("http", uc.scheme);
  15322. EXPECT_EQ("example.com", uc.host);
  15323. EXPECT_EQ("8080", uc.port);
  15324. EXPECT_EQ("/path", uc.path);
  15325. EXPECT_EQ("?q=1", uc.query);
  15326. }
  15327. {
  15328. detail::UrlComponents uc;
  15329. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  15330. EXPECT_EQ("https", uc.scheme);
  15331. EXPECT_EQ("example.com", uc.host);
  15332. EXPECT_TRUE(uc.port.empty());
  15333. EXPECT_EQ("/path", uc.path);
  15334. }
  15335. {
  15336. detail::UrlComponents uc;
  15337. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  15338. EXPECT_EQ("::1", uc.host);
  15339. EXPECT_EQ("8080", uc.port);
  15340. EXPECT_EQ("/path", uc.path);
  15341. }
  15342. {
  15343. detail::UrlComponents uc;
  15344. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  15345. }
  15346. {
  15347. // Bytes after the IPv6 literal must be a delimiter, not folded into
  15348. // the path while the connection still targets the bracketed host.
  15349. detail::UrlComponents uc;
  15350. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  15351. }
  15352. {
  15353. detail::UrlComponents uc;
  15354. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  15355. }
  15356. {
  15357. detail::UrlComponents uc;
  15358. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  15359. EXPECT_EQ("::1", uc.host);
  15360. EXPECT_TRUE(uc.port.empty());
  15361. EXPECT_EQ("/path", uc.path);
  15362. }
  15363. {
  15364. detail::UrlComponents uc;
  15365. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  15366. EXPECT_TRUE(uc.scheme.empty());
  15367. EXPECT_EQ("example.com", uc.host);
  15368. EXPECT_EQ("/path", uc.path);
  15369. EXPECT_EQ("?q=1", uc.query);
  15370. }
  15371. {
  15372. detail::UrlComponents uc;
  15373. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  15374. EXPECT_TRUE(uc.host.empty());
  15375. EXPECT_EQ("/path", uc.path);
  15376. EXPECT_EQ("?q=1", uc.query);
  15377. }
  15378. {
  15379. detail::UrlComponents uc;
  15380. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  15381. EXPECT_EQ("example.com", uc.host);
  15382. EXPECT_EQ("8080", uc.port);
  15383. }
  15384. {
  15385. // Unix socket path — must not be parsed as host
  15386. detail::UrlComponents uc;
  15387. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  15388. EXPECT_TRUE(uc.host.empty());
  15389. }
  15390. {
  15391. detail::UrlComponents uc;
  15392. ASSERT_TRUE(detail::parse_url("", uc));
  15393. EXPECT_TRUE(uc.host.empty());
  15394. EXPECT_TRUE(uc.path.empty());
  15395. }
  15396. {
  15397. detail::UrlComponents uc;
  15398. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  15399. }
  15400. {
  15401. detail::UrlComponents uc;
  15402. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  15403. }
  15404. {
  15405. // Accepted by parse_url; callers restrict to http/https
  15406. detail::UrlComponents uc;
  15407. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  15408. EXPECT_EQ("ftp", uc.scheme);
  15409. }
  15410. {
  15411. detail::UrlComponents uc;
  15412. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  15413. }
  15414. {
  15415. detail::UrlComponents uc;
  15416. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  15417. }
  15418. }
  15419. TEST(ParseUrlTest, FragmentHandling) {
  15420. {
  15421. detail::UrlComponents uc;
  15422. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  15423. EXPECT_EQ("/path", uc.path);
  15424. EXPECT_TRUE(uc.query.empty());
  15425. }
  15426. {
  15427. detail::UrlComponents uc;
  15428. ASSERT_TRUE(detail::parse_url("#frag", uc));
  15429. EXPECT_TRUE(uc.path.empty());
  15430. EXPECT_TRUE(uc.query.empty());
  15431. }
  15432. }
  15433. TEST(ParseUrlTest, UserinfoHandling) {
  15434. // Userinfo with @ but no colon — host includes @
  15435. detail::UrlComponents uc;
  15436. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  15437. EXPECT_EQ("user@host.com", uc.host);
  15438. EXPECT_EQ("/path", uc.path);
  15439. }
  15440. TEST(ParseUrlTest, IPv6EdgeCases) {
  15441. {
  15442. detail::UrlComponents uc;
  15443. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  15444. EXPECT_TRUE(uc.scheme.empty());
  15445. EXPECT_EQ("::1", uc.host);
  15446. EXPECT_EQ("8080", uc.port);
  15447. }
  15448. {
  15449. // Zone ID '%25' is not in [a-fA-F0-9:]
  15450. detail::UrlComponents uc;
  15451. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  15452. }
  15453. }
  15454. TEST(ParseUrlTest, SchemeEdgeCases) {
  15455. {
  15456. detail::UrlComponents uc;
  15457. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  15458. }
  15459. {
  15460. detail::UrlComponents uc;
  15461. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  15462. }
  15463. {
  15464. detail::UrlComponents uc;
  15465. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  15466. }
  15467. }
  15468. TEST(ParseUrlTest, PortEdgeCases) {
  15469. {
  15470. detail::UrlComponents uc;
  15471. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  15472. EXPECT_TRUE(uc.port.empty());
  15473. EXPECT_EQ("/path", uc.path);
  15474. }
  15475. {
  15476. // parse_url accepts any port string; validation is done by parse_port
  15477. detail::UrlComponents uc;
  15478. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  15479. EXPECT_EQ("abc", uc.port);
  15480. }
  15481. }
  15482. TEST(ParseUrlTest, WebSocketPatterns) {
  15483. {
  15484. detail::UrlComponents uc;
  15485. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  15486. EXPECT_EQ("ws", uc.scheme);
  15487. EXPECT_EQ("echo.example.com", uc.host);
  15488. EXPECT_EQ("8080", uc.port);
  15489. EXPECT_EQ("/ws", uc.path);
  15490. }
  15491. {
  15492. detail::UrlComponents uc;
  15493. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  15494. EXPECT_EQ("wss", uc.scheme);
  15495. EXPECT_EQ("echo.example.com", uc.host);
  15496. EXPECT_TRUE(uc.port.empty());
  15497. EXPECT_EQ("/ws", uc.path);
  15498. }
  15499. }
  15500. TEST(ParseUrlTest, QueryOnly) {
  15501. detail::UrlComponents uc;
  15502. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  15503. EXPECT_TRUE(uc.host.empty());
  15504. EXPECT_TRUE(uc.path.empty());
  15505. EXPECT_EQ("?q=1&r=2", uc.query);
  15506. }
  15507. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  15508. detail::UrlComponents uc;
  15509. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  15510. EXPECT_TRUE(uc.scheme.empty());
  15511. EXPECT_EQ("example.com", uc.host);
  15512. EXPECT_EQ("443", uc.port);
  15513. EXPECT_EQ("/path", uc.path);
  15514. }
  15515. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  15516. // If ipv6 regex working, regex match codepath is taken.
  15517. // else port will default to 80 in Client impl
  15518. int clientImplMagicPort = 80;
  15519. int port = 4321;
  15520. // above ports must be different to avoid false negative
  15521. EXPECT_NE(clientImplMagicPort, port);
  15522. std::string ipV6TestURL = "http://[ff06::c3]";
  15523. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  15524. CLIENT_PRIVATE_KEY_FILE);
  15525. EXPECT_EQ(cli.port(), port);
  15526. }
  15527. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  15528. auto file_path = "./www/dir/index.html";
  15529. auto dir_path = "./www/dir";
  15530. detail::FileStat stat_file(file_path);
  15531. EXPECT_TRUE(stat_file.is_file());
  15532. EXPECT_FALSE(stat_file.is_dir());
  15533. detail::FileStat stat_dir(dir_path);
  15534. EXPECT_FALSE(stat_dir.is_file());
  15535. EXPECT_TRUE(stat_dir.is_dir());
  15536. }
  15537. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  15538. // IPv4 with default HTTP port (80)
  15539. EXPECT_EQ("example.com",
  15540. detail::make_host_and_port_string("example.com", 80, false));
  15541. // IPv4 with default HTTPS port (443)
  15542. EXPECT_EQ("example.com",
  15543. detail::make_host_and_port_string("example.com", 443, true));
  15544. // IPv4 with non-default HTTP port
  15545. EXPECT_EQ("example.com:8080",
  15546. detail::make_host_and_port_string("example.com", 8080, false));
  15547. // IPv4 with non-default HTTPS port
  15548. EXPECT_EQ("example.com:8443",
  15549. detail::make_host_and_port_string("example.com", 8443, true));
  15550. // IPv6 with default HTTP port (80)
  15551. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  15552. // IPv6 with default HTTPS port (443)
  15553. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  15554. // IPv6 with non-default HTTP port
  15555. EXPECT_EQ("[::1]:8080",
  15556. detail::make_host_and_port_string("::1", 8080, false));
  15557. // IPv6 with non-default HTTPS port
  15558. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  15559. // IPv6 full address with default port
  15560. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  15561. detail::make_host_and_port_string(
  15562. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  15563. // IPv6 full address with non-default port
  15564. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  15565. detail::make_host_and_port_string(
  15566. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  15567. // IPv6 localhost with non-default port
  15568. EXPECT_EQ("[::1]:3000",
  15569. detail::make_host_and_port_string("::1", 3000, false));
  15570. // IPv6 with zone ID (link-local address) with default port
  15571. EXPECT_EQ("[fe80::1%eth0]",
  15572. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  15573. // IPv6 with zone ID (link-local address) with non-default port
  15574. EXPECT_EQ("[fe80::1%eth0]:8080",
  15575. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  15576. // Edge case: Port 443 with is_ssl=false (should add port)
  15577. EXPECT_EQ("example.com:443",
  15578. detail::make_host_and_port_string("example.com", 443, false));
  15579. // Edge case: Port 80 with is_ssl=true (should add port)
  15580. EXPECT_EQ("example.com:80",
  15581. detail::make_host_and_port_string("example.com", 80, true));
  15582. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  15583. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  15584. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  15585. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  15586. // Security fix: Already bracketed IPv6 should not get double brackets
  15587. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  15588. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  15589. EXPECT_EQ("[::1]:8080",
  15590. detail::make_host_and_port_string("[::1]", 8080, false));
  15591. EXPECT_EQ("[2001:db8::1]:8080",
  15592. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  15593. EXPECT_EQ("[fe80::1%eth0]",
  15594. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  15595. EXPECT_EQ("[fe80::1%eth0]:8080",
  15596. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  15597. // Edge case: Empty host (should return as-is)
  15598. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  15599. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  15600. // This is a known limitation but shouldn't crash
  15601. EXPECT_EQ("[host:name]",
  15602. detail::make_host_and_port_string("host:name", 80, false));
  15603. // Port number edge cases (no validation, but should not crash)
  15604. EXPECT_EQ("example.com:0",
  15605. detail::make_host_and_port_string("example.com", 0, false));
  15606. EXPECT_EQ("example.com:-1",
  15607. detail::make_host_and_port_string("example.com", -1, false));
  15608. EXPECT_EQ("example.com:65535",
  15609. detail::make_host_and_port_string("example.com", 65535, false));
  15610. EXPECT_EQ("example.com:65536",
  15611. detail::make_host_and_port_string("example.com", 65536, false));
  15612. }
  15613. #ifdef CPPHTTPLIB_SSL_ENABLED
  15614. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  15615. httplib::SSLClient cli("roblox.com", 443);
  15616. cli.set_follow_location(true);
  15617. auto res = cli.Get("/");
  15618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15619. EXPECT_EQ(StatusCode::OK_200, res->status);
  15620. }
  15621. #endif
  15622. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  15623. Server svr;
  15624. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15625. EXPECT_EQ(res.status, 400);
  15626. });
  15627. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15628. auto se = detail::scope_exit([&] {
  15629. svr.stop();
  15630. thread.join();
  15631. ASSERT_FALSE(svr.is_running());
  15632. });
  15633. svr.wait_until_ready();
  15634. Client cli(HOST, PORT);
  15635. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  15636. }
  15637. TEST(InvalidHeaderCharsTest, is_field_name) {
  15638. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  15639. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  15640. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  15641. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  15642. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  15643. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  15644. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  15645. EXPECT_FALSE(detail::fields::is_field_name(""));
  15646. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  15647. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  15648. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  15649. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  15650. }
  15651. TEST(InvalidHeaderCharsTest, is_field_value) {
  15652. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  15653. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  15654. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  15655. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  15656. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  15657. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  15658. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  15659. EXPECT_TRUE(detail::fields::is_field_value(""));
  15660. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  15661. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  15662. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  15663. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  15664. EXPECT_TRUE(detail::fields::is_field_value("0"));
  15665. }
  15666. TEST(InvalidHeaderCharsTest, OnServer) {
  15667. Server svr;
  15668. svr.Get("/test_name", [&](const Request &req, Response &res) {
  15669. std::string header = "Not Set";
  15670. if (req.has_param("header")) { header = req.get_param_value("header"); }
  15671. res.set_header(header, "value");
  15672. res.set_content("Page Content Page Content", "text/plain");
  15673. });
  15674. svr.Get("/test_value", [&](const Request &req, Response &res) {
  15675. std::string header = "Not Set";
  15676. if (req.has_param("header")) { header = req.get_param_value("header"); }
  15677. res.set_header("X-Test", header);
  15678. res.set_content("Page Content Page Content", "text/plain");
  15679. });
  15680. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15681. auto se = detail::scope_exit([&] {
  15682. svr.stop();
  15683. thread.join();
  15684. ASSERT_FALSE(svr.is_running());
  15685. });
  15686. svr.wait_until_ready();
  15687. Client cli(HOST, PORT);
  15688. {
  15689. auto res = cli.Get(
  15690. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15692. EXPECT_EQ("Page Content Page Content", res->body);
  15693. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15694. }
  15695. {
  15696. auto res = cli.Get(
  15697. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15699. EXPECT_EQ("Page Content Page Content", res->body);
  15700. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15701. }
  15702. }
  15703. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  15704. auto handled = false;
  15705. Server svr;
  15706. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  15707. thread t = thread([&] { svr.listen(HOST, PORT); });
  15708. auto se = detail::scope_exit([&] {
  15709. svr.stop();
  15710. t.join();
  15711. ASSERT_FALSE(svr.is_running());
  15712. ASSERT_FALSE(handled);
  15713. });
  15714. svr.wait_until_ready();
  15715. auto req = "POST /test HTTP/1.1\r\n"
  15716. "Content-Length: x\r\n"
  15717. "\r\n";
  15718. std::string response;
  15719. ASSERT_TRUE(send_request(1, req, &response));
  15720. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  15721. response.substr(0, response.find("\r\n")));
  15722. }
  15723. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  15724. // case-insensitive, and a server that receives a 100-continue expectation in
  15725. // an HTTP/1.0 request MUST ignore it.
  15726. static void probe_expect(int port, const std::string &req, bool *got_100) {
  15727. std::string response;
  15728. ASSERT_TRUE(send_request(1, req, &response, port));
  15729. *got_100 = response.find("100 Continue") != std::string::npos;
  15730. }
  15731. class ExpectTokenTest : public ::testing::Test {
  15732. protected:
  15733. void SetUp() override {
  15734. svr_.Post("/p", [](const Request &, Response &res) {
  15735. res.set_content("ok", "text/plain");
  15736. });
  15737. port_ = svr_.bind_to_any_port(HOST);
  15738. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15739. svr_.wait_until_ready();
  15740. }
  15741. void TearDown() override {
  15742. svr_.stop();
  15743. if (thread_.joinable()) { thread_.join(); }
  15744. }
  15745. std::string request(const char *version, const char *expect_value) const {
  15746. return std::string("POST /p ") + version +
  15747. "\r\n"
  15748. "Host: localhost\r\n"
  15749. "Content-Length: 2\r\n"
  15750. "Connection: close\r\n"
  15751. "Expect: " +
  15752. expect_value +
  15753. "\r\n"
  15754. "\r\n"
  15755. "hi";
  15756. }
  15757. Server svr_;
  15758. int port_ = 0;
  15759. thread thread_;
  15760. };
  15761. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  15762. bool got_100 = false;
  15763. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  15764. EXPECT_TRUE(got_100);
  15765. }
  15766. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  15767. bool got_100 = true;
  15768. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  15769. EXPECT_FALSE(got_100);
  15770. }
  15771. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  15772. bool got_100 = false;
  15773. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  15774. EXPECT_TRUE(got_100);
  15775. }
  15776. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  15777. bool got_100 = false;
  15778. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  15779. EXPECT_TRUE(got_100);
  15780. }
  15781. // `100 Continue` is sent only when the server starts reading the body, so a
  15782. // request rejected before that never invites the client to send it. The
  15783. // requests below carry the expectation but withhold the body, as a client
  15784. // waiting for `100 Continue` would.
  15785. // A POST that expects `100 Continue` and withholds its two-byte body.
  15786. static std::string expect_headers_only(const std::string &path) {
  15787. return "POST " + path +
  15788. " HTTP/1.1\r\n"
  15789. "Host: localhost\r\n"
  15790. "Content-Length: 2\r\n"
  15791. "Expect: 100-continue\r\n"
  15792. "\r\n";
  15793. }
  15794. class ExpectLazyContinueTest : public ::testing::Test {
  15795. protected:
  15796. void SetUp() override {
  15797. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  15798. if (req.path == "/pre-routing") {
  15799. res.status = StatusCode::Unauthorized_401;
  15800. return Server::HandlerResponse::Handled;
  15801. }
  15802. return Server::HandlerResponse::Unhandled;
  15803. });
  15804. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  15805. if (req.matched_route == "/pre-request") {
  15806. res.status = StatusCode::Forbidden_403;
  15807. return Server::HandlerResponse::Handled;
  15808. }
  15809. return Server::HandlerResponse::Unhandled;
  15810. });
  15811. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  15812. res.set_content("ok", "text/plain");
  15813. });
  15814. svr_.Post("/pre-request", [](const Request &, Response &res) {
  15815. res.set_content("ok", "text/plain");
  15816. });
  15817. svr_.Post("/reader-used", [](const Request &, Response &res,
  15818. const ContentReader &content_reader) {
  15819. std::string body;
  15820. content_reader([&](const char *data, size_t len) {
  15821. body.append(data, len);
  15822. return true;
  15823. });
  15824. res.set_content(body, "text/plain");
  15825. });
  15826. svr_.Post("/reader-unused",
  15827. [](const Request &, Response &res, const ContentReader &) {
  15828. res.set_content("ignored", "text/plain");
  15829. });
  15830. port_ = svr_.bind_to_any_port(HOST);
  15831. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15832. svr_.wait_until_ready();
  15833. }
  15834. void TearDown() override {
  15835. svr_.stop();
  15836. if (thread_.joinable()) { thread_.join(); }
  15837. }
  15838. // Sends `req` and reads until the server closes the connection. Returns
  15839. // false if the read had to wait for the client-side timeout instead.
  15840. bool send_until_closed(const std::string &req, std::string *resp) const {
  15841. auto start = std::chrono::steady_clock::now();
  15842. if (!send_request(3, req, resp, port_)) { return false; }
  15843. auto elapsed = std::chrono::steady_clock::now() - start;
  15844. return elapsed < std::chrono::seconds(2);
  15845. }
  15846. // The final response comes without `100 Continue`, and the server closes
  15847. // the connection since the body may or may not follow.
  15848. void expect_final_without_interim(const std::string &path,
  15849. const char *status_line) const {
  15850. std::string resp;
  15851. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  15852. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  15853. EXPECT_EQ(0u, resp.find(status_line));
  15854. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  15855. }
  15856. Server svr_;
  15857. int port_ = 0;
  15858. thread thread_;
  15859. };
  15860. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  15861. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  15862. }
  15863. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  15864. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  15865. }
  15866. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  15867. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  15868. }
  15869. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  15870. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  15871. }
  15872. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  15873. // The body follows once `100 Continue` has had time to arrive.
  15874. auto req = expect_headers_only("/reader-used");
  15875. req.insert(req.size() - 2, "Connection: close\r\n");
  15876. std::string resp;
  15877. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  15878. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  15879. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  15880. EXPECT_NE(std::string::npos, resp.find("hi"));
  15881. }
  15882. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  15883. // Large enough for the client to add `Expect: 100-continue` itself.
  15884. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  15885. std::atomic<bool> body_sent{false};
  15886. Client cli(HOST, port_);
  15887. auto res = cli.Post(
  15888. "/pre-request", length,
  15889. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  15890. body_sent = true;
  15891. std::string chunk(len, 'x');
  15892. sink.write(chunk.data(), chunk.size());
  15893. return true;
  15894. },
  15895. "application/octet-stream");
  15896. ASSERT_TRUE(res);
  15897. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  15898. EXPECT_FALSE(body_sent);
  15899. }
  15900. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  15901. Server svr;
  15902. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  15903. return StatusCode::ExpectationFailed_417;
  15904. });
  15905. svr.Post("/p", [](const Request &, Response &res) {
  15906. res.set_content("ok", "text/plain");
  15907. });
  15908. auto port = svr.bind_to_any_port(HOST);
  15909. thread t = thread([&] { svr.listen_after_bind(); });
  15910. auto se = detail::scope_exit([&] {
  15911. svr.stop();
  15912. t.join();
  15913. });
  15914. svr.wait_until_ready();
  15915. std::string resp;
  15916. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  15917. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  15918. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  15919. // Exactly one response: the route handler must not run after the 417.
  15920. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  15921. }
  15922. #ifndef _WIN32
  15923. TEST(Expect100ContinueTest, ServerClosesConnection) {
  15924. static constexpr char reject[] = "Unauthorized";
  15925. static constexpr char accept[] = "Upload accepted";
  15926. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  15927. Server svr;
  15928. svr.set_expect_100_continue_handler(
  15929. [](const Request & /*req*/, Response &res) {
  15930. res.status = StatusCode::Unauthorized_401;
  15931. res.set_content(reject, "text/plain");
  15932. return res.status;
  15933. });
  15934. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  15935. res.set_content(accept, "text/plain");
  15936. });
  15937. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15938. auto se = detail::scope_exit([&] {
  15939. svr.stop();
  15940. thread.join();
  15941. ASSERT_FALSE(svr.is_running());
  15942. });
  15943. svr.wait_until_ready();
  15944. {
  15945. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  15946. curl_easy_init(), &curl_easy_cleanup};
  15947. ASSERT_NE(curl, nullptr);
  15948. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  15949. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  15950. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  15951. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  15952. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  15953. &curl_slist_free_all};
  15954. ASSERT_NE(list, nullptr);
  15955. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  15956. struct read_data {
  15957. size_t read_size;
  15958. size_t total_size;
  15959. } data = {0, total_size};
  15960. using read_callback_t =
  15961. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  15962. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  15963. void *userdata) -> size_t {
  15964. read_data *d = (read_data *)userdata;
  15965. if (!userdata || d->read_size >= d->total_size) { return 0; }
  15966. std::fill_n(ptr, size * nmemb, 'A');
  15967. d->read_size += size * nmemb;
  15968. return size * nmemb;
  15969. };
  15970. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  15971. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  15972. std::vector<char> buffer;
  15973. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  15974. using write_callback_t =
  15975. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  15976. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  15977. void *userdata) -> size_t {
  15978. std::vector<char> *buf = (std::vector<char> *)userdata;
  15979. buf->reserve(buf->size() + size * nmemb + 1);
  15980. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  15981. return size * nmemb;
  15982. };
  15983. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  15984. {
  15985. const auto res = curl_easy_perform(curl.get());
  15986. ASSERT_EQ(res, CURLE_OK);
  15987. }
  15988. {
  15989. auto response_code = long{};
  15990. const auto res =
  15991. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  15992. ASSERT_EQ(res, CURLE_OK);
  15993. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  15994. }
  15995. {
  15996. auto dl = curl_off_t{};
  15997. const auto res =
  15998. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  15999. ASSERT_EQ(res, CURLE_OK);
  16000. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  16001. }
  16002. {
  16003. buffer.push_back('\0');
  16004. ASSERT_STRCASEEQ(buffer.data(), reject);
  16005. }
  16006. }
  16007. }
  16008. #endif
  16009. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  16010. // Regression test for #2458.
  16011. //
  16012. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  16013. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  16014. // ticket can make the client socket spuriously readable during the
  16015. // 100-continue wait. If the readiness is mistaken for an incoming response,
  16016. // the client withholds the body and then blocks reading a response that never
  16017. // comes, failing with `Failed to read connection`.
  16018. //
  16019. // A correct client (like curl) sends the body once no `100 Continue` arrives
  16020. // within the timeout. This raw OpenSSL server deliberately never sends
  16021. // `100 Continue`; the client must still deliver the body and receive 200.
  16022. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  16023. signal(SIGPIPE, SIG_IGN);
  16024. const auto port = PORT + 4;
  16025. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16026. ASSERT_NE(srv, INVALID_SOCKET);
  16027. int opt = 1;
  16028. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  16029. sockaddr_in addr{};
  16030. addr.sin_family = AF_INET;
  16031. addr.sin_port = htons(static_cast<uint16_t>(port));
  16032. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16033. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16034. ASSERT_EQ(0, ::listen(srv, 1));
  16035. std::atomic<size_t> server_body_bytes{0};
  16036. auto server_thread = std::thread([&] {
  16037. sockaddr_in cli_addr{};
  16038. socklen_t cli_len = sizeof(cli_addr);
  16039. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16040. if (cli == INVALID_SOCKET) { return; }
  16041. // Bound the lifetime of the server side so a buggy client (which never
  16042. // sends the body) cannot make this thread block forever on join.
  16043. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  16044. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  16045. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  16046. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  16047. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  16048. SSL *ssl = SSL_new(ctx);
  16049. SSL_set_fd(ssl, static_cast<int>(cli));
  16050. if (SSL_accept(ssl) > 0) {
  16051. // Read the request headers. Reading here also flushes the TLS 1.3
  16052. // session tickets to the client. Deliberately do NOT send
  16053. // `100 Continue`.
  16054. std::string buf;
  16055. char tmp[1024];
  16056. while (buf.find("\r\n\r\n") == std::string::npos) {
  16057. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16058. if (n <= 0) { break; }
  16059. buf.append(tmp, static_cast<size_t>(n));
  16060. }
  16061. // A correct client sends the body now; count what arrives.
  16062. auto pos = buf.find("\r\n\r\n");
  16063. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  16064. while (body < 4096) {
  16065. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16066. if (n <= 0) { break; }
  16067. body += static_cast<size_t>(n);
  16068. }
  16069. server_body_bytes = body;
  16070. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  16071. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  16072. SSL_shutdown(ssl);
  16073. }
  16074. SSL_free(ssl);
  16075. detail::close_socket(cli);
  16076. SSL_CTX_free(ctx);
  16077. });
  16078. auto se = detail::scope_exit([&] {
  16079. server_thread.join();
  16080. detail::close_socket(srv);
  16081. });
  16082. SSLClient cli("127.0.0.1", port);
  16083. cli.enable_server_certificate_verification(false);
  16084. cli.set_connection_timeout(5, 0);
  16085. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  16086. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  16087. std::string body(4096, 'A');
  16088. auto res = cli.Put("/api/test", body, "application/json");
  16089. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  16090. EXPECT_EQ(StatusCode::OK_200, res->status);
  16091. EXPECT_EQ(body.size(), server_body_bytes.load());
  16092. }
  16093. #endif
  16094. template <typename S, typename C>
  16095. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  16096. svr.Get("/stream", [&](const Request &, Response &res) {
  16097. auto data = new std::string("01234567890123456789");
  16098. res.set_content_provider(
  16099. data->size(), "text/plain",
  16100. [&, data](size_t offset, size_t length, DataSink &sink) {
  16101. const size_t DATA_CHUNK_SIZE = 4;
  16102. const auto &d = *data;
  16103. std::this_thread::sleep_for(std::chrono::seconds(1));
  16104. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  16105. return true;
  16106. },
  16107. [data](bool success) {
  16108. EXPECT_FALSE(success);
  16109. delete data;
  16110. });
  16111. });
  16112. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  16113. auto i = new size_t(0);
  16114. res.set_content_provider(
  16115. "text/plain",
  16116. [i](size_t, DataSink &sink) {
  16117. if (*i < 5) {
  16118. std::this_thread::sleep_for(std::chrono::seconds(1));
  16119. sink.write("abcd", 4);
  16120. (*i)++;
  16121. } else {
  16122. sink.done();
  16123. }
  16124. return true;
  16125. },
  16126. [i](bool success) {
  16127. EXPECT_FALSE(success);
  16128. delete i;
  16129. });
  16130. });
  16131. svr.Get("/chunked", [&](const Request &, Response &res) {
  16132. auto i = new size_t(0);
  16133. res.set_chunked_content_provider(
  16134. "text/plain",
  16135. [i](size_t, DataSink &sink) {
  16136. if (*i < 5) {
  16137. std::this_thread::sleep_for(std::chrono::seconds(1));
  16138. sink.os << "abcd";
  16139. (*i)++;
  16140. } else {
  16141. sink.done();
  16142. }
  16143. return true;
  16144. },
  16145. [i](bool success) {
  16146. EXPECT_FALSE(success);
  16147. delete i;
  16148. });
  16149. });
  16150. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16151. auto se = detail::scope_exit([&] {
  16152. svr.stop();
  16153. listen_thread.join();
  16154. ASSERT_FALSE(svr.is_running());
  16155. });
  16156. svr.wait_until_ready();
  16157. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  16158. {
  16159. auto start = std::chrono::steady_clock::now();
  16160. auto res = cli.Get("/stream");
  16161. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16162. std::chrono::steady_clock::now() - start)
  16163. .count();
  16164. ASSERT_FALSE(res);
  16165. EXPECT_EQ(Error::Read, res.error());
  16166. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16167. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16168. }
  16169. {
  16170. auto start = std::chrono::steady_clock::now();
  16171. auto res = cli.Get("/stream_without_length");
  16172. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16173. std::chrono::steady_clock::now() - start)
  16174. .count();
  16175. ASSERT_FALSE(res);
  16176. EXPECT_EQ(Error::Read, res.error());
  16177. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16178. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16179. }
  16180. {
  16181. auto start = std::chrono::steady_clock::now();
  16182. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  16183. EXPECT_EQ("abcd", string(data, data_length));
  16184. return true;
  16185. });
  16186. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16187. std::chrono::steady_clock::now() - start)
  16188. .count();
  16189. ASSERT_FALSE(res);
  16190. EXPECT_EQ(Error::Read, res.error());
  16191. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16192. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16193. }
  16194. }
  16195. TEST(MaxTimeoutTest, ContentStream) {
  16196. time_t timeout = 2000;
  16197. time_t threshold = 200;
  16198. Server svr;
  16199. Client cli("localhost", PORT);
  16200. max_timeout_test(svr, cli, timeout, threshold);
  16201. }
  16202. #ifdef CPPHTTPLIB_SSL_ENABLED
  16203. TEST(MaxTimeoutTest, ContentStreamSSL) {
  16204. time_t timeout = 2000;
  16205. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  16206. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16207. SSLClient cli("localhost", PORT);
  16208. cli.enable_server_certificate_verification(false);
  16209. max_timeout_test(svr, cli, timeout, threshold);
  16210. }
  16211. #endif
  16212. class EventDispatcher {
  16213. public:
  16214. EventDispatcher() {}
  16215. bool wait_event(DataSink *sink) {
  16216. unique_lock<mutex> lk(m_);
  16217. int id = id_;
  16218. // Wait with timeout to prevent hanging if client disconnects
  16219. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  16220. [&] { return cid_ == id; })) {
  16221. return false; // Timeout occurred
  16222. }
  16223. sink->write(message_.data(), message_.size());
  16224. return true;
  16225. }
  16226. void send_event(const string &message) {
  16227. lock_guard<mutex> lk(m_);
  16228. cid_ = id_++;
  16229. message_ = message;
  16230. cv_.notify_all();
  16231. }
  16232. private:
  16233. mutex m_;
  16234. condition_variable cv_;
  16235. atomic_int id_{0};
  16236. atomic_int cid_{-1};
  16237. string message_;
  16238. };
  16239. TEST(ClientInThreadTest, Issue2068) {
  16240. EventDispatcher ed;
  16241. Server svr;
  16242. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  16243. res.set_chunked_content_provider("text/event-stream",
  16244. [&](size_t /*offset*/, DataSink &sink) {
  16245. return ed.wait_event(&sink);
  16246. });
  16247. });
  16248. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  16249. svr.wait_until_ready();
  16250. thread event_thread([&] {
  16251. int id = 0;
  16252. while (svr.is_running()) {
  16253. this_thread::sleep_for(chrono::milliseconds(500));
  16254. std::stringstream ss;
  16255. ss << "data: " << id << "\n\n";
  16256. ed.send_event(ss.str());
  16257. id++;
  16258. }
  16259. });
  16260. auto se = detail::scope_exit([&] {
  16261. svr.stop();
  16262. listen_thread.join();
  16263. event_thread.join();
  16264. ASSERT_FALSE(svr.is_running());
  16265. });
  16266. {
  16267. auto client = detail::make_unique<Client>(HOST, PORT);
  16268. client->set_read_timeout(std::chrono::minutes(10));
  16269. std::atomic<bool> stop{false};
  16270. std::thread t([&] {
  16271. client->Get("/event1",
  16272. [&](const char *, size_t) -> bool { return !stop; });
  16273. });
  16274. std::this_thread::sleep_for(std::chrono::seconds(2));
  16275. stop = true;
  16276. client->stop();
  16277. t.join();
  16278. // Reset client after thread has finished
  16279. client.reset();
  16280. }
  16281. }
  16282. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  16283. auto handled = false;
  16284. Server svr;
  16285. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16286. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16287. auto se = detail::scope_exit([&] {
  16288. svr.stop();
  16289. t.join();
  16290. ASSERT_FALSE(svr.is_running());
  16291. ASSERT_FALSE(handled);
  16292. });
  16293. svr.wait_until_ready();
  16294. // Two Content-Length headers with different values — must be rejected
  16295. auto req = "POST /test HTTP/1.1\r\n"
  16296. "Content-Length: 5\r\n"
  16297. "Content-Length: 10\r\n"
  16298. "\r\n"
  16299. "hello";
  16300. std::string response;
  16301. ASSERT_TRUE(send_request(1, req, &response));
  16302. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16303. response.substr(0, response.find("\r\n")));
  16304. }
  16305. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  16306. auto handled = false;
  16307. Server svr;
  16308. svr.Post("/test", [&](const Request &, Response &res) {
  16309. handled = true;
  16310. res.set_content("ok", "text/plain");
  16311. });
  16312. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16313. auto se = detail::scope_exit([&] {
  16314. svr.stop();
  16315. t.join();
  16316. ASSERT_FALSE(svr.is_running());
  16317. ASSERT_TRUE(handled);
  16318. });
  16319. svr.wait_until_ready();
  16320. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  16321. auto req = "POST /test HTTP/1.1\r\n"
  16322. "Content-Length: 5\r\n"
  16323. "Content-Length: 5\r\n"
  16324. "\r\n"
  16325. "hello";
  16326. std::string response;
  16327. ASSERT_TRUE(send_request(1, req, &response));
  16328. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  16329. }
  16330. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  16331. Server svr;
  16332. svr.Get("/", [](const Request &req, Response &res) {
  16333. EXPECT_EQ(2U, req.trailers.size());
  16334. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  16335. // Denied
  16336. EXPECT_FALSE(req.has_trailer("Content-Length"));
  16337. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  16338. // Accepted
  16339. EXPECT_TRUE(req.has_trailer("X-Hello"));
  16340. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  16341. EXPECT_TRUE(req.has_trailer("X-World"));
  16342. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  16343. res.set_content("ok", "text/plain");
  16344. });
  16345. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16346. auto se = detail::scope_exit([&] {
  16347. svr.stop();
  16348. t.join();
  16349. ASSERT_FALSE(svr.is_running());
  16350. });
  16351. svr.wait_until_ready();
  16352. const std::string req = "GET / HTTP/1.1\r\n"
  16353. "Transfer-Encoding: chunked\r\n"
  16354. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  16355. "\r\n"
  16356. "0\r\n"
  16357. "Content-Length: 10\r\n"
  16358. "Host: internal.local\r\n"
  16359. "Content-Type: malicious/content\r\n"
  16360. "Cookie: any\r\n"
  16361. "Set-Cookie: any\r\n"
  16362. "X-Forwarded-For: attacker.com\r\n"
  16363. "X-Real-Ip: 1.1.1.1\r\n"
  16364. "X-Hello: hello\r\n"
  16365. "X-World: world\r\n"
  16366. "\r\n";
  16367. std::string res;
  16368. ASSERT_TRUE(send_request(1, req, &res));
  16369. }
  16370. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  16371. // several field lines, and the combined value is what has to be parsed. A
  16372. // Trailer field split across lines therefore declares every name it lists;
  16373. // reading only the first line silently drops the trailers the later lines
  16374. // declare. The prohibited-trailer filter still applies to every line.
  16375. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  16376. Server svr;
  16377. size_t observed_trailer_count = 0;
  16378. std::string observed_hello;
  16379. std::string observed_world;
  16380. bool observed_content_length = true;
  16381. svr.Get("/", [&](const Request &req, Response &res) {
  16382. observed_trailer_count = req.trailers.size();
  16383. observed_hello = req.get_trailer_value("X-Hello");
  16384. observed_world = req.get_trailer_value("X-World");
  16385. observed_content_length = req.has_trailer("Content-Length");
  16386. res.set_content("ok", "text/plain");
  16387. });
  16388. auto port = svr.bind_to_any_port(HOST);
  16389. thread t = thread([&]() { svr.listen_after_bind(); });
  16390. auto se = detail::scope_exit([&] {
  16391. svr.stop();
  16392. t.join();
  16393. ASSERT_FALSE(svr.is_running());
  16394. });
  16395. svr.wait_until_ready();
  16396. const std::string req = "GET / HTTP/1.1\r\n"
  16397. "Transfer-Encoding: chunked\r\n"
  16398. "Trailer: X-Hello\r\n"
  16399. "Trailer: X-World, Content-Length\r\n"
  16400. "\r\n"
  16401. "0\r\n"
  16402. "X-Hello: hello\r\n"
  16403. "X-World: world\r\n"
  16404. "Content-Length: 10\r\n"
  16405. "\r\n";
  16406. std::string res;
  16407. ASSERT_TRUE(send_request(1, req, &res, port));
  16408. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  16409. // Accepted: both field lines contribute to the declared set
  16410. EXPECT_EQ(2U, observed_trailer_count);
  16411. EXPECT_EQ(observed_hello, "hello");
  16412. EXPECT_EQ(observed_world, "world");
  16413. // Denied: a prohibited name stays prohibited on a later field line
  16414. EXPECT_FALSE(observed_content_length);
  16415. }
  16416. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  16417. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  16418. // unbounded run of fields that are never declared, because the counter would
  16419. // only advance for declared fields.
  16420. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  16421. Server svr;
  16422. bool handler_called = false;
  16423. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  16424. handler_called = true;
  16425. res.set_content("ok", "text/plain");
  16426. });
  16427. auto port = svr.bind_to_any_port(HOST);
  16428. thread t = thread([&]() { svr.listen_after_bind(); });
  16429. auto se = detail::scope_exit([&] {
  16430. svr.stop();
  16431. t.join();
  16432. ASSERT_FALSE(svr.is_running());
  16433. });
  16434. svr.wait_until_ready();
  16435. // Declare nothing, then send far more undeclared trailer fields than the
  16436. // header-count limit. Parsing must stop and reject the request rather than
  16437. // read every line.
  16438. std::string req = "GET / HTTP/1.1\r\n"
  16439. "Transfer-Encoding: chunked\r\n"
  16440. "\r\n"
  16441. "0\r\n";
  16442. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  16443. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  16444. }
  16445. req += "\r\n";
  16446. std::string res;
  16447. ASSERT_TRUE(send_request(1, req, &res, port));
  16448. // The request is rejected before the handler runs.
  16449. EXPECT_FALSE(handler_called);
  16450. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  16451. }
  16452. // The set of declared trailer names is capped so a peer cannot grow it without
  16453. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  16454. // declared past the cap is not honored, even if the field is actually sent.
  16455. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  16456. Server svr;
  16457. // One name inside the cap and one past it, so the test tracks the cap rather
  16458. // than a fixed count.
  16459. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  16460. const std::string within_cap_name = "X-T-0";
  16461. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  16462. bool observed_within_cap = false;
  16463. bool observed_past_cap = false;
  16464. svr.Get("/", [&](const Request &req, Response &res) {
  16465. observed_within_cap = req.has_trailer(within_cap_name);
  16466. observed_past_cap = req.has_trailer(past_cap_name);
  16467. res.set_content("ok", "text/plain");
  16468. });
  16469. auto port = svr.bind_to_any_port(HOST);
  16470. thread t = thread([&]() { svr.listen_after_bind(); });
  16471. auto se = detail::scope_exit([&] {
  16472. svr.stop();
  16473. t.join();
  16474. ASSERT_FALSE(svr.is_running());
  16475. });
  16476. svr.wait_until_ready();
  16477. // Declare more trailer names than the cap in a single Trailer field, then
  16478. // actually send the first (within the cap) and the last (past it).
  16479. std::string trailer_decl = "Trailer: ";
  16480. for (int i = 0; i < declared_count; i++) {
  16481. if (i != 0) { trailer_decl += ", "; }
  16482. trailer_decl += "X-T-" + std::to_string(i);
  16483. }
  16484. trailer_decl += "\r\n";
  16485. const std::string req = "GET / HTTP/1.1\r\n"
  16486. "Transfer-Encoding: chunked\r\n" +
  16487. trailer_decl +
  16488. "\r\n"
  16489. "0\r\n" +
  16490. within_cap_name + ": a\r\n" + past_cap_name +
  16491. ": b\r\n"
  16492. "\r\n";
  16493. std::string res;
  16494. ASSERT_TRUE(send_request(1, req, &res, port));
  16495. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  16496. // A name within the cap is honored; one declared past the cap is dropped.
  16497. EXPECT_TRUE(observed_within_cap);
  16498. EXPECT_FALSE(observed_past_cap);
  16499. }
  16500. // A direct client that is not listed in trusted_proxies must not be able to
  16501. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  16502. // the peer address on the actual TCP connection determines whether the
  16503. // header is honored.
  16504. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  16505. Server svr;
  16506. // Deliberately does NOT include the loopback address the test client
  16507. // actually connects from, so the direct connection is not a trusted proxy.
  16508. svr.set_trusted_proxies({"203.0.113.66"});
  16509. std::string observed_remote_addr;
  16510. svr.Get("/ip", [&](const Request &req, Response &res) {
  16511. observed_remote_addr = req.remote_addr;
  16512. res.set_content("ok", "text/plain");
  16513. });
  16514. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16515. auto se = detail::scope_exit([&] {
  16516. svr.stop();
  16517. t.join();
  16518. ASSERT_FALSE(svr.is_running());
  16519. });
  16520. svr.wait_until_ready();
  16521. Client cli(HOST, PORT);
  16522. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  16523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16524. EXPECT_EQ(StatusCode::OK_200, res->status);
  16525. // The connecting peer is not a trusted proxy, so the spoofed header must be
  16526. // ignored entirely and the real connection-level address retained.
  16527. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16528. observed_remote_addr == "127.0.0.1");
  16529. }
  16530. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  16531. Server svr;
  16532. std::string observed_remote_addr;
  16533. std::string observed_xff;
  16534. svr.Get("/ip", [&](const Request &req, Response &res) {
  16535. observed_remote_addr = req.remote_addr;
  16536. observed_xff = req.get_header_value("X-Forwarded-For");
  16537. res.set_content("ok", "text/plain");
  16538. });
  16539. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16540. auto se = detail::scope_exit([&] {
  16541. svr.stop();
  16542. t.join();
  16543. ASSERT_FALSE(svr.is_running());
  16544. });
  16545. svr.wait_until_ready();
  16546. Client cli(HOST, PORT);
  16547. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  16548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16549. EXPECT_EQ(StatusCode::OK_200, res->status);
  16550. EXPECT_EQ(observed_xff, "203.0.113.66");
  16551. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16552. observed_remote_addr == "127.0.0.1");
  16553. }
  16554. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  16555. Server svr;
  16556. svr.set_trusted_proxies({"203.0.113.66"});
  16557. std::string observed_remote_addr;
  16558. std::string observed_xff;
  16559. svr.Get("/ip", [&](const Request &req, Response &res) {
  16560. observed_remote_addr = req.remote_addr;
  16561. observed_xff = req.get_header_value("X-Forwarded-For");
  16562. res.set_content("ok", "text/plain");
  16563. });
  16564. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16565. auto se = detail::scope_exit([&] {
  16566. svr.stop();
  16567. t.join();
  16568. ASSERT_FALSE(svr.is_running());
  16569. });
  16570. svr.wait_until_ready();
  16571. Client cli(HOST, PORT);
  16572. auto res = cli.Get("/ip");
  16573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16574. EXPECT_EQ(StatusCode::OK_200, res->status);
  16575. EXPECT_EQ(observed_xff, "");
  16576. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16577. observed_remote_addr == "127.0.0.1");
  16578. }
  16579. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  16580. Server svr;
  16581. // Include the loopback address the test client actually connects from, so
  16582. // the direct connection itself is recognized as the trusted proxy hop.
  16583. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  16584. std::string observed_remote_addr;
  16585. std::string observed_xff;
  16586. svr.Get("/ip", [&](const Request &req, Response &res) {
  16587. observed_remote_addr = req.remote_addr;
  16588. observed_xff = req.get_header_value("X-Forwarded-For");
  16589. res.set_content("ok", "text/plain");
  16590. });
  16591. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16592. auto se = detail::scope_exit([&] {
  16593. svr.stop();
  16594. t.join();
  16595. ASSERT_FALSE(svr.is_running());
  16596. });
  16597. svr.wait_until_ready();
  16598. Client cli(HOST, PORT);
  16599. auto res = cli.Get(
  16600. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  16601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16602. EXPECT_EQ(StatusCode::OK_200, res->status);
  16603. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  16604. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16605. }
  16606. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  16607. Server svr;
  16608. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  16609. std::string observed_remote_addr;
  16610. std::string observed_xff;
  16611. svr.Get("/ip", [&](const Request &req, Response &res) {
  16612. observed_remote_addr = req.remote_addr;
  16613. observed_xff = req.get_header_value("X-Forwarded-For");
  16614. res.set_content("ok", "text/plain");
  16615. });
  16616. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16617. auto se = detail::scope_exit([&] {
  16618. svr.stop();
  16619. t.join();
  16620. ASSERT_FALSE(svr.is_running());
  16621. });
  16622. svr.wait_until_ready();
  16623. Client cli(HOST, PORT);
  16624. auto res = cli.Get(
  16625. "/ip",
  16626. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  16627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16628. EXPECT_EQ(StatusCode::OK_200, res->status);
  16629. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  16630. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16631. }
  16632. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  16633. Server svr;
  16634. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16635. std::string observed_remote_addr;
  16636. std::string observed_xff;
  16637. svr.Get("/ip", [&](const Request &req, Response &res) {
  16638. observed_remote_addr = req.remote_addr;
  16639. observed_xff = req.get_header_value("X-Forwarded-For");
  16640. res.set_content("ok", "text/plain");
  16641. });
  16642. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16643. auto se = detail::scope_exit([&] {
  16644. svr.stop();
  16645. t.join();
  16646. ASSERT_FALSE(svr.is_running());
  16647. });
  16648. svr.wait_until_ready();
  16649. Client cli(HOST, PORT);
  16650. auto res = cli.Get(
  16651. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  16652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16653. EXPECT_EQ(StatusCode::OK_200, res->status);
  16654. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  16655. // by the closest hop) is used. The leftmost entry is fully client-controlled
  16656. // and must not be selected.
  16657. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  16658. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  16659. }
  16660. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  16661. Server svr;
  16662. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  16663. std::string observed_remote_addr;
  16664. svr.Get("/ip", [&](const Request &req, Response &res) {
  16665. observed_remote_addr = req.remote_addr;
  16666. res.set_content("ok", "text/plain");
  16667. });
  16668. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16669. auto se = detail::scope_exit([&] {
  16670. svr.stop();
  16671. t.join();
  16672. ASSERT_FALSE(svr.is_running());
  16673. });
  16674. svr.wait_until_ready();
  16675. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  16676. // a forged address and the trusted proxy's own address; the forged value must
  16677. // not win over the address the trusted proxy actually recorded.
  16678. Client cli(HOST, PORT);
  16679. auto res = cli.Get(
  16680. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  16681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16682. EXPECT_EQ(StatusCode::OK_200, res->status);
  16683. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  16684. }
  16685. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  16686. Server svr;
  16687. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16688. std::string observed_remote_addr;
  16689. std::string observed_xff;
  16690. svr.Get("/ip", [&](const Request &req, Response &res) {
  16691. observed_remote_addr = req.remote_addr;
  16692. observed_xff = req.get_header_value("X-Forwarded-For");
  16693. res.set_content("ok", "text/plain");
  16694. });
  16695. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16696. auto se = detail::scope_exit([&] {
  16697. svr.stop();
  16698. t.join();
  16699. ASSERT_FALSE(svr.is_running());
  16700. });
  16701. svr.wait_until_ready();
  16702. Client cli(HOST, PORT);
  16703. auto res = cli.Get(
  16704. "/ip",
  16705. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  16706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16707. EXPECT_EQ(StatusCode::OK_200, res->status);
  16708. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  16709. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  16710. }
  16711. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  16712. Server svr;
  16713. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16714. std::string observed_remote_addr;
  16715. std::string observed_xff;
  16716. svr.Get("/ip", [&](const Request &req, Response &res) {
  16717. observed_remote_addr = req.remote_addr;
  16718. observed_xff = req.get_header_value("X-Forwarded-For");
  16719. res.set_content("ok", "text/plain");
  16720. });
  16721. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16722. auto se = detail::scope_exit([&] {
  16723. svr.stop();
  16724. t.join();
  16725. ASSERT_FALSE(svr.is_running());
  16726. });
  16727. svr.wait_until_ready();
  16728. std::string raw_req =
  16729. "GET /ip HTTP/1.1\r\n"
  16730. "Host: localhost\r\n"
  16731. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  16732. "Connection: close\r\n"
  16733. "\r\n";
  16734. std::string out;
  16735. ASSERT_TRUE(send_request(5, raw_req, &out));
  16736. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16737. // Header parser trims surrounding whitespace of the header value
  16738. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  16739. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  16740. }
  16741. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  16742. // one comma-joined value, in the order received. Proxies such as HAProxy append
  16743. // their own X-Forwarded-For as a separate field line rather than extending the
  16744. // one the client sent, so every occurrence has to be taken into account.
  16745. // Reading only the first one hands back the address the client chose.
  16746. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  16747. Server svr;
  16748. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16749. std::string observed_remote_addr;
  16750. size_t observed_xff_count = 0;
  16751. svr.Get("/ip", [&](const Request &req, Response &res) {
  16752. observed_remote_addr = req.remote_addr;
  16753. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  16754. res.set_content("ok", "text/plain");
  16755. });
  16756. auto port = svr.bind_to_any_port(HOST);
  16757. thread t = thread([&]() { svr.listen_after_bind(); });
  16758. auto se = detail::scope_exit([&] {
  16759. svr.stop();
  16760. t.join();
  16761. ASSERT_FALSE(svr.is_running());
  16762. });
  16763. svr.wait_until_ready();
  16764. // The client supplies the first field line; the trusted proxy appends the
  16765. // address it observed as a second one.
  16766. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  16767. "Host: localhost\r\n"
  16768. "X-Forwarded-For: 1.2.3.4\r\n"
  16769. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  16770. "Connection: close\r\n"
  16771. "\r\n";
  16772. std::string out;
  16773. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  16774. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16775. EXPECT_EQ(observed_xff_count, 2U);
  16776. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16777. // The same chain spread over one field line per hop derives the same client
  16778. // address, i.e. the split and the comma-joined representations agree.
  16779. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  16780. "Host: localhost\r\n"
  16781. "X-Forwarded-For: 1.2.3.4\r\n"
  16782. "X-Forwarded-For: 198.51.100.23\r\n"
  16783. "X-Forwarded-For: 192.0.2.45\r\n"
  16784. "Connection: close\r\n"
  16785. "\r\n";
  16786. out.clear();
  16787. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  16788. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16789. EXPECT_EQ(observed_xff_count, 3U);
  16790. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16791. }
  16792. // An X-Forwarded-For header whose value parses to zero IP segments must not
  16793. // crash the server (it used to call front() on an empty vector inside
  16794. // get_client_ip). The connection-level remote address must be retained instead.
  16795. static void run_malformed_xff_test(const std::string &xff_value) {
  16796. Server svr;
  16797. svr.set_trusted_proxies({"192.0.2.45"});
  16798. std::string observed_remote_addr;
  16799. svr.Get("/ip", [&](const Request &req, Response &res) {
  16800. observed_remote_addr = req.remote_addr;
  16801. res.set_content("ok", "text/plain");
  16802. });
  16803. int port = 0;
  16804. thread t = thread([&]() {
  16805. port = svr.bind_to_any_port(HOST);
  16806. svr.listen_after_bind();
  16807. });
  16808. auto se = detail::scope_exit([&] {
  16809. svr.stop();
  16810. t.join();
  16811. ASSERT_FALSE(svr.is_running());
  16812. });
  16813. svr.wait_until_ready();
  16814. Client cli(HOST, port);
  16815. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  16816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16817. EXPECT_EQ(StatusCode::OK_200, res->status);
  16818. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16819. observed_remote_addr == "127.0.0.1");
  16820. }
  16821. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  16822. run_malformed_xff_test("");
  16823. }
  16824. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  16825. run_malformed_xff_test(",");
  16826. }
  16827. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  16828. run_malformed_xff_test(", , ,");
  16829. }
  16830. // The same rule applies to Accept: a request whose acceptable types are spread
  16831. // over several field lines must be negotiated against all of them.
  16832. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  16833. // case-insensitive connection options. Comparing the whole field value against
  16834. // one option misses a client that sends several of them, and misses every
  16835. // casing but the one written in the comparison.
  16836. //
  16837. // Sends req, reads the response, then reuses the same socket for a second
  16838. // request to find out whether the server kept the connection.
  16839. static void probe_connection_reuse(int port, const std::string &req,
  16840. bool *announced_close, bool *reusable) {
  16841. auto error = Error::Success;
  16842. auto sock = detail::create_client_socket(
  16843. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  16844. /*connection_timeout_sec=*/5, 0,
  16845. /*read_timeout_sec=*/1, 0,
  16846. /*write_timeout_sec=*/5, 0, std::string(), error);
  16847. ASSERT_NE(sock, INVALID_SOCKET);
  16848. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  16849. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  16850. "Host: localhost\r\n"
  16851. "Connection: close\r\n"
  16852. "\r\n";
  16853. std::string first_response;
  16854. std::string second_response;
  16855. detail::process_client_socket(
  16856. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  16857. [&](Stream &strm) {
  16858. if (strm.write(req.data(), req.size()) !=
  16859. static_cast<ssize_t>(req.size())) {
  16860. return false;
  16861. }
  16862. char buf[512];
  16863. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  16864. // Headers plus the two-byte body of the handler below
  16865. while (reader.getline()) {
  16866. first_response += reader.ptr();
  16867. if (first_response.find("ok") != std::string::npos) { break; }
  16868. }
  16869. if (strm.write(second.data(), second.size()) !=
  16870. static_cast<ssize_t>(second.size())) {
  16871. return true;
  16872. }
  16873. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  16874. while (reader2.getline()) {
  16875. second_response += reader2.ptr();
  16876. if (second_response.find("ok") != std::string::npos) { break; }
  16877. }
  16878. return true;
  16879. });
  16880. *announced_close =
  16881. first_response.find("Connection: close") != std::string::npos;
  16882. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  16883. }
  16884. class ConnectionTokenTest : public ::testing::Test {
  16885. protected:
  16886. void SetUp() override {
  16887. svr_.Get("/keepalive", [](const Request &, Response &res) {
  16888. res.set_content("ok", "text/plain");
  16889. });
  16890. port_ = svr_.bind_to_any_port(HOST);
  16891. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16892. svr_.wait_until_ready();
  16893. }
  16894. void TearDown() override {
  16895. svr_.stop();
  16896. if (thread_.joinable()) { thread_.join(); }
  16897. }
  16898. Server svr_;
  16899. int port_ = 0;
  16900. thread thread_;
  16901. };
  16902. // "close" alongside another option still closes the connection, and the
  16903. // response says so rather than leaving the peer to discover it.
  16904. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  16905. bool announced_close = false;
  16906. bool reusable = true;
  16907. probe_connection_reuse(port_,
  16908. "GET /keepalive HTTP/1.1\r\n"
  16909. "Host: localhost\r\n"
  16910. "Connection: keep-alive, close\r\n"
  16911. "\r\n",
  16912. &announced_close, &reusable);
  16913. EXPECT_TRUE(announced_close);
  16914. EXPECT_FALSE(reusable);
  16915. }
  16916. // "close" split over two field lines is the same list, so it is honored too.
  16917. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  16918. bool announced_close = false;
  16919. bool reusable = true;
  16920. probe_connection_reuse(port_,
  16921. "GET /keepalive HTTP/1.1\r\n"
  16922. "Host: localhost\r\n"
  16923. "Connection: keep-alive\r\n"
  16924. "Connection: close\r\n"
  16925. "\r\n",
  16926. &announced_close, &reusable);
  16927. EXPECT_TRUE(announced_close);
  16928. EXPECT_FALSE(reusable);
  16929. }
  16930. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  16931. // keep-alive in the spelling everyone actually sends keeps its connection.
  16932. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  16933. bool announced_close = false;
  16934. bool reusable = false;
  16935. probe_connection_reuse(port_,
  16936. "GET /keepalive HTTP/1.0\r\n"
  16937. "Host: localhost\r\n"
  16938. "Connection: keep-alive\r\n"
  16939. "\r\n",
  16940. &announced_close, &reusable);
  16941. EXPECT_FALSE(announced_close);
  16942. EXPECT_TRUE(reusable);
  16943. }
  16944. // A token the value merely contains is not the token itself.
  16945. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  16946. bool announced_close = false;
  16947. bool reusable = false;
  16948. probe_connection_reuse(port_,
  16949. "GET /keepalive HTTP/1.1\r\n"
  16950. "Host: localhost\r\n"
  16951. "Connection: notclose\r\n"
  16952. "\r\n",
  16953. &announced_close, &reusable);
  16954. EXPECT_FALSE(announced_close);
  16955. EXPECT_TRUE(reusable);
  16956. }
  16957. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  16958. Server svr;
  16959. std::vector<std::string> observed_types;
  16960. svr.Get("/", [&](const Request &req, Response &res) {
  16961. observed_types = req.accept_content_types;
  16962. res.set_content("ok", "text/plain");
  16963. });
  16964. auto port = svr.bind_to_any_port(HOST);
  16965. thread t = thread([&]() { svr.listen_after_bind(); });
  16966. auto se = detail::scope_exit([&] {
  16967. svr.stop();
  16968. t.join();
  16969. ASSERT_FALSE(svr.is_running());
  16970. });
  16971. svr.wait_until_ready();
  16972. Client cli(HOST, port);
  16973. Headers headers;
  16974. headers.emplace("Accept", "text/plain;q=0.5");
  16975. headers.emplace("Accept", "application/json");
  16976. auto res = cli.Get("/", headers);
  16977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16978. EXPECT_EQ(StatusCode::OK_200, res->status);
  16979. // Sorted by q-value, so the second field line's type comes first
  16980. ASSERT_EQ(2U, observed_types.size());
  16981. EXPECT_EQ("application/json", observed_types[0]);
  16982. EXPECT_EQ("text/plain", observed_types[1]);
  16983. }
  16984. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  16985. // empty field line must not contribute a bare comma to the combined value.
  16986. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  16987. Server svr;
  16988. std::vector<std::string> observed_types;
  16989. svr.Get("/", [&](const Request &req, Response &res) {
  16990. observed_types = req.accept_content_types;
  16991. res.set_content("ok", "text/plain");
  16992. });
  16993. auto port = svr.bind_to_any_port(HOST);
  16994. thread t = thread([&]() { svr.listen_after_bind(); });
  16995. auto se = detail::scope_exit([&] {
  16996. svr.stop();
  16997. t.join();
  16998. ASSERT_FALSE(svr.is_running());
  16999. });
  17000. svr.wait_until_ready();
  17001. // Empty first field line, then a real one
  17002. std::string raw_req = "GET / HTTP/1.1\r\n"
  17003. "Host: localhost\r\n"
  17004. "Accept:\r\n"
  17005. "Accept: application/json\r\n"
  17006. "Connection: close\r\n"
  17007. "\r\n";
  17008. std::string out;
  17009. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17010. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17011. ASSERT_EQ(1U, observed_types.size());
  17012. EXPECT_EQ("application/json", observed_types[0]);
  17013. }
  17014. // The skip in get_combined_header_value() is what keeps an empty field line
  17015. // from contributing a bare comma. Only a trailing empty field line exercises
  17016. // it: a leading one is already covered by the "combined is still empty" check,
  17017. // and parse_accept_header() now ignores the empty element either way, so the
  17018. // request-level test above can no longer tell the two apart.
  17019. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  17020. Headers headers;
  17021. headers.emplace("Accept", "text/html");
  17022. headers.emplace("Accept", "");
  17023. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  17024. headers.clear();
  17025. headers.emplace("Accept", "");
  17026. headers.emplace("Accept", "application/json");
  17027. EXPECT_EQ("application/json",
  17028. detail::get_combined_header_value(headers, "Accept"));
  17029. }
  17030. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17031. // An encoding offered on a later Accept-Encoding field line is still offered.
  17032. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  17033. Server svr;
  17034. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17035. res.set_content(std::string(1024, 'x'), "text/plain");
  17036. });
  17037. auto port = svr.bind_to_any_port(HOST);
  17038. thread t = thread([&]() { svr.listen_after_bind(); });
  17039. auto se = detail::scope_exit([&] {
  17040. svr.stop();
  17041. t.join();
  17042. ASSERT_FALSE(svr.is_running());
  17043. });
  17044. svr.wait_until_ready();
  17045. Client cli(HOST, port);
  17046. cli.set_decompress(false);
  17047. Headers headers;
  17048. headers.emplace("Accept-Encoding", "identity");
  17049. headers.emplace("Accept-Encoding", "gzip");
  17050. auto res = cli.Get("/", headers);
  17051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17052. EXPECT_EQ(StatusCode::OK_200, res->status);
  17053. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  17054. }
  17055. #endif
  17056. #ifndef _WIN32
  17057. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  17058. Server svr;
  17059. svr.Post("/post", [&](const Request &req, Response &res) {
  17060. res.set_content(req.body, "text/plain");
  17061. });
  17062. svr.Put("/put", [&](const Request &req, Response &res) {
  17063. res.set_content(req.body, "text/plain");
  17064. });
  17065. svr.Patch("/patch", [&](const Request &req, Response &res) {
  17066. res.set_content(req.body, "text/plain");
  17067. });
  17068. svr.Delete("/delete", [&](const Request &req, Response &res) {
  17069. res.set_content(req.body, "text/plain");
  17070. });
  17071. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17072. auto se = detail::scope_exit([&] {
  17073. svr.stop();
  17074. t.join();
  17075. ASSERT_FALSE(svr.is_running());
  17076. });
  17077. svr.wait_until_ready();
  17078. std::string resp;
  17079. // POST without Content-Length
  17080. ASSERT_TRUE(send_request(5,
  17081. "POST /post HTTP/1.1\r\n"
  17082. "Host: localhost\r\n"
  17083. "Connection: close\r\n"
  17084. "\r\n",
  17085. &resp));
  17086. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17087. // PUT without Content-Length
  17088. resp.clear();
  17089. ASSERT_TRUE(send_request(5,
  17090. "PUT /put HTTP/1.1\r\n"
  17091. "Host: localhost\r\n"
  17092. "Connection: close\r\n"
  17093. "\r\n",
  17094. &resp));
  17095. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17096. // PATCH without Content-Length
  17097. resp.clear();
  17098. ASSERT_TRUE(send_request(5,
  17099. "PATCH /patch HTTP/1.1\r\n"
  17100. "Host: localhost\r\n"
  17101. "Connection: close\r\n"
  17102. "\r\n",
  17103. &resp));
  17104. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17105. // DELETE without Content-Length
  17106. resp.clear();
  17107. ASSERT_TRUE(send_request(5,
  17108. "DELETE /delete HTTP/1.1\r\n"
  17109. "Host: localhost\r\n"
  17110. "Connection: close\r\n"
  17111. "\r\n",
  17112. &resp));
  17113. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17114. }
  17115. #endif
  17116. //==============================================================================
  17117. // open_stream() Tests
  17118. //==============================================================================
  17119. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  17120. std::string result;
  17121. char buf[8192];
  17122. ssize_t n;
  17123. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17124. result.append(buf, static_cast<size_t>(n));
  17125. }
  17126. return result;
  17127. }
  17128. // Mock stream for unit tests
  17129. class MockStream : public Stream {
  17130. public:
  17131. std::string data;
  17132. size_t pos = 0;
  17133. ssize_t error_after = -1; // -1 = no error
  17134. explicit MockStream(const std::string &d, ssize_t err = -1)
  17135. : data(d), error_after(err) {}
  17136. bool is_readable() const override { return true; }
  17137. bool wait_readable() const override { return true; }
  17138. bool wait_writable() const override { return true; }
  17139. ssize_t read(char *ptr, size_t size) override {
  17140. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  17141. if (pos >= data.size()) return 0;
  17142. size_t limit =
  17143. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  17144. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  17145. std::memcpy(ptr, data.data() + pos, to_read);
  17146. pos += to_read;
  17147. return static_cast<ssize_t>(to_read);
  17148. }
  17149. ssize_t write(const char *, size_t) override { return -1; }
  17150. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  17151. ip = "127.0.0.1";
  17152. port = 0;
  17153. }
  17154. void get_local_ip_and_port(std::string &ip, int &port) const override {
  17155. ip = "127.0.0.1";
  17156. port = 0;
  17157. }
  17158. socket_t socket() const override { return INVALID_SOCKET; }
  17159. time_t duration() const override { return 0; }
  17160. };
  17161. TEST(StreamHandleTest, Basic) {
  17162. ClientImpl::StreamHandle handle;
  17163. EXPECT_FALSE(handle.is_valid());
  17164. handle.response = detail::make_unique<Response>();
  17165. handle.error = Error::Connection;
  17166. EXPECT_FALSE(handle.is_valid());
  17167. handle.error = Error::Success;
  17168. EXPECT_TRUE(handle.is_valid());
  17169. }
  17170. TEST(BodyReaderTest, Basic) {
  17171. MockStream stream("Hello, World!");
  17172. detail::BodyReader reader;
  17173. reader.stream = &stream;
  17174. reader.content_length = 13;
  17175. char buf[32];
  17176. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  17177. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  17178. EXPECT_TRUE(reader.eof);
  17179. }
  17180. TEST(BodyReaderTest, NoStream) {
  17181. detail::BodyReader reader;
  17182. char buf[32];
  17183. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  17184. EXPECT_EQ(Error::Connection, reader.last_error);
  17185. }
  17186. TEST(BodyReaderTest, Error) {
  17187. MockStream stream("Hello, World!", 5);
  17188. detail::BodyReader reader;
  17189. reader.stream = &stream;
  17190. reader.content_length = 13;
  17191. char buf[32];
  17192. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  17193. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  17194. EXPECT_EQ(Error::Read, reader.last_error);
  17195. }
  17196. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  17197. // Mock-based StreamHandle tests relying on private internals are removed.
  17198. class OpenStreamTest : public ::testing::Test {
  17199. protected:
  17200. void SetUp() override {
  17201. svr_.Get("/hello", [](const Request &, Response &res) {
  17202. res.set_content("Hello World!", "text/plain");
  17203. });
  17204. svr_.Get("/large", [](const Request &, Response &res) {
  17205. res.set_content(std::string(10000, 'X'), "text/plain");
  17206. });
  17207. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  17208. res.set_content("Hello World!", "image/jpeg");
  17209. res.set_header("Content-Encoding", "UTF-8");
  17210. });
  17211. svr_.Get("/chunked", [](const Request &, Response &res) {
  17212. res.set_chunked_content_provider("text/plain",
  17213. [](size_t offset, DataSink &sink) {
  17214. if (offset < 15) {
  17215. sink.write("chunk", 5);
  17216. return true;
  17217. }
  17218. sink.done();
  17219. return true;
  17220. });
  17221. });
  17222. svr_.Get("/compressible", [](const Request &, Response &res) {
  17223. res.set_chunked_content_provider("text/plain", [](size_t offset,
  17224. DataSink &sink) {
  17225. if (offset < 100 * 1024) {
  17226. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  17227. sink.write(chunk.data(), chunk.size());
  17228. return true;
  17229. }
  17230. sink.done();
  17231. return true;
  17232. });
  17233. });
  17234. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  17235. [](const Request & /*req*/, Response &res) {
  17236. auto i = new int(0);
  17237. res.set_header("Trailer", "Content-Length, X-Allowed");
  17238. res.set_chunked_content_provider(
  17239. "text/plain",
  17240. [i](size_t /*offset*/, DataSink &sink) {
  17241. switch (*i) {
  17242. case 0: sink.os << "123"; break;
  17243. case 1: sink.os << "456"; break;
  17244. case 2: sink.os << "789"; break;
  17245. case 3: {
  17246. sink.done_with_trailer(
  17247. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  17248. } break;
  17249. }
  17250. (*i)++;
  17251. return true;
  17252. },
  17253. [i](bool success) {
  17254. EXPECT_TRUE(success);
  17255. delete i;
  17256. });
  17257. });
  17258. // Echo headers endpoint for header-related tests
  17259. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  17260. std::string body;
  17261. for (const auto &h : req.headers) {
  17262. body.append(h.first);
  17263. body.push_back(':');
  17264. body.append(h.second);
  17265. body.push_back('\n');
  17266. }
  17267. res.set_content(body, "text/plain");
  17268. });
  17269. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  17270. std::string body;
  17271. for (const auto &h : req.headers) {
  17272. body.append(h.first);
  17273. body.push_back(':');
  17274. body.append(h.second);
  17275. body.push_back('\n');
  17276. }
  17277. res.set_content(body, "text/plain");
  17278. });
  17279. port_ = svr_.bind_to_any_port("127.0.0.1");
  17280. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17281. svr_.wait_until_ready();
  17282. }
  17283. void TearDown() override {
  17284. svr_.stop();
  17285. if (thread_.joinable()) thread_.join();
  17286. }
  17287. Server svr_;
  17288. std::thread thread_;
  17289. int port_ = 0;
  17290. };
  17291. TEST_F(OpenStreamTest, Basic) {
  17292. Client cli("127.0.0.1", port_);
  17293. auto handle = cli.open_stream("GET", "/hello");
  17294. EXPECT_TRUE(handle.is_valid());
  17295. EXPECT_EQ("Hello World!", read_all(handle));
  17296. }
  17297. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  17298. Client cli("127.0.0.1", port_);
  17299. auto handle = cli.open_stream("GET", "/unknown-encoding");
  17300. ASSERT_TRUE(handle.is_valid());
  17301. EXPECT_EQ("Hello World!", read_all(handle));
  17302. }
  17303. TEST_F(OpenStreamTest, SmallBuffer) {
  17304. Client cli("127.0.0.1", port_);
  17305. auto handle = cli.open_stream("GET", "/hello");
  17306. std::string result;
  17307. char buf[4];
  17308. ssize_t n;
  17309. while ((n = handle.read(buf, sizeof(buf))) > 0)
  17310. result.append(buf, static_cast<size_t>(n));
  17311. EXPECT_EQ("Hello World!", result);
  17312. }
  17313. TEST_F(OpenStreamTest, DefaultHeaders) {
  17314. Client cli("127.0.0.1", port_);
  17315. // open_stream GET should include Host, User-Agent and Accept-Encoding
  17316. {
  17317. auto handle = cli.open_stream("GET", "/echo-headers");
  17318. ASSERT_TRUE(handle.is_valid());
  17319. auto body = read_all(handle);
  17320. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  17321. std::string::npos);
  17322. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  17323. std::string::npos);
  17324. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  17325. }
  17326. // open_stream POST with body and no explicit content_type should NOT add
  17327. // text/plain Content-Type (behavior differs from non-streaming path), but
  17328. // should include Content-Length
  17329. {
  17330. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  17331. ASSERT_TRUE(handle.is_valid());
  17332. auto body = read_all(handle);
  17333. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  17334. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  17335. }
  17336. // open_stream POST with explicit Content-Type should preserve it
  17337. {
  17338. auto handle = cli.open_stream("POST", "/echo-headers", {},
  17339. {{"Content-Type", "application/custom"}},
  17340. "{}", "application/custom");
  17341. ASSERT_TRUE(handle.is_valid());
  17342. auto body = read_all(handle);
  17343. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  17344. }
  17345. // User-specified User-Agent must not be overwritten for stream API
  17346. {
  17347. auto handle = cli.open_stream("GET", "/echo-headers", {},
  17348. {{"User-Agent", "MyAgent/1.2"}});
  17349. ASSERT_TRUE(handle.is_valid());
  17350. auto body = read_all(handle);
  17351. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  17352. }
  17353. }
  17354. TEST_F(OpenStreamTest, Large) {
  17355. Client cli("127.0.0.1", port_);
  17356. auto handle = cli.open_stream("GET", "/large");
  17357. EXPECT_EQ(10000u, read_all(handle).size());
  17358. }
  17359. TEST_F(OpenStreamTest, ConnectionError) {
  17360. Client cli("127.0.0.1", 9999);
  17361. auto handle = cli.open_stream("GET", "/hello");
  17362. EXPECT_FALSE(handle.is_valid());
  17363. }
  17364. TEST_F(OpenStreamTest, Chunked) {
  17365. Client cli("127.0.0.1", port_);
  17366. auto handle = cli.open_stream("GET", "/chunked");
  17367. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17368. "Transfer-Encoding") == "chunked");
  17369. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  17370. }
  17371. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  17372. Client cli("127.0.0.1", port_);
  17373. auto handle =
  17374. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  17375. ASSERT_TRUE(handle.is_valid());
  17376. // Consume body to allow trailers to be received/parsed
  17377. auto body = read_all(handle);
  17378. // Explicitly parse trailers (ensure trailers are available for assertion)
  17379. handle.parse_trailers_if_needed();
  17380. EXPECT_EQ(std::string("123456789"), body);
  17381. // The response should include a Trailer header declaring both names
  17382. ASSERT_TRUE(handle.response);
  17383. EXPECT_TRUE(handle.response->has_header("Trailer"));
  17384. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  17385. handle.response->get_header_value("Trailer"));
  17386. // Prohibited trailer must not be present
  17387. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  17388. // Allowed trailer should be present
  17389. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  17390. EXPECT_EQ(std::string("yes"),
  17391. handle.response->get_trailer_value("X-Allowed"));
  17392. // Verify trailers are NOT present as regular headers
  17393. EXPECT_EQ(std::string(""),
  17394. handle.response->get_header_value("Content-Length"));
  17395. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  17396. }
  17397. static std::thread serve_single_response(std::promise<int> &port_promise,
  17398. const std::string &response) {
  17399. return std::thread([&port_promise, response] {
  17400. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17401. default_socket_options(srv);
  17402. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  17403. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  17404. sockaddr_in addr{};
  17405. addr.sin_family = AF_INET;
  17406. addr.sin_port = htons(0); // Let OS assign a free port
  17407. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17408. int opt = 1;
  17409. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  17410. #ifdef _WIN32
  17411. reinterpret_cast<const char *>(&opt),
  17412. #else
  17413. &opt,
  17414. #endif
  17415. sizeof(opt));
  17416. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  17417. ::listen(srv, 1) != 0) {
  17418. port_promise.set_value(-1);
  17419. detail::close_socket(srv);
  17420. return;
  17421. }
  17422. socklen_t addr_len = sizeof(addr);
  17423. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  17424. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  17425. sockaddr_in cli_addr{};
  17426. socklen_t cli_len = sizeof(cli_addr);
  17427. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17428. if (cli != INVALID_SOCKET) {
  17429. // Read the complete HTTP request (until the blank line that terminates
  17430. // headers) before sending the response. If the server closes the socket
  17431. // while the client's request data is still unread in the kernel receive
  17432. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  17433. // connection on both sides: it discards the client's receive buffer
  17434. // (which already holds our response) and causes any in-progress write on
  17435. // the client to fail with ECONNRESET. Reading all request data first
  17436. // ensures close() emits a graceful FIN.
  17437. {
  17438. char rbuf[256];
  17439. std::string req;
  17440. while (req.find("\r\n\r\n") == std::string::npos) {
  17441. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  17442. if (n <= 0) { break; }
  17443. req.append(rbuf, static_cast<size_t>(n));
  17444. }
  17445. }
  17446. ::send(cli,
  17447. #ifdef _WIN32
  17448. static_cast<const char *>(response.c_str()),
  17449. static_cast<int>(response.size()),
  17450. #else
  17451. response.c_str(), response.size(),
  17452. #endif
  17453. 0);
  17454. detail::close_socket(cli);
  17455. }
  17456. detail::close_socket(srv);
  17457. });
  17458. }
  17459. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  17460. #ifndef _WIN32
  17461. signal(SIGPIPE, SIG_IGN);
  17462. #endif
  17463. std::promise<int> port_promise;
  17464. auto port_future = port_promise.get_future();
  17465. auto server_thread =
  17466. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  17467. "Content-Type: text/plain\r\n"
  17468. "Content-Length: not-a-number\r\n"
  17469. "Connection: close\r\n"
  17470. "\r\n"
  17471. "hello");
  17472. auto port = port_future.get();
  17473. ASSERT_GT(port, 0);
  17474. Client cli("127.0.0.1", port);
  17475. auto handle = cli.open_stream("GET", "/");
  17476. EXPECT_FALSE(handle.is_valid());
  17477. server_thread.join();
  17478. }
  17479. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  17480. #ifndef _WIN32
  17481. signal(SIGPIPE, SIG_IGN);
  17482. #endif
  17483. std::promise<int> port_promise;
  17484. auto port_future = port_promise.get_future();
  17485. auto server_thread = serve_single_response(
  17486. port_promise, "HTTP/1.1 200 OK\r\n"
  17487. "Content-Type: text/plain\r\n"
  17488. "Content-Length: 99999999999999999999999999\r\n"
  17489. "Connection: close\r\n"
  17490. "\r\n"
  17491. "hello");
  17492. auto port = port_future.get();
  17493. ASSERT_GT(port, 0);
  17494. // Historically std::stoull would throw std::out_of_range here and crash
  17495. // the process, then parsing silently clamped to a bogus framing length and
  17496. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  17497. // so the stream fails to open, matching the not-a-number case above. The
  17498. // process still must NOT terminate.
  17499. Client cli("127.0.0.1", port);
  17500. auto handle = cli.open_stream("GET", "/");
  17501. EXPECT_FALSE(handle.is_valid());
  17502. server_thread.join();
  17503. }
  17504. // Serves `response` to the single request `fn` makes with a fresh client.
  17505. template <typename Fn>
  17506. static void with_single_response(const std::string &response, Fn fn) {
  17507. #ifndef _WIN32
  17508. signal(SIGPIPE, SIG_IGN);
  17509. #endif
  17510. std::promise<int> port_promise;
  17511. auto port_future = port_promise.get_future();
  17512. auto server_thread = serve_single_response(port_promise, response);
  17513. auto se = detail::scope_exit([&] { server_thread.join(); });
  17514. auto port = port_future.get();
  17515. ASSERT_GT(port, 0);
  17516. Client cli("127.0.0.1", port);
  17517. fn(cli);
  17518. }
  17519. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  17520. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  17521. // the chunked coding and drop Content-Length, so a front-end that trusts
  17522. // Content-Length would disagree about where the body ends (response
  17523. // smuggling). The client must reject such a response.
  17524. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  17525. for (const char *te : {"chunked", "gzip, chunked"}) {
  17526. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  17527. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  17528. "\r\n" + "Connection: close\r\n" + "\r\n" +
  17529. "5\r\nhello\r\n0\r\n\r\n";
  17530. with_single_response(response, [&](Client &cli) {
  17531. auto res = cli.Get("/");
  17532. EXPECT_FALSE(static_cast<bool>(res)) << te;
  17533. EXPECT_EQ(Error::Read, res.error()) << te;
  17534. });
  17535. with_single_response(response, [&](Client &cli) {
  17536. auto handle = cli.open_stream("GET", "/");
  17537. EXPECT_FALSE(handle.is_valid()) << te;
  17538. EXPECT_EQ(Error::Read, handle.error) << te;
  17539. });
  17540. }
  17541. }
  17542. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  17543. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  17544. // closing the connection (unlike a request, which must be rejected).
  17545. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  17546. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  17547. "Transfer-Encoding: chunked\r\n"
  17548. "Connection: close\r\n"
  17549. "\r\n"
  17550. "5\r\nhello\r\n0\r\n\r\n",
  17551. "HTTP/1.1 200 OK\r\n"
  17552. "Transfer-Encoding: gzip\r\n"
  17553. "Connection: close\r\n"
  17554. "\r\n"
  17555. "hello"}) {
  17556. with_single_response(response, [&](Client &cli) {
  17557. auto res = cli.Get("/");
  17558. ASSERT_TRUE(static_cast<bool>(res)) << response;
  17559. EXPECT_EQ("hello", res->body);
  17560. });
  17561. with_single_response(response, [&](Client &cli) {
  17562. auto handle = cli.open_stream("GET", "/");
  17563. ASSERT_TRUE(handle.is_valid()) << response;
  17564. EXPECT_EQ("hello", read_all(handle));
  17565. });
  17566. }
  17567. }
  17568. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  17569. // framing headers describe nothing to read and must not be rejected.
  17570. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  17571. const std::string framing = "Content-Length: 5\r\n"
  17572. "Transfer-Encoding: chunked\r\n"
  17573. "Connection: close\r\n"
  17574. "\r\n";
  17575. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  17576. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  17577. });
  17578. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  17579. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  17580. });
  17581. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  17582. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  17583. with_single_response(response, [&](Client &cli) {
  17584. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  17585. });
  17586. with_single_response(response, [&](Client &cli) {
  17587. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  17588. });
  17589. }
  17590. }
  17591. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17592. TEST_F(OpenStreamTest, Gzip) {
  17593. Client cli("127.0.0.1", port_);
  17594. auto handle = cli.open_stream("GET", "/compressible", {},
  17595. {{"Accept-Encoding", "gzip"}});
  17596. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  17597. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17598. }
  17599. #endif
  17600. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  17601. TEST_F(OpenStreamTest, Brotli) {
  17602. Client cli("127.0.0.1", port_);
  17603. auto handle =
  17604. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  17605. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  17606. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17607. }
  17608. #endif
  17609. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  17610. TEST_F(OpenStreamTest, Zstd) {
  17611. Client cli("127.0.0.1", port_);
  17612. auto handle = cli.open_stream("GET", "/compressible", {},
  17613. {{"Accept-Encoding", "zstd"}});
  17614. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  17615. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17616. }
  17617. #endif
  17618. #ifdef CPPHTTPLIB_SSL_ENABLED
  17619. class SSLOpenStreamTest : public ::testing::Test {
  17620. protected:
  17621. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  17622. void SetUp() override {
  17623. svr_.Get("/hello", [](const Request &, Response &res) {
  17624. res.set_content("Hello SSL World!", "text/plain");
  17625. });
  17626. svr_.Get("/chunked", [](const Request &, Response &res) {
  17627. res.set_chunked_content_provider("text/plain",
  17628. [](size_t offset, DataSink &sink) {
  17629. if (offset < 15) {
  17630. sink.write("chunk", 5);
  17631. return true;
  17632. }
  17633. sink.done();
  17634. return true;
  17635. });
  17636. });
  17637. svr_.Post("/echo", [](const Request &req, Response &res) {
  17638. res.set_content(req.body, req.get_header_value("Content-Type"));
  17639. });
  17640. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  17641. std::string body = req.body;
  17642. res.set_chunked_content_provider(
  17643. "text/plain", [body](size_t offset, DataSink &sink) {
  17644. if (offset < body.size()) {
  17645. sink.write(body.data() + offset, body.size() - offset);
  17646. }
  17647. sink.done();
  17648. return true;
  17649. });
  17650. });
  17651. port_ = svr_.bind_to_any_port("127.0.0.1");
  17652. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17653. svr_.wait_until_ready();
  17654. }
  17655. void TearDown() override {
  17656. svr_.stop();
  17657. if (thread_.joinable()) thread_.join();
  17658. }
  17659. SSLServer svr_;
  17660. std::thread thread_;
  17661. int port_ = 0;
  17662. };
  17663. TEST_F(SSLOpenStreamTest, Basic) {
  17664. SSLClient cli("127.0.0.1", port_);
  17665. cli.enable_server_certificate_verification(false);
  17666. auto handle = cli.open_stream("GET", "/hello");
  17667. ASSERT_TRUE(handle.is_valid());
  17668. EXPECT_EQ("Hello SSL World!", read_all(handle));
  17669. }
  17670. TEST_F(SSLOpenStreamTest, Chunked) {
  17671. SSLClient cli("127.0.0.1", port_);
  17672. cli.enable_server_certificate_verification(false);
  17673. auto handle = cli.open_stream("GET", "/chunked");
  17674. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  17675. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17676. "Transfer-Encoding") == "chunked");
  17677. auto body = read_all(handle);
  17678. EXPECT_EQ("chunkchunkchunk", body);
  17679. }
  17680. TEST_F(SSLOpenStreamTest, Post) {
  17681. SSLClient cli("127.0.0.1", port_);
  17682. cli.enable_server_certificate_verification(false);
  17683. auto handle =
  17684. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  17685. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  17686. EXPECT_EQ(200, handle.response->status);
  17687. auto body = read_all(handle);
  17688. EXPECT_EQ("Hello SSL POST", body);
  17689. }
  17690. TEST_F(SSLOpenStreamTest, PostChunked) {
  17691. SSLClient cli("127.0.0.1", port_);
  17692. cli.enable_server_certificate_verification(false);
  17693. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  17694. "Chunked SSL Data", "text/plain");
  17695. ASSERT_TRUE(handle.is_valid());
  17696. EXPECT_EQ(200, handle.response->status);
  17697. auto body = read_all(handle);
  17698. EXPECT_EQ("Chunked SSL Data", body);
  17699. }
  17700. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  17701. // Content-Length is terminated by the server closing the connection. When the
  17702. // SSL peer sends a close_notify after the body, the client must treat it as a
  17703. // clean EOF and return a successful response rather than an error.
  17704. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  17705. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17706. ASSERT_TRUE(svr.is_valid());
  17707. svr.set_keep_alive_max_count(1);
  17708. const std::string expected_body = "Hello from connection-close response!";
  17709. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  17710. res.set_content_provider("text/plain",
  17711. [&](size_t offset, DataSink &sink) -> bool {
  17712. if (offset < expected_body.size()) {
  17713. sink.write(expected_body.data() + offset,
  17714. expected_body.size() - offset);
  17715. }
  17716. sink.done();
  17717. return true;
  17718. });
  17719. });
  17720. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  17721. auto se = detail::scope_exit([&] {
  17722. svr.stop();
  17723. listen_thread.join();
  17724. ASSERT_FALSE(svr.is_running());
  17725. });
  17726. svr.wait_until_ready();
  17727. SSLClient cli(HOST, PORT);
  17728. cli.enable_server_certificate_verification(false);
  17729. auto res = cli.Get("/no-content-length");
  17730. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  17731. EXPECT_EQ(StatusCode::OK_200, res->status);
  17732. EXPECT_EQ(expected_body, res->body);
  17733. }
  17734. #endif // CPPHTTPLIB_SSL_ENABLED
  17735. //==============================================================================
  17736. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  17737. // results for various scenarios.
  17738. //==============================================================================
  17739. TEST(ParityTest, GetVsOpenStream) {
  17740. Server svr;
  17741. const std::string path = "/parity";
  17742. const std::string content = "Parity test content: hello world";
  17743. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  17744. res.set_content(content, "text/plain");
  17745. });
  17746. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17747. auto se = detail::scope_exit([&] {
  17748. svr.stop();
  17749. t.join();
  17750. ASSERT_FALSE(svr.is_running());
  17751. });
  17752. svr.wait_until_ready();
  17753. Client cli(HOST, PORT);
  17754. // Non-stream path
  17755. auto r1 = cli.Get(path);
  17756. ASSERT_TRUE(r1);
  17757. EXPECT_EQ(StatusCode::OK_200, r1->status);
  17758. // Stream path
  17759. auto h = cli.open_stream("GET", path);
  17760. ASSERT_TRUE(h.is_valid());
  17761. EXPECT_EQ(r1->body, read_all(h));
  17762. }
  17763. // Helper to compress data with provided compressor type T
  17764. template <typename Compressor>
  17765. static std::string compress_payload_for_parity(const std::string &in) {
  17766. std::string out;
  17767. Compressor compressor;
  17768. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  17769. [&](const char *data, size_t n) {
  17770. out.append(data, n);
  17771. return true;
  17772. });
  17773. EXPECT_TRUE(ok);
  17774. return out;
  17775. }
  17776. // Helper function for compression parity tests
  17777. template <typename Compressor>
  17778. static void test_compression_parity(const std::string &original,
  17779. const std::string &path,
  17780. const std::string &encoding) {
  17781. const std::string compressed =
  17782. compress_payload_for_parity<Compressor>(original);
  17783. Server svr;
  17784. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  17785. res.set_content(compressed, "application/octet-stream");
  17786. res.set_header("Content-Encoding", encoding);
  17787. });
  17788. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  17789. auto se = detail::scope_exit([&] {
  17790. svr.stop();
  17791. t.join();
  17792. ASSERT_FALSE(svr.is_running());
  17793. });
  17794. svr.wait_until_ready();
  17795. Client cli(HOST, PORT);
  17796. // Non-streaming
  17797. {
  17798. auto res = cli.Get(path);
  17799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17800. EXPECT_EQ(StatusCode::OK_200, res->status);
  17801. EXPECT_EQ(original, res->body);
  17802. }
  17803. // Streaming
  17804. {
  17805. auto h = cli.open_stream("GET", path);
  17806. ASSERT_TRUE(h.is_valid());
  17807. EXPECT_EQ(original, read_all(h));
  17808. }
  17809. }
  17810. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17811. TEST(ParityTest, Gzip) {
  17812. test_compression_parity<detail::gzip_compressor>(
  17813. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  17814. }
  17815. #endif
  17816. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  17817. TEST(ParityTest, Brotli) {
  17818. test_compression_parity<detail::brotli_compressor>(
  17819. "Hello, brotli parity test payload", "/parity-br", "br");
  17820. }
  17821. #endif
  17822. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  17823. TEST(ParityTest, Zstd) {
  17824. test_compression_parity<detail::zstd_compressor>(
  17825. "Zstandard parity test payload", "/parity-zstd", "zstd");
  17826. }
  17827. #endif
  17828. //==============================================================================
  17829. // New Stream API Tests
  17830. //==============================================================================
  17831. inline std::string read_body(httplib::stream::Result &result) {
  17832. std::string body;
  17833. while (result.next()) {
  17834. body.append(result.data(), result.size());
  17835. }
  17836. return body;
  17837. }
  17838. TEST(ClientConnectionTest, Basic) {
  17839. httplib::ClientConnection conn;
  17840. EXPECT_FALSE(conn.is_open());
  17841. conn.sock = 1;
  17842. EXPECT_TRUE(conn.is_open());
  17843. httplib::ClientConnection conn2(std::move(conn));
  17844. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  17845. conn2.sock = INVALID_SOCKET;
  17846. }
  17847. // Unified test server for all stream::* tests
  17848. class StreamApiTest : public ::testing::Test {
  17849. protected:
  17850. void SetUp() override {
  17851. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  17852. res.set_content("Hello World!", "text/plain");
  17853. });
  17854. svr_.Get("/echo-params",
  17855. [](const httplib::Request &req, httplib::Response &res) {
  17856. std::string r;
  17857. for (const auto &p : req.params) {
  17858. if (!r.empty()) r += "&";
  17859. r += p.first + "=" + p.second;
  17860. }
  17861. res.set_content(r, "text/plain");
  17862. });
  17863. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17864. res.set_content(req.body, req.get_header_value("Content-Type"));
  17865. });
  17866. svr_.Post("/echo-headers",
  17867. [](const httplib::Request &req, httplib::Response &res) {
  17868. std::string r;
  17869. for (const auto &h : req.headers)
  17870. r += h.first + ": " + h.second + "\n";
  17871. res.set_content(r, "text/plain");
  17872. });
  17873. svr_.Post("/echo-params",
  17874. [](const httplib::Request &req, httplib::Response &res) {
  17875. std::string r = "params:";
  17876. for (const auto &p : req.params)
  17877. r += p.first + "=" + p.second + ";";
  17878. res.set_content(r + " body:" + req.body, "text/plain");
  17879. });
  17880. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  17881. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  17882. });
  17883. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17884. res.set_content("PUT:" + req.body, "text/plain");
  17885. });
  17886. svr_.Patch("/echo",
  17887. [](const httplib::Request &req, httplib::Response &res) {
  17888. res.set_content("PATCH:" + req.body, "text/plain");
  17889. });
  17890. svr_.Delete(
  17891. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  17892. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  17893. "text/plain");
  17894. });
  17895. svr_.Get("/head-test",
  17896. [](const httplib::Request &, httplib::Response &res) {
  17897. res.set_content("body for HEAD", "text/plain");
  17898. });
  17899. svr_.Options("/options",
  17900. [](const httplib::Request &, httplib::Response &res) {
  17901. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  17902. });
  17903. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  17904. svr_.wait_until_ready();
  17905. }
  17906. void TearDown() override {
  17907. svr_.stop();
  17908. if (thread_.joinable()) thread_.join();
  17909. }
  17910. httplib::Server svr_;
  17911. std::thread thread_;
  17912. };
  17913. // stream::Get tests
  17914. TEST_F(StreamApiTest, GetBasic) {
  17915. httplib::Client cli(HOST, PORT);
  17916. auto result = httplib::stream::Get(cli, "/hello");
  17917. ASSERT_TRUE(result.is_valid());
  17918. EXPECT_EQ(200, result.status());
  17919. EXPECT_EQ("Hello World!", read_body(result));
  17920. }
  17921. TEST_F(StreamApiTest, GetWithParams) {
  17922. httplib::Client cli(HOST, PORT);
  17923. httplib::Params params{{"foo", "bar"}};
  17924. auto result = httplib::stream::Get(cli, "/echo-params", params);
  17925. ASSERT_TRUE(result.is_valid());
  17926. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  17927. }
  17928. TEST_F(StreamApiTest, GetConnectionError) {
  17929. httplib::Client cli(HOST, 9999);
  17930. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  17931. }
  17932. TEST_F(StreamApiTest, Get404) {
  17933. httplib::Client cli(HOST, PORT);
  17934. auto result = httplib::stream::Get(cli, "/nonexistent");
  17935. EXPECT_TRUE(result.is_valid());
  17936. EXPECT_EQ(404, result.status());
  17937. }
  17938. // stream::Post tests
  17939. TEST_F(StreamApiTest, PostBasic) {
  17940. httplib::Client cli(HOST, PORT);
  17941. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  17942. "application/json");
  17943. ASSERT_TRUE(result.is_valid());
  17944. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  17945. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  17946. }
  17947. TEST_F(StreamApiTest, PostWithHeaders) {
  17948. httplib::Client cli(HOST, PORT);
  17949. httplib::Headers headers{{"X-Custom", "value"}};
  17950. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  17951. "text/plain");
  17952. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  17953. }
  17954. TEST_F(StreamApiTest, PostWithParams) {
  17955. httplib::Client cli(HOST, PORT);
  17956. httplib::Params params{{"k", "v"}};
  17957. auto result =
  17958. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  17959. auto body = read_body(result);
  17960. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  17961. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  17962. }
  17963. TEST_F(StreamApiTest, PostLarge) {
  17964. httplib::Client cli(HOST, PORT);
  17965. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  17966. size_t total = 0;
  17967. while (result.next()) {
  17968. total += result.size();
  17969. }
  17970. EXPECT_EQ(100u * 1024u, total);
  17971. }
  17972. // stream::Put/Patch tests
  17973. TEST_F(StreamApiTest, PutAndPatch) {
  17974. httplib::Client cli(HOST, PORT);
  17975. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  17976. EXPECT_EQ("PUT:test", read_body(put));
  17977. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  17978. EXPECT_EQ("PATCH:test", read_body(patch));
  17979. }
  17980. // stream::Delete tests
  17981. TEST_F(StreamApiTest, Delete) {
  17982. httplib::Client cli(HOST, PORT);
  17983. auto del1 = httplib::stream::Delete(cli, "/resource");
  17984. EXPECT_EQ("Deleted", read_body(del1));
  17985. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  17986. EXPECT_EQ("Deleted:data", read_body(del2));
  17987. }
  17988. // stream::Head/Options tests
  17989. TEST_F(StreamApiTest, HeadAndOptions) {
  17990. httplib::Client cli(HOST, PORT);
  17991. auto head = httplib::stream::Head(cli, "/head-test");
  17992. EXPECT_TRUE(head.is_valid());
  17993. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  17994. auto opts = httplib::stream::Options(cli, "/options");
  17995. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  17996. }
  17997. // SSL stream::* tests
  17998. #ifdef CPPHTTPLIB_SSL_ENABLED
  17999. class SSLStreamApiTest : public ::testing::Test {
  18000. protected:
  18001. void SetUp() override {
  18002. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18003. res.set_content("Hello SSL!", "text/plain");
  18004. });
  18005. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18006. res.set_content(req.body, "text/plain");
  18007. });
  18008. port_ = svr_.bind_to_any_port("127.0.0.1");
  18009. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18010. svr_.wait_until_ready();
  18011. }
  18012. void TearDown() override {
  18013. svr_.stop();
  18014. if (thread_.joinable()) thread_.join();
  18015. }
  18016. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  18017. std::thread thread_;
  18018. int port_ = 0;
  18019. };
  18020. TEST_F(SSLStreamApiTest, GetAndPost) {
  18021. httplib::SSLClient cli("127.0.0.1", port_);
  18022. cli.enable_server_certificate_verification(false);
  18023. auto get = httplib::stream::Get(cli, "/hello");
  18024. EXPECT_EQ("Hello SSL!", read_body(get));
  18025. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  18026. EXPECT_EQ("test", read_body(post));
  18027. }
  18028. #endif
  18029. // Tests for Error::Timeout and Error::ConnectionClosed error types
  18030. // These errors are set in SocketStream/SSLSocketStream and propagated through
  18031. // BodyReader
  18032. TEST(ErrorHandlingTest, StreamReadTimeout) {
  18033. // Test that read timeout during streaming is detected
  18034. // Use a large content-length response where server delays mid-stream
  18035. Server svr;
  18036. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18037. // Send a large response with delay in the middle
  18038. res.set_content_provider(
  18039. 1000, // content_length
  18040. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  18041. if (offset < 100) {
  18042. // Send first 100 bytes immediately
  18043. std::string data(100, 'A');
  18044. sink.write(data.c_str(), data.size());
  18045. return true;
  18046. }
  18047. // Then delay longer than client timeout
  18048. std::this_thread::sleep_for(std::chrono::seconds(3));
  18049. std::string data(900, 'B');
  18050. sink.write(data.c_str(), data.size());
  18051. return true;
  18052. });
  18053. });
  18054. auto port = 8091;
  18055. std::thread t([&]() { svr.listen("localhost", port); });
  18056. svr.wait_until_ready();
  18057. Client cli("localhost", port);
  18058. cli.set_read_timeout(1, 0); // 1 second timeout
  18059. auto handle = cli.open_stream("GET", "/slow-stream");
  18060. ASSERT_TRUE(handle.is_valid());
  18061. char buf[256];
  18062. ssize_t total = 0;
  18063. ssize_t n;
  18064. bool got_error = false;
  18065. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18066. total += n;
  18067. }
  18068. if (n < 0) {
  18069. got_error = true;
  18070. // Should be timeout or read error
  18071. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18072. handle.get_read_error() == Error::Read)
  18073. << "Actual error: " << to_string(handle.get_read_error());
  18074. }
  18075. // Either we got an error, or we got less data than expected
  18076. EXPECT_TRUE(got_error || total < 1000)
  18077. << "Expected timeout but got all " << total << " bytes";
  18078. svr.stop();
  18079. t.join();
  18080. }
  18081. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  18082. // Test connection closed detection via BodyReader
  18083. Server svr;
  18084. std::atomic<bool> close_now{false};
  18085. svr.Get("/will-close", [&](const Request &, Response &res) {
  18086. res.set_content_provider(
  18087. 10000, // Large content_length that we won't fully send
  18088. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18089. if (offset < 100) {
  18090. std::string data(100, 'X');
  18091. sink.write(data.c_str(), data.size());
  18092. return true;
  18093. }
  18094. // Wait for signal then abort
  18095. while (!close_now) {
  18096. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18097. }
  18098. return false; // Abort - server will close connection
  18099. });
  18100. });
  18101. auto port = 8092;
  18102. std::thread t([&]() { svr.listen("localhost", port); });
  18103. svr.wait_until_ready();
  18104. Client cli("localhost", port);
  18105. auto handle = cli.open_stream("GET", "/will-close");
  18106. ASSERT_TRUE(handle.is_valid());
  18107. char buf[256];
  18108. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18109. EXPECT_GT(n, 0) << "First read should succeed";
  18110. // Signal server to close
  18111. close_now = true;
  18112. // Keep reading until error or EOF
  18113. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18114. // Keep reading
  18115. }
  18116. // Should get an error since content_length wasn't satisfied
  18117. if (n < 0) {
  18118. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  18119. handle.get_read_error() == Error::Read)
  18120. << "Actual error: " << to_string(handle.get_read_error());
  18121. }
  18122. svr.stop();
  18123. t.join();
  18124. }
  18125. #ifdef CPPHTTPLIB_SSL_ENABLED
  18126. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  18127. // Test that read timeout during SSL streaming is detected
  18128. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18129. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18130. res.set_content_provider(
  18131. 1000, "text/plain",
  18132. [](size_t offset, size_t /*length*/, DataSink &sink) {
  18133. if (offset < 100) {
  18134. std::string data(100, 'A');
  18135. sink.write(data.c_str(), data.size());
  18136. return true;
  18137. }
  18138. std::this_thread::sleep_for(std::chrono::seconds(3));
  18139. std::string data(900, 'B');
  18140. sink.write(data.c_str(), data.size());
  18141. return true;
  18142. });
  18143. });
  18144. auto port = 8093;
  18145. std::thread t([&]() { svr.listen("localhost", port); });
  18146. svr.wait_until_ready();
  18147. SSLClient cli("localhost", port);
  18148. cli.enable_server_certificate_verification(false);
  18149. cli.set_read_timeout(1, 0); // 1 second timeout
  18150. auto handle = cli.open_stream("GET", "/slow-stream");
  18151. ASSERT_TRUE(handle.is_valid());
  18152. char buf[256];
  18153. ssize_t total = 0;
  18154. ssize_t n;
  18155. bool got_error = false;
  18156. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18157. total += n;
  18158. }
  18159. if (n < 0) {
  18160. got_error = true;
  18161. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18162. handle.get_read_error() == Error::Read)
  18163. << "Actual error: " << to_string(handle.get_read_error());
  18164. }
  18165. EXPECT_TRUE(got_error || total < 1000)
  18166. << "Expected timeout but got all " << total << " bytes";
  18167. svr.stop();
  18168. t.join();
  18169. }
  18170. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  18171. // Test SSL connection closed detection
  18172. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18173. std::atomic<bool> close_now{false};
  18174. svr.Get("/will-close", [&](const Request &, Response &res) {
  18175. res.set_content_provider(
  18176. 10000, "text/plain",
  18177. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18178. if (offset < 100) {
  18179. std::string data(100, 'X');
  18180. sink.write(data.c_str(), data.size());
  18181. return true;
  18182. }
  18183. while (!close_now) {
  18184. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18185. }
  18186. return false;
  18187. });
  18188. });
  18189. auto port = 8094;
  18190. std::thread t([&]() { svr.listen("localhost", port); });
  18191. svr.wait_until_ready();
  18192. SSLClient cli("localhost", port);
  18193. cli.enable_server_certificate_verification(false);
  18194. auto handle = cli.open_stream("GET", "/will-close");
  18195. ASSERT_TRUE(handle.is_valid());
  18196. char buf[256];
  18197. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18198. EXPECT_GT(n, 0);
  18199. // Signal server to close
  18200. close_now = true;
  18201. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18202. // Keep reading
  18203. }
  18204. if (n < 0) {
  18205. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  18206. handle.get_read_error() == Error::Read)
  18207. << "Actual error: " << to_string(handle.get_read_error());
  18208. }
  18209. svr.stop();
  18210. t.join();
  18211. }
  18212. #endif
  18213. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  18214. using namespace httplib;
  18215. // Create a test file
  18216. const char *fname = "etag_testfile.txt";
  18217. const char *content = "etag-content";
  18218. {
  18219. std::ofstream ofs(fname);
  18220. ofs << content;
  18221. ASSERT_TRUE(ofs.good());
  18222. }
  18223. Server svr;
  18224. svr.set_mount_point("/static", ".");
  18225. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  18226. svr.wait_until_ready();
  18227. Client cli(HOST, PORT);
  18228. // First request: should get 200 with ETag header
  18229. auto res1 = cli.Get("/static/etag_testfile.txt");
  18230. ASSERT_TRUE(res1);
  18231. ASSERT_EQ(200, res1->status);
  18232. ASSERT_TRUE(res1->has_header("ETag"));
  18233. std::string etag = res1->get_header_value("ETag");
  18234. EXPECT_FALSE(etag.empty());
  18235. // Verify ETag format: W/"hex-hex"
  18236. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  18237. EXPECT_EQ('W', etag[0]);
  18238. EXPECT_EQ('/', etag[1]);
  18239. EXPECT_EQ('"', etag[2]);
  18240. EXPECT_EQ('"', etag.back());
  18241. // Exact match: expect 304 Not Modified
  18242. Headers h2 = {{"If-None-Match", etag}};
  18243. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  18244. ASSERT_TRUE(res2);
  18245. EXPECT_EQ(304, res2->status);
  18246. // Wildcard match: expect 304 Not Modified
  18247. Headers h3 = {{"If-None-Match", "*"}};
  18248. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  18249. ASSERT_TRUE(res3);
  18250. EXPECT_EQ(304, res3->status);
  18251. // Non-matching ETag: expect 200
  18252. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  18253. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  18254. ASSERT_TRUE(res4);
  18255. EXPECT_EQ(200, res4->status);
  18256. // Multiple ETags with one matching: expect 304
  18257. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  18258. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  18259. ASSERT_TRUE(res5);
  18260. EXPECT_EQ(304, res5->status);
  18261. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  18262. // that equivalent to the single comma-separated list above, so the match on
  18263. // the second line must still be found.
  18264. Headers h6;
  18265. h6.emplace("If-None-Match", "W/\"other\"");
  18266. h6.emplace("If-None-Match", etag);
  18267. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  18268. ASSERT_TRUE(res6);
  18269. EXPECT_EQ(304, res6->status);
  18270. svr.stop();
  18271. t.join();
  18272. std::remove(fname);
  18273. }
  18274. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  18275. using namespace httplib;
  18276. Server svr;
  18277. svr.set_mount_point("/static", ".");
  18278. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18279. svr.wait_until_ready();
  18280. Client cli(HOST, PORT);
  18281. // Send If-None-Match: * to a non-existent file
  18282. Headers h = {{"If-None-Match", "*"}};
  18283. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  18284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18285. EXPECT_EQ(404, res->status);
  18286. svr.stop();
  18287. t.join();
  18288. }
  18289. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  18290. using namespace httplib;
  18291. // Create a test file
  18292. const char *fname = "etag_boundary_testfile.txt";
  18293. const char *content = "boundary-test";
  18294. {
  18295. std::ofstream ofs(fname);
  18296. ofs << content;
  18297. ASSERT_TRUE(ofs.good());
  18298. }
  18299. Server svr;
  18300. svr.set_mount_point("/static", ".");
  18301. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  18302. svr.wait_until_ready();
  18303. Client cli(HOST, PORT);
  18304. // Get the actual ETag
  18305. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  18306. ASSERT_TRUE(res1);
  18307. ASSERT_EQ(200, res1->status);
  18308. ASSERT_TRUE(res1->has_header("ETag"));
  18309. std::string etag = res1->get_header_value("ETag");
  18310. // Test 1: Very long ETag value (longer than actual ETag)
  18311. // Should NOT match and return 200 (not trigger out-of-bounds read)
  18312. Headers h1 = {{"If-None-Match", "W/"
  18313. "\"very-long-etag-value-that-is-much-longer-"
  18314. "than-the-actual-etag-value\""}};
  18315. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  18316. ASSERT_TRUE(res2);
  18317. EXPECT_EQ(200, res2->status); // Should not match
  18318. // Test 2: Long string followed by wildcard
  18319. // Should match on "*" and return 304 (without out-of-bounds read on the long
  18320. // string)
  18321. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  18322. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  18323. ASSERT_TRUE(res3);
  18324. EXPECT_EQ(304, res3->status); // Should match on "*"
  18325. // Test 3: Wildcard followed by long string
  18326. // Should match on "*" immediately and return 304
  18327. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  18328. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  18329. ASSERT_TRUE(res4);
  18330. EXPECT_EQ(304, res4->status); // Should match on "*"
  18331. // Test 4: Multiple long non-matching values
  18332. // Should NOT match and return 200 (test that all comparisons are safe)
  18333. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  18334. "W/\"second-long-non-matching-value\", "
  18335. "W/\"third-long-non-matching-value\""}};
  18336. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  18337. ASSERT_TRUE(res5);
  18338. EXPECT_EQ(200, res5->status); // Should not match
  18339. // Test 5: Single character that is not "*" (edge case)
  18340. Headers h5 = {{"If-None-Match", "X"}};
  18341. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  18342. ASSERT_TRUE(res6);
  18343. EXPECT_EQ(200, res6->status); // Should not match
  18344. svr.stop();
  18345. t.join();
  18346. std::remove(fname);
  18347. }
  18348. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  18349. using namespace httplib;
  18350. // Create a test file
  18351. const char *fname = "ims_testfile.txt";
  18352. const char *content = "if-modified-since-test";
  18353. {
  18354. std::ofstream ofs(fname);
  18355. ofs << content;
  18356. ASSERT_TRUE(ofs.good());
  18357. }
  18358. Server svr;
  18359. svr.set_mount_point("/static", ".");
  18360. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18361. svr.wait_until_ready();
  18362. Client cli(HOST, PORT);
  18363. // First request: should get 200 with Last-Modified header
  18364. auto res1 = cli.Get("/static/ims_testfile.txt");
  18365. ASSERT_TRUE(res1);
  18366. ASSERT_EQ(200, res1->status);
  18367. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18368. std::string last_modified = res1->get_header_value("Last-Modified");
  18369. EXPECT_FALSE(last_modified.empty());
  18370. // If-Modified-Since with same time: expect 304
  18371. Headers h2 = {{"If-Modified-Since", last_modified}};
  18372. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  18373. ASSERT_TRUE(res2);
  18374. EXPECT_EQ(304, res2->status);
  18375. // If-Modified-Since with future time: expect 304
  18376. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18377. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  18378. ASSERT_TRUE(res3);
  18379. EXPECT_EQ(304, res3->status);
  18380. // If-Modified-Since with past time: expect 200
  18381. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18382. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  18383. ASSERT_TRUE(res4);
  18384. EXPECT_EQ(200, res4->status);
  18385. // If-None-Match takes precedence over If-Modified-Since
  18386. // (send matching ETag with old If-Modified-Since -> should still be 304)
  18387. ASSERT_TRUE(res1->has_header("ETag"));
  18388. std::string etag = res1->get_header_value("ETag");
  18389. Headers h5 = {{"If-None-Match", etag},
  18390. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18391. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  18392. ASSERT_TRUE(res5);
  18393. EXPECT_EQ(304, res5->status);
  18394. svr.stop();
  18395. t.join();
  18396. std::remove(fname);
  18397. }
  18398. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  18399. using namespace httplib;
  18400. Server svr;
  18401. // Endpoint that returns compressible content
  18402. svr.Get("/compressible", [](const Request &, Response &res) {
  18403. // Return a large enough body to trigger compression
  18404. std::string body(1000, 'a');
  18405. res.set_content(body, "text/plain");
  18406. });
  18407. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18408. svr.wait_until_ready();
  18409. Client cli(HOST, PORT);
  18410. // Request with gzip support: should get Vary header when compressed
  18411. cli.set_compress(true);
  18412. auto res1 = cli.Get("/compressible");
  18413. ASSERT_TRUE(res1);
  18414. EXPECT_EQ(200, res1->status);
  18415. // If Content-Encoding is set, Vary should also be set
  18416. if (res1->has_header("Content-Encoding")) {
  18417. EXPECT_TRUE(res1->has_header("Vary"));
  18418. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  18419. }
  18420. // Request without Accept-Encoding header: should not have compression
  18421. Headers h_no_compress;
  18422. auto res2 = cli.Get("/compressible", h_no_compress);
  18423. ASSERT_TRUE(res2);
  18424. EXPECT_EQ(200, res2->status);
  18425. // Verify Vary header is present when compression is applied
  18426. // (the exact behavior depends on server configuration)
  18427. svr.stop();
  18428. t.join();
  18429. }
  18430. TEST(ETagTest, IfRangeWithETag) {
  18431. using namespace httplib;
  18432. // Create a test file with known content
  18433. const char *fname = "if_range_testfile.txt";
  18434. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  18435. {
  18436. std::ofstream ofs(fname);
  18437. ofs << content;
  18438. ASSERT_TRUE(ofs.good());
  18439. }
  18440. Server svr;
  18441. svr.set_mount_point("/static", ".");
  18442. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18443. svr.wait_until_ready();
  18444. Client cli(HOST, PORT);
  18445. // First request: get ETag
  18446. auto res1 = cli.Get("/static/if_range_testfile.txt");
  18447. ASSERT_TRUE(res1);
  18448. ASSERT_EQ(200, res1->status);
  18449. ASSERT_TRUE(res1->has_header("ETag"));
  18450. std::string etag = res1->get_header_value("ETag");
  18451. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  18452. // Since our server generates weak ETags (W/"..."), If-Range with our
  18453. // ETag should NOT result in partial content - it should return full content.
  18454. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  18455. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  18456. ASSERT_TRUE(res2);
  18457. // Weak ETag in If-Range -> full content (200), not partial (206)
  18458. EXPECT_EQ(200, res2->status);
  18459. EXPECT_EQ(content, res2->body);
  18460. EXPECT_FALSE(res2->has_header("Content-Range"));
  18461. // Range request with non-matching If-Range (ETag): should get 200 (full
  18462. // content)
  18463. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  18464. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  18465. ASSERT_TRUE(res3);
  18466. EXPECT_EQ(200, res3->status);
  18467. EXPECT_EQ(content, res3->body);
  18468. EXPECT_FALSE(res3->has_header("Content-Range"));
  18469. // Range request with strong ETag (hypothetical - our server doesn't generate
  18470. // strong ETags, but if client sends a strong ETag that doesn't match, it
  18471. // should return full content)
  18472. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  18473. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  18474. ASSERT_TRUE(res4);
  18475. EXPECT_EQ(200, res4->status);
  18476. EXPECT_EQ(content, res4->body);
  18477. EXPECT_FALSE(res4->has_header("Content-Range"));
  18478. svr.stop();
  18479. t.join();
  18480. std::remove(fname);
  18481. }
  18482. TEST(ETagTest, IfRangeWithDate) {
  18483. using namespace httplib;
  18484. // Create a test file
  18485. const char *fname = "if_range_date_testfile.txt";
  18486. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  18487. {
  18488. std::ofstream ofs(fname);
  18489. ofs << content;
  18490. ASSERT_TRUE(ofs.good());
  18491. }
  18492. Server svr;
  18493. svr.set_mount_point("/static", ".");
  18494. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18495. svr.wait_until_ready();
  18496. Client cli(HOST, PORT);
  18497. // First request: get Last-Modified
  18498. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  18499. ASSERT_TRUE(res1);
  18500. ASSERT_EQ(200, res1->status);
  18501. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18502. std::string last_modified = res1->get_header_value("Last-Modified");
  18503. // Range request with matching If-Range (date): should get 206
  18504. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  18505. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  18506. ASSERT_TRUE(res2);
  18507. EXPECT_EQ(206, res2->status);
  18508. EXPECT_EQ("FGHIJ", res2->body);
  18509. // Range request with old If-Range date: should get 200 (full content)
  18510. Headers h3 = {{"Range", "bytes=5-9"},
  18511. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18512. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  18513. ASSERT_TRUE(res3);
  18514. EXPECT_EQ(200, res3->status);
  18515. EXPECT_EQ(content, res3->body);
  18516. // Range request with future If-Range date: should get 206
  18517. Headers h4 = {{"Range", "bytes=0-4"},
  18518. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18519. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  18520. ASSERT_TRUE(res4);
  18521. EXPECT_EQ(206, res4->status);
  18522. EXPECT_EQ("ABCDE", res4->body);
  18523. svr.stop();
  18524. t.join();
  18525. std::remove(fname);
  18526. }
  18527. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  18528. using namespace httplib;
  18529. const char *fname = "etag_malformed.txt";
  18530. const char *content = "malformed-etag";
  18531. {
  18532. std::ofstream ofs(fname);
  18533. ofs << content;
  18534. ASSERT_TRUE(ofs.good());
  18535. }
  18536. Server svr;
  18537. svr.set_mount_point("/static", ".");
  18538. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18539. svr.wait_until_ready();
  18540. Client cli(HOST, PORT);
  18541. // baseline: should get 200 and an ETag
  18542. auto res1 = cli.Get("/static/etag_malformed.txt");
  18543. ASSERT_TRUE(res1);
  18544. ASSERT_EQ(200, res1->status);
  18545. ASSERT_TRUE(res1->has_header("ETag"));
  18546. // Malformed ETag value (missing quotes) should be treated as non-matching
  18547. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  18548. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  18549. ASSERT_TRUE(res_bad);
  18550. EXPECT_EQ(200, res_bad->status);
  18551. // Whitespace-only header value should be considered invalid / non-matching
  18552. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  18553. "Host: localhost\r\n"
  18554. "If-None-Match: \r\n"
  18555. "Connection: close\r\n"
  18556. "\r\n";
  18557. std::string out;
  18558. ASSERT_TRUE(send_request(5, raw_req, &out));
  18559. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18560. svr.stop();
  18561. t.join();
  18562. std::remove(fname);
  18563. }
  18564. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  18565. using namespace httplib;
  18566. const char *fname = "ims_invalid_format.txt";
  18567. const char *content = "ims-bad-format";
  18568. {
  18569. std::ofstream ofs(fname);
  18570. ofs << content;
  18571. ASSERT_TRUE(ofs.good());
  18572. }
  18573. Server svr;
  18574. svr.set_mount_point("/static", ".");
  18575. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18576. svr.wait_until_ready();
  18577. Client cli(HOST, PORT);
  18578. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  18579. ASSERT_TRUE(res1);
  18580. ASSERT_EQ(200, res1->status);
  18581. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18582. // If-Modified-Since with invalid format should not result in 304
  18583. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  18584. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  18585. ASSERT_TRUE(res_bad);
  18586. EXPECT_EQ(200, res_bad->status);
  18587. // If-Range with invalid date format should be treated as mismatch -> full
  18588. // content (200)
  18589. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  18590. {"If-Range", "invalid-date"}};
  18591. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  18592. ASSERT_TRUE(res_ifrange);
  18593. EXPECT_EQ(200, res_ifrange->status);
  18594. svr.stop();
  18595. t.join();
  18596. std::remove(fname);
  18597. }
  18598. TEST(ETagTest, IfRangeWithMalformedETag) {
  18599. using namespace httplib;
  18600. const char *fname = "ifrange_malformed.txt";
  18601. const std::string content = "0123456789";
  18602. {
  18603. std::ofstream ofs(fname);
  18604. ofs << content;
  18605. ASSERT_TRUE(ofs.good());
  18606. }
  18607. Server svr;
  18608. svr.set_mount_point("/static", ".");
  18609. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18610. svr.wait_until_ready();
  18611. Client cli(HOST, PORT);
  18612. // First request: get ETag
  18613. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  18614. ASSERT_TRUE(res1);
  18615. ASSERT_EQ(200, res1->status);
  18616. ASSERT_TRUE(res1->has_header("ETag"));
  18617. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  18618. // full content (200)
  18619. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  18620. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  18621. ASSERT_TRUE(res2);
  18622. EXPECT_EQ(200, res2->status);
  18623. EXPECT_EQ(content, res2->body);
  18624. svr.stop();
  18625. t.join();
  18626. std::remove(fname);
  18627. }
  18628. TEST(ETagTest, ExtremeLargeDateValues) {
  18629. using namespace httplib;
  18630. const char *fname = "ims_extreme_date.txt";
  18631. const char *content = "ims-extreme-date";
  18632. {
  18633. std::ofstream ofs(fname);
  18634. ofs << content;
  18635. ASSERT_TRUE(ofs.good());
  18636. }
  18637. Server svr;
  18638. svr.set_mount_point("/static", ".");
  18639. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18640. svr.wait_until_ready();
  18641. Client cli(HOST, PORT);
  18642. auto res1 = cli.Get(std::string("/static/") + fname);
  18643. ASSERT_TRUE(res1);
  18644. ASSERT_EQ(200, res1->status);
  18645. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18646. // Extremely large year that may overflow date parsing routines.
  18647. Headers h_large_date = {
  18648. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18649. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  18650. ASSERT_TRUE(res_bad);
  18651. // Expect server to treat this as invalid/mismatch and return full content
  18652. EXPECT_EQ(200, res_bad->status);
  18653. // If-Range with extremely large date should be treated as mismatch -> full
  18654. // content (200)
  18655. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  18656. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18657. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  18658. ASSERT_TRUE(res_ifrange);
  18659. EXPECT_EQ(200, res_ifrange->status);
  18660. svr.stop();
  18661. t.join();
  18662. std::remove(fname);
  18663. }
  18664. TEST(ETagTest, NegativeFileModificationTime) {
  18665. using namespace httplib;
  18666. const char *fname = "ims_negative_mtime.txt";
  18667. const std::string content = "negative-mtime";
  18668. {
  18669. std::ofstream ofs(fname);
  18670. ofs << content;
  18671. ASSERT_TRUE(ofs.good());
  18672. }
  18673. // Try to set file mtime to a negative value. This may fail on some
  18674. // platforms/filesystems; if it fails, the test will still verify server
  18675. // behaves safely by performing a regular conditional request.
  18676. #if defined(__APPLE__) || defined(__linux__)
  18677. bool set_negative = false;
  18678. do {
  18679. struct timeval times[2];
  18680. // access time: now
  18681. times[0].tv_sec = time(nullptr);
  18682. times[0].tv_usec = 0;
  18683. // modification time: negative (e.g., -1)
  18684. times[1].tv_sec = -1;
  18685. times[1].tv_usec = 0;
  18686. if (utimes(fname, times) == 0) { set_negative = true; }
  18687. } while (0);
  18688. #else
  18689. bool set_negative = false;
  18690. #endif
  18691. Server svr;
  18692. svr.set_mount_point("/static", ".");
  18693. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18694. svr.wait_until_ready();
  18695. Client cli(HOST, PORT);
  18696. auto res1 = cli.Get(std::string("/static/") + fname);
  18697. ASSERT_TRUE(res1);
  18698. ASSERT_EQ(200, res1->status);
  18699. bool has_last_modified = res1->has_header("Last-Modified");
  18700. std::string last_modified;
  18701. if (has_last_modified) {
  18702. last_modified = res1->get_header_value("Last-Modified");
  18703. }
  18704. if (set_negative) {
  18705. // If we successfully set a negative mtime, ensure server returns a
  18706. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  18707. // with an old date and ensure server handles it without crash.
  18708. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  18709. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  18710. ASSERT_TRUE(res2);
  18711. // Behavior may vary; at minimum ensure server responds (200 or 304).
  18712. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  18713. } else {
  18714. // Could not set negative mtime on this platform; fall back to verifying
  18715. // that normal invalid/malformed dates are treated safely (non-304).
  18716. Headers h_bad_date = {
  18717. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18718. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  18719. ASSERT_TRUE(res_bad);
  18720. EXPECT_EQ(200, res_bad->status);
  18721. }
  18722. svr.stop();
  18723. t.join();
  18724. std::remove(fname);
  18725. }
  18726. //==============================================================================
  18727. // Integration Tests with Server
  18728. //==============================================================================
  18729. class SSEIntegrationTest : public ::testing::Test {
  18730. protected:
  18731. void SetUp() override {
  18732. stop_server_.store(false);
  18733. events_.clear();
  18734. server_ = httplib::detail::make_unique<Server>();
  18735. setup_server();
  18736. start_server();
  18737. }
  18738. void TearDown() override {
  18739. stop_server_.store(true);
  18740. event_cv_.notify_all();
  18741. server_->stop();
  18742. if (server_thread_.joinable()) { server_thread_.join(); }
  18743. }
  18744. void setup_server() {
  18745. // Simple SSE endpoint
  18746. server_->Get("/events", [this](const Request &req, Response &res) {
  18747. auto last_id = req.get_header_value("Last-Event-ID");
  18748. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  18749. res.set_chunked_content_provider(
  18750. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  18751. std::unique_lock<std::mutex> lock(event_mutex_);
  18752. if (event_cv_.wait_for(
  18753. lock, std::chrono::milliseconds(200), [this] {
  18754. return !events_.empty() || stop_server_.load();
  18755. })) {
  18756. if (stop_server_.load()) { return false; }
  18757. if (!events_.empty()) {
  18758. std::string event = events_.front();
  18759. events_.erase(events_.begin());
  18760. sink.write(event.data(), event.size());
  18761. return true;
  18762. }
  18763. }
  18764. return !stop_server_.load();
  18765. });
  18766. });
  18767. // Endpoint that returns error
  18768. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  18769. res.status = 500;
  18770. res.set_content("Internal Server Error", "text/plain");
  18771. });
  18772. // Endpoint for custom event types
  18773. server_->Get("/custom-events", [](const Request &, Response &res) {
  18774. res.set_chunked_content_provider(
  18775. "text/event-stream", [](size_t offset, DataSink &sink) {
  18776. if (offset == 0) {
  18777. std::string event = "event: update\ndata: updated\n\n"
  18778. "event: delete\ndata: deleted\n\n";
  18779. sink.write(event.data(), event.size());
  18780. }
  18781. return false; // End stream after sending
  18782. });
  18783. });
  18784. }
  18785. void start_server() {
  18786. port_ = server_->bind_to_any_port(HOST);
  18787. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18788. // Wait for server to start
  18789. while (!server_->is_running()) {
  18790. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18791. }
  18792. }
  18793. int get_port() const { return port_; }
  18794. void send_event(const std::string &event) {
  18795. std::lock_guard<std::mutex> lock(event_mutex_);
  18796. events_.push_back(event);
  18797. event_cv_.notify_all();
  18798. }
  18799. std::unique_ptr<Server> server_;
  18800. std::thread server_thread_;
  18801. std::mutex event_mutex_;
  18802. std::condition_variable event_cv_;
  18803. std::vector<std::string> events_;
  18804. std::atomic<bool> stop_server_{false};
  18805. std::string last_received_event_id_;
  18806. int port_ = 0;
  18807. };
  18808. //==============================================================================
  18809. // SSE Parsing Tests
  18810. //==============================================================================
  18811. class SSEParsingTest : public SSEIntegrationTest {
  18812. protected:
  18813. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  18814. // A trailing sentinel event tells when the whole stream has been parsed.
  18815. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  18816. auto body = stream + "event: end\ndata: end\n\n";
  18817. server_->Get("/parse", [body](const Request &, Response &res) {
  18818. res.set_content(body, "text/event-stream");
  18819. });
  18820. return collect("/parse");
  18821. }
  18822. // Runs SSEClient against path until an "end" event arrives and returns the
  18823. // messages dispatched before it
  18824. std::vector<sse::SSEMessage> collect(const std::string &path) {
  18825. Client client(HOST, get_port());
  18826. sse::SSEClient sse(client, path);
  18827. std::mutex mutex;
  18828. std::condition_variable cv;
  18829. std::vector<sse::SSEMessage> messages;
  18830. auto done = false;
  18831. sse.on_message([&](const sse::SSEMessage &msg) {
  18832. std::lock_guard<std::mutex> lock(mutex);
  18833. // Ignore a replay from a reconnect that races with stop()
  18834. if (!done) { messages.push_back(msg); }
  18835. });
  18836. sse.on_event("end", [&](const sse::SSEMessage &) {
  18837. std::lock_guard<std::mutex> lock(mutex);
  18838. done = true;
  18839. cv.notify_all();
  18840. });
  18841. sse.set_reconnect_interval(100);
  18842. sse.start_async();
  18843. {
  18844. std::unique_lock<std::mutex> lock(mutex);
  18845. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  18846. }
  18847. sse.stop();
  18848. EXPECT_TRUE(done);
  18849. return messages;
  18850. }
  18851. };
  18852. TEST_F(SSEParsingTest, SingleLineData) {
  18853. auto msgs = parse("data: hello\n\n");
  18854. ASSERT_EQ(msgs.size(), 1u);
  18855. EXPECT_EQ(msgs[0].data, "hello");
  18856. EXPECT_EQ(msgs[0].event, "message");
  18857. }
  18858. TEST_F(SSEParsingTest, MultiLineData) {
  18859. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  18860. ASSERT_EQ(msgs.size(), 1u);
  18861. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  18862. }
  18863. TEST_F(SSEParsingTest, CustomEventType) {
  18864. auto msgs = parse("event: update\ndata: payload\n\n");
  18865. ASSERT_EQ(msgs.size(), 1u);
  18866. EXPECT_EQ(msgs[0].event, "update");
  18867. EXPECT_EQ(msgs[0].data, "payload");
  18868. }
  18869. TEST_F(SSEParsingTest, EventIdHandling) {
  18870. auto msgs = parse("id: 12345\ndata: test\n\n");
  18871. ASSERT_EQ(msgs.size(), 1u);
  18872. EXPECT_EQ(msgs[0].id, "12345");
  18873. }
  18874. TEST_F(SSEParsingTest, EmptyEventId) {
  18875. auto msgs = parse("id:\ndata: test\n\n");
  18876. ASSERT_EQ(msgs.size(), 1u);
  18877. EXPECT_EQ(msgs[0].id, "");
  18878. }
  18879. TEST_F(SSEParsingTest, CommentsIgnored) {
  18880. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  18881. ASSERT_EQ(msgs.size(), 1u);
  18882. EXPECT_EQ(msgs[0].data, "hello");
  18883. EXPECT_EQ(msgs[0].event, "message");
  18884. }
  18885. TEST_F(SSEParsingTest, ColonInValue) {
  18886. auto msgs = parse("data: hello:world:test\n\n");
  18887. ASSERT_EQ(msgs.size(), 1u);
  18888. EXPECT_EQ(msgs[0].data, "hello:world:test");
  18889. }
  18890. TEST_F(SSEParsingTest, FieldNameOnly) {
  18891. // A line without a colon is a field name with an empty value
  18892. auto msgs = parse("data\n\n");
  18893. ASSERT_EQ(msgs.size(), 1u);
  18894. EXPECT_EQ(msgs[0].data, "");
  18895. }
  18896. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  18897. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  18898. ASSERT_EQ(msgs.size(), 1u);
  18899. EXPECT_EQ(msgs[0].event, "update");
  18900. EXPECT_EQ(msgs[0].data, "hello");
  18901. }
  18902. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  18903. auto msgs = parse("data\r\n\r\n");
  18904. ASSERT_EQ(msgs.size(), 1u);
  18905. EXPECT_EQ(msgs[0].data, "");
  18906. }
  18907. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  18908. auto msgs = parse("unknown: value\ndata: hello\n\n");
  18909. ASSERT_EQ(msgs.size(), 1u);
  18910. EXPECT_EQ(msgs[0].data, "hello");
  18911. EXPECT_EQ(msgs[0].event, "message");
  18912. }
  18913. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  18914. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  18915. ASSERT_EQ(msgs.size(), 2u);
  18916. EXPECT_EQ(msgs[0].data, "hello");
  18917. EXPECT_EQ(msgs[1].data, "hello");
  18918. }
  18919. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  18920. // An event without data is not dispatched, and its type must not leak
  18921. // into the next event
  18922. auto msgs = parse("event: update\n\ndata: hello\n\n");
  18923. ASSERT_EQ(msgs.size(), 1u);
  18924. EXPECT_EQ(msgs[0].event, "message");
  18925. EXPECT_EQ(msgs[0].data, "hello");
  18926. }
  18927. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  18928. // The first connection sends only an id; the second echoes back the
  18929. // Last-Event-ID it was reconnected with
  18930. std::atomic<int> connection_count{0};
  18931. server_->Get("/id-only", [&](const Request &req, Response &res) {
  18932. if (connection_count++ == 0) {
  18933. res.set_content("id: 42\n\n", "text/event-stream");
  18934. } else {
  18935. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  18936. "\n\nevent: end\ndata: end\n\n",
  18937. "text/event-stream");
  18938. }
  18939. });
  18940. auto msgs = collect("/id-only");
  18941. ASSERT_EQ(msgs.size(), 1u);
  18942. EXPECT_EQ(msgs[0].data, "42");
  18943. }
  18944. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  18945. // The first connection sets an id and then clears it with an empty one; the
  18946. // second reports whether it was reconnected with a Last-Event-ID
  18947. std::atomic<int> connection_count{0};
  18948. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  18949. if (connection_count++ == 0) {
  18950. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  18951. "text/event-stream");
  18952. } else {
  18953. res.set_content(
  18954. std::string("data: ") +
  18955. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  18956. "\n\nevent: end\ndata: end\n\n",
  18957. "text/event-stream");
  18958. }
  18959. });
  18960. auto msgs = collect("/id-clear");
  18961. ASSERT_EQ(msgs.size(), 3u);
  18962. EXPECT_EQ(msgs[0].id, "1");
  18963. EXPECT_EQ(msgs[1].id, "");
  18964. EXPECT_EQ(msgs[2].data, "not sent");
  18965. }
  18966. TEST_F(SSEParsingTest, CompleteEventParsing) {
  18967. auto msgs = parse("event: notification\nid: evt-42\n"
  18968. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  18969. ASSERT_EQ(msgs.size(), 1u);
  18970. EXPECT_EQ(msgs[0].event, "notification");
  18971. EXPECT_EQ(msgs[0].id, "evt-42");
  18972. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  18973. }
  18974. TEST(SSEMessageTest, Clear) {
  18975. sse::SSEMessage msg;
  18976. msg.event = "custom";
  18977. msg.data = "some data";
  18978. msg.id = "123";
  18979. msg.clear();
  18980. EXPECT_EQ(msg.event, "message");
  18981. EXPECT_EQ(msg.data, "");
  18982. EXPECT_EQ(msg.id, "");
  18983. }
  18984. //==============================================================================
  18985. // SSE Integration Tests
  18986. //==============================================================================
  18987. // Test: Successful connection and on_open callback
  18988. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  18989. // Add a simple endpoint that sends one event and closes
  18990. server_->Get("/simple-event", [](const Request &, Response &res) {
  18991. res.set_chunked_content_provider(
  18992. "text/event-stream", [](size_t offset, DataSink &sink) {
  18993. if (offset == 0) {
  18994. std::string event = "data: hello\n\n";
  18995. sink.write(event.data(), event.size());
  18996. }
  18997. return false; // Close stream after sending
  18998. });
  18999. });
  19000. Client client("localhost", get_port());
  19001. sse::SSEClient sse(client, "/simple-event");
  19002. std::atomic<bool> open_called{false};
  19003. std::atomic<bool> message_received{false};
  19004. sse.on_open([&open_called]() { open_called.store(true); });
  19005. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  19006. if (msg.data == "hello") { message_received.store(true); }
  19007. });
  19008. sse.set_reconnect_interval(100);
  19009. sse.set_max_reconnect_attempts(1);
  19010. // Start async
  19011. sse.start_async();
  19012. // Wait for message to be processed
  19013. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19014. sse.stop();
  19015. EXPECT_TRUE(open_called.load());
  19016. EXPECT_TRUE(message_received.load());
  19017. }
  19018. // Test: on_message callback
  19019. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  19020. // Endpoint that sends multiple events then closes
  19021. server_->Get("/multi-event", [](const Request &, Response &res) {
  19022. res.set_chunked_content_provider(
  19023. "text/event-stream", [](size_t offset, DataSink &sink) {
  19024. if (offset == 0) {
  19025. std::string events = "data: message1\n\ndata: message2\n\n";
  19026. sink.write(events.data(), events.size());
  19027. }
  19028. return false;
  19029. });
  19030. });
  19031. Client client("localhost", get_port());
  19032. sse::SSEClient sse(client, "/multi-event");
  19033. std::vector<std::string> received_messages;
  19034. std::mutex messages_mutex;
  19035. sse.on_message([&](const sse::SSEMessage &msg) {
  19036. std::lock_guard<std::mutex> lock(messages_mutex);
  19037. received_messages.push_back(msg.data);
  19038. });
  19039. sse.set_reconnect_interval(100);
  19040. sse.set_max_reconnect_attempts(1);
  19041. sse.start_async();
  19042. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19043. sse.stop();
  19044. std::lock_guard<std::mutex> lock(messages_mutex);
  19045. EXPECT_GE(received_messages.size(), 2u);
  19046. if (received_messages.size() >= 2) {
  19047. EXPECT_EQ(received_messages[0], "message1");
  19048. EXPECT_EQ(received_messages[1], "message2");
  19049. }
  19050. }
  19051. // Test: on_event for specific types
  19052. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  19053. Client client("localhost", get_port());
  19054. sse::SSEClient sse(client, "/custom-events");
  19055. std::atomic<bool> update_received{false};
  19056. std::atomic<bool> delete_received{false};
  19057. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  19058. if (msg.data == "updated") { update_received.store(true); }
  19059. });
  19060. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  19061. if (msg.data == "deleted") { delete_received.store(true); }
  19062. });
  19063. sse.set_max_reconnect_attempts(1);
  19064. sse.start_async();
  19065. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  19066. sse.stop();
  19067. EXPECT_TRUE(update_received.load());
  19068. EXPECT_TRUE(delete_received.load());
  19069. }
  19070. // Test: on_error callback on connection failure
  19071. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  19072. // Connect to a non-existent port
  19073. Client client("localhost", 59999);
  19074. sse::SSEClient sse(client, "/events");
  19075. std::atomic<bool> error_called{false};
  19076. Error received_error = Error::Success;
  19077. sse.on_error([&](Error err) {
  19078. error_called.store(true);
  19079. received_error = err;
  19080. });
  19081. sse.set_reconnect_interval(50);
  19082. sse.set_max_reconnect_attempts(1);
  19083. sse.start_async();
  19084. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  19085. sse.stop();
  19086. EXPECT_TRUE(error_called.load());
  19087. EXPECT_NE(received_error, Error::Success);
  19088. }
  19089. // Test: Last-Event-ID header sent on reconnect
  19090. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  19091. // Endpoint that sends event with ID
  19092. server_->Get("/event-with-id", [](const Request &, Response &res) {
  19093. res.set_chunked_content_provider(
  19094. "text/event-stream", [](size_t offset, DataSink &sink) {
  19095. if (offset == 0) {
  19096. std::string event = "id: evt-123\ndata: test\n\n";
  19097. sink.write(event.data(), event.size());
  19098. }
  19099. return false;
  19100. });
  19101. });
  19102. Client client("localhost", get_port());
  19103. sse::SSEClient sse(client, "/event-with-id");
  19104. std::atomic<bool> id_received{false};
  19105. sse.on_message([&](const sse::SSEMessage &msg) {
  19106. if (!msg.id.empty()) { id_received.store(true); }
  19107. });
  19108. sse.set_reconnect_interval(100);
  19109. sse.set_max_reconnect_attempts(1);
  19110. sse.start_async();
  19111. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19112. sse.stop();
  19113. EXPECT_TRUE(id_received.load());
  19114. EXPECT_EQ(sse.last_event_id(), "evt-123");
  19115. }
  19116. // Test: Manual stop
  19117. TEST_F(SSEIntegrationTest, ManualStop) {
  19118. // Endpoint that sends one event and stays open briefly
  19119. std::atomic<bool> handler_running{true};
  19120. server_->Get("/stay-open", [&handler_running](const Request &,
  19121. Response &res) {
  19122. res.set_chunked_content_provider(
  19123. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  19124. if (offset == 0) {
  19125. std::string event = "data: connected\n\n";
  19126. sink.write(event.data(), event.size());
  19127. }
  19128. // Keep connection open while handler_running is true
  19129. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  19130. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19131. }
  19132. return false;
  19133. });
  19134. });
  19135. Client client("localhost", get_port());
  19136. sse::SSEClient sse(client, "/stay-open");
  19137. std::atomic<bool> connected{false};
  19138. sse.on_open([&connected]() { connected.store(true); });
  19139. sse.set_reconnect_interval(100);
  19140. sse.set_max_reconnect_attempts(1);
  19141. sse.start_async();
  19142. // Wait for connection to establish
  19143. for (int i = 0; i < 20 && !connected.load(); ++i) {
  19144. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19145. }
  19146. EXPECT_TRUE(connected.load());
  19147. EXPECT_TRUE(sse.is_connected());
  19148. // Signal handler to stop
  19149. handler_running.store(false);
  19150. // Stop SSE client
  19151. sse.stop();
  19152. EXPECT_FALSE(sse.is_connected());
  19153. }
  19154. // Test: SSEClient with custom headers
  19155. TEST_F(SSEIntegrationTest, CustomHeaders) {
  19156. // Setup a server endpoint that checks for custom header
  19157. std::atomic<bool> header_received{false};
  19158. server_->Get("/header-check", [&](const Request &req, Response &res) {
  19159. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  19160. header_received.store(true);
  19161. }
  19162. res.set_chunked_content_provider("text/event-stream",
  19163. [](size_t, DataSink &) { return false; });
  19164. });
  19165. Client client("localhost", get_port());
  19166. Headers headers = {{"X-Custom-Header", "custom-value"}};
  19167. sse::SSEClient sse(client, "/header-check", headers);
  19168. sse.set_max_reconnect_attempts(1);
  19169. sse.start_async();
  19170. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  19171. sse.stop();
  19172. EXPECT_TRUE(header_received.load());
  19173. }
  19174. // Test: Reconnect interval configuration
  19175. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  19176. Client client("localhost", get_port());
  19177. sse::SSEClient sse(client, "/events");
  19178. auto &result = sse.set_reconnect_interval(500);
  19179. // Builder pattern should return reference to self
  19180. EXPECT_EQ(&result, &sse);
  19181. }
  19182. // Test: Max reconnect attempts
  19183. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  19184. // Connect to non-existent port to force reconnects
  19185. Client client("localhost", 59998);
  19186. sse::SSEClient sse(client, "/events");
  19187. std::atomic<int> error_count{0};
  19188. sse.on_error([&](Error) { error_count.fetch_add(1); });
  19189. sse.set_reconnect_interval(50);
  19190. sse.set_max_reconnect_attempts(2);
  19191. auto start = std::chrono::steady_clock::now();
  19192. sse.start(); // Blocking call
  19193. auto end = std::chrono::steady_clock::now();
  19194. // Should have stopped after 2 failed attempts
  19195. EXPECT_GE(error_count.load(), 2);
  19196. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  19197. auto duration =
  19198. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  19199. #ifdef _WIN32
  19200. // Windows is much slower for socket connection failures
  19201. EXPECT_LT(duration.count(), 7000);
  19202. #else
  19203. EXPECT_LT(duration.count(), 1000);
  19204. #endif
  19205. }
  19206. // Test: Multi-line data in integration
  19207. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  19208. // Endpoint with multi-line data
  19209. server_->Get("/multiline-data", [](const Request &, Response &res) {
  19210. res.set_chunked_content_provider(
  19211. "text/event-stream", [](size_t offset, DataSink &sink) {
  19212. if (offset == 0) {
  19213. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  19214. sink.write(event.data(), event.size());
  19215. }
  19216. return false;
  19217. });
  19218. });
  19219. Client client("localhost", get_port());
  19220. sse::SSEClient sse(client, "/multiline-data");
  19221. std::string received_data;
  19222. std::mutex data_mutex;
  19223. sse.on_message([&](const sse::SSEMessage &msg) {
  19224. std::lock_guard<std::mutex> lock(data_mutex);
  19225. received_data = msg.data;
  19226. });
  19227. sse.set_reconnect_interval(100);
  19228. sse.set_max_reconnect_attempts(1);
  19229. sse.start_async();
  19230. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19231. sse.stop();
  19232. std::lock_guard<std::mutex> lock(data_mutex);
  19233. EXPECT_EQ(received_data, "line1\nline2\nline3");
  19234. }
  19235. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  19236. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  19237. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  19238. DataSink &sink) {
  19239. if (offset == 0) {
  19240. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  19241. sink.write(events.data(), events.size());
  19242. }
  19243. return false;
  19244. });
  19245. });
  19246. Client client("localhost", get_port());
  19247. sse::SSEClient sse(client, "/empty-data-lines");
  19248. std::mutex mutex;
  19249. std::condition_variable cv;
  19250. std::vector<std::string> received;
  19251. sse.on_message([&](const sse::SSEMessage &msg) {
  19252. std::lock_guard<std::mutex> lock(mutex);
  19253. received.push_back(msg.data);
  19254. cv.notify_all();
  19255. });
  19256. sse.set_max_reconnect_attempts(1);
  19257. sse.start_async();
  19258. {
  19259. std::unique_lock<std::mutex> lock(mutex);
  19260. cv.wait_for(lock, std::chrono::seconds(2),
  19261. [&] { return received.size() >= 3; });
  19262. }
  19263. sse.stop();
  19264. ASSERT_GE(received.size(), 3u);
  19265. EXPECT_EQ(received[0], "");
  19266. EXPECT_EQ(received[1], "\nhello");
  19267. EXPECT_EQ(received[2], "");
  19268. }
  19269. // Test: Auto-reconnect after server disconnection
  19270. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  19271. std::atomic<int> connection_count{0};
  19272. std::atomic<int> message_count{0};
  19273. // Endpoint that sends one event and closes, forcing reconnect
  19274. server_->Get("/reconnect-test",
  19275. [&connection_count](const Request &, Response &res) {
  19276. connection_count.fetch_add(1);
  19277. res.set_chunked_content_provider(
  19278. "text/event-stream", [](size_t offset, DataSink &sink) {
  19279. if (offset == 0) {
  19280. std::string event = "data: hello\n\n";
  19281. sink.write(event.data(), event.size());
  19282. }
  19283. return false; // Close connection after sending
  19284. });
  19285. });
  19286. Client client("localhost", get_port());
  19287. sse::SSEClient sse(client, "/reconnect-test");
  19288. sse.on_message([&message_count](const sse::SSEMessage &) {
  19289. message_count.fetch_add(1);
  19290. });
  19291. sse.set_reconnect_interval(100);
  19292. sse.set_max_reconnect_attempts(3);
  19293. sse.start_async();
  19294. // Wait long enough for multiple reconnects
  19295. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19296. sse.stop();
  19297. // Should have connected multiple times (initial + reconnects)
  19298. EXPECT_GE(connection_count.load(), 2);
  19299. // Should have received messages from multiple connections
  19300. EXPECT_GE(message_count.load(), 2);
  19301. }
  19302. // Test: A retry field that is not all ASCII digits is ignored
  19303. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  19304. std::atomic<int> connection_count{0};
  19305. server_->Get("/bad-retry",
  19306. [&connection_count](const Request &, Response &res) {
  19307. connection_count.fetch_add(1);
  19308. res.set_chunked_content_provider(
  19309. "text/event-stream", [](size_t offset, DataSink &sink) {
  19310. if (offset == 0) {
  19311. std::string event = "retry: -1\ndata: hello\n\n";
  19312. sink.write(event.data(), event.size());
  19313. }
  19314. return false;
  19315. });
  19316. });
  19317. Client client("localhost", get_port());
  19318. sse::SSEClient sse(client, "/bad-retry");
  19319. sse.set_reconnect_interval(10000);
  19320. sse.start_async();
  19321. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19322. sse.stop();
  19323. EXPECT_EQ(connection_count.load(), 1);
  19324. }
  19325. // Test: A retry field of all ASCII digits sets the reconnection time
  19326. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  19327. std::atomic<int> connection_count{0};
  19328. server_->Get("/zero-retry",
  19329. [&connection_count](const Request &, Response &res) {
  19330. connection_count.fetch_add(1);
  19331. res.set_chunked_content_provider(
  19332. "text/event-stream", [](size_t offset, DataSink &sink) {
  19333. if (offset == 0) {
  19334. std::string event = "retry: 0\ndata: hello\n\n";
  19335. sink.write(event.data(), event.size());
  19336. }
  19337. return false;
  19338. });
  19339. });
  19340. Client client("localhost", get_port());
  19341. sse::SSEClient sse(client, "/zero-retry");
  19342. sse.set_reconnect_interval(10000);
  19343. sse.start_async();
  19344. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19345. sse.stop();
  19346. // The server-supplied interval is applied, but never below 100ms, so
  19347. // "retry: 0" does not cause a busy reconnect loop
  19348. EXPECT_GE(connection_count.load(), 2);
  19349. EXPECT_LE(connection_count.load(), 10);
  19350. }
  19351. // Test: Last-Event-ID sent on reconnect
  19352. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  19353. std::atomic<int> connection_count{0};
  19354. std::vector<std::string> received_last_event_ids;
  19355. std::mutex id_mutex;
  19356. // Endpoint that checks Last-Event-ID header and sends event with ID
  19357. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  19358. int conn = connection_count.fetch_add(1);
  19359. // Capture the Last-Event-ID header from each connection
  19360. {
  19361. std::lock_guard<std::mutex> lock(id_mutex);
  19362. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  19363. }
  19364. res.set_chunked_content_provider(
  19365. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  19366. if (offset == 0) {
  19367. std::string event =
  19368. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  19369. sink.write(event.data(), event.size());
  19370. }
  19371. return false;
  19372. });
  19373. });
  19374. Client client("localhost", get_port());
  19375. sse::SSEClient sse(client, "/reconnect-with-id");
  19376. sse.set_reconnect_interval(100);
  19377. sse.set_max_reconnect_attempts(3);
  19378. sse.start_async();
  19379. // Wait for at least 2 connections
  19380. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19381. sse.stop();
  19382. // Verify behavior
  19383. std::lock_guard<std::mutex> lock(id_mutex);
  19384. EXPECT_GE(received_last_event_ids.size(), 2u);
  19385. // First connection should have no Last-Event-ID
  19386. if (!received_last_event_ids.empty()) {
  19387. EXPECT_EQ(received_last_event_ids[0], "");
  19388. }
  19389. // Second connection should have Last-Event-ID from first connection
  19390. if (received_last_event_ids.size() >= 2) {
  19391. EXPECT_EQ(received_last_event_ids[1], "event-0");
  19392. }
  19393. }
  19394. // Test: set_headers updates headers used on reconnect
  19395. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  19396. std::vector<std::string> received_tokens;
  19397. std::mutex token_mutex;
  19398. // Endpoint that captures Authorization header
  19399. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  19400. {
  19401. std::lock_guard<std::mutex> lock(token_mutex);
  19402. received_tokens.push_back(req.get_header_value("Authorization"));
  19403. }
  19404. res.set_chunked_content_provider(
  19405. "text/event-stream", [](size_t offset, DataSink &sink) {
  19406. if (offset == 0) {
  19407. std::string event = "data: hello\n\n";
  19408. sink.write(event.data(), event.size());
  19409. }
  19410. return false; // Close connection to trigger reconnect
  19411. });
  19412. });
  19413. Client client("localhost", get_port());
  19414. Headers headers = {{"Authorization", "Bearer old-token"}};
  19415. sse::SSEClient sse(client, "/auth-check", headers);
  19416. // Update headers on each successful connection
  19417. sse.on_open(
  19418. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  19419. sse.set_reconnect_interval(100);
  19420. sse.set_max_reconnect_attempts(3);
  19421. sse.start_async();
  19422. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19423. sse.stop();
  19424. std::lock_guard<std::mutex> lock(token_mutex);
  19425. ASSERT_GE(received_tokens.size(), 2u);
  19426. // First connection uses original header
  19427. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  19428. // Second connection uses updated header from set_headers
  19429. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  19430. }
  19431. // Test: 401 allows reconnection (so on_error can refresh headers)
  19432. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  19433. std::atomic<int> connection_count{0};
  19434. // Endpoint: returns 401 on first attempt, 200 on second
  19435. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  19436. int conn = connection_count.fetch_add(1);
  19437. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  19438. res.status = StatusCode::Unauthorized_401;
  19439. res.set_content("Unauthorized", "text/plain");
  19440. return;
  19441. }
  19442. res.set_chunked_content_provider(
  19443. "text/event-stream", [](size_t offset, DataSink &sink) {
  19444. if (offset == 0) {
  19445. std::string event = "data: authenticated\n\n";
  19446. sink.write(event.data(), event.size());
  19447. }
  19448. return false;
  19449. });
  19450. });
  19451. Client client("localhost", get_port());
  19452. Headers headers = {{"Authorization", "Bearer expired"}};
  19453. sse::SSEClient sse(client, "/auth-retry", headers);
  19454. std::atomic<bool> message_received{false};
  19455. // Refresh token on error
  19456. sse.on_error(
  19457. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  19458. sse.on_message([&](const sse::SSEMessage &msg) {
  19459. if (msg.data == "authenticated") { message_received.store(true); }
  19460. });
  19461. sse.set_reconnect_interval(100);
  19462. sse.set_max_reconnect_attempts(3);
  19463. sse.start_async();
  19464. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19465. sse.stop();
  19466. // Should have reconnected after 401 and succeeded with new token
  19467. EXPECT_GE(connection_count.load(), 2);
  19468. EXPECT_TRUE(message_received.load());
  19469. }
  19470. TEST(Issue2318Test, EmptyHostString) {
  19471. {
  19472. httplib::Client cli_empty("", PORT);
  19473. auto res = cli_empty.Get("/");
  19474. ASSERT_FALSE(res);
  19475. EXPECT_EQ(httplib::Error::Connection, res.error());
  19476. }
  19477. {
  19478. httplib::Client cli(" ", PORT);
  19479. auto res = cli.Get("/");
  19480. ASSERT_FALSE(res);
  19481. EXPECT_EQ(httplib::Error::Connection, res.error());
  19482. }
  19483. }
  19484. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19485. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  19486. Server svr;
  19487. // Set a small payload limit (1KB)
  19488. svr.set_payload_max_length(1024);
  19489. svr.Post("/test", [&](const Request &req, Response &res) {
  19490. res.set_content("Body size: " + std::to_string(req.body.size()),
  19491. "text/plain");
  19492. });
  19493. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19494. auto se = detail::scope_exit([&] {
  19495. svr.stop();
  19496. listen_thread.join();
  19497. });
  19498. svr.wait_until_ready();
  19499. // Create data that compresses well but exceeds limit when decompressed
  19500. // 8KB of repeated null bytes compresses to a very small size
  19501. std::string original_data(8 * 1024, '\0');
  19502. // Compress the data using gzip
  19503. std::string compressed_data;
  19504. detail::gzip_compressor compressor;
  19505. compressor.compress(original_data.data(), original_data.size(), true,
  19506. [&](const char *data, size_t size) {
  19507. compressed_data.append(data, size);
  19508. return true;
  19509. });
  19510. // Verify compression worked (compressed should be much smaller)
  19511. ASSERT_LT(compressed_data.size(), original_data.size());
  19512. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  19513. // Send compressed data with Content-Encoding: gzip
  19514. Client cli(HOST, PORT);
  19515. Headers headers = {{"Content-Encoding", "gzip"}};
  19516. auto res =
  19517. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  19518. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  19519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19520. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  19521. }
  19522. #endif
  19523. // ============================================================================
  19524. // OpenSSL-Specific Tests
  19525. // ============================================================================
  19526. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  19527. X509 *readCertificate(const std::string &strFileName) {
  19528. std::ifstream inStream(strFileName);
  19529. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  19530. std::istreambuf_iterator<char>());
  19531. if (strCertPEM.empty()) return (nullptr);
  19532. BIO *pbCert = BIO_new(BIO_s_mem());
  19533. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  19534. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  19535. BIO_free(pbCert);
  19536. return (pCert);
  19537. }
  19538. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  19539. std::ifstream inStream(strFileName);
  19540. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  19541. std::istreambuf_iterator<char>());
  19542. if (strPrivateKeyPEM.empty()) return (nullptr);
  19543. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  19544. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  19545. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  19546. BIO_free(pbPrivKey);
  19547. return (pPrivateKey);
  19548. }
  19549. TEST(BindServerTest, UpdateCerts) {
  19550. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19551. int port = svr.bind_to_any_port("0.0.0.0");
  19552. ASSERT_TRUE(svr.is_valid());
  19553. ASSERT_TRUE(port > 0);
  19554. X509 *cert = readCertificate(SERVER_CERT_FILE);
  19555. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  19556. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  19557. ASSERT_TRUE(cert != nullptr);
  19558. ASSERT_TRUE(ca_cert != nullptr);
  19559. ASSERT_TRUE(key != nullptr);
  19560. X509_STORE *cert_store = X509_STORE_new();
  19561. X509_STORE_add_cert(cert_store, ca_cert);
  19562. // svr.update_certs(cert, key, cert_store); // deprecated
  19563. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  19564. CLIENT_CA_CERT_FILE);
  19565. ASSERT_TRUE(svr.is_valid());
  19566. svr.stop();
  19567. X509_STORE_free(cert_store);
  19568. X509_free(cert);
  19569. X509_free(ca_cert);
  19570. EVP_PKEY_free(key);
  19571. }
  19572. // Test that update_certs() updates client CA list correctly
  19573. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  19574. // Start with file-based constructor
  19575. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19576. ASSERT_TRUE(svr.is_valid());
  19577. // Initially no client CA list should be set
  19578. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  19579. ASSERT_TRUE(ssl_ctx != nullptr);
  19580. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  19581. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  19582. EXPECT_EQ(0, count_before);
  19583. // Now update with client CA (PEM string)
  19584. std::string cert_pem, key_pem, ca_pem;
  19585. read_file(SERVER_CERT_FILE, cert_pem);
  19586. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  19587. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  19588. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  19589. ASSERT_TRUE(svr.is_valid());
  19590. // Now client CA list should be set
  19591. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  19592. ASSERT_TRUE(ca_list_after != nullptr);
  19593. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  19594. }
  19595. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  19596. // Test that the file-path SSLServer constructor properly sets the client CA
  19597. // list that is sent to clients during the TLS handshake (CertificateRequest)
  19598. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19599. ASSERT_TRUE(svr.is_valid());
  19600. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  19601. ASSERT_TRUE(ssl_ctx != nullptr);
  19602. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  19603. ASSERT_TRUE(ca_list != nullptr);
  19604. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  19605. }
  19606. #endif
  19607. // ============================================================================
  19608. // MbedTLS-Specific Tests
  19609. // ============================================================================
  19610. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  19611. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  19612. using namespace httplib::tls;
  19613. // Track if callback was invoked
  19614. bool callback_invoked = false;
  19615. // The callback receives void* ctx which is actually MbedTlsContext*
  19616. // We can access the mbedtls_ssl_config via the context
  19617. auto setup_callback = [&callback_invoked](void *ctx) {
  19618. callback_invoked = true;
  19619. // Cast to MbedTlsContext* to access the ssl config
  19620. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  19621. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  19622. // Use static variables to hold certificate data (simplified for test)
  19623. static mbedtls_x509_crt own_cert;
  19624. static mbedtls_pk_context own_key;
  19625. static mbedtls_x509_crt ca_chain;
  19626. static bool initialized = false;
  19627. if (!initialized) {
  19628. mbedtls_x509_crt_init(&own_cert);
  19629. mbedtls_pk_init(&own_key);
  19630. mbedtls_x509_crt_init(&ca_chain);
  19631. // Load server certificate
  19632. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  19633. return false;
  19634. }
  19635. // Load server private key.
  19636. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  19637. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  19638. #if MBEDTLS_VERSION_MAJOR == 3
  19639. ,
  19640. mbedtls_ctr_drbg_random, nullptr
  19641. #endif
  19642. ) != 0) {
  19643. return false;
  19644. }
  19645. // Load CA chain for client verification
  19646. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  19647. return false;
  19648. }
  19649. initialized = true;
  19650. }
  19651. // Configure the SSL config
  19652. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  19653. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  19654. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  19655. // Set minimum TLS version using mbedTLS native API
  19656. #if MBEDTLS_VERSION_MAJOR >= 3
  19657. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  19658. #else
  19659. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  19660. MBEDTLS_SSL_MINOR_VERSION_3);
  19661. #endif
  19662. return true;
  19663. };
  19664. SSLServer svr(setup_callback);
  19665. ASSERT_TRUE(svr.is_valid());
  19666. ASSERT_TRUE(callback_invoked);
  19667. svr.Get("/test", [&](const Request &req, Response &res) {
  19668. res.set_content("test", "text/plain");
  19669. auto cert = req.peer_cert();
  19670. ASSERT_TRUE(static_cast<bool>(cert));
  19671. auto common_name = cert.subject_cn();
  19672. EXPECT_EQ("Common Name", common_name);
  19673. });
  19674. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  19675. auto se = detail::scope_exit([&] {
  19676. svr.stop();
  19677. t.join();
  19678. ASSERT_FALSE(svr.is_running());
  19679. });
  19680. svr.wait_until_ready();
  19681. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  19682. cli.enable_server_certificate_verification(false);
  19683. cli.set_connection_timeout(30);
  19684. auto res = cli.Get("/test");
  19685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19686. ASSERT_EQ(StatusCode::OK_200, res->status);
  19687. }
  19688. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  19689. // context (owning mbedtls_ssl_config) before shutting down a still-open
  19690. // keep-alive SSL session, which reads through that config in
  19691. // mbedtls_ssl_close_notify.
  19692. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  19693. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19694. ASSERT_TRUE(svr.is_valid());
  19695. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  19696. res.set_content("test", "text/plain");
  19697. });
  19698. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  19699. auto se = detail::scope_exit([&] {
  19700. svr.stop();
  19701. t.join();
  19702. ASSERT_FALSE(svr.is_running());
  19703. });
  19704. svr.wait_until_ready();
  19705. {
  19706. SSLClient cli(HOST, PORT);
  19707. cli.enable_server_certificate_verification(false);
  19708. cli.set_keep_alive(true);
  19709. auto res = cli.Get("/test");
  19710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19711. ASSERT_EQ(StatusCode::OK_200, res->status);
  19712. // cli is destructed here with the keep-alive SSL session still open.
  19713. }
  19714. }
  19715. #endif
  19716. // WebSocket Tests
  19717. TEST(WebSocketTest, RSVBitsMustBeZero) {
  19718. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  19719. // defining the meaning of these bits has been negotiated.
  19720. auto make_frame = [](uint8_t first_byte) {
  19721. std::string frame;
  19722. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  19723. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  19724. frame += "Hello";
  19725. return frame;
  19726. };
  19727. // RSV1 set (0x40)
  19728. {
  19729. detail::BufferStream strm;
  19730. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  19731. ws::Opcode opcode;
  19732. std::string payload;
  19733. bool fin;
  19734. EXPECT_EQ(
  19735. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19736. ws::impl::FrameRead::Fail);
  19737. }
  19738. // RSV2 set (0x20)
  19739. {
  19740. detail::BufferStream strm;
  19741. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  19742. ws::Opcode opcode;
  19743. std::string payload;
  19744. bool fin;
  19745. EXPECT_EQ(
  19746. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19747. ws::impl::FrameRead::Fail);
  19748. }
  19749. // RSV3 set (0x10)
  19750. {
  19751. detail::BufferStream strm;
  19752. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  19753. ws::Opcode opcode;
  19754. std::string payload;
  19755. bool fin;
  19756. EXPECT_EQ(
  19757. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19758. ws::impl::FrameRead::Fail);
  19759. }
  19760. // No RSV bits set - should succeed
  19761. {
  19762. detail::BufferStream strm;
  19763. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  19764. ws::Opcode opcode;
  19765. std::string payload;
  19766. bool fin;
  19767. EXPECT_EQ(
  19768. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19769. ws::impl::FrameRead::Ok);
  19770. EXPECT_EQ(ws::Opcode::Text, opcode);
  19771. EXPECT_EQ("Hello", payload);
  19772. EXPECT_TRUE(fin);
  19773. }
  19774. }
  19775. TEST(WebSocketTest, ControlFrameValidation) {
  19776. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  19777. // payload length <= 125.
  19778. // Ping with FIN=0 - must be rejected
  19779. {
  19780. detail::BufferStream strm;
  19781. std::string frame;
  19782. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  19783. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  19784. strm.write(frame.data(), frame.size());
  19785. ws::Opcode opcode;
  19786. std::string payload;
  19787. bool fin;
  19788. EXPECT_EQ(
  19789. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19790. ws::impl::FrameRead::Fail);
  19791. }
  19792. // Close with FIN=0 - must be rejected
  19793. {
  19794. detail::BufferStream strm;
  19795. std::string frame;
  19796. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  19797. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  19798. strm.write(frame.data(), frame.size());
  19799. ws::Opcode opcode;
  19800. std::string payload;
  19801. bool fin;
  19802. EXPECT_EQ(
  19803. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19804. ws::impl::FrameRead::Fail);
  19805. }
  19806. // Ping with payload_len=126 (extended length) - must be rejected
  19807. {
  19808. detail::BufferStream strm;
  19809. std::string frame;
  19810. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  19811. frame += static_cast<char>(126); // payload_len=126 (>125)
  19812. frame += static_cast<char>(0x00); // extended length high byte
  19813. frame += static_cast<char>(126); // extended length low byte
  19814. frame += std::string(126, 'x');
  19815. strm.write(frame.data(), frame.size());
  19816. ws::Opcode opcode;
  19817. std::string payload;
  19818. bool fin;
  19819. EXPECT_EQ(
  19820. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19821. ws::impl::FrameRead::Fail);
  19822. }
  19823. // Ping with FIN=1 and payload_len=125 - should succeed
  19824. {
  19825. detail::BufferStream strm;
  19826. std::string frame;
  19827. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  19828. frame += static_cast<char>(125); // payload_len=125
  19829. frame += std::string(125, 'x');
  19830. strm.write(frame.data(), frame.size());
  19831. ws::Opcode opcode;
  19832. std::string payload;
  19833. bool fin;
  19834. EXPECT_EQ(
  19835. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19836. ws::impl::FrameRead::Ok);
  19837. EXPECT_EQ(ws::Opcode::Ping, opcode);
  19838. EXPECT_EQ(125u, payload.size());
  19839. EXPECT_TRUE(fin);
  19840. }
  19841. }
  19842. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  19843. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  19844. // length MUST be 0.
  19845. // MSB set - must be rejected
  19846. {
  19847. detail::BufferStream strm;
  19848. std::string frame;
  19849. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  19850. frame += static_cast<char>(127); // 64-bit extended length
  19851. frame += static_cast<char>(0x80); // MSB set (invalid)
  19852. frame += std::string(7, '\0'); // remaining 7 bytes of length
  19853. strm.write(frame.data(), frame.size());
  19854. ws::Opcode opcode;
  19855. std::string payload;
  19856. bool fin;
  19857. EXPECT_EQ(
  19858. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19859. ws::impl::FrameRead::Fail);
  19860. }
  19861. // MSB clear - should pass length parsing (will be rejected by max_len,
  19862. // but that's a different check; use a small length to verify)
  19863. {
  19864. detail::BufferStream strm;
  19865. std::string frame;
  19866. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  19867. frame += static_cast<char>(127); // 64-bit extended length
  19868. frame += std::string(7, '\0'); // high bytes = 0
  19869. frame += static_cast<char>(0x03); // length = 3
  19870. frame += "abc";
  19871. strm.write(frame.data(), frame.size());
  19872. ws::Opcode opcode;
  19873. std::string payload;
  19874. bool fin;
  19875. EXPECT_EQ(
  19876. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19877. ws::impl::FrameRead::Ok);
  19878. EXPECT_EQ(ws::Opcode::Text, opcode);
  19879. EXPECT_EQ("abc", payload);
  19880. }
  19881. }
  19882. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  19883. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  19884. // Valid UTF-8
  19885. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  19886. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  19887. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  19888. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  19889. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  19890. // Invalid UTF-8
  19891. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  19892. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  19893. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  19894. EXPECT_FALSE(
  19895. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  19896. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  19897. }
  19898. TEST(WebSocketTest, ConnectAndDisconnect) {
  19899. Server svr;
  19900. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19901. std::string msg;
  19902. while (ws.read(msg)) {}
  19903. });
  19904. auto port = svr.bind_to_any_port(HOST);
  19905. std::thread t([&]() { svr.listen_after_bind(); });
  19906. svr.wait_until_ready();
  19907. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19908. auto res = client.connect();
  19909. ASSERT_TRUE(res);
  19910. EXPECT_EQ(Error::Success, res.error());
  19911. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  19912. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  19913. EXPECT_TRUE(client.is_open());
  19914. client.close();
  19915. EXPECT_FALSE(client.is_open());
  19916. svr.stop();
  19917. t.join();
  19918. }
  19919. TEST(WebSocketTest, ValidURL) {
  19920. ws::WebSocketClient ws1("ws://localhost:8080/path");
  19921. EXPECT_TRUE(ws1.is_valid());
  19922. ws::WebSocketClient ws2("ws://example.com/path");
  19923. EXPECT_TRUE(ws2.is_valid());
  19924. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  19925. EXPECT_TRUE(ws3.is_valid());
  19926. #ifdef CPPHTTPLIB_SSL_ENABLED
  19927. ws::WebSocketClient wss1("wss://example.com/path");
  19928. EXPECT_TRUE(wss1.is_valid());
  19929. ws::WebSocketClient wss2("wss://example.com:443/path");
  19930. EXPECT_TRUE(wss2.is_valid());
  19931. #endif
  19932. }
  19933. TEST(WebSocketTest, InvalidURL) {
  19934. // No scheme
  19935. ws::WebSocketClient ws1("localhost:8080/path");
  19936. EXPECT_FALSE(ws1.is_valid());
  19937. // No path
  19938. ws::WebSocketClient ws2("ws://localhost:8080");
  19939. EXPECT_FALSE(ws2.is_valid());
  19940. // Empty string
  19941. ws::WebSocketClient ws3("");
  19942. EXPECT_FALSE(ws3.is_valid());
  19943. // Missing host
  19944. ws::WebSocketClient ws4("ws://:8080/path");
  19945. EXPECT_FALSE(ws4.is_valid());
  19946. // Port number overflow — should not crash
  19947. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  19948. EXPECT_FALSE(ws5.is_valid());
  19949. // Port out of range
  19950. ws::WebSocketClient ws6("ws://localhost:99999/path");
  19951. EXPECT_FALSE(ws6.is_valid());
  19952. }
  19953. TEST(WebSocketTest, UnsupportedScheme) {
  19954. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  19955. ws::WebSocketClient ws1("http://localhost:8080/path");
  19956. EXPECT_FALSE(ws1.is_valid());
  19957. ws::WebSocketClient ws2("https://localhost:8080/path");
  19958. EXPECT_FALSE(ws2.is_valid());
  19959. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  19960. EXPECT_FALSE(ws3.is_valid());
  19961. #else
  19962. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  19963. std::invalid_argument);
  19964. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  19965. std::invalid_argument);
  19966. #endif
  19967. }
  19968. TEST(WebSocketTest, ConnectWhenInvalid) {
  19969. ws::WebSocketClient ws("not a valid url");
  19970. EXPECT_FALSE(ws.is_valid());
  19971. auto res = ws.connect();
  19972. EXPECT_FALSE(res);
  19973. EXPECT_EQ(Error::Connection, res.error());
  19974. EXPECT_EQ(-1, res.status());
  19975. }
  19976. TEST(WebSocketTest, ConnectRefusedReportsError) {
  19977. // Grab a port that is free, then close it again so nothing listens there
  19978. Server svr;
  19979. auto port = svr.bind_to_any_port(HOST);
  19980. svr.stop();
  19981. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19982. auto res = client.connect();
  19983. ASSERT_FALSE(res);
  19984. EXPECT_EQ(Error::Connection, res.error());
  19985. EXPECT_EQ(-1, res.status());
  19986. }
  19987. TEST(WebSocketTest, DefaultPort) {
  19988. ws::WebSocketClient ws1("ws://example.com/path");
  19989. EXPECT_TRUE(ws1.is_valid());
  19990. // ws:// defaults to port 80 (verified by successful parse)
  19991. #ifdef CPPHTTPLIB_SSL_ENABLED
  19992. ws::WebSocketClient ws2("wss://example.com/path");
  19993. EXPECT_TRUE(ws2.is_valid());
  19994. // wss:// defaults to port 443 (verified by successful parse)
  19995. #endif
  19996. }
  19997. TEST(WebSocketTest, IPv6LiteralAddress) {
  19998. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  19999. EXPECT_TRUE(ws1.is_valid());
  20000. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  20001. EXPECT_TRUE(ws2.is_valid());
  20002. }
  20003. TEST(WebSocketTest, ComplexPath) {
  20004. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  20005. EXPECT_TRUE(ws1.is_valid());
  20006. ws::WebSocketClient ws2("ws://localhost:8080/");
  20007. EXPECT_TRUE(ws2.is_valid());
  20008. }
  20009. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  20010. Server svr;
  20011. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20012. std::string msg;
  20013. while (ws.read(msg)) {}
  20014. });
  20015. auto port = svr.bind_to_any_port(HOST);
  20016. std::thread t([&]() { svr.listen_after_bind(); });
  20017. svr.wait_until_ready();
  20018. auto another_host = "example.com";
  20019. auto wrong_ip = "192.0.2.1";
  20020. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20021. client.set_hostname_addr_map({{another_host, wrong_ip}});
  20022. ASSERT_TRUE(client.connect());
  20023. EXPECT_TRUE(client.is_open());
  20024. client.close();
  20025. svr.stop();
  20026. t.join();
  20027. }
  20028. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  20029. Server svr;
  20030. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20031. std::string msg;
  20032. while (ws.read(msg)) {}
  20033. });
  20034. auto port = svr.bind_to_any_port(HOST);
  20035. std::thread t([&]() { svr.listen_after_bind(); });
  20036. svr.wait_until_ready();
  20037. auto wrong_ip = "192.0.2.1";
  20038. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20039. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  20040. client.set_connection_timeout(1);
  20041. client.set_read_timeout(1);
  20042. client.set_write_timeout(1);
  20043. EXPECT_FALSE(client.connect());
  20044. EXPECT_FALSE(client.is_open());
  20045. svr.stop();
  20046. t.join();
  20047. }
  20048. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  20049. // A mapped value that is not an IP literal must be resolved. HOST resolves
  20050. // from the hosts file, so this test needs no external DNS. "target.invalid"
  20051. // (RFC 6761) is only a map key and the Host header value.
  20052. auto host = "target.invalid";
  20053. Server svr;
  20054. std::string received_host;
  20055. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20056. received_host = req.get_header_value("Host");
  20057. std::string msg;
  20058. while (ws.read(msg)) {}
  20059. });
  20060. auto port = svr.bind_to_any_port(HOST);
  20061. std::thread t([&]() { svr.listen_after_bind(); });
  20062. // ASSERT_* below returns from the test body, which would leave t joinable
  20063. // and make ~thread call std::terminate.
  20064. auto se = detail::scope_exit([&] {
  20065. svr.stop();
  20066. if (t.joinable()) { t.join(); }
  20067. });
  20068. svr.wait_until_ready();
  20069. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  20070. std::to_string(port) + "/ws");
  20071. client.set_hostname_addr_map({{host, HOST}});
  20072. ASSERT_TRUE(client.connect());
  20073. EXPECT_TRUE(client.is_open());
  20074. client.close();
  20075. svr.stop();
  20076. t.join();
  20077. // The mapping only redirects the connection; the identity stays host_.
  20078. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  20079. }
  20080. class WebSocketIntegrationTest : public ::testing::Test {
  20081. protected:
  20082. void SetUp() override {
  20083. server_ = httplib::detail::make_unique<Server>();
  20084. setup_server();
  20085. start_server();
  20086. }
  20087. void TearDown() override {
  20088. server_->stop();
  20089. if (server_thread_.joinable()) { server_thread_.join(); }
  20090. }
  20091. void setup_server() {
  20092. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  20093. std::string msg;
  20094. ws::ReadResult ret;
  20095. while ((ret = ws.read(msg))) {
  20096. if (ret == ws::Binary) {
  20097. ws.send(msg.data(), msg.size());
  20098. } else {
  20099. ws.send(msg);
  20100. }
  20101. }
  20102. });
  20103. server_->WebSocket("/ws-echo-string",
  20104. [](const Request &, ws::WebSocket &ws) {
  20105. std::string msg;
  20106. while (ws.read(msg)) {
  20107. ws.send("echo: " + msg);
  20108. }
  20109. });
  20110. server_->WebSocket(
  20111. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  20112. // Echo back request metadata
  20113. ws.send("path:" + req.path);
  20114. ws.send("header:" + req.get_header_value("X-Test-Header"));
  20115. std::string msg;
  20116. while (ws.read(msg)) {}
  20117. });
  20118. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  20119. std::string msg;
  20120. ws.read(msg); // wait for a message
  20121. ws.close();
  20122. });
  20123. server_->WebSocket("/ws-close-status",
  20124. [](const Request &, ws::WebSocket &ws) {
  20125. std::string msg;
  20126. ws.read(msg); // wait for a message
  20127. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  20128. });
  20129. server_->WebSocket(
  20130. "/ws-subprotocol",
  20131. [](const Request &, ws::WebSocket &ws) {
  20132. std::string msg;
  20133. while (ws.read(msg)) {
  20134. ws.send(msg);
  20135. }
  20136. },
  20137. [](const std::vector<std::string> &protocols) -> std::string {
  20138. for (const auto &p : protocols) {
  20139. if (p == "graphql-ws") { return p; }
  20140. }
  20141. return "";
  20142. });
  20143. }
  20144. void start_server() {
  20145. port_ = server_->bind_to_any_port(HOST);
  20146. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20147. server_->wait_until_ready();
  20148. }
  20149. std::unique_ptr<Server> server_;
  20150. std::thread server_thread_;
  20151. int port_ = 0;
  20152. };
  20153. TEST_F(WebSocketIntegrationTest, TextEcho) {
  20154. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20155. "/ws-echo");
  20156. ASSERT_TRUE(client.connect());
  20157. ASSERT_TRUE(client.is_open());
  20158. ASSERT_TRUE(client.send("Hello WebSocket"));
  20159. std::string msg;
  20160. EXPECT_EQ(ws::Text, client.read(msg));
  20161. EXPECT_EQ("Hello WebSocket", msg);
  20162. client.close();
  20163. }
  20164. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  20165. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20166. "/ws-echo");
  20167. ASSERT_TRUE(client.connect());
  20168. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  20169. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  20170. std::string msg;
  20171. EXPECT_EQ(ws::Binary, client.read(msg));
  20172. EXPECT_EQ(binary_data, msg);
  20173. client.close();
  20174. }
  20175. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  20176. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20177. "/ws-echo");
  20178. ASSERT_TRUE(client.connect());
  20179. for (int i = 0; i < 10; i++) {
  20180. auto text = "message " + std::to_string(i);
  20181. ASSERT_TRUE(client.send(text));
  20182. std::string msg;
  20183. ASSERT_TRUE(client.read(msg));
  20184. EXPECT_EQ(text, msg);
  20185. }
  20186. client.close();
  20187. }
  20188. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  20189. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20190. "/ws-close");
  20191. ASSERT_TRUE(client.connect());
  20192. // Send a message to trigger the server to close
  20193. ASSERT_TRUE(client.send("trigger close"));
  20194. // The server will close, so read should return false
  20195. std::string msg;
  20196. EXPECT_FALSE(client.read(msg));
  20197. EXPECT_FALSE(client.is_open());
  20198. }
  20199. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  20200. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20201. "/ws-echo");
  20202. ASSERT_TRUE(client.connect());
  20203. // 128KB message
  20204. std::string large_data(128 * 1024, 'X');
  20205. ASSERT_TRUE(client.send(large_data));
  20206. std::string msg;
  20207. ASSERT_TRUE(client.read(msg));
  20208. EXPECT_EQ(large_data, msg);
  20209. client.close();
  20210. }
  20211. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  20212. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20213. "/ws-echo");
  20214. ASSERT_TRUE(client.connect());
  20215. const int num_threads = 4;
  20216. std::vector<std::thread> threads;
  20217. std::atomic<int> send_count{0};
  20218. for (int t = 0; t < num_threads; t++) {
  20219. threads.emplace_back([&client, &send_count, t]() {
  20220. for (int i = 0; i < 5; i++) {
  20221. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  20222. if (client.send(text)) { send_count++; }
  20223. }
  20224. });
  20225. }
  20226. for (auto &th : threads) {
  20227. th.join();
  20228. }
  20229. int received = 0;
  20230. std::string msg;
  20231. while (received < send_count.load()) {
  20232. if (!client.read(msg)) { break; }
  20233. received++;
  20234. }
  20235. EXPECT_EQ(send_count.load(), received);
  20236. client.close();
  20237. }
  20238. TEST_F(WebSocketIntegrationTest, ReadString) {
  20239. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20240. "/ws-echo-string");
  20241. ASSERT_TRUE(client.connect());
  20242. ASSERT_TRUE(client.send("hello"));
  20243. std::string msg;
  20244. ASSERT_TRUE(client.read(msg));
  20245. EXPECT_EQ("echo: hello", msg);
  20246. ASSERT_TRUE(client.send("world"));
  20247. ASSERT_TRUE(client.read(msg));
  20248. EXPECT_EQ("echo: world", msg);
  20249. client.close();
  20250. }
  20251. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  20252. Headers headers = {{"X-Test-Header", "test-value"}};
  20253. ws::WebSocketClient client(
  20254. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  20255. ASSERT_TRUE(client.connect());
  20256. std::string msg;
  20257. ASSERT_TRUE(client.read(msg));
  20258. EXPECT_EQ("path:/ws-request-info", msg);
  20259. ASSERT_TRUE(client.read(msg));
  20260. EXPECT_EQ("header:test-value", msg);
  20261. client.close();
  20262. }
  20263. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  20264. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20265. "/ws-echo");
  20266. client.set_read_timeout(1, 0); // 1 second
  20267. ASSERT_TRUE(client.connect());
  20268. // Don't send anything — server echo handler waits for a message, so read()
  20269. // should time out. The connection survives it: nothing was consumed.
  20270. std::string msg;
  20271. EXPECT_EQ(client.read(msg), ws::Timeout);
  20272. EXPECT_TRUE(client.is_open());
  20273. // And it is still usable afterwards.
  20274. EXPECT_TRUE(client.send("after timeout"));
  20275. EXPECT_EQ(client.read(msg), ws::Text);
  20276. EXPECT_EQ(msg, "after timeout");
  20277. }
  20278. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  20279. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20280. "/ws-echo");
  20281. client.set_read_timeout(1, 0);
  20282. ASSERT_TRUE(client.connect());
  20283. ASSERT_TRUE(client.send("first"));
  20284. std::string msg;
  20285. ASSERT_EQ(client.read(msg), ws::Text);
  20286. ASSERT_EQ(msg, "first");
  20287. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  20288. // not be used with a read timeout: it would reprocess the previous message.
  20289. EXPECT_EQ(client.read(msg), ws::Timeout);
  20290. EXPECT_EQ(msg, "first");
  20291. }
  20292. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  20293. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20294. "/ws-echo");
  20295. ASSERT_TRUE(client.connect());
  20296. // Setting it once the connection is open reaches the live stream, not just
  20297. // the seed for the next connect().
  20298. client.set_read_timeout(1, 0);
  20299. std::string msg;
  20300. EXPECT_EQ(client.read(msg), ws::Timeout);
  20301. EXPECT_TRUE(client.is_open());
  20302. }
  20303. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  20304. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20305. "/ws-echo");
  20306. client.set_read_timeout(5, 0);
  20307. ASSERT_TRUE(client.connect());
  20308. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  20309. // The server should reject it and close the connection.
  20310. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  20311. client.send(oversized);
  20312. // The server's read() should have failed due to payload limit,
  20313. // so our read() should return false (connection closed).
  20314. std::string msg;
  20315. EXPECT_FALSE(client.read(msg));
  20316. }
  20317. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  20318. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20319. "/ws-echo");
  20320. client.set_read_timeout(10, 0);
  20321. ASSERT_TRUE(client.connect());
  20322. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  20323. // This should succeed.
  20324. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  20325. ASSERT_TRUE(client.send(at_limit));
  20326. std::string msg;
  20327. ASSERT_TRUE(client.read(msg));
  20328. EXPECT_EQ(at_limit.size(), msg.size());
  20329. client.close();
  20330. }
  20331. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  20332. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20333. "/nonexistent");
  20334. auto res = client.connect();
  20335. EXPECT_FALSE(res);
  20336. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  20337. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  20338. EXPECT_FALSE(client.is_open());
  20339. }
  20340. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  20341. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20342. "/ws-echo");
  20343. ASSERT_TRUE(client.connect());
  20344. ASSERT_TRUE(client.send(""));
  20345. std::string msg;
  20346. EXPECT_EQ(ws::Text, client.read(msg));
  20347. EXPECT_EQ("", msg);
  20348. client.close();
  20349. }
  20350. TEST_F(WebSocketIntegrationTest, Reconnect) {
  20351. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20352. "/ws-echo");
  20353. // First connection
  20354. ASSERT_TRUE(client.connect());
  20355. ASSERT_TRUE(client.send("first"));
  20356. std::string msg;
  20357. ASSERT_TRUE(client.read(msg));
  20358. EXPECT_EQ("first", msg);
  20359. client.close();
  20360. EXPECT_FALSE(client.is_open());
  20361. // Reconnect using the same client object
  20362. ASSERT_TRUE(client.connect());
  20363. ASSERT_TRUE(client.is_open());
  20364. ASSERT_TRUE(client.send("second"));
  20365. ASSERT_TRUE(client.read(msg));
  20366. EXPECT_EQ("second", msg);
  20367. client.close();
  20368. }
  20369. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  20370. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20371. "/ws-close-status");
  20372. ASSERT_TRUE(client.connect());
  20373. // Trigger the server to close with GoingAway status
  20374. ASSERT_TRUE(client.send("trigger"));
  20375. // read() should return false after receiving the close frame
  20376. std::string msg;
  20377. EXPECT_FALSE(client.read(msg));
  20378. EXPECT_FALSE(client.is_open());
  20379. }
  20380. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  20381. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20382. "/ws-echo");
  20383. ASSERT_TRUE(client.connect());
  20384. client.close(ws::CloseStatus::GoingAway, "client leaving");
  20385. EXPECT_FALSE(client.is_open());
  20386. }
  20387. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  20388. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  20389. ws::WebSocketClient client(
  20390. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20391. ASSERT_TRUE(client.connect());
  20392. // Server should have selected graphql-ws
  20393. EXPECT_EQ("graphql-ws", client.subprotocol());
  20394. client.close();
  20395. }
  20396. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  20397. Headers headers;
  20398. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  20399. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  20400. ws::WebSocketClient client(
  20401. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20402. ASSERT_TRUE(client.connect());
  20403. // The offer on the second field line counts too, so graphql-ws is selected
  20404. EXPECT_EQ("graphql-ws", client.subprotocol());
  20405. client.close();
  20406. }
  20407. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  20408. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  20409. ws::WebSocketClient client(
  20410. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20411. ASSERT_TRUE(client.connect());
  20412. // Server should not have selected any subprotocol
  20413. EXPECT_TRUE(client.subprotocol().empty());
  20414. client.close();
  20415. }
  20416. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  20417. // Connect without requesting any subprotocol
  20418. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20419. "/ws-subprotocol");
  20420. ASSERT_TRUE(client.connect());
  20421. EXPECT_TRUE(client.subprotocol().empty());
  20422. client.close();
  20423. }
  20424. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  20425. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20426. "/ws-echo");
  20427. client.set_tcp_nodelay(true);
  20428. client.set_connection_timeout(3, 0);
  20429. bool socket_options_called = false;
  20430. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  20431. ASSERT_TRUE(client.connect());
  20432. ASSERT_TRUE(client.is_open());
  20433. EXPECT_TRUE(socket_options_called);
  20434. ASSERT_TRUE(client.send("hello"));
  20435. std::string msg;
  20436. auto result = client.read(msg);
  20437. EXPECT_EQ(result, ws::ReadResult::Text);
  20438. EXPECT_EQ(msg, "hello");
  20439. client.close();
  20440. }
  20441. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  20442. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20443. "/ws-echo");
  20444. client.set_connection_timeout(std::chrono::seconds(3));
  20445. client.set_write_timeout(std::chrono::seconds(3));
  20446. // A sub-second remainder exercises the seconds/microseconds split.
  20447. client.set_read_timeout(std::chrono::milliseconds(1500));
  20448. ASSERT_TRUE(client.connect());
  20449. auto start = std::chrono::steady_clock::now();
  20450. std::string msg;
  20451. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  20452. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  20453. std::chrono::steady_clock::now() - start)
  20454. .count();
  20455. // Above 1s so that dropping the microseconds half of the split fails here.
  20456. // Ignoring the setter altogether would not reach this line at all: a client
  20457. // waits forever by default.
  20458. EXPECT_GE(elapsed, 1400);
  20459. EXPECT_LT(elapsed, 30000);
  20460. }
  20461. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  20462. Server svr;
  20463. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  20464. if (!req.has_header("Authorization")) {
  20465. res.status = StatusCode::Unauthorized_401;
  20466. res.set_content("Unauthorized", "text/plain");
  20467. return Server::HandlerResponse::Handled;
  20468. }
  20469. return Server::HandlerResponse::Unhandled;
  20470. });
  20471. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20472. std::string msg;
  20473. while (ws.read(msg)) {
  20474. ws.send(msg);
  20475. }
  20476. });
  20477. auto port = svr.bind_to_any_port("localhost");
  20478. std::thread t([&]() { svr.listen_after_bind(); });
  20479. svr.wait_until_ready();
  20480. // Without Authorization header - should be rejected before upgrade
  20481. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  20482. EXPECT_FALSE(client1.connect());
  20483. // The rejection is framed like any other HTTP response
  20484. {
  20485. Client cli("localhost", port);
  20486. Headers headers = {{"Upgrade", "websocket"},
  20487. {"Connection", "Upgrade"},
  20488. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20489. {"Sec-WebSocket-Version", "13"}};
  20490. auto res = cli.Get("/ws", headers);
  20491. ASSERT_TRUE(res);
  20492. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20493. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  20494. EXPECT_EQ("Unauthorized", res->body);
  20495. }
  20496. // With Authorization header - should succeed
  20497. Headers headers = {{"Authorization", "Bearer token123"}};
  20498. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  20499. headers);
  20500. ASSERT_TRUE(client2.connect());
  20501. ASSERT_TRUE(client2.send("hello"));
  20502. std::string msg;
  20503. ASSERT_TRUE(client2.read(msg));
  20504. EXPECT_EQ("hello", msg);
  20505. client2.close();
  20506. svr.stop();
  20507. t.join();
  20508. }
  20509. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  20510. Server svr;
  20511. std::atomic<int> pre_request_calls{0};
  20512. std::atomic<bool> route_matched{false};
  20513. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  20514. pre_request_calls++;
  20515. if (req.matched_route == "/ws/:id") { route_matched = true; }
  20516. if (req.get_header_value("Authorization") != "Bearer token123") {
  20517. res.status = StatusCode::Unauthorized_401;
  20518. res.set_content("Unauthorized", "text/plain");
  20519. return Server::HandlerResponse::Handled;
  20520. }
  20521. return Server::HandlerResponse::Unhandled;
  20522. });
  20523. std::atomic<bool> handler_called{false};
  20524. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  20525. handler_called = true;
  20526. ws.send(req.matched_route + " " + req.path_params.at("id"));
  20527. });
  20528. auto port = svr.bind_to_any_port("localhost");
  20529. std::thread t([&]() { svr.listen_after_bind(); });
  20530. svr.wait_until_ready();
  20531. // Without Authorization header - should be rejected before upgrade
  20532. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  20533. "/ws/1");
  20534. EXPECT_FALSE(client1.connect());
  20535. EXPECT_FALSE(handler_called);
  20536. EXPECT_EQ(1, pre_request_calls);
  20537. EXPECT_TRUE(route_matched);
  20538. // The rejection is an ordinary HTTP response, not a protocol switch
  20539. {
  20540. Client cli("localhost", port);
  20541. Headers headers = {{"Upgrade", "websocket"},
  20542. {"Connection", "Upgrade"},
  20543. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20544. {"Sec-WebSocket-Version", "13"}};
  20545. auto res = cli.Get("/ws/1", headers);
  20546. ASSERT_TRUE(res);
  20547. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20548. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  20549. EXPECT_EQ("Unauthorized", res->body);
  20550. }
  20551. EXPECT_FALSE(handler_called);
  20552. // With Authorization header - should succeed
  20553. Headers headers = {{"Authorization", "Bearer token123"}};
  20554. ws::WebSocketClient client2(
  20555. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  20556. ASSERT_TRUE(client2.connect());
  20557. std::string msg;
  20558. ASSERT_TRUE(client2.read(msg));
  20559. EXPECT_EQ("/ws/:id 2", msg);
  20560. EXPECT_TRUE(handler_called);
  20561. client2.close();
  20562. svr.stop();
  20563. t.join();
  20564. }
  20565. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  20566. Server svr;
  20567. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20568. // A read timeout is how a handler gets control back. Without it, a handler
  20569. // parked in read() can never write on the connection it is reading.
  20570. ws.set_read_timeout(std::chrono::milliseconds(100));
  20571. std::string msg;
  20572. while (ws.is_open()) {
  20573. auto r = ws.read(msg);
  20574. if (r == httplib::ws::Timeout) {
  20575. ws.send("tick");
  20576. continue;
  20577. }
  20578. if (r == httplib::ws::Fail) { break; }
  20579. ws.send(msg);
  20580. }
  20581. });
  20582. auto port = svr.bind_to_any_port("localhost");
  20583. std::thread t([&]() { svr.listen_after_bind(); });
  20584. svr.wait_until_ready();
  20585. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20586. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  20587. ASSERT_TRUE(client.connect());
  20588. // The client sends nothing, so anything it receives came out of the
  20589. // handler's timeout path.
  20590. std::string msg;
  20591. ASSERT_EQ(client.read(msg), ws::Text);
  20592. EXPECT_EQ("tick", msg);
  20593. client.close();
  20594. svr.stop();
  20595. t.join();
  20596. }
  20597. // Stream::read may return fewer bytes than asked for. This is that contract at
  20598. // its worst -- one byte per call -- which is what a frame header straddling a
  20599. // read buffer's boundary looks like to the frame parser.
  20600. class WsByteAtATimeStream : public Stream {
  20601. public:
  20602. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  20603. bool is_readable() const override { return true; }
  20604. bool wait_readable() const override { return true; }
  20605. bool wait_writable() const override { return true; }
  20606. ssize_t read(char *ptr, size_t size) override {
  20607. if (size == 0 || pos_ >= data_.size()) { return 0; }
  20608. *ptr = data_[pos_++];
  20609. return 1;
  20610. }
  20611. ssize_t write(const char *, size_t size) override {
  20612. return static_cast<ssize_t>(size);
  20613. }
  20614. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  20615. ip = "127.0.0.1";
  20616. port = 0;
  20617. }
  20618. void get_local_ip_and_port(std::string &ip, int &port) const override {
  20619. ip = "127.0.0.1";
  20620. port = 0;
  20621. }
  20622. socket_t socket() const override { return INVALID_SOCKET; }
  20623. time_t duration() const override { return 0; }
  20624. private:
  20625. std::string data_;
  20626. size_t pos_ = 0;
  20627. };
  20628. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  20629. // A 200-byte payload uses the 16-bit extended length, so the header, the
  20630. // length and the mask key are all multi-byte fields here. Each used to be
  20631. // read with a single read() call, which fails as soon as one is split.
  20632. std::string body(200, 'x');
  20633. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  20634. std::string frame;
  20635. frame += static_cast<char>(0x81); // FIN + Text
  20636. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  20637. frame += static_cast<char>(body.size() >> 8);
  20638. frame += static_cast<char>(body.size() & 0xff);
  20639. for (size_t i = 0; i < 4; i++) {
  20640. frame += static_cast<char>(mask[i]);
  20641. }
  20642. for (size_t i = 0; i < body.size(); i++) {
  20643. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  20644. }
  20645. WsByteAtATimeStream strm(frame);
  20646. ws::Opcode opcode;
  20647. std::string payload;
  20648. bool fin = false;
  20649. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  20650. /*expect_masked=*/true, 1024),
  20651. ws::impl::FrameRead::Ok);
  20652. EXPECT_TRUE(fin);
  20653. EXPECT_EQ(opcode, ws::Opcode::Text);
  20654. EXPECT_EQ(payload, body);
  20655. }
  20656. TEST(WebSocketTest, QueryStringInHandshake) {
  20657. Server svr;
  20658. std::mutex mtx;
  20659. std::string received_target;
  20660. std::string received_token;
  20661. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20662. {
  20663. std::lock_guard<std::mutex> lock(mtx);
  20664. received_target = req.target;
  20665. if (req.has_param("token")) {
  20666. received_token = req.get_param_value("token");
  20667. }
  20668. }
  20669. std::string msg;
  20670. while (ws.read(msg)) {
  20671. ws.send(msg);
  20672. }
  20673. });
  20674. auto port = svr.bind_to_any_port("localhost");
  20675. std::thread t([&]() { svr.listen_after_bind(); });
  20676. svr.wait_until_ready();
  20677. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  20678. "/ws?token=ABC&session=123");
  20679. ASSERT_TRUE(client.connect());
  20680. // Round-trip ensures the handler has run and captured the request.
  20681. ASSERT_TRUE(client.send("hello"));
  20682. std::string msg;
  20683. ASSERT_TRUE(client.read(msg));
  20684. EXPECT_EQ("hello", msg);
  20685. client.close();
  20686. {
  20687. std::lock_guard<std::mutex> lock(mtx);
  20688. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  20689. EXPECT_EQ("ABC", received_token);
  20690. }
  20691. svr.stop();
  20692. t.join();
  20693. }
  20694. // Run a handshake against a throwaway server and hand the request the server
  20695. // received back to the caller, so tests can assert on the headers the client
  20696. // actually put on the wire.
  20697. static void capture_websocket_handshake_request(
  20698. const Headers &client_headers,
  20699. std::function<void(const Request &, int port)> verify) {
  20700. Server svr;
  20701. std::mutex mtx;
  20702. Request received;
  20703. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20704. {
  20705. std::lock_guard<std::mutex> lock(mtx);
  20706. received = req;
  20707. }
  20708. std::string msg;
  20709. while (ws.read(msg)) {
  20710. ws.send(msg);
  20711. }
  20712. });
  20713. auto port = svr.bind_to_any_port("localhost");
  20714. std::thread t([&]() { svr.listen_after_bind(); });
  20715. auto se = detail::scope_exit([&] {
  20716. svr.stop();
  20717. t.join();
  20718. });
  20719. svr.wait_until_ready();
  20720. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  20721. client_headers);
  20722. ASSERT_TRUE(client.connect());
  20723. ASSERT_TRUE(client.send("hello"));
  20724. std::string msg;
  20725. ASSERT_TRUE(client.read(msg));
  20726. client.close();
  20727. {
  20728. std::lock_guard<std::mutex> lock(mtx);
  20729. verify(received, port);
  20730. }
  20731. }
  20732. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  20733. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  20734. // Non-default port must be present in the Host header. Default ports
  20735. // (80/443) are omitted; that logic is covered by
  20736. // MakeHostAndPortStringTest.
  20737. EXPECT_EQ("localhost:" + std::to_string(port),
  20738. req.get_header_value("Host"));
  20739. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  20740. req.get_header_value("User-Agent"));
  20741. EXPECT_FALSE(req.has_header("Accept"));
  20742. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  20743. EXPECT_FALSE(req.has_header("Content-Length"));
  20744. });
  20745. }
  20746. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  20747. capture_websocket_handshake_request(
  20748. {{"Host", "example.com"},
  20749. {"User-Agent", "custom-agent"},
  20750. {"X-Custom", "value"}},
  20751. [](const Request &req, int) {
  20752. EXPECT_EQ("example.com", req.get_header_value("Host"));
  20753. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  20754. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  20755. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  20756. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  20757. });
  20758. }
  20759. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  20760. capture_websocket_handshake_request(
  20761. {{"Upgrade", "bogus"},
  20762. {"Connection", "close"},
  20763. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  20764. {"Sec-WebSocket-Version", "8"}},
  20765. [](const Request &req, int) {
  20766. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  20767. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  20768. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  20769. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  20770. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  20771. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  20772. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  20773. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  20774. req.get_header_value("Sec-WebSocket-Key"));
  20775. });
  20776. }
  20777. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  20778. // A header the client refuses to send must abort the handshake before any
  20779. // part of it reaches the wire; a lone request line would otherwise sit in
  20780. // the peer's buffer as a truncated request.
  20781. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20782. ASSERT_NE(INVALID_SOCKET, srv);
  20783. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  20784. sockaddr_in addr{};
  20785. addr.sin_family = AF_INET;
  20786. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  20787. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20788. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  20789. ASSERT_EQ(0, ::listen(srv, 1));
  20790. sockaddr_in bound{};
  20791. socklen_t bound_len = sizeof(bound);
  20792. ASSERT_EQ(
  20793. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  20794. auto port = ntohs(bound.sin_port);
  20795. ssize_t received = -1;
  20796. std::thread t([&] {
  20797. // Bound every blocking call so a regression fails the test with a bad
  20798. // value instead of hanging the suite.
  20799. fd_set rfds;
  20800. FD_ZERO(&rfds);
  20801. FD_SET(srv, &rfds);
  20802. timeval tv{5, 0};
  20803. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  20804. 0) {
  20805. return;
  20806. }
  20807. sockaddr_in cli_addr{};
  20808. socklen_t cli_len = sizeof(cli_addr);
  20809. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  20810. if (cli == INVALID_SOCKET) { return; }
  20811. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  20812. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20813. char buf[4096];
  20814. received = ::recv(cli, buf, sizeof(buf), 0);
  20815. });
  20816. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  20817. // connect() has already shut the socket down by the time it returns false,
  20818. // so the peer sees EOF without waiting for the client to be destroyed.
  20819. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  20820. {{"X-Bad", "a\r\nInjected: 1"}});
  20821. EXPECT_FALSE(client.connect());
  20822. t.join();
  20823. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  20824. EXPECT_EQ(0, received);
  20825. }
  20826. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  20827. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  20828. // contains "upgrade" as a substring is a different token and must not
  20829. // start a WebSocket handshake.
  20830. auto make_request = [](const std::vector<std::string> &connection_values) {
  20831. Request req;
  20832. req.method = "GET";
  20833. req.headers.emplace("Upgrade", "websocket");
  20834. for (const auto &value : connection_values) {
  20835. req.headers.emplace("Connection", value);
  20836. }
  20837. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  20838. req.headers.emplace("Sec-WebSocket-Version", "13");
  20839. return req;
  20840. };
  20841. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  20842. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  20843. EXPECT_TRUE(
  20844. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  20845. EXPECT_TRUE(
  20846. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  20847. EXPECT_TRUE(
  20848. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  20849. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  20850. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  20851. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  20852. EXPECT_FALSE(
  20853. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  20854. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  20855. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  20856. }
  20857. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  20858. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  20859. // asks recipients to match each protocol-name case-insensitively, and RFC
  20860. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  20861. // client naming websocket alongside another protocol, or on a second field
  20862. // line, is offering websocket; a value that merely contains "websocket" as a
  20863. // substring is a different protocol name and is not.
  20864. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  20865. Request req;
  20866. req.method = "GET";
  20867. for (const auto &value : upgrade_values) {
  20868. req.headers.emplace("Upgrade", value);
  20869. }
  20870. req.headers.emplace("Connection", "Upgrade");
  20871. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  20872. req.headers.emplace("Sec-WebSocket-Version", "13");
  20873. return req;
  20874. };
  20875. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  20876. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  20877. EXPECT_TRUE(
  20878. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  20879. EXPECT_TRUE(
  20880. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  20881. EXPECT_TRUE(
  20882. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  20883. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  20884. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  20885. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  20886. EXPECT_FALSE(
  20887. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  20888. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  20889. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  20890. }
  20891. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  20892. Server svr;
  20893. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  20894. auto port = svr.bind_to_any_port("localhost");
  20895. std::thread t([&]() { svr.listen_after_bind(); });
  20896. auto se = detail::scope_exit([&] {
  20897. svr.stop();
  20898. t.join();
  20899. });
  20900. svr.wait_until_ready();
  20901. Headers headers = {{"Upgrade", "websocket"},
  20902. {"Connection", "notupgrade"},
  20903. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20904. {"Sec-WebSocket-Version", "13"}};
  20905. Client cli("localhost", port);
  20906. auto res = cli.Get("/ws", headers);
  20907. // The route exists only as a WebSocket route, so a request that fails the
  20908. // handshake check falls through to ordinary routing.
  20909. ASSERT_TRUE(res);
  20910. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  20911. }
  20912. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  20913. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  20914. // Connection value is the only thing left for the client to reject.
  20915. Server svr;
  20916. svr.Get("/ws", [](const Request &req, Response &res) {
  20917. res.status = StatusCode::SwitchingProtocol_101;
  20918. res.set_header("Upgrade", "websocket");
  20919. res.set_header("Connection", "notupgrade");
  20920. res.set_header("Sec-WebSocket-Accept",
  20921. detail::websocket_accept_key(
  20922. req.get_header_value("Sec-WebSocket-Key")));
  20923. });
  20924. auto port = svr.bind_to_any_port("localhost");
  20925. std::thread t([&]() { svr.listen_after_bind(); });
  20926. auto se = detail::scope_exit([&] {
  20927. svr.stop();
  20928. t.join();
  20929. });
  20930. svr.wait_until_ready();
  20931. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20932. auto res = client.connect();
  20933. EXPECT_FALSE(res);
  20934. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  20935. EXPECT_FALSE(client.is_open());
  20936. }
  20937. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  20938. // The socket path doubles as the URL host, so it must not contain '/'.
  20939. const char *shard = getenv("GTEST_SHARD_INDEX");
  20940. const std::string sock_path =
  20941. shard ? std::string("httplib-ws-") + shard + ".sock"
  20942. : std::string("httplib-ws.sock");
  20943. std::remove(sock_path.c_str());
  20944. Server svr;
  20945. std::mutex mtx;
  20946. std::string received_host;
  20947. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20948. {
  20949. std::lock_guard<std::mutex> lock(mtx);
  20950. received_host = req.get_header_value("Host");
  20951. }
  20952. std::string msg;
  20953. while (ws.read(msg)) {
  20954. ws.send(msg);
  20955. }
  20956. });
  20957. svr.set_address_family(AF_UNIX);
  20958. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  20959. auto se = detail::scope_exit([&] {
  20960. svr.stop();
  20961. t.join();
  20962. std::remove(sock_path.c_str());
  20963. });
  20964. svr.wait_until_ready();
  20965. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  20966. client.set_address_family(AF_UNIX);
  20967. ASSERT_TRUE(client.connect());
  20968. ASSERT_TRUE(client.send("hello"));
  20969. std::string msg;
  20970. ASSERT_TRUE(client.read(msg));
  20971. client.close();
  20972. {
  20973. std::lock_guard<std::mutex> lock(mtx);
  20974. // There is no host:port for a Unix socket, so the same "localhost"
  20975. // placeholder the HTTP client uses is expected.
  20976. EXPECT_EQ("localhost", received_host);
  20977. }
  20978. }
  20979. // Two threads must never parse WebSocket frames from the same stream.
  20980. // close() used to read the peer's Close reply with its own frame read, so it
  20981. // raced a reader thread that was in the middle of a payload: the payload loop
  20982. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  20983. // so bytes taken by close() were replaced with bytes from further along the
  20984. // stream. The message kept its length and silently changed content.
  20985. //
  20986. // The raw peer below sends a frame header plus part of the payload, waits for
  20987. // the handler to call close(), and only then sends the rest. Whichever thread
  20988. // would win the race for those bytes, the message must arrive intact, because
  20989. // close() must not touch the stream while read() owns it.
  20990. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  20991. #ifndef _WIN32
  20992. signal(SIGPIPE, SIG_IGN);
  20993. #endif
  20994. const size_t payload_len = 120; // fits the 7-bit length field
  20995. const size_t prefix_len = 8;
  20996. const int attempts = 8;
  20997. std::string expected(payload_len, '\0');
  20998. for (size_t i = 0; i < payload_len; i++) {
  20999. expected[i] = static_cast<char>('a' + i % 26);
  21000. }
  21001. std::atomic<bool> peer_stalled{false};
  21002. std::atomic<bool> handler_done{false};
  21003. std::mutex received_mutex;
  21004. std::vector<std::string> received;
  21005. // Bound every wait, so a regression fails the test instead of hanging the
  21006. // suite.
  21007. auto wait_for = [](const std::atomic<bool> &flag) {
  21008. for (int i = 0; i < 500 && !flag; i++) {
  21009. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21010. }
  21011. };
  21012. Server svr;
  21013. svr.set_websocket_ping_interval(0);
  21014. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  21015. std::thread reader([&]() {
  21016. std::string msg;
  21017. while (ws.read(msg)) {
  21018. std::lock_guard<std::mutex> guard(received_mutex);
  21019. received.push_back(msg);
  21020. }
  21021. });
  21022. // Wait until the peer stalls mid-payload, so the reader thread is parked
  21023. // inside read_websocket_frame() when close() runs.
  21024. wait_for(peer_stalled);
  21025. ws.close();
  21026. reader.join();
  21027. handler_done = true;
  21028. });
  21029. auto port = svr.bind_to_any_port("127.0.0.1");
  21030. std::thread t([&]() { svr.listen_after_bind(); });
  21031. auto se = detail::scope_exit([&] {
  21032. svr.stop();
  21033. t.join();
  21034. });
  21035. svr.wait_until_ready();
  21036. auto send_bytes = [](socket_t s, const std::string &data) {
  21037. #ifdef _WIN32
  21038. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  21039. #else
  21040. auto n = ::send(s, data.data(), data.size(), 0);
  21041. #endif
  21042. return n == static_cast<decltype(n)>(data.size());
  21043. };
  21044. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  21045. // Every length used here fits the 7-bit length field.
  21046. auto masked_header = [](uint8_t first_byte, size_t len) {
  21047. std::string h;
  21048. h += static_cast<char>(first_byte);
  21049. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  21050. h.append(4, '\0'); // mask key
  21051. return h;
  21052. };
  21053. for (int attempt = 0; attempt < attempts; attempt++) {
  21054. peer_stalled = false;
  21055. handler_done = false;
  21056. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  21057. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  21058. auto se_sock = detail::scope_exit([&] {
  21059. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  21060. });
  21061. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21062. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  21063. sockaddr_in addr{};
  21064. addr.sin_family = AF_INET;
  21065. addr.sin_port = htons(static_cast<uint16_t>(port));
  21066. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21067. ASSERT_EQ(
  21068. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  21069. << "attempt " << attempt;
  21070. ASSERT_TRUE(send_bytes(sock,
  21071. "GET /ws HTTP/1.1\r\n"
  21072. "Host: 127.0.0.1\r\n"
  21073. "Upgrade: websocket\r\n"
  21074. "Connection: Upgrade\r\n"
  21075. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  21076. "Sec-WebSocket-Version: 13\r\n"
  21077. "\r\n"))
  21078. << "attempt " << attempt;
  21079. std::string response;
  21080. while (response.find("\r\n\r\n") == std::string::npos) {
  21081. char buf[512];
  21082. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  21083. if (n <= 0) { break; }
  21084. response.append(buf, static_cast<size_t>(n));
  21085. }
  21086. ASSERT_NE(std::string::npos, response.find(" 101 "))
  21087. << "attempt " << attempt;
  21088. // Send the header of a Binary message but only the first prefix_len bytes
  21089. // of its payload, leaving the reader thread stalled inside the payload.
  21090. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  21091. expected.substr(0, prefix_len)))
  21092. << "attempt " << attempt;
  21093. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21094. peer_stalled = true;
  21095. // Let close() send its Close frame and park in its own read before the
  21096. // rest of the payload arrives, so both threads are waiting for it.
  21097. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21098. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  21099. close_frame += static_cast<char>(0x03); // status 1000
  21100. close_frame += static_cast<char>(0xE8);
  21101. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  21102. << "attempt " << attempt;
  21103. // Closing the peer releases the reader thread even on the buggy path,
  21104. // where it waits for bytes another thread already consumed.
  21105. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21106. detail::close_socket(sock);
  21107. sock = INVALID_SOCKET;
  21108. wait_for(handler_done);
  21109. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  21110. }
  21111. std::lock_guard<std::mutex> guard(received_mutex);
  21112. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  21113. << "a message in flight when close() ran was dropped";
  21114. for (size_t i = 0; i < received.size(); i++) {
  21115. EXPECT_EQ(expected, received[i]) << "message " << i;
  21116. }
  21117. }
  21118. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  21119. class WebSocketSSLIntegrationTest : public ::testing::Test {
  21120. protected:
  21121. void SetUp() override {
  21122. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  21123. SERVER_PRIVATE_KEY_FILE);
  21124. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21125. std::string msg;
  21126. ws::ReadResult ret;
  21127. while ((ret = ws.read(msg))) {
  21128. if (ret == ws::Binary) {
  21129. ws.send(msg.data(), msg.size());
  21130. } else {
  21131. ws.send(msg);
  21132. }
  21133. }
  21134. });
  21135. port_ = server_->bind_to_any_port(HOST);
  21136. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21137. server_->wait_until_ready();
  21138. }
  21139. void TearDown() override {
  21140. server_->stop();
  21141. if (server_thread_.joinable()) { server_thread_.join(); }
  21142. }
  21143. std::unique_ptr<SSLServer> server_;
  21144. std::thread server_thread_;
  21145. int port_ = 0;
  21146. };
  21147. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  21148. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21149. "/ws-echo");
  21150. client.enable_server_certificate_verification(false);
  21151. ASSERT_TRUE(client.connect());
  21152. ASSERT_TRUE(client.is_open());
  21153. ASSERT_TRUE(client.send("Hello WSS"));
  21154. std::string msg;
  21155. EXPECT_EQ(ws::Text, client.read(msg));
  21156. EXPECT_EQ("Hello WSS", msg);
  21157. client.close();
  21158. }
  21159. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  21160. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  21161. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  21162. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  21163. // client (without calling close() first) is the only path that runs
  21164. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  21165. // bug exactly.
  21166. //
  21167. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  21168. // when linked against an instrumented libssl; run under Valgrind to catch it
  21169. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  21170. // suite (the freed session otherwise stalls on the close handshake) — this test
  21171. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  21172. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  21173. {
  21174. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21175. "/ws-echo");
  21176. client.enable_server_certificate_verification(false);
  21177. client.set_read_timeout(2, 0);
  21178. client.set_write_timeout(2, 0);
  21179. ASSERT_TRUE(client.connect());
  21180. ASSERT_TRUE(client.is_open());
  21181. ASSERT_TRUE(client.send("still open"));
  21182. // Intentionally do NOT call client.close(): leaving scope runs
  21183. // shutdown_and_close() with the WebSocket still open, which must send the
  21184. // close frame while the TLS session is still alive.
  21185. }
  21186. }
  21187. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  21188. // shutdown_and_close() at the start of connect(), reproducing the same
  21189. // use-after-free within the test body rather than at scope exit. The second
  21190. // connect must succeed and echo, proving the close handshake ran over a live
  21191. // session. See the note above about memory-tool requirements.
  21192. TEST_F(WebSocketSSLIntegrationTest,
  21193. ReconnectWhileOpenSendsCloseOverLiveSession) {
  21194. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21195. "/ws-echo");
  21196. client.enable_server_certificate_verification(false);
  21197. client.set_read_timeout(2, 0);
  21198. client.set_write_timeout(2, 0);
  21199. ASSERT_TRUE(client.connect());
  21200. ASSERT_TRUE(client.is_open());
  21201. ASSERT_TRUE(client.send("still open"));
  21202. // Reconnect without closing first: connect() calls shutdown_and_close() on
  21203. // the still-open connection, which must not touch a freed TLS session.
  21204. ASSERT_TRUE(client.connect());
  21205. ASSERT_TRUE(client.is_open());
  21206. ASSERT_TRUE(client.send("after reconnect"));
  21207. std::string msg;
  21208. EXPECT_EQ(ws::Text, client.read(msg));
  21209. EXPECT_EQ("after reconnect", msg);
  21210. client.close();
  21211. }
  21212. #endif
  21213. #ifdef CPPHTTPLIB_SSL_ENABLED
  21214. class WebSocketSSLCATest : public ::testing::Test {
  21215. protected:
  21216. void SetUp() override {
  21217. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  21218. SERVER_PRIVATE_KEY_FILE);
  21219. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21220. std::string msg;
  21221. while (ws.read(msg)) {
  21222. ws.send(msg);
  21223. }
  21224. });
  21225. port_ = server_->bind_to_any_port("127.0.0.1");
  21226. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21227. server_->wait_until_ready();
  21228. }
  21229. void TearDown() override {
  21230. server_->stop();
  21231. if (server_thread_.joinable()) { server_thread_.join(); }
  21232. }
  21233. std::string url() const {
  21234. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  21235. }
  21236. std::unique_ptr<SSLServer> server_;
  21237. std::thread server_thread_;
  21238. int port_ = 0;
  21239. };
  21240. // A custom CA loaded as PEM verifies the server with full certificate
  21241. // verification enabled
  21242. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  21243. ws::WebSocketClient client(url());
  21244. std::string cert;
  21245. read_file(SERVER_CERT2_FILE, cert);
  21246. client.load_ca_cert_store(cert.c_str(), cert.size());
  21247. ASSERT_TRUE(client.connect());
  21248. ASSERT_TRUE(client.send("hello"));
  21249. std::string msg;
  21250. EXPECT_EQ(ws::Text, client.read(msg));
  21251. EXPECT_EQ("hello", msg);
  21252. client.close();
  21253. }
  21254. // A custom CA that does not cover the server must fail verification (the
  21255. // custom CA is exclusive; system certs are not loaded alongside it)
  21256. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  21257. ws::WebSocketClient client(url());
  21258. std::string cert;
  21259. read_file(CLIENT_CA_CERT_FILE, cert);
  21260. client.load_ca_cert_store(cert.c_str(), cert.size());
  21261. auto res = client.connect();
  21262. ASSERT_FALSE(res);
  21263. EXPECT_EQ(Error::SSLServerVerification, res.error());
  21264. EXPECT_EQ(-1, res.status());
  21265. EXPECT_NE(0u, res.ssl_backend_error());
  21266. }
  21267. // The same CA as a file path rather than PEM in memory
  21268. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  21269. ws::WebSocketClient client(url());
  21270. client.set_ca_cert_path(SERVER_CERT2_FILE);
  21271. ASSERT_TRUE(client.connect());
  21272. ASSERT_TRUE(client.send("hello"));
  21273. std::string msg;
  21274. EXPECT_EQ(ws::Text, client.read(msg));
  21275. EXPECT_EQ("hello", msg);
  21276. client.close();
  21277. }
  21278. // ...and a CA file that does not cover the server still fails, so it is the
  21279. // path above that decides the outcome
  21280. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  21281. ws::WebSocketClient client(url());
  21282. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  21283. ASSERT_FALSE(client.connect());
  21284. }
  21285. // Regression test: reconnecting with a native custom CA store used to reuse
  21286. // a store handle the previous TLS context had already freed (use-after-free
  21287. // under the OpenSSL backend). The context now lives as long as the client.
  21288. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  21289. ws::WebSocketClient client(url());
  21290. std::string cert;
  21291. read_file(SERVER_CERT2_FILE, cert);
  21292. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  21293. ASSERT_TRUE(client.connect());
  21294. client.close();
  21295. ASSERT_TRUE(client.connect());
  21296. ASSERT_TRUE(client.send("again"));
  21297. std::string msg;
  21298. EXPECT_EQ(ws::Text, client.read(msg));
  21299. EXPECT_EQ("again", msg);
  21300. client.close();
  21301. }
  21302. // Regression test: a certificate with a trusted chain but no identity match
  21303. // for the server IP must be rejected. The Mbed TLS backend used to skip
  21304. // verification entirely for IP hosts, so this connection succeeded there.
  21305. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  21306. // chain verification while the identity check must still fail.
  21307. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  21308. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21309. ASSERT_TRUE(svr.is_valid());
  21310. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21311. std::string msg;
  21312. while (ws.read(msg)) {
  21313. ws.send(msg);
  21314. }
  21315. });
  21316. auto port = svr.bind_to_any_port("127.0.0.1");
  21317. auto t = std::thread([&]() { svr.listen_after_bind(); });
  21318. auto se = detail::scope_exit([&] {
  21319. svr.stop();
  21320. t.join();
  21321. });
  21322. svr.wait_until_ready();
  21323. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  21324. "/echo");
  21325. std::string cert;
  21326. read_file(SERVER_CERT_FILE, cert);
  21327. client.load_ca_cert_store(cert.c_str(), cert.size());
  21328. ASSERT_FALSE(client.connect());
  21329. }
  21330. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  21331. // SNI, so nothing binds the host name to the TLS session. These bind the
  21332. // server to "localhost" instead, the only shape that exercises the SNI and
  21333. // hostname-verification path with certificate verification left enabled.
  21334. class WebSocketSSLDnsHostTest : public ::testing::Test {
  21335. protected:
  21336. void Start(const char *cert_file) {
  21337. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  21338. SERVER_PRIVATE_KEY_FILE);
  21339. ASSERT_TRUE(server_->is_valid());
  21340. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21341. std::string msg;
  21342. while (ws.read(msg)) {
  21343. ws.send(msg);
  21344. }
  21345. });
  21346. port_ = server_->bind_to_any_port("localhost");
  21347. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21348. server_->wait_until_ready();
  21349. }
  21350. void TearDown() override {
  21351. if (server_) { server_->stop(); }
  21352. if (server_thread_.joinable()) { server_thread_.join(); }
  21353. }
  21354. std::string url() const {
  21355. return "wss://localhost:" + std::to_string(port_) + "/echo";
  21356. }
  21357. std::unique_ptr<SSLServer> server_;
  21358. std::thread server_thread_;
  21359. int port_ = 0;
  21360. };
  21361. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  21362. // out and the connection is usable
  21363. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  21364. Start(SERVER_CERT2_FILE);
  21365. ws::WebSocketClient client(url());
  21366. client.set_ca_cert_path(SERVER_CERT2_FILE);
  21367. ASSERT_TRUE(client.connect());
  21368. ASSERT_TRUE(client.send("hello"));
  21369. std::string msg;
  21370. EXPECT_EQ(ws::Text, client.read(msg));
  21371. EXPECT_EQ("hello", msg);
  21372. client.close();
  21373. }
  21374. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  21375. // while the identity check must still reject "localhost"
  21376. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  21377. Start(SERVER_CERT_FILE);
  21378. ws::WebSocketClient client(url());
  21379. client.set_ca_cert_path(SERVER_CERT_FILE);
  21380. auto res = client.connect();
  21381. ASSERT_FALSE(res);
  21382. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  21383. EXPECT_EQ(-1, res.status());
  21384. }
  21385. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  21386. // disabled: the chain is still checked, only the identity check is skipped
  21387. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  21388. Start(SERVER_CERT_FILE);
  21389. ws::WebSocketClient client(url());
  21390. client.set_ca_cert_path(SERVER_CERT_FILE);
  21391. client.enable_server_hostname_verification(false);
  21392. ASSERT_TRUE(client.connect());
  21393. ASSERT_TRUE(client.send("hello"));
  21394. std::string msg;
  21395. EXPECT_EQ(ws::Text, client.read(msg));
  21396. EXPECT_EQ("hello", msg);
  21397. client.close();
  21398. }
  21399. // A CA that did not sign the server certificate fails the chain, even though
  21400. // the name would match
  21401. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  21402. Start(SERVER_CERT2_FILE);
  21403. ws::WebSocketClient client(url());
  21404. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  21405. ASSERT_FALSE(client.connect());
  21406. }
  21407. // With verification disabled, neither the chain nor the name is checked
  21408. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  21409. Start(SERVER_CERT_FILE);
  21410. ws::WebSocketClient client(url());
  21411. client.enable_server_certificate_verification(false);
  21412. ASSERT_TRUE(client.connect());
  21413. ASSERT_TRUE(client.send("hello"));
  21414. std::string msg;
  21415. EXPECT_EQ(ws::Text, client.read(msg));
  21416. EXPECT_EQ("hello", msg);
  21417. client.close();
  21418. }
  21419. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  21420. protected:
  21421. void SetUp() override {
  21422. server_ = httplib::detail::make_unique<SSLServer>(
  21423. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21424. ASSERT_TRUE(server_->is_valid());
  21425. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21426. std::string msg;
  21427. while (ws.read(msg)) {
  21428. ws.send(msg);
  21429. }
  21430. });
  21431. port_ = server_->bind_to_any_port("localhost");
  21432. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21433. server_->wait_until_ready();
  21434. }
  21435. void TearDown() override {
  21436. server_->stop();
  21437. if (server_thread_.joinable()) { server_thread_.join(); }
  21438. }
  21439. std::string url() const {
  21440. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  21441. }
  21442. void ConnectWithClientCert(const std::string &client_cert_file,
  21443. const std::string &client_private_key_file,
  21444. const char *private_key_password) {
  21445. std::string cert_pem, key_pem;
  21446. read_file(client_cert_file, cert_pem);
  21447. read_file(client_private_key_file, key_pem);
  21448. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  21449. key_pem.c_str(), key_pem.size(),
  21450. private_key_password};
  21451. ws::WebSocketClient client(url(), pem);
  21452. ASSERT_TRUE(client.is_valid());
  21453. client.enable_server_certificate_verification(false);
  21454. ASSERT_TRUE(client.connect());
  21455. ASSERT_TRUE(client.send("hello"));
  21456. std::string msg;
  21457. EXPECT_EQ(ws::Text, client.read(msg));
  21458. EXPECT_EQ("hello", msg);
  21459. client.close();
  21460. }
  21461. std::unique_ptr<SSLServer> server_;
  21462. std::thread server_thread_;
  21463. int port_ = 0;
  21464. };
  21465. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  21466. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  21467. }
  21468. // Control for the tests above: the fixture's server really does require a
  21469. // client certificate, so it is the PEM the constructor installed that decides
  21470. // the outcome.
  21471. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  21472. ws::WebSocketClient client(url());
  21473. ASSERT_TRUE(client.is_valid());
  21474. client.enable_server_certificate_verification(false);
  21475. EXPECT_FALSE(client.connect());
  21476. }
  21477. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  21478. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  21479. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  21480. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  21481. }
  21482. #endif
  21483. #if !defined(_WIN32)
  21484. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  21485. auto secret_dir = std::string("./symlink_test_secret");
  21486. auto served_dir = std::string("./symlink_test_served");
  21487. auto secret_file = secret_dir + "/secret.txt";
  21488. auto symlink_path = served_dir + "/escape";
  21489. // Setup: create directories and files
  21490. mkdir(secret_dir.c_str(), 0755);
  21491. mkdir(served_dir.c_str(), 0755);
  21492. {
  21493. std::ofstream ofs(secret_file);
  21494. ofs << "SECRET_DATA";
  21495. }
  21496. // Create symlink using absolute path so it resolves correctly
  21497. #ifdef PATH_MAX
  21498. char abs_secret[PATH_MAX];
  21499. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  21500. #else
  21501. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  21502. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  21503. ASSERT_NE(nullptr, abs_secret);
  21504. #endif
  21505. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  21506. auto se = detail::scope_exit([&] {
  21507. unlink(symlink_path.c_str());
  21508. unlink(secret_file.c_str());
  21509. rmdir(served_dir.c_str());
  21510. rmdir(secret_dir.c_str());
  21511. });
  21512. Server svr;
  21513. svr.set_mount_point("/", served_dir);
  21514. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  21515. auto se2 = detail::scope_exit([&] {
  21516. svr.stop();
  21517. listen_thread.join();
  21518. });
  21519. svr.wait_until_ready();
  21520. Client cli("localhost", PORT);
  21521. // Symlink pointing outside base dir should be blocked
  21522. auto res = cli.Get("/escape/secret.txt");
  21523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21524. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  21525. }
  21526. #endif
  21527. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  21528. // "GET /smuggled" request), reads the first response, and only then sends the
  21529. // embedded request as the body. Returns how many times /smuggled ran.
  21530. //
  21531. // The body is sent AFTER receiving the first response (as in the original
  21532. // PoC) so that the stream_line_reader cannot buffer it together with the
  21533. // headers of the first request.
  21534. static int count_smuggled_requests(const std::string &outer_head,
  21535. std::string &first_response) {
  21536. Server svr;
  21537. svr.set_mount_point("/", "./www");
  21538. std::atomic<int> smuggled_count(0);
  21539. svr.Get("/smuggled", [&](const Request &, Response &res) {
  21540. smuggled_count++;
  21541. res.set_content("oops", "text/plain");
  21542. });
  21543. svr.Post("/post", [&](const Request &req, Response &res) {
  21544. res.set_content(req.body, "text/plain");
  21545. });
  21546. auto port = svr.bind_to_any_port("localhost");
  21547. thread t = thread([&] { svr.listen_after_bind(); });
  21548. auto se = detail::scope_exit([&] {
  21549. svr.stop();
  21550. t.join();
  21551. });
  21552. svr.wait_until_ready();
  21553. auto error = Error::Success;
  21554. auto sock = detail::create_client_socket(
  21555. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  21556. /*connection_timeout_sec=*/2, 0,
  21557. /*read_timeout_sec=*/2, 0,
  21558. /*write_timeout_sec=*/2, 0, std::string(), error);
  21559. EXPECT_NE(INVALID_SOCKET, sock);
  21560. if (sock == INVALID_SOCKET) { return -1; }
  21561. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21562. // The "smuggled" request will be sent as the body of the outer request
  21563. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  21564. "Host: localhost\r\n"
  21565. "Connection: close\r\n"
  21566. "\r\n";
  21567. auto head = outer_head;
  21568. auto len = std::to_string(smuggled.size());
  21569. for (auto pos = head.find("{len}"); pos != std::string::npos;
  21570. pos = head.find("{len}", pos + len.size())) {
  21571. head.replace(pos, 5, len);
  21572. }
  21573. // Step 1: Send only the outer request headers (no body yet)
  21574. auto sent = send(sock, head.data(), head.size(), 0);
  21575. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  21576. // Step 2: Read the first response
  21577. char buf[4096];
  21578. for (;;) {
  21579. auto n = recv(sock, buf, sizeof(buf), 0);
  21580. if (n <= 0) break;
  21581. first_response.append(buf, static_cast<size_t>(n));
  21582. // Stop once we have a complete response (headers + body)
  21583. auto hdr_end = first_response.find("\r\n\r\n");
  21584. if (hdr_end != std::string::npos) {
  21585. // Check for Content-Length to know when the body is complete
  21586. auto cl_pos = first_response.find("Content-Length:");
  21587. if (cl_pos != std::string::npos) {
  21588. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  21589. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  21590. auto cl = std::stoul(
  21591. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  21592. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  21593. } else {
  21594. break; // No Content-Length, assume headers-only response
  21595. }
  21596. }
  21597. }
  21598. // Step 3: Now send the body, which looks like a new HTTP request. On a
  21599. // vulnerable server the keep-alive loop reads this as a second request. The
  21600. // server may already have closed the connection, so the result is ignored.
  21601. send(sock, smuggled.data(), smuggled.size(), 0);
  21602. // Half-close so that a server which drained the body sees EOF and closes,
  21603. // instead of the read below waiting for the read timeout.
  21604. #ifdef _WIN32
  21605. ::shutdown(sock, SD_SEND);
  21606. #else
  21607. ::shutdown(sock, SHUT_WR);
  21608. #endif
  21609. // Step 4: Read until the server closes the connection
  21610. for (;;) {
  21611. auto n = recv(sock, buf, sizeof(buf), 0);
  21612. if (n <= 0) break;
  21613. }
  21614. return smuggled_count.load();
  21615. }
  21616. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  21617. // A GET request with Content-Length to a static file handler must have its
  21618. // body drained before the keep-alive connection is reused. Otherwise the
  21619. // unread body bytes are interpreted as the next HTTP request.
  21620. std::string first_response;
  21621. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  21622. "Host: localhost\r\n"
  21623. "Content-Length: {len}\r\n"
  21624. "\r\n",
  21625. first_response));
  21626. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  21627. }
  21628. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  21629. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  21630. // be answered with 400 and the connection closed. Treating it as "no body"
  21631. // leaves the body to be parsed as the next request.
  21632. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  21633. const char *targets[] = {
  21634. "GET /file", // handler that never reads the body
  21635. "GET /not-found", // no handler matches (404)
  21636. "POST /post", // handler that reads the body
  21637. };
  21638. for (auto target : targets) {
  21639. for (auto value : values) {
  21640. std::string first_response;
  21641. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  21642. " HTTP/1.1\r\n"
  21643. "Host: localhost\r\n"
  21644. "Content-Length: " +
  21645. value + "\r\n\r\n",
  21646. first_response))
  21647. << target << " with Content-Length: " << value;
  21648. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  21649. << target << " with Content-Length: " << value;
  21650. }
  21651. }
  21652. }
  21653. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  21654. // A 400 for an unparseable request line leaves the rest of the message
  21655. // unread, so the connection must be closed rather than reused.
  21656. std::string first_response;
  21657. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  21658. "Host: localhost\r\n"
  21659. "Content-Length: {len}\r\n"
  21660. "\r\n",
  21661. first_response));
  21662. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  21663. }
  21664. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  21665. // Same as above for a header block that fails to parse.
  21666. std::string first_response;
  21667. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  21668. "Host: localhost\r\n"
  21669. "Bad Header\r\n"
  21670. "Content-Length: {len}\r\n"
  21671. "\r\n",
  21672. first_response));
  21673. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  21674. }
  21675. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  21676. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  21677. // server must not read another request on that connection, even when the
  21678. // request had no body to drain.
  21679. std::string first_response;
  21680. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  21681. "Host: localhost\r\n"
  21682. "\r\n",
  21683. first_response));
  21684. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  21685. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  21686. }
  21687. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  21688. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  21689. // must be rejected with 400 Bad Request.
  21690. Server svr;
  21691. svr.Post("/test", [&](const Request &, Response &res) {
  21692. res.set_content("ok", "text/plain");
  21693. });
  21694. thread t = thread([&] { svr.listen(HOST, PORT); });
  21695. auto se = detail::scope_exit([&] {
  21696. svr.stop();
  21697. t.join();
  21698. ASSERT_FALSE(svr.is_running());
  21699. });
  21700. svr.wait_until_ready();
  21701. // Exact "chunked"
  21702. {
  21703. auto req = "POST /test HTTP/1.1\r\n"
  21704. "Host: localhost\r\n"
  21705. "Content-Length: 5\r\n"
  21706. "Transfer-Encoding: chunked\r\n"
  21707. "Connection: close\r\n"
  21708. "\r\n"
  21709. "hello";
  21710. std::string response;
  21711. ASSERT_TRUE(send_request(1, req, &response));
  21712. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21713. response.substr(0, response.find("\r\n")));
  21714. }
  21715. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  21716. {
  21717. auto req = "POST /test HTTP/1.1\r\n"
  21718. "Host: localhost\r\n"
  21719. "Content-Length: 5\r\n"
  21720. "Transfer-Encoding: gzip, chunked\r\n"
  21721. "Connection: close\r\n"
  21722. "\r\n"
  21723. "hello";
  21724. std::string response;
  21725. ASSERT_TRUE(send_request(1, req, &response));
  21726. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21727. response.substr(0, response.find("\r\n")));
  21728. }
  21729. }
  21730. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  21731. Server svr;
  21732. svr.Post("/test", [&](const Request &, Response &res) {
  21733. res.set_content("ok", "text/plain");
  21734. });
  21735. thread t = thread([&] { svr.listen(HOST, PORT); });
  21736. auto se = detail::scope_exit([&] {
  21737. svr.stop();
  21738. t.join();
  21739. ASSERT_FALSE(svr.is_running());
  21740. });
  21741. svr.wait_until_ready();
  21742. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  21743. // length cannot be determined, so the server must answer 400 and close
  21744. // rather than treat the request as bodyless and leave the body in the
  21745. // socket for the next request to pick up.
  21746. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  21747. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  21748. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  21749. std::string response;
  21750. ASSERT_TRUE(send_request(1, req, &response));
  21751. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21752. response.substr(0, response.find("\r\n")))
  21753. << transfer_encoding;
  21754. }
  21755. // RFC 9110 5.3: the codings may also be split across several
  21756. // Transfer-Encoding lines, which combine in the order they were received.
  21757. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  21758. // just like the single-line "chunked, gzip" above.
  21759. {
  21760. auto req = "POST /test HTTP/1.1\r\n"
  21761. "Host: localhost\r\n"
  21762. "Transfer-Encoding: chunked\r\n"
  21763. "Transfer-Encoding: gzip\r\n"
  21764. "\r\n"
  21765. "0\r\n\r\n";
  21766. std::string response;
  21767. ASSERT_TRUE(send_request(1, req, &response));
  21768. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21769. response.substr(0, response.find("\r\n")));
  21770. }
  21771. // A sequence ending in chunked stays valid.
  21772. auto req = "POST /test HTTP/1.1\r\n"
  21773. "Host: localhost\r\n"
  21774. "Transfer-Encoding: gzip, chunked\r\n"
  21775. "Connection: close\r\n"
  21776. "\r\n"
  21777. "0\r\n\r\n";
  21778. std::string response;
  21779. ASSERT_TRUE(send_request(1, req, &response));
  21780. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  21781. // ...including when it is spread over several lines.
  21782. auto split_req = "POST /test HTTP/1.1\r\n"
  21783. "Host: localhost\r\n"
  21784. "Transfer-Encoding: gzip\r\n"
  21785. "Transfer-Encoding: chunked\r\n"
  21786. "Connection: close\r\n"
  21787. "\r\n"
  21788. "0\r\n\r\n";
  21789. std::string split_response;
  21790. ASSERT_TRUE(send_request(1, split_req, &split_response));
  21791. EXPECT_EQ("HTTP/1.1 200 OK",
  21792. split_response.substr(0, split_response.find("\r\n")));
  21793. }
  21794. // Regression for issue #2450: a DELETE without Content-Length on a
  21795. // keep-alive connection must not let the post-response drain consume the
  21796. // next request's bytes.
  21797. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  21798. Server svr;
  21799. std::atomic<int> delete_count(0);
  21800. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  21801. delete_count++;
  21802. res.status = StatusCode::NoContent_204;
  21803. });
  21804. auto port = svr.bind_to_any_port(HOST);
  21805. thread t = thread([&] { svr.listen_after_bind(); });
  21806. auto se = detail::scope_exit([&] {
  21807. svr.stop();
  21808. t.join();
  21809. });
  21810. svr.wait_until_ready();
  21811. auto error = Error::Success;
  21812. auto sock = detail::create_client_socket(
  21813. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  21814. /*connection_timeout_sec=*/2, 0,
  21815. /*read_timeout_sec=*/2, 0,
  21816. /*write_timeout_sec=*/2, 0, std::string(), error);
  21817. ASSERT_NE(INVALID_SOCKET, sock);
  21818. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21819. auto send_request_and_read_response = [&](const std::string &req,
  21820. std::string &out) -> bool {
  21821. auto sent = send(sock, req.data(), req.size(), 0);
  21822. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  21823. char buf[4096];
  21824. for (;;) {
  21825. auto n = recv(sock, buf, sizeof(buf), 0);
  21826. if (n <= 0) { return !out.empty(); }
  21827. out.append(buf, static_cast<size_t>(n));
  21828. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  21829. }
  21830. };
  21831. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  21832. "Host: localhost\r\n"
  21833. "\r\n";
  21834. std::string resp1;
  21835. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  21836. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  21837. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  21838. "Host: localhost\r\n"
  21839. "Connection: close\r\n"
  21840. "\r\n";
  21841. std::string resp2;
  21842. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  21843. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  21844. EXPECT_EQ(2, delete_count.load());
  21845. }
  21846. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  21847. Server svr;
  21848. svr.Post("/ingest", [&](const Request &, Response &res,
  21849. const ContentReader &content_reader) {
  21850. auto consumed = content_reader([](const char *, size_t) { return false; });
  21851. EXPECT_FALSE(consumed);
  21852. res.status = StatusCode::Conflict_409;
  21853. res.set_header("Connection", "close");
  21854. });
  21855. auto port = svr.bind_to_any_port(HOST);
  21856. thread t = thread([&] { svr.listen_after_bind(); });
  21857. auto se = detail::scope_exit([&] {
  21858. svr.stop();
  21859. t.join();
  21860. });
  21861. svr.wait_until_ready();
  21862. auto error = Error::Success;
  21863. auto sock = detail::create_client_socket(
  21864. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  21865. /*connection_timeout_sec=*/2, 0,
  21866. /*read_timeout_sec=*/1, 0,
  21867. /*write_timeout_sec=*/2, 0, std::string(), error);
  21868. ASSERT_NE(INVALID_SOCKET, sock);
  21869. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21870. std::string request = "POST /ingest HTTP/1.1\r\n"
  21871. "Host: localhost\r\n"
  21872. "Transfer-Encoding: chunked\r\n"
  21873. "\r\n"
  21874. "4\r\n"
  21875. "data\r\n";
  21876. auto sent = send(sock, request.data(), request.size(), 0);
  21877. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  21878. std::string response;
  21879. ssize_t received = 0;
  21880. do {
  21881. char buf[4096];
  21882. received = recv(sock, buf, sizeof(buf), 0);
  21883. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  21884. } while (received > 0);
  21885. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  21886. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  21887. EXPECT_EQ(0, received);
  21888. }
  21889. namespace no_proxy_test {
  21890. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  21891. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  21892. // calling listen().
  21893. class ScopedServer {
  21894. public:
  21895. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  21896. ~ScopedServer() {
  21897. svr_.stop();
  21898. if (th_.joinable()) { th_.join(); }
  21899. }
  21900. Server &svr() { return svr_; }
  21901. int port() const { return port_; }
  21902. void listen() {
  21903. th_ = std::thread([this] { svr_.listen_after_bind(); });
  21904. svr_.wait_until_ready();
  21905. }
  21906. private:
  21907. Server svr_;
  21908. std::thread th_;
  21909. int port_ = 0;
  21910. };
  21911. class ProxyAndTargetServers {
  21912. public:
  21913. ProxyAndTargetServers() {
  21914. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  21915. proxy_hits_++;
  21916. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  21917. res.set_content("via-proxy", "text/plain");
  21918. });
  21919. target_.Get(".*", [this](const Request &req, Response &res) {
  21920. target_hits_++;
  21921. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  21922. res.set_content("direct", "text/plain");
  21923. });
  21924. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  21925. target_port_ = target_.bind_to_any_port("127.0.0.1");
  21926. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  21927. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  21928. proxy_mock_.wait_until_ready();
  21929. target_.wait_until_ready();
  21930. }
  21931. ~ProxyAndTargetServers() {
  21932. proxy_mock_.stop();
  21933. target_.stop();
  21934. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  21935. if (target_thread_.joinable()) { target_thread_.join(); }
  21936. }
  21937. Server &proxy_mock() { return proxy_mock_; }
  21938. Server &target() { return target_; }
  21939. int proxy_port() const { return proxy_port_; }
  21940. int target_port() const { return target_port_; }
  21941. int proxy_hits() const { return proxy_hits_.load(); }
  21942. int target_hits() const { return target_hits_.load(); }
  21943. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  21944. void reset_counters() {
  21945. proxy_hits_ = 0;
  21946. target_hits_ = 0;
  21947. last_had_proxy_authz_ = false;
  21948. }
  21949. private:
  21950. Server proxy_mock_;
  21951. Server target_;
  21952. std::thread proxy_thread_;
  21953. std::thread target_thread_;
  21954. int proxy_port_ = 0;
  21955. int target_port_ = 0;
  21956. std::atomic<int> proxy_hits_{0};
  21957. std::atomic<int> target_hits_{0};
  21958. std::atomic<bool> last_had_proxy_authz_{false};
  21959. };
  21960. inline std::unique_ptr<Client> make_client(const std::string &host,
  21961. ProxyAndTargetServers &s) {
  21962. auto cli = detail::make_unique<Client>(host, s.target_port());
  21963. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  21964. cli->set_proxy("127.0.0.1", s.proxy_port());
  21965. return cli;
  21966. }
  21967. } // namespace no_proxy_test
  21968. using no_proxy_test::make_client;
  21969. using no_proxy_test::ProxyAndTargetServers;
  21970. TEST(NoProxyTest, ExactHostnameBypasses) {
  21971. ProxyAndTargetServers s;
  21972. auto cli = make_client("example.com", s);
  21973. cli->set_no_proxy({"example.com"});
  21974. auto res = cli->Get("/");
  21975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21976. EXPECT_EQ(0, s.proxy_hits());
  21977. EXPECT_EQ(1, s.target_hits());
  21978. }
  21979. TEST(NoProxyTest, SubdomainBypasses) {
  21980. ProxyAndTargetServers s;
  21981. auto cli = make_client("foo.example.com", s);
  21982. cli->set_no_proxy({"example.com"});
  21983. auto res = cli->Get("/");
  21984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21985. EXPECT_EQ(0, s.proxy_hits());
  21986. EXPECT_EQ(1, s.target_hits());
  21987. }
  21988. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  21989. // Regression guard: "evilexample.com" must not be considered a subdomain
  21990. // of "example.com". Without the dot-boundary rule, a naive endsWith
  21991. // check would let traffic bypass the proxy and leak credentials direct
  21992. // to the attacker host.
  21993. ProxyAndTargetServers s;
  21994. auto cli = make_client("evilexample.com", s);
  21995. cli->set_no_proxy({"example.com"});
  21996. auto res = cli->Get("/");
  21997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21998. EXPECT_GE(s.proxy_hits(), 1);
  21999. EXPECT_EQ(0, s.target_hits());
  22000. }
  22001. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  22002. ProxyAndTargetServers s;
  22003. auto cli = make_client("example.com.evil.com", s);
  22004. cli->set_no_proxy({"example.com"});
  22005. auto res = cli->Get("/");
  22006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22007. EXPECT_GE(s.proxy_hits(), 1);
  22008. EXPECT_EQ(0, s.target_hits());
  22009. }
  22010. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  22011. ProxyAndTargetServers s;
  22012. auto cli = make_client("example.com", s);
  22013. cli->set_no_proxy({".example.com"});
  22014. auto res = cli->Get("/");
  22015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22016. EXPECT_EQ(0, s.proxy_hits());
  22017. EXPECT_EQ(1, s.target_hits());
  22018. }
  22019. TEST(NoProxyTest, CaseInsensitiveHostname) {
  22020. ProxyAndTargetServers s;
  22021. auto cli = make_client("Example.COM", s);
  22022. cli->set_no_proxy({"EXAMPLE.com"});
  22023. auto res = cli->Get("/");
  22024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22025. EXPECT_EQ(0, s.proxy_hits());
  22026. EXPECT_EQ(1, s.target_hits());
  22027. }
  22028. TEST(NoProxyTest, TrailingDotIsNormalized) {
  22029. ProxyAndTargetServers s;
  22030. auto cli = make_client("example.com.", s);
  22031. cli->set_no_proxy({"example.com"});
  22032. auto res = cli->Get("/");
  22033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22034. EXPECT_EQ(0, s.proxy_hits());
  22035. EXPECT_EQ(1, s.target_hits());
  22036. }
  22037. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  22038. // Trailing dots must be normalized on BOTH sides — host and entry.
  22039. // An implementation that only strips the host-side trailing dot would
  22040. // fail to match host "example.com" against entry "example.com." because
  22041. // a literal substring search would compare 11 chars against 12.
  22042. ProxyAndTargetServers s;
  22043. auto cli = make_client("example.com", s);
  22044. cli->set_no_proxy({"example.com."});
  22045. auto res = cli->Get("/");
  22046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22047. EXPECT_EQ(0, s.proxy_hits());
  22048. EXPECT_EQ(1, s.target_hits());
  22049. }
  22050. TEST(NoProxyTest, WildcardBypassesEverything) {
  22051. ProxyAndTargetServers s;
  22052. auto cli = make_client("anything.invalid.test", s);
  22053. cli->set_no_proxy({"*"});
  22054. auto res = cli->Get("/");
  22055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22056. EXPECT_EQ(0, s.proxy_hits());
  22057. EXPECT_EQ(1, s.target_hits());
  22058. }
  22059. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  22060. ProxyAndTargetServers s;
  22061. Client cli("127.0.0.1", s.target_port());
  22062. cli.set_proxy("127.0.0.1", s.proxy_port());
  22063. cli.set_no_proxy({"127.0.0.1"});
  22064. auto res = cli.Get("/");
  22065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22066. EXPECT_EQ(0, s.proxy_hits());
  22067. EXPECT_EQ(1, s.target_hits());
  22068. }
  22069. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  22070. ProxyAndTargetServers s;
  22071. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  22072. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  22073. cli.set_proxy("127.0.0.1", s.proxy_port());
  22074. cli.set_no_proxy({"::1"});
  22075. auto res = cli.Get("/");
  22076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22077. EXPECT_EQ(0, s.proxy_hits());
  22078. EXPECT_EQ(1, s.target_hits());
  22079. }
  22080. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  22081. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  22082. // must still be recognized as IPv6 for CIDR matching. Implementations
  22083. // that detect IPv6 only when the host begins with '[' would parse the
  22084. // host as a hostname and miss the match.
  22085. ProxyAndTargetServers s;
  22086. Client cli("fe80::1", s.target_port());
  22087. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  22088. cli.set_proxy("127.0.0.1", s.proxy_port());
  22089. cli.set_no_proxy({"fe80::/10"});
  22090. auto res = cli.Get("/");
  22091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22092. EXPECT_EQ(0, s.proxy_hits());
  22093. EXPECT_EQ(1, s.target_hits());
  22094. }
  22095. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  22096. ProxyAndTargetServers s;
  22097. Client cli("::1", s.target_port());
  22098. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  22099. cli.set_proxy("127.0.0.1", s.proxy_port());
  22100. cli.set_no_proxy({"[::1]"});
  22101. auto res = cli.Get("/");
  22102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22103. EXPECT_EQ(0, s.proxy_hits());
  22104. EXPECT_EQ(1, s.target_hits());
  22105. }
  22106. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  22107. ProxyAndTargetServers s;
  22108. Client cli("fe80::1", s.target_port());
  22109. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  22110. cli.set_proxy("127.0.0.1", s.proxy_port());
  22111. cli.set_no_proxy({"[fe80::]/10"});
  22112. auto res = cli.Get("/");
  22113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22114. EXPECT_EQ(0, s.proxy_hits());
  22115. EXPECT_EQ(1, s.target_hits());
  22116. }
  22117. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  22118. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  22119. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  22120. // tricks via address-family conversion.
  22121. ProxyAndTargetServers s;
  22122. Client cli("::ffff:127.0.0.1", s.target_port());
  22123. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  22124. cli.set_proxy("127.0.0.1", s.proxy_port());
  22125. cli.set_no_proxy({"127.0.0.1"});
  22126. auto res = cli.Get("/");
  22127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22128. EXPECT_GE(s.proxy_hits(), 1);
  22129. EXPECT_EQ(0, s.target_hits());
  22130. }
  22131. TEST(NoProxyTest, IPv4CidrMatch) {
  22132. ProxyAndTargetServers s;
  22133. Client cli("127.0.0.1", s.target_port());
  22134. cli.set_proxy("127.0.0.1", s.proxy_port());
  22135. cli.set_no_proxy({"127.0.0.0/8"});
  22136. auto res = cli.Get("/");
  22137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22138. EXPECT_EQ(0, s.proxy_hits());
  22139. EXPECT_EQ(1, s.target_hits());
  22140. }
  22141. TEST(NoProxyTest, IPv4CidrNonMatch) {
  22142. ProxyAndTargetServers s;
  22143. Client cli("127.0.0.1", s.target_port());
  22144. cli.set_proxy("127.0.0.1", s.proxy_port());
  22145. cli.set_no_proxy({"10.0.0.0/8"});
  22146. auto res = cli.Get("/");
  22147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22148. EXPECT_GE(s.proxy_hits(), 1);
  22149. EXPECT_EQ(0, s.target_hits());
  22150. }
  22151. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  22152. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  22153. // IPv4 target matches.
  22154. ProxyAndTargetServers s;
  22155. Client cli("127.0.0.1", s.target_port());
  22156. cli.set_proxy("127.0.0.1", s.proxy_port());
  22157. cli.set_no_proxy({"0.0.0.0/0"});
  22158. auto res = cli.Get("/");
  22159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22160. EXPECT_EQ(0, s.proxy_hits());
  22161. EXPECT_EQ(1, s.target_hits());
  22162. }
  22163. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  22164. ProxyAndTargetServers s;
  22165. Client cli("127.0.0.1", s.target_port());
  22166. cli.set_proxy("127.0.0.1", s.proxy_port());
  22167. cli.set_no_proxy({"127.0.0.1"});
  22168. auto res = cli.Get("/");
  22169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22170. EXPECT_EQ(0, s.proxy_hits());
  22171. EXPECT_EQ(1, s.target_hits());
  22172. }
  22173. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  22174. ProxyAndTargetServers s;
  22175. Client cli("127.0.0.1", s.target_port());
  22176. cli.set_proxy("127.0.0.1", s.proxy_port());
  22177. cli.set_no_proxy({"127.0.0.0/33"});
  22178. auto res = cli.Get("/");
  22179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22180. EXPECT_GE(s.proxy_hits(), 1);
  22181. EXPECT_EQ(0, s.target_hits());
  22182. }
  22183. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  22184. // Empty prefix after the slash must be rejected, not silently treated as /32.
  22185. ProxyAndTargetServers s;
  22186. Client cli("127.0.0.1", s.target_port());
  22187. cli.set_proxy("127.0.0.1", s.proxy_port());
  22188. cli.set_no_proxy({"127.0.0.1/"});
  22189. auto res = cli.Get("/");
  22190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22191. EXPECT_GE(s.proxy_hits(), 1);
  22192. EXPECT_EQ(0, s.target_hits());
  22193. }
  22194. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  22195. ProxyAndTargetServers s;
  22196. auto cli = make_client("internal.corp", s);
  22197. cli->set_proxy_basic_auth("u", "p");
  22198. cli->set_no_proxy({"internal.corp"});
  22199. auto res = cli->Get("/");
  22200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22201. EXPECT_EQ(1, s.target_hits());
  22202. EXPECT_EQ(0, s.proxy_hits());
  22203. EXPECT_FALSE(s.last_had_proxy_authz())
  22204. << "Proxy-Authorization must not be sent direct to the target";
  22205. }
  22206. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  22207. ProxyAndTargetServers s;
  22208. auto cli = make_client("public.example", s);
  22209. cli->set_proxy_basic_auth("u", "p");
  22210. cli->set_no_proxy({"internal.corp"}); // does not match
  22211. auto res = cli->Get("/");
  22212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22213. EXPECT_GE(s.proxy_hits(), 1);
  22214. EXPECT_TRUE(s.last_had_proxy_authz());
  22215. }
  22216. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  22217. ProxyAndTargetServers s;
  22218. auto cli = make_client("anything.test", s);
  22219. auto res = cli->Get("/");
  22220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22221. EXPECT_GE(s.proxy_hits(), 1);
  22222. EXPECT_EQ(0, s.target_hits());
  22223. }
  22224. TEST(NoProxyTest, PortSpecificEntryRejected) {
  22225. ProxyAndTargetServers s;
  22226. auto cli = make_client("example.com", s);
  22227. cli->set_no_proxy({"example.com:8080"});
  22228. auto res = cli->Get("/");
  22229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22230. EXPECT_GE(s.proxy_hits(), 1);
  22231. EXPECT_EQ(0, s.target_hits());
  22232. }
  22233. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  22234. ProxyAndTargetServers s;
  22235. auto cli = make_client("anything.test", s);
  22236. cli->set_no_proxy({"", " ", "\t"});
  22237. auto res = cli->Get("/");
  22238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22239. EXPECT_GE(s.proxy_hits(), 1);
  22240. EXPECT_EQ(0, s.target_hits());
  22241. }
  22242. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  22243. // An entry with leading/trailing whitespace must still match — env-style
  22244. // values are commonly pasted with stray spaces and an implementation
  22245. // that feeds the raw token directly to inet_pton would fail to match
  22246. // valid CIDRs because of the spaces.
  22247. ProxyAndTargetServers s;
  22248. Client cli("127.0.0.1", s.target_port());
  22249. cli.set_proxy("127.0.0.1", s.proxy_port());
  22250. cli.set_no_proxy({" 127.0.0.0/8 "});
  22251. auto res = cli.Get("/");
  22252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22253. EXPECT_EQ(0, s.proxy_hits());
  22254. EXPECT_EQ(1, s.target_hits());
  22255. }
  22256. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  22257. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  22258. // go direct and must NOT carry Proxy-Authorization.
  22259. std::atomic<int> proxy_hits{0};
  22260. std::atomic<int> target_hits{0};
  22261. std::atomic<bool> target_saw_authz{false};
  22262. no_proxy_test::ScopedServer proxy_mock, target;
  22263. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  22264. proxy_hits++;
  22265. res.status = 302;
  22266. res.set_header("Location", "http://127.0.0.1:" +
  22267. std::to_string(target.port()) + "/landed");
  22268. });
  22269. target.svr().Get(".*", [&](const Request &req, Response &res) {
  22270. target_hits++;
  22271. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  22272. res.set_content("direct", "text/plain");
  22273. });
  22274. proxy_mock.listen();
  22275. target.listen();
  22276. Client cli("public.example", target.port());
  22277. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  22278. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22279. cli.set_proxy_basic_auth("u", "p");
  22280. cli.set_no_proxy({"127.0.0.1"});
  22281. cli.set_follow_location(true);
  22282. auto res = cli.Get("/redir");
  22283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22284. EXPECT_GE(proxy_hits.load(), 1);
  22285. EXPECT_GE(target_hits.load(), 1);
  22286. EXPECT_FALSE(target_saw_authz.load());
  22287. }
  22288. #ifdef CPPHTTPLIB_SSL_ENABLED
  22289. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  22290. // Direct origin replying 407 must not trigger the digest retry; otherwise
  22291. // proxy creds would be sent to the (possibly hostile) origin.
  22292. std::atomic<int> target_hits{0};
  22293. std::atomic<bool> target_saw_proxy_authz{false};
  22294. no_proxy_test::ScopedServer target;
  22295. target.svr().Get(".*", [&](const Request &req, Response &res) {
  22296. target_hits++;
  22297. if (req.has_header("Proxy-Authorization")) {
  22298. target_saw_proxy_authz = true;
  22299. }
  22300. res.status = StatusCode::ProxyAuthenticationRequired_407;
  22301. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  22302. "nonce=\"abc\", algorithm=MD5");
  22303. });
  22304. target.listen();
  22305. // The proxy address is set to the target's port: the bypass MUST kick in;
  22306. // if it doesn't, the test still routes "via proxy" to the same server and
  22307. // the Proxy-Authorization assertion below catches the leak.
  22308. Client cli("evil.example", target.port());
  22309. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  22310. cli.set_proxy("127.0.0.1", target.port());
  22311. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  22312. cli.set_no_proxy({"evil.example"});
  22313. auto res = cli.Get("/x");
  22314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22315. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  22316. EXPECT_EQ(1, target_hits.load());
  22317. EXPECT_FALSE(target_saw_proxy_authz.load());
  22318. }
  22319. #endif
  22320. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  22321. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  22322. std::atomic<int> proxy_hits{0};
  22323. std::atomic<int> bypass_hits{0};
  22324. std::atomic<bool> proxy_saw_c_url{false};
  22325. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  22326. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  22327. proxy_hits++;
  22328. if (req.path.find("/start") != std::string::npos) {
  22329. res.status = 302;
  22330. res.set_header("Location", "http://127.0.0.1:" +
  22331. std::to_string(bypass_server.port()) +
  22332. "/middle");
  22333. return;
  22334. }
  22335. if (req.path.find("/end") != std::string::npos) {
  22336. proxy_saw_c_url = true;
  22337. res.set_content("c-via-proxy", "text/plain");
  22338. return;
  22339. }
  22340. res.set_content("unexpected", "text/plain");
  22341. });
  22342. // public.example's "advertised" port is arbitrary (the request never lands
  22343. // there — it goes through the proxy), but use a dynamic value to stay
  22344. // friendly with sharded parallel runs.
  22345. int public_port = bypass_server.port();
  22346. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  22347. bypass_hits++;
  22348. res.status = 302;
  22349. res.set_header("Location", "http://public.example:" +
  22350. std::to_string(public_port) + "/end");
  22351. });
  22352. proxy_mock.listen();
  22353. bypass_server.listen();
  22354. Client cli("public.example", public_port);
  22355. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  22356. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22357. cli.set_no_proxy({"127.0.0.1"});
  22358. cli.set_follow_location(true);
  22359. auto res = cli.Get("/start");
  22360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22361. EXPECT_EQ(StatusCode::OK_200, res->status);
  22362. EXPECT_EQ("c-via-proxy", res->body);
  22363. EXPECT_GE(proxy_hits.load(), 2);
  22364. EXPECT_GE(bypass_hits.load(), 1);
  22365. EXPECT_TRUE(proxy_saw_c_url.load());
  22366. }
  22367. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  22368. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  22369. // request reconnects to the correct endpoint.
  22370. std::atomic<int> proxy_hits{0};
  22371. std::atomic<int> target_hits{0};
  22372. no_proxy_test::ScopedServer proxy_mock, target;
  22373. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  22374. proxy_hits++;
  22375. res.set_content("via-proxy", "text/plain");
  22376. });
  22377. target.svr().Get(".*", [&](const Request &, Response &res) {
  22378. target_hits++;
  22379. res.set_content("direct", "text/plain");
  22380. });
  22381. proxy_mock.listen();
  22382. target.listen();
  22383. Client cli("public.example", target.port());
  22384. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  22385. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22386. cli.set_keep_alive(true);
  22387. auto res1 = cli.Get("/a");
  22388. ASSERT_TRUE(res1);
  22389. EXPECT_EQ("via-proxy", res1->body);
  22390. EXPECT_EQ(1, proxy_hits.load());
  22391. EXPECT_EQ(0, target_hits.load());
  22392. cli.set_no_proxy({"public.example"});
  22393. auto res2 = cli.Get("/b");
  22394. ASSERT_TRUE(res2);
  22395. EXPECT_EQ("direct", res2->body);
  22396. EXPECT_EQ(1, proxy_hits.load());
  22397. EXPECT_EQ(1, target_hits.load());
  22398. }
  22399. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  22400. namespace proxy_tunnel_test {
  22401. // SSLServer counterpart to no_proxy_test::ScopedServer.
  22402. class ScopedSSLServer {
  22403. public:
  22404. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  22405. port_ = svr_.bind_to_any_port("127.0.0.1");
  22406. }
  22407. ~ScopedSSLServer() {
  22408. svr_.stop();
  22409. if (th_.joinable()) { th_.join(); }
  22410. }
  22411. SSLServer &svr() { return svr_; }
  22412. int port() const { return port_; }
  22413. void listen() {
  22414. th_ = std::thread([this] { svr_.listen_after_bind(); });
  22415. svr_.wait_until_ready();
  22416. }
  22417. private:
  22418. SSLServer svr_;
  22419. std::thread th_;
  22420. int port_ = 0;
  22421. };
  22422. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  22423. class ScopedConnectProxy {
  22424. public:
  22425. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  22426. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  22427. if (listen_fd_ < 0) { return; }
  22428. int yes = 1;
  22429. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  22430. sockaddr_in a{};
  22431. a.sin_family = AF_INET;
  22432. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  22433. a.sin_port = 0;
  22434. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  22435. return;
  22436. }
  22437. socklen_t alen = sizeof(a);
  22438. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  22439. 0) {
  22440. return;
  22441. }
  22442. port_ = ntohs(a.sin_port);
  22443. if (::listen(listen_fd_, 1) != 0) { return; }
  22444. th_ = std::thread([this] { run(); });
  22445. }
  22446. ~ScopedConnectProxy() {
  22447. stop_ = true;
  22448. if (listen_fd_ >= 0) {
  22449. ::shutdown(listen_fd_, SHUT_RDWR);
  22450. ::close(listen_fd_);
  22451. }
  22452. if (th_.joinable()) { th_.join(); }
  22453. }
  22454. int port() const { return port_; }
  22455. int connect_hits() const { return connect_hits_.load(); }
  22456. // Head of the last CONNECT request, as the proxy saw it on the wire.
  22457. std::string connect_request() const {
  22458. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  22459. return connect_request_;
  22460. }
  22461. private:
  22462. void run() {
  22463. while (!stop_.load()) {
  22464. fd_set rfds;
  22465. FD_ZERO(&rfds);
  22466. FD_SET(listen_fd_, &rfds);
  22467. timeval tv{0, 100 * 1000};
  22468. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  22469. if (sel <= 0) { continue; }
  22470. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  22471. if (client_fd < 0) { continue; }
  22472. std::string req;
  22473. char buf[2048];
  22474. while (req.find("\r\n\r\n") == std::string::npos) {
  22475. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  22476. if (n <= 0) { break; }
  22477. req.append(buf, static_cast<size_t>(n));
  22478. }
  22479. if (req.compare(0, 7, "CONNECT") != 0) {
  22480. ::close(client_fd);
  22481. continue;
  22482. }
  22483. connect_hits_++;
  22484. {
  22485. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  22486. connect_request_ = req;
  22487. }
  22488. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  22489. ::send(client_fd, ok, std::strlen(ok), 0);
  22490. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  22491. sockaddr_in o{};
  22492. o.sin_family = AF_INET;
  22493. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  22494. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  22495. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  22496. 0) {
  22497. ::close(client_fd);
  22498. ::close(origin_fd);
  22499. continue;
  22500. }
  22501. auto forward = [](int from, int to) {
  22502. char b[8192];
  22503. for (;;) {
  22504. ssize_t n = ::recv(from, b, sizeof(b), 0);
  22505. if (n <= 0) { break; }
  22506. ssize_t off = 0;
  22507. while (off < n) {
  22508. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  22509. if (s <= 0) {
  22510. off = n;
  22511. break;
  22512. }
  22513. off += s;
  22514. }
  22515. }
  22516. ::shutdown(to, SHUT_WR);
  22517. };
  22518. std::thread t1([&] { forward(client_fd, origin_fd); });
  22519. std::thread t2([&] { forward(origin_fd, client_fd); });
  22520. t1.join();
  22521. t2.join();
  22522. ::close(client_fd);
  22523. ::close(origin_fd);
  22524. }
  22525. }
  22526. int forward_port_ = -1;
  22527. int listen_fd_ = -1;
  22528. int port_ = 0;
  22529. std::thread th_;
  22530. std::atomic<bool> stop_{false};
  22531. std::atomic<int> connect_hits_{0};
  22532. mutable std::mutex connect_request_mutex_;
  22533. std::string connect_request_;
  22534. };
  22535. // Sends one request through the CONNECT proxy to the TLS origin with a
  22536. // credential configured for each hop, and checks that each credential reaches
  22537. // only the hop it was configured for: the proxy's on the CONNECT request, the
  22538. // origin's (every header in origin_headers) on the tunnelled request.
  22539. void CredentialsStayWithTheirHop(
  22540. const std::function<void(SSLClient &)> &set_credentials,
  22541. const std::string &scheme,
  22542. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  22543. std::atomic<int> origin_hits{0};
  22544. std::atomic<bool> origin_saw_proxy_authz{false};
  22545. std::atomic<bool> origin_saw_headers{false};
  22546. ScopedSSLServer origin;
  22547. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  22548. origin_hits++;
  22549. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  22550. origin_saw_headers =
  22551. std::all_of(origin_headers.begin(), origin_headers.end(),
  22552. [&](const std::string &h) { return req.has_header(h); });
  22553. res.set_content("ok", "text/plain");
  22554. });
  22555. origin.listen();
  22556. ScopedConnectProxy proxy(origin.port());
  22557. ASSERT_NE(0, proxy.port());
  22558. // Pinned to 127.0.0.1 for the same reason as the test below.
  22559. SSLClient cli("127.0.0.1", origin.port());
  22560. cli.enable_server_certificate_verification(false);
  22561. cli.set_proxy("127.0.0.1", proxy.port());
  22562. set_credentials(cli);
  22563. auto res = cli.Get("/x");
  22564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22565. EXPECT_EQ(StatusCode::OK_200, res->status);
  22566. EXPECT_EQ(1, origin_hits.load());
  22567. EXPECT_EQ(1, proxy.connect_hits());
  22568. EXPECT_TRUE(origin_saw_headers.load());
  22569. EXPECT_FALSE(origin_saw_proxy_authz.load())
  22570. << "Proxy-Authorization must not be sent inside the tunnel";
  22571. auto connect_req = proxy.connect_request();
  22572. EXPECT_NE(std::string::npos,
  22573. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  22574. for (const auto &h : origin_headers) {
  22575. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  22576. << h << " must not be sent to the proxy on CONNECT";
  22577. }
  22578. }
  22579. } // namespace proxy_tunnel_test
  22580. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  22581. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22582. [](SSLClient &cli) {
  22583. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  22584. cli.set_basic_auth("origin-user", "origin-pass");
  22585. },
  22586. "Basic");
  22587. }
  22588. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  22589. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22590. [](SSLClient &cli) {
  22591. cli.set_proxy_bearer_token_auth("proxy-token");
  22592. cli.set_bearer_token_auth("origin-token");
  22593. },
  22594. "Bearer");
  22595. }
  22596. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  22597. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22598. [](SSLClient &cli) {
  22599. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  22600. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  22601. {"Cookie", "sid=origin-session"},
  22602. {"X-Api-Key", "origin-key"}});
  22603. },
  22604. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  22605. }
  22606. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  22607. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  22608. // retry; otherwise proxy creds would be sent to the origin.
  22609. std::atomic<int> origin_hits{0};
  22610. std::atomic<bool> origin_saw_proxy_authz{false};
  22611. proxy_tunnel_test::ScopedSSLServer origin;
  22612. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  22613. origin_hits++;
  22614. if (req.has_header("Proxy-Authorization")) {
  22615. origin_saw_proxy_authz = true;
  22616. }
  22617. res.status = StatusCode::ProxyAuthenticationRequired_407;
  22618. res.set_header("Proxy-Authenticate",
  22619. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  22620. "algorithm=MD5");
  22621. });
  22622. origin.listen();
  22623. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  22624. ASSERT_NE(0, proxy.port());
  22625. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  22626. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  22627. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  22628. // and answer with its own status, making this test flaky.
  22629. SSLClient cli("127.0.0.1", origin.port());
  22630. cli.enable_server_certificate_verification(false);
  22631. cli.set_proxy("127.0.0.1", proxy.port());
  22632. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  22633. auto res = cli.Get("/x");
  22634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22635. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  22636. EXPECT_EQ(1, origin_hits.load());
  22637. EXPECT_FALSE(origin_saw_proxy_authz.load());
  22638. EXPECT_EQ(1, proxy.connect_hits());
  22639. }
  22640. #endif