test.cc 972 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definitions are linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  68. } // namespace tls
  69. } // namespace httplib
  70. #endif
  71. using namespace std;
  72. using namespace httplib;
  73. const char *HOST = "localhost";
  74. static int get_base_port() {
  75. const char *shard = getenv("GTEST_SHARD_INDEX");
  76. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  77. }
  78. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  79. // New standalone tests MUST use svr.bind_to_any_port() instead.
  80. const int PORT = get_base_port();
  81. const string LONG_QUERY_VALUE = string(25000, '@');
  82. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  83. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  84. const string TOO_LONG_QUERY_URL =
  85. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  86. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  87. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  88. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  89. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  90. return file.name == key;
  91. });
  92. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  93. return *it;
  94. #else
  95. if (it != items.end()) { return *it; }
  96. throw std::runtime_error("invalid multipart form data name error");
  97. #endif
  98. }
  99. static void read_file(const std::string &path, std::string &out) {
  100. std::ifstream fs(path, std::ios_base::binary);
  101. if (!fs) {
  102. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  103. return;
  104. #else
  105. throw std::runtime_error("File not found: " + path);
  106. #endif
  107. }
  108. fs.seekg(0, std::ios_base::end);
  109. auto size = fs.tellg();
  110. fs.seekg(0);
  111. out.resize(static_cast<size_t>(size));
  112. fs.read(&out[0], static_cast<std::streamsize>(size));
  113. }
  114. class UnixSocketTest : public ::testing::Test {
  115. protected:
  116. void TearDown() override { std::remove(pathname_.c_str()); }
  117. void client_GET(const std::string &addr) {
  118. httplib::Client cli{addr};
  119. cli.set_address_family(AF_UNIX);
  120. ASSERT_TRUE(cli.is_valid());
  121. const auto &result = cli.Get(pattern_);
  122. ASSERT_TRUE(result) << "error: " << result.error();
  123. const auto &resp = result.value();
  124. EXPECT_EQ(resp.status, StatusCode::OK_200);
  125. EXPECT_EQ(resp.body, content_);
  126. }
  127. static std::string make_sock_path() {
  128. const char *shard = getenv("GTEST_SHARD_INDEX");
  129. return shard ? std::string("./httplib-server-") + shard + ".sock"
  130. : "./httplib-server.sock";
  131. }
  132. const std::string pathname_{make_sock_path()};
  133. const std::string pattern_{"/hi"};
  134. const std::string content_{"Hello World!"};
  135. };
  136. TEST_F(UnixSocketTest, pathname) {
  137. httplib::Server svr;
  138. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  139. res.set_content(content_, "text/plain");
  140. });
  141. std::thread t{[&] {
  142. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  143. }};
  144. auto se = detail::scope_exit([&] {
  145. svr.stop();
  146. t.join();
  147. ASSERT_FALSE(svr.is_running());
  148. });
  149. svr.wait_until_ready();
  150. ASSERT_TRUE(svr.is_running());
  151. client_GET(pathname_);
  152. // ".//x.sock", which is not taken for a URL
  153. client_GET("./" + pathname_.substr(1));
  154. }
  155. #if defined(__linux__) || \
  156. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  157. TEST_F(UnixSocketTest, PeerPid) {
  158. httplib::Server svr;
  159. std::string remote_port_val;
  160. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  161. res.set_content(content_, "text/plain");
  162. remote_port_val = std::to_string(req.remote_port);
  163. });
  164. std::thread t{[&] {
  165. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  166. }};
  167. auto se = detail::scope_exit([&] {
  168. svr.stop();
  169. t.join();
  170. ASSERT_FALSE(svr.is_running());
  171. });
  172. svr.wait_until_ready();
  173. ASSERT_TRUE(svr.is_running());
  174. client_GET(pathname_);
  175. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  176. }
  177. #endif
  178. #ifdef __linux__
  179. TEST_F(UnixSocketTest, abstract) {
  180. constexpr char svr_path[]{"\x00httplib-server.sock"};
  181. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  182. httplib::Server svr;
  183. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  184. res.set_content(content_, "text/plain");
  185. });
  186. std::thread t{[&] {
  187. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  188. }};
  189. auto se = detail::scope_exit([&] {
  190. svr.stop();
  191. t.join();
  192. ASSERT_FALSE(svr.is_running());
  193. });
  194. svr.wait_until_ready();
  195. ASSERT_TRUE(svr.is_running());
  196. client_GET(abstract_addr);
  197. }
  198. #endif
  199. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  200. httplib::Server svr;
  201. std::string received_host_header;
  202. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  203. // Capture the Host header sent by the client
  204. auto host_iter = req.headers.find("Host");
  205. if (host_iter != req.headers.end()) {
  206. received_host_header = host_iter->second;
  207. }
  208. res.set_content(content_, "text/plain");
  209. });
  210. std::thread t{[&] {
  211. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  212. }};
  213. auto se = detail::scope_exit([&] {
  214. svr.stop();
  215. t.join();
  216. ASSERT_FALSE(svr.is_running());
  217. });
  218. svr.wait_until_ready();
  219. ASSERT_TRUE(svr.is_running());
  220. // Test that Host header is automatically set to "localhost" for Unix socket
  221. // connections
  222. httplib::Client cli{pathname_};
  223. cli.set_address_family(AF_UNIX);
  224. ASSERT_TRUE(cli.is_valid());
  225. const auto &result = cli.Get(pattern_);
  226. ASSERT_TRUE(result) << "error: " << result.error();
  227. const auto &resp = result.value();
  228. EXPECT_EQ(resp.status, StatusCode::OK_200);
  229. EXPECT_EQ(resp.body, content_);
  230. // Verify that Host header was automatically set to "localhost"
  231. EXPECT_EQ(received_host_header, "localhost");
  232. }
  233. #ifndef _WIN32
  234. TEST(SocketStream, wait_writable_UNIX) {
  235. int fds[2];
  236. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  237. const auto asSocketStream = [&](socket_t fd,
  238. std::function<bool(Stream &)> func) {
  239. return detail::process_client_socket(
  240. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  241. };
  242. asSocketStream(fds[0], [&](Stream &s0) {
  243. EXPECT_EQ(s0.socket(), fds[0]);
  244. EXPECT_TRUE(s0.wait_writable());
  245. EXPECT_TRUE(s0.is_peer_alive());
  246. EXPECT_EQ(0, close(fds[1]));
  247. EXPECT_FALSE(s0.is_peer_alive());
  248. return true;
  249. });
  250. EXPECT_EQ(0, close(fds[0]));
  251. }
  252. TEST(SocketStream, wait_writable_INET) {
  253. sockaddr_in addr;
  254. memset(&addr, 0, sizeof(addr));
  255. addr.sin_family = AF_INET;
  256. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  257. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  258. int disconnected_svr_sock = -1;
  259. std::thread svr{[&] {
  260. const int s = socket(AF_INET, SOCK_STREAM, 0);
  261. ASSERT_LE(0, s);
  262. // PORT + 1 is shared with the SSL redirect tests and with
  263. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  264. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  265. // because that happens on a worker thread the ASSERT does not stop the
  266. // test: it runs on and fails at the disconnected_svr_sock check instead.
  267. default_socket_options(s);
  268. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  269. ASSERT_EQ(0, listen(s, 1));
  270. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  271. ASSERT_EQ(0, close(s));
  272. }};
  273. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  274. std::thread cli{[&] {
  275. const int s = socket(AF_INET, SOCK_STREAM, 0);
  276. ASSERT_LE(0, s);
  277. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  278. ASSERT_EQ(0, close(s));
  279. }};
  280. cli.join();
  281. svr.join();
  282. ASSERT_NE(disconnected_svr_sock, -1);
  283. const auto asSocketStream = [&](socket_t fd,
  284. std::function<bool(Stream &)> func) {
  285. return detail::process_client_socket(
  286. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  287. };
  288. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  289. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  290. // wait_writable() returns true because select_write() only checks if the
  291. // send buffer has space. Peer disconnection is detected later by send().
  292. EXPECT_TRUE(ss.wait_writable());
  293. return true;
  294. });
  295. ASSERT_EQ(0, close(disconnected_svr_sock));
  296. }
  297. #endif // #ifndef _WIN32
  298. TEST(SetSocketOptTest, TcpNoDelay) {
  299. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  300. ASSERT_NE(sock, INVALID_SOCKET);
  301. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  302. int val = 0;
  303. socklen_t len = sizeof(val);
  304. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  305. reinterpret_cast<char *>(&val), &len));
  306. EXPECT_NE(val, 0);
  307. detail::close_socket(sock);
  308. }
  309. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  310. // accept() reports failures through WSAGetLastError() on Windows and through
  311. // errno everywhere else. Asking the wrong one is what made the accept loop
  312. // treat every recoverable failure as fatal on Windows.
  313. struct Classification {
  314. bool resource;
  315. bool transient;
  316. };
  317. auto classify = [](int err) {
  318. #ifdef _WIN32
  319. WSASetLastError(err);
  320. #else
  321. errno = err;
  322. #endif
  323. // Read both before asserting: an assertion may clobber the error slot.
  324. Classification c;
  325. c.resource = detail::is_accept_resource_error();
  326. c.transient = detail::is_accept_transient_error();
  327. return c;
  328. };
  329. #ifdef _WIN32
  330. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  331. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  332. WSAECONNRESET, WSAECONNABORTED};
  333. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  334. #else
  335. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  336. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  337. ECONNABORTED};
  338. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  339. #endif
  340. for (auto err : resource_errors) {
  341. const auto c = classify(err);
  342. EXPECT_TRUE(c.resource) << "error " << err;
  343. EXPECT_FALSE(c.transient) << "error " << err;
  344. }
  345. for (auto err : transient_errors) {
  346. const auto c = classify(err);
  347. EXPECT_TRUE(c.transient) << "error " << err;
  348. EXPECT_FALSE(c.resource) << "error " << err;
  349. }
  350. for (auto err : fatal_errors) {
  351. const auto c = classify(err);
  352. EXPECT_FALSE(c.resource) << "error " << err;
  353. EXPECT_FALSE(c.transient) << "error " << err;
  354. }
  355. #ifdef _WIN32
  356. WSASetLastError(0);
  357. #else
  358. errno = 0;
  359. #endif
  360. }
  361. TEST(ClientTest, MoveConstructible) {
  362. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  363. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  364. }
  365. TEST(ClientTest, MoveAssignable) {
  366. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  367. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  368. }
  369. #ifdef _WIN32
  370. TEST(StartupTest, WSAStartup) {
  371. WSADATA wsaData;
  372. int ret = WSAStartup(0x0002, &wsaData);
  373. ASSERT_EQ(0, ret);
  374. }
  375. #endif
  376. TEST(DecodePathTest, PercentCharacter) {
  377. EXPECT_EQ(
  378. decode_path_component(
  379. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  380. U8("descrip=Gastos áéíóúñÑ 6"));
  381. }
  382. TEST(DecodePathTest, PercentCharacterNUL) {
  383. string expected;
  384. expected.push_back('x');
  385. expected.push_back('\0');
  386. expected.push_back('x');
  387. EXPECT_EQ(decode_path_component("x%00x"), expected);
  388. }
  389. TEST(DecodePathTest, UnicodeEncoding) {
  390. // %u0041 = 'A' (1-byte UTF-8)
  391. EXPECT_EQ("A", decode_path_component("%u0041"));
  392. // %u00E9 = 'é' (2-byte UTF-8)
  393. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  394. // %u3042 = 'あ' (3-byte UTF-8)
  395. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  396. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  397. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  398. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  399. // neighbours)
  400. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  401. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  402. }
  403. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  404. // A sign or whitespace inside the two-character escape window must not be
  405. // accepted as a valid percent-encoding; the sequence is passed through
  406. // literally, matching decode_uri_component / decode_path_component.
  407. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  408. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  409. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  410. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  411. // Well-formed escapes still decode.
  412. EXPECT_EQ("-", decode_query_component("%2D", false));
  413. EXPECT_EQ("A", decode_query_component("%41", false));
  414. }
  415. TEST(SanitizeFilenameTest, VariousPatterns) {
  416. // Path traversal
  417. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  418. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  419. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  420. // Normal and edge cases
  421. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  422. EXPECT_EQ("filename.txt",
  423. httplib::sanitize_filename("/path/to/filename.txt"));
  424. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  425. EXPECT_EQ("", httplib::sanitize_filename(".."));
  426. EXPECT_EQ("", httplib::sanitize_filename(""));
  427. // Null bytes stripped
  428. EXPECT_EQ("safe.txt",
  429. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  430. // Whitespace-only rejected
  431. EXPECT_EQ("", httplib::sanitize_filename(" "));
  432. }
  433. // Forward declaration (see the base64_encode note below): split builds move the
  434. // definition into httplib.cc, so re-declaring it here lets the test link.
  435. namespace httplib {
  436. namespace detail {
  437. bool is_chunked_transfer_encoding(const Headers &headers);
  438. } // namespace detail
  439. } // namespace httplib
  440. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  441. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  442. auto make = [](std::initializer_list<const char *> lines) {
  443. Headers h;
  444. for (auto te : lines) {
  445. if (te) { h.emplace("Transfer-Encoding", te); }
  446. }
  447. return h;
  448. };
  449. // Sole coding, matched case-insensitively.
  450. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  452. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  453. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  454. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  455. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  456. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  457. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  458. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  459. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  460. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  461. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  462. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  463. // were received, into one list. Headers preserves that order, so the answer
  464. // is decided by the last coding of the last line and the order the lines
  465. // arrived in is significant.
  466. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  467. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  468. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  469. // The split can fall anywhere in the list.
  470. EXPECT_TRUE(
  471. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  472. EXPECT_FALSE(
  473. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  474. // A trailing line naming no coding leaves the list ending in nothing, so it
  475. // must not inherit the chunked from the line before it.
  476. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  477. }
  478. // Forward declarations (see the base64_encode note below).
  479. namespace httplib {
  480. namespace detail {
  481. bool parse_status_line(const char *line, std::string &version, int &status,
  482. std::string &reason);
  483. std::string file_extension(const std::string &path);
  484. std::string
  485. find_content_type(const std::string &path,
  486. const std::map<std::string, std::string> &user_data,
  487. const std::string &default_content_type);
  488. bool can_compress_content_type(const std::string &content_type);
  489. bool is_prohibited_header_name(const std::string &name);
  490. #ifdef CPPHTTPLIB_SSL_ENABLED
  491. bool match_hostname(const std::string &pattern, const std::string &hostname);
  492. #endif
  493. } // namespace detail
  494. } // namespace httplib
  495. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  496. struct {
  497. const char *line;
  498. const char *version;
  499. int status;
  500. const char *reason;
  501. } cases[] = {
  502. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  503. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  504. // The reason phrase may be empty, or left out along with its space.
  505. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  506. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  507. };
  508. for (const auto &c : cases) {
  509. std::string version;
  510. int status = 0;
  511. std::string reason = "unset";
  512. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  513. << c.line;
  514. EXPECT_EQ(c.version, version);
  515. EXPECT_EQ(c.status, status);
  516. EXPECT_EQ(c.reason, reason);
  517. }
  518. }
  519. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  520. const char *lines[] = {
  521. "HTTP/2 200 OK\r\n",
  522. "HTTP/1.2 200 OK\r\n",
  523. "HTTP/1.1 20 OK\r\n",
  524. "HTTP/1.1 2000 OK\r\n",
  525. "HTTP/1.1 2x0 OK\r\n",
  526. "HTTP/1.1 200 OK\r\n",
  527. "HTTP/1.1 200OK\r\n",
  528. "HTTP/1.1 200 O\rK\r\n",
  529. "HTTP/1.1 200 OK",
  530. "HTTP/1.1 200 OK\r\nX",
  531. "",
  532. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  533. "HTTP/1.1 200 OK\n",
  534. #endif
  535. };
  536. for (auto line : lines) {
  537. std::string version;
  538. int status = 0;
  539. std::string reason;
  540. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  541. << line;
  542. }
  543. }
  544. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  545. // Long enough to overflow the stack when matched with std::regex.
  546. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  547. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  548. std::string version;
  549. int status = 0;
  550. std::string reason;
  551. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  552. EXPECT_EQ(200, status);
  553. EXPECT_EQ(long_reason, reason);
  554. }
  555. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  556. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  557. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  558. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  559. EXPECT_EQ("", detail::file_extension("noext"));
  560. EXPECT_EQ("", detail::file_extension("a."));
  561. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  562. EXPECT_EQ("", detail::file_extension("a.b-c"));
  563. // Long enough to overflow the stack when matched with std::regex.
  564. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  565. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  566. }
  567. #ifdef CPPHTTPLIB_SSL_ENABLED
  568. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  569. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  570. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  571. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  572. // A wildcard needs two labels after it, in the leftmost label only
  573. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  574. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  575. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  576. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  577. EXPECT_FALSE(
  578. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  579. // No name may have an empty label
  580. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  581. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  582. }
  583. #endif
  584. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  585. detail::case_ignore::hash hash;
  586. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  587. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  588. // Long enough to overflow the stack if hashed one call per character.
  589. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  590. }
  591. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  592. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  593. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  594. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  595. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  596. // Same 26-bit hash as html, svg and js.
  597. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  598. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  599. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  600. }
  601. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  602. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  603. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  604. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  605. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  606. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  607. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  608. // Same 26-bit hash as application/json.
  609. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  610. }
  611. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  612. Request req;
  613. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  614. EXPECT_TRUE(req.is_multipart_form_data());
  615. std::string boundary;
  616. EXPECT_TRUE(detail::parse_multipart_boundary(
  617. req.get_header_value("Content-Type"), boundary));
  618. EXPECT_EQ("x", boundary);
  619. }
  620. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  621. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  622. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  623. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  624. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  625. // Same 26-bit hash as REMOTE_ADDR.
  626. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  627. }
  628. // Forward declaration: in split builds split.py strips `inline` and moves the
  629. // definition into httplib.cc, so detail::base64_encode is not visible from the
  630. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  631. // in both header-only and split builds.
  632. namespace httplib {
  633. namespace detail {
  634. std::string base64_encode(const std::string &in);
  635. } // namespace detail
  636. } // namespace httplib
  637. TEST(Base64EncodeTest, KnownAnswers) {
  638. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  639. // where the accumulator's top bit is already set before the next shift.
  640. EXPECT_EQ("", detail::base64_encode(""));
  641. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  642. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  643. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  644. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  645. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  646. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  647. // High bytes keep the top bit set across several rounds.
  648. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  649. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  650. }
  651. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  652. string unescapedCharacters = "-_.!~*'()";
  653. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  654. }
  655. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  656. string reservedCharacters = ";,/?:@&=+$";
  657. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  658. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  659. }
  660. TEST(ClientQueryOrder, PreserveOrder) {
  661. // This test reproduces Issue #2259: client may reorder query parameters
  662. // when sending a GET request. The expected behavior is that the client
  663. // preserves the original query string order when the caller supplied it
  664. // as part of the path.
  665. Server svr;
  666. svr.Get("/", [&](const Request &req, Response &res) {
  667. // Echo back the raw target so the test can assert ordering
  668. res.set_content(req.target, "text/plain");
  669. });
  670. std::thread t{[&] { svr.listen(HOST, PORT); }};
  671. auto se = detail::scope_exit([&] {
  672. svr.stop();
  673. t.join();
  674. ASSERT_FALSE(svr.is_running());
  675. });
  676. svr.wait_until_ready();
  677. Client cli(HOST, PORT);
  678. ASSERT_TRUE(cli.is_valid());
  679. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  680. auto res = cli.Get(original);
  681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  682. // Expect the echoed target to exactly match the original path (order
  683. // preserved)
  684. EXPECT_EQ(res->body, original);
  685. }
  686. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  687. string chineseCharacters = U8("中国語");
  688. string russianCharacters = U8("дом");
  689. string brazilianCharacters = U8("óculos");
  690. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  691. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  692. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  693. "%D0%B4%D0%BE%D0%BC");
  694. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  695. }
  696. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  697. string unescapedCharacters = "-_.!~*'()";
  698. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  699. }
  700. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  701. string reservedCharacters = ";,/?:@&=+$";
  702. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  703. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  704. }
  705. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  706. string chineseCharacters = U8("中国語");
  707. string russianCharacters = U8("дом");
  708. string brazilianCharacters = U8("óculos");
  709. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  710. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  711. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  712. "%D0%B4%D0%BE%D0%BC");
  713. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  714. }
  715. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  716. // Issue #2082 use case: encoding path component with ampersand
  717. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  718. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  719. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  720. }
  721. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  722. string unescapedCharacters = "-_.!~*'()";
  723. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  724. }
  725. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  726. string reservedCharacters = ";,/?:@&=+$#";
  727. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  728. }
  729. TEST(EncodeUriTest, TestUTF8Characters) {
  730. string chineseCharacters = U8("中国語");
  731. string russianCharacters = U8("дом");
  732. string brazilianCharacters = U8("óculos");
  733. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  734. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  735. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  736. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  737. }
  738. TEST(EncodeUriTest, TestCompleteUri) {
  739. string uri =
  740. "https://example.com/path/to/resource?query=value&param=test#fragment";
  741. EXPECT_EQ(
  742. httplib::encode_uri(uri),
  743. "https://example.com/path/to/resource?query=value&param=test#fragment");
  744. }
  745. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  746. string uri =
  747. "https://example.com/path with spaces/file name.html?q=hello world";
  748. EXPECT_EQ(httplib::encode_uri(uri),
  749. "https://example.com/path%20with%20spaces/"
  750. "file%20name.html?q=hello%20world");
  751. }
  752. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  753. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  754. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  755. }
  756. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  757. string unescapedCharacters = "-_.!~*'()";
  758. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  759. }
  760. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  761. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  762. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  763. string encodedBrazilian = "%C3%B3culos";
  764. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  765. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  766. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  767. }
  768. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  769. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  770. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  771. "Piri Tommy Villiers - on & on");
  772. }
  773. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  774. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  775. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  776. }
  777. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  778. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  779. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  780. }
  781. TEST(DecodeUriTest, TestUTF8Characters) {
  782. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  783. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  784. string encodedBrazilian = "%C3%B3culos";
  785. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  786. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  787. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  788. }
  789. TEST(DecodeUriTest, TestCompleteUri) {
  790. string encodedUri = "https://example.com/path%20with%20spaces/"
  791. "file%20name.html?q=hello%20world";
  792. EXPECT_EQ(
  793. httplib::decode_uri(encodedUri),
  794. "https://example.com/path with spaces/file name.html?q=hello world");
  795. }
  796. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  797. string original =
  798. "https://example.com/path with spaces/file name.html?q=hello world";
  799. string encoded = httplib::encode_uri(original);
  800. string decoded = httplib::decode_uri(encoded);
  801. EXPECT_EQ(decoded, original);
  802. }
  803. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  804. // decode_uri is the inverse of encode_uri: an escaped reserved character
  805. // stays encoded so it is not promoted into a real delimiter, while
  806. // non-reserved escapes still decode (like JS decodeURI).
  807. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  808. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  809. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  810. "%3F%3A%40%26%3D%2B%24%2C%3B");
  811. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  812. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  813. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  814. "http://example.com/a%2Fb");
  815. // decode_uri_component still decodes the reserved character.
  816. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  817. }
  818. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  819. string original = "Piri Tommy Villiers - on & on";
  820. string encoded = httplib::encode_uri_component(original);
  821. string decoded = httplib::decode_uri_component(encoded);
  822. EXPECT_EQ(decoded, original);
  823. }
  824. TEST(TrimTests, TrimStringTests) {
  825. EXPECT_EQ("abc", detail::trim_copy("abc"));
  826. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  827. EXPECT_TRUE(detail::trim_copy("").empty());
  828. }
  829. TEST(AsciiTest, LocaleIndependentClassification) {
  830. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  831. // which consult the global C locale: std::isalnum(0xC5) can return true
  832. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  833. // helpers must classify every byte by the ASCII grammar alone.
  834. for (int i = 0; i < 256; i++) {
  835. auto c = static_cast<char>(i);
  836. auto is_digit = i >= '0' && i <= '9';
  837. auto is_upper = i >= 'A' && i <= 'Z';
  838. auto is_lower = i >= 'a' && i <= 'z';
  839. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  840. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  841. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  842. << "byte " << i;
  843. }
  844. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  845. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  846. // Non-ASCII bytes must be percent-encoded, never passed through as
  847. // alphanumeric.
  848. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  849. }
  850. TEST(FromCharsTest, Double) {
  851. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  852. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  853. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  854. auto parse = [](const std::string &s, double &v) {
  855. return detail::from_chars(s.data(), s.data() + s.size(), v);
  856. };
  857. double v = -1.0;
  858. // Representative quality values.
  859. EXPECT_EQ(parse("0", v).ec, std::errc{});
  860. EXPECT_DOUBLE_EQ(v, 0.0);
  861. EXPECT_EQ(parse("1", v).ec, std::errc{});
  862. EXPECT_DOUBLE_EQ(v, 1.0);
  863. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  864. EXPECT_DOUBLE_EQ(v, 0.8);
  865. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  866. EXPECT_DOUBLE_EQ(v, 0.001);
  867. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  868. EXPECT_DOUBLE_EQ(v, 1.0);
  869. // A missing integer or fractional part is tolerated.
  870. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  871. EXPECT_DOUBLE_EQ(v, 0.5);
  872. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  873. EXPECT_DOUBLE_EQ(v, 5.0);
  874. // Values outside [0, 1] still parse; the caller range-checks them.
  875. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  876. EXPECT_DOUBLE_EQ(v, 123.456);
  877. // Stops at the first byte that is not part of the number and reports where.
  878. std::string trailing = "0.9, text/html";
  879. auto r = parse(trailing, v);
  880. EXPECT_EQ(r.ec, std::errc{});
  881. EXPECT_DOUBLE_EQ(v, 0.9);
  882. EXPECT_EQ(*r.ptr, ',');
  883. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  884. // outright, and an 'e'/'E' simply ends the number.
  885. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  886. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  887. std::string exp_input = "1.5e3";
  888. r = parse(exp_input, v);
  889. EXPECT_EQ(r.ec, std::errc{});
  890. EXPECT_DOUBLE_EQ(v, 1.5);
  891. EXPECT_EQ(*r.ptr, 'e');
  892. // Invalid inputs.
  893. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  894. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  895. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  896. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  897. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  898. // Pathological but well-formed inputs must stay bounded (no overflow, no
  899. // out-of-bounds table access) and stay within [0, 1] for the caller.
  900. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  901. std::errc{});
  902. EXPECT_DOUBLE_EQ(v, 0.0);
  903. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  904. std::errc{});
  905. EXPECT_GE(v, 0.0);
  906. EXPECT_LE(v, 1.0);
  907. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  908. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  909. }
  910. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  911. // Simple case without quality values
  912. std::vector<std::string> result1;
  913. EXPECT_TRUE(detail::parse_accept_header(
  914. "text/html,application/json,text/plain", result1));
  915. EXPECT_EQ(result1.size(), 3U);
  916. EXPECT_EQ(result1[0], "text/html");
  917. EXPECT_EQ(result1[1], "application/json");
  918. EXPECT_EQ(result1[2], "text/plain");
  919. // With quality values
  920. std::vector<std::string> result2;
  921. EXPECT_TRUE(detail::parse_accept_header(
  922. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  923. EXPECT_EQ(result2.size(), 3U);
  924. EXPECT_EQ(result2[0], "application/json"); // highest q value
  925. EXPECT_EQ(result2[1], "text/html");
  926. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  927. }
  928. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  929. // Mixed with and without quality values
  930. std::vector<std::string> result;
  931. EXPECT_TRUE(detail::parse_accept_header(
  932. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  933. EXPECT_EQ(result.size(), 3U);
  934. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  935. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  936. EXPECT_EQ(result[2], "application/json"); // q=0.5
  937. }
  938. TEST(ParseAcceptHeaderTest, EdgeCases) {
  939. // Empty header
  940. std::vector<std::string> empty_result;
  941. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  942. EXPECT_TRUE(empty_result.empty());
  943. // Single type
  944. std::vector<std::string> single_result;
  945. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  946. EXPECT_EQ(single_result.size(), 1U);
  947. EXPECT_EQ(single_result[0], "application/json");
  948. // Wildcard types
  949. std::vector<std::string> wildcard_result;
  950. EXPECT_TRUE(detail::parse_accept_header(
  951. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  952. EXPECT_EQ(wildcard_result.size(), 3U);
  953. EXPECT_EQ(wildcard_result[0], "application/json");
  954. EXPECT_EQ(wildcard_result[1], "text/*");
  955. EXPECT_EQ(wildcard_result[2], "*/*");
  956. }
  957. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  958. // Common browser Accept header
  959. std::vector<std::string> browser_result;
  960. EXPECT_TRUE(
  961. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  962. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  963. browser_result));
  964. EXPECT_EQ(browser_result.size(), 6U);
  965. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  966. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  967. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  968. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  969. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  970. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  971. // API client header
  972. std::vector<std::string> api_result;
  973. EXPECT_TRUE(detail::parse_accept_header(
  974. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  975. api_result));
  976. EXPECT_EQ(api_result.size(), 3U);
  977. EXPECT_EQ(api_result[0], "application/json");
  978. EXPECT_EQ(api_result[1], "application/xml");
  979. EXPECT_EQ(api_result[2], "text/plain");
  980. }
  981. TEST(ParseAcceptHeaderTest, SpecialCases) {
  982. // Quality value with 3 decimal places
  983. std::vector<std::string> decimal_result;
  984. EXPECT_TRUE(detail::parse_accept_header(
  985. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  986. EXPECT_EQ(decimal_result.size(), 2U);
  987. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  988. EXPECT_EQ(decimal_result[1], "text/html");
  989. // Zero quality (should still be included but with lowest priority)
  990. std::vector<std::string> zero_q_result;
  991. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  992. zero_q_result));
  993. EXPECT_EQ(zero_q_result.size(), 2U);
  994. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  995. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  996. // No spaces around commas
  997. std::vector<std::string> no_space_result;
  998. EXPECT_TRUE(detail::parse_accept_header(
  999. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1000. no_space_result));
  1001. EXPECT_EQ(no_space_result.size(), 3U);
  1002. EXPECT_EQ(no_space_result[0], "text/html");
  1003. EXPECT_EQ(no_space_result[1], "application/json");
  1004. EXPECT_EQ(no_space_result[2], "text/plain");
  1005. }
  1006. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1007. // Quality values always use '.' as the decimal separator, so parsing must
  1008. // not depend on the process locale. An embedding application may have
  1009. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1010. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1011. std::string saved = cur ? cur : "C";
  1012. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1013. "fr_FR.UTF-8"};
  1014. bool switched = false;
  1015. for (const auto loc : comma_locales) {
  1016. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1017. std::localeconv()->decimal_point[0] == ',') {
  1018. switched = true;
  1019. break;
  1020. }
  1021. }
  1022. if (!switched) {
  1023. std::setlocale(LC_NUMERIC, saved.c_str());
  1024. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1025. }
  1026. // The higher-weighted type appears later in the list, so a correct parse
  1027. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1028. // sensitive parse reads both weights as 0 and leaves the original order.
  1029. std::vector<std::string> result;
  1030. EXPECT_TRUE(detail::parse_accept_header(
  1031. "application/json;q=0.1,text/html;q=0.9", result));
  1032. ASSERT_EQ(result.size(), 2U);
  1033. EXPECT_EQ(result[0], "text/html");
  1034. EXPECT_EQ(result[1], "application/json");
  1035. std::setlocale(LC_NUMERIC, saved.c_str());
  1036. }
  1037. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1038. std::vector<std::string> result;
  1039. // Invalid quality value (> 1.0)
  1040. EXPECT_FALSE(
  1041. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1042. // Invalid quality value (< 0.0)
  1043. EXPECT_FALSE(
  1044. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1045. // Invalid quality value (not a number)
  1046. EXPECT_FALSE(detail::parse_accept_header(
  1047. "text/html;q=invalid,application/json", result));
  1048. // A valid numeric prefix does not make the entire quality value valid.
  1049. EXPECT_FALSE(detail::parse_accept_header(
  1050. "text/html;q=0.5junk,application/json", result));
  1051. // Empty quality value
  1052. EXPECT_FALSE(
  1053. detail::parse_accept_header("text/html;q=,application/json", result));
  1054. // Invalid media type format (no slash and not wildcard)
  1055. EXPECT_FALSE(
  1056. detail::parse_accept_header("invalidtype,application/json", result));
  1057. // Valid cases should still work
  1058. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1059. EXPECT_EQ(result.size(), 1U);
  1060. EXPECT_EQ(result[0], "*/*");
  1061. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1062. EXPECT_EQ(result.size(), 1U);
  1063. EXPECT_EQ(result[0], "*");
  1064. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1065. EXPECT_EQ(result.size(), 1U);
  1066. EXPECT_EQ(result[0], "text/*");
  1067. }
  1068. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1069. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1070. // and must not be answered with 400 Bad Request.
  1071. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1072. struct {
  1073. const char *value;
  1074. std::vector<std::string> expected;
  1075. } cases[] = {
  1076. {",application/json", {"application/json"}},
  1077. {"text/html,", {"text/html"}},
  1078. {"text/html,,*/*", {"text/html", "*/*"}},
  1079. // An empty element may be spelled with whitespace in it
  1080. {"text/html, , application/json", {"text/html", "application/json"}},
  1081. // Nothing but empty elements is an empty list, which means the same
  1082. // thing as no Accept header at all
  1083. {",,,", {}},
  1084. // Quality values still apply across ignored empty elements
  1085. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1086. };
  1087. for (const auto &c : cases) {
  1088. std::vector<std::string> result;
  1089. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1090. << "value: " << c.value;
  1091. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1092. }
  1093. // An invalid entry is still rejected when empty elements surround it
  1094. std::vector<std::string> result;
  1095. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1096. }
  1097. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1098. // or ';' inside one does not end the list element or the parameter. Section
  1099. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1100. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1101. struct {
  1102. const char *value;
  1103. std::vector<std::string> expected;
  1104. } cases[] = {
  1105. {"text/html;profile=\"a,b\",application/json",
  1106. {"text/html", "application/json"}},
  1107. // A "q=" inside a quoted value is not the weight
  1108. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1109. {"text/html", "application/json"}},
  1110. // The weight after a quoted value still applies
  1111. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1112. {"application/json", "text/html"}},
  1113. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1114. {"application/json", "text/html"}},
  1115. {"text/html;profile=\"a\\\"b\",application/json",
  1116. {"text/html", "application/json"}},
  1117. // An escaped backslash does not escape the '"' after it
  1118. {"text/html;profile=\"a\\\\\",application/json",
  1119. {"text/html", "application/json"}},
  1120. };
  1121. for (const auto &c : cases) {
  1122. std::vector<std::string> result;
  1123. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1124. << "value: " << c.value;
  1125. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1126. }
  1127. }
  1128. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1129. Server svr;
  1130. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1131. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1132. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1133. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1134. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1135. res.set_content("ok", "text/plain");
  1136. });
  1137. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1138. EXPECT_TRUE(false);
  1139. res.set_content("bad request", "text/plain");
  1140. });
  1141. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1142. auto se = detail::scope_exit([&] {
  1143. svr.stop();
  1144. listen_thread.join();
  1145. ASSERT_FALSE(svr.is_running());
  1146. });
  1147. svr.wait_until_ready();
  1148. Client cli("localhost", PORT);
  1149. {
  1150. auto res = cli.Get(
  1151. "/accept_ok",
  1152. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1154. EXPECT_EQ(StatusCode::OK_200, res->status);
  1155. }
  1156. {
  1157. auto res = cli.Get("/accept_bad_request",
  1158. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1160. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1161. }
  1162. }
  1163. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1164. Server svr;
  1165. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1166. res.set_content("ok", "text/plain");
  1167. });
  1168. std::atomic<int> start_count{0};
  1169. std::atomic<bool> running_when_called{false};
  1170. svr.set_start_handler([&]() {
  1171. running_when_called = svr.is_running();
  1172. start_count++;
  1173. });
  1174. auto port = svr.bind_to_any_port(HOST);
  1175. std::thread t([&]() { svr.listen_after_bind(); });
  1176. auto se = detail::scope_exit([&] {
  1177. svr.stop();
  1178. t.join();
  1179. ASSERT_FALSE(svr.is_running());
  1180. });
  1181. svr.wait_until_ready();
  1182. // A successful request proves the accept loop is running, which the start
  1183. // handler precedes; so by now the handler must have run exactly once.
  1184. Client cli(HOST, port);
  1185. cli.set_connection_timeout(std::chrono::seconds(5));
  1186. auto res = cli.Get("/");
  1187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1188. EXPECT_EQ(StatusCode::OK_200, res->status);
  1189. EXPECT_EQ(1, start_count.load());
  1190. EXPECT_TRUE(running_when_called.load());
  1191. }
  1192. TEST(DivideTest, DivideStringTests) {
  1193. auto divide = [](const std::string &str, char d) {
  1194. std::string lhs;
  1195. std::string rhs;
  1196. detail::divide(str, d,
  1197. [&](const char *lhs_data, std::size_t lhs_size,
  1198. const char *rhs_data, std::size_t rhs_size) {
  1199. lhs.assign(lhs_data, lhs_size);
  1200. rhs.assign(rhs_data, rhs_size);
  1201. });
  1202. return std::make_pair(std::move(lhs), std::move(rhs));
  1203. };
  1204. {
  1205. const auto res = divide("", '=');
  1206. EXPECT_EQ(res.first, "");
  1207. EXPECT_EQ(res.second, "");
  1208. }
  1209. {
  1210. const auto res = divide("=", '=');
  1211. EXPECT_EQ(res.first, "");
  1212. EXPECT_EQ(res.second, "");
  1213. }
  1214. {
  1215. const auto res = divide(" ", '=');
  1216. EXPECT_EQ(res.first, " ");
  1217. EXPECT_EQ(res.second, "");
  1218. }
  1219. {
  1220. const auto res = divide("a", '=');
  1221. EXPECT_EQ(res.first, "a");
  1222. EXPECT_EQ(res.second, "");
  1223. }
  1224. {
  1225. const auto res = divide("a=", '=');
  1226. EXPECT_EQ(res.first, "a");
  1227. EXPECT_EQ(res.second, "");
  1228. }
  1229. {
  1230. const auto res = divide("=b", '=');
  1231. EXPECT_EQ(res.first, "");
  1232. EXPECT_EQ(res.second, "b");
  1233. }
  1234. {
  1235. const auto res = divide("a=b", '=');
  1236. EXPECT_EQ(res.first, "a");
  1237. EXPECT_EQ(res.second, "b");
  1238. }
  1239. {
  1240. const auto res = divide("a=b=", '=');
  1241. EXPECT_EQ(res.first, "a");
  1242. EXPECT_EQ(res.second, "b=");
  1243. }
  1244. {
  1245. const auto res = divide("a=b=c", '=');
  1246. EXPECT_EQ(res.first, "a");
  1247. EXPECT_EQ(res.second, "b=c");
  1248. }
  1249. }
  1250. TEST(SplitTest, ParseQueryString) {
  1251. string s = "key1=val1&key2=val2&key3=val3";
  1252. Params dic;
  1253. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1254. [&](const char *b, const char *e) {
  1255. string key, val;
  1256. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1257. if (key.empty()) {
  1258. key.assign(b2, e2);
  1259. } else {
  1260. val.assign(b2, e2);
  1261. }
  1262. });
  1263. dic.emplace(key, val);
  1264. });
  1265. EXPECT_EQ("val1", dic.find("key1")->second);
  1266. EXPECT_EQ("val2", dic.find("key2")->second);
  1267. EXPECT_EQ("val3", dic.find("key3")->second);
  1268. }
  1269. TEST(SplitTest, ParseInvalidQueryTests) {
  1270. {
  1271. string s = " ";
  1272. Params dict;
  1273. detail::parse_query_text(s, dict);
  1274. EXPECT_TRUE(dict.empty());
  1275. }
  1276. {
  1277. string s = " = =";
  1278. Params dict;
  1279. detail::parse_query_text(s, dict);
  1280. EXPECT_TRUE(dict.empty());
  1281. }
  1282. }
  1283. TEST(ParseQueryTest, ParseQueryString) {
  1284. {
  1285. std::string s = "key1=val1&key2=val2&key3=val3";
  1286. Params dic;
  1287. detail::parse_query_text(s, dic);
  1288. EXPECT_EQ("val1", dic.find("key1")->second);
  1289. EXPECT_EQ("val2", dic.find("key2")->second);
  1290. EXPECT_EQ("val3", dic.find("key3")->second);
  1291. }
  1292. {
  1293. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1294. Params dic;
  1295. detail::parse_query_text(s, dic);
  1296. EXPECT_EQ("", dic.find("key1")->second);
  1297. EXPECT_EQ("val1", dic.find("key2")->second);
  1298. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1299. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1300. }
  1301. }
  1302. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1303. Params dic;
  1304. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1305. dic.emplace("key1", "val1");
  1306. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1307. dic.emplace("key2", "val2");
  1308. dic.emplace("key3", "val3");
  1309. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1310. }
  1311. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1312. Params params;
  1313. params.emplace("a", "1");
  1314. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1315. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1316. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1317. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1318. // Long enough to overflow the stack when matched with std::regex.
  1319. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1320. EXPECT_EQ("/p?" + long_query + "&a=1",
  1321. append_query_params("/p?" + long_query, params));
  1322. }
  1323. // Joins every entry of a Headers or Params into "key=value " so a whole
  1324. // traversal can be compared in one assertion. Both are instantiations of the
  1325. // same insertion-ordered container, so one helper serves both.
  1326. template <typename Map> static std::string entries_to_string(const Map &m) {
  1327. std::string s;
  1328. for (const auto &entry : m) {
  1329. s += entry.first + "=" + entry.second + " ";
  1330. }
  1331. return s;
  1332. }
  1333. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1334. // Params used to be a std::multimap, which sorted by name and handed the
  1335. // caller's query back alphabetised. A client signing its query string could
  1336. // not reproduce the order it asked for.
  1337. Params dic;
  1338. dic.emplace("zulu", "1");
  1339. dic.emplace("alpha", "2");
  1340. dic.emplace("mike", "3");
  1341. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1342. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1343. }
  1344. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1345. Params dic;
  1346. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1347. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1348. }
  1349. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1350. Request req;
  1351. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1352. req.params);
  1353. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1354. EXPECT_EQ("first", req.get_param_value("tag"));
  1355. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1356. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1357. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1358. EXPECT_EQ("", req.get_param_value("tag", 3));
  1359. }
  1360. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1361. // Params shares its container with Headers, which matches field names
  1362. // case-insensitively. Parameter names must not pick that up.
  1363. Params dic;
  1364. dic.emplace("Key", "upper");
  1365. dic.emplace("key", "lower");
  1366. EXPECT_EQ(2U, dic.size());
  1367. EXPECT_EQ(1U, dic.count("Key"));
  1368. EXPECT_EQ(1U, dic.count("key"));
  1369. EXPECT_EQ("upper", dic.find("Key")->second);
  1370. EXPECT_EQ("lower", dic.find("key")->second);
  1371. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1372. }
  1373. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1374. Server svr;
  1375. std::string order;
  1376. svr.Get("/order", [&](const Request &req, Response &res) {
  1377. order = entries_to_string(req.params);
  1378. res.set_content("ok", "text/plain");
  1379. });
  1380. auto port = svr.bind_to_any_port(HOST);
  1381. thread t = thread([&] { svr.listen_after_bind(); });
  1382. auto se = detail::scope_exit([&] {
  1383. svr.stop();
  1384. t.join();
  1385. ASSERT_FALSE(svr.is_running());
  1386. });
  1387. svr.wait_until_ready();
  1388. Client cli(HOST, port);
  1389. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1390. ASSERT_TRUE(res);
  1391. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1392. }
  1393. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1394. Server svr;
  1395. std::string field_order, file_order;
  1396. svr.Post("/order", [&](const Request &req, Response &res) {
  1397. for (const auto &field : req.form.fields) {
  1398. field_order += field.first + "=" + field.second.content + " ";
  1399. }
  1400. for (const auto &file : req.form.files) {
  1401. file_order += file.first + "=" + file.second.filename + " ";
  1402. }
  1403. res.set_content("ok", "text/plain");
  1404. });
  1405. auto port = svr.bind_to_any_port(HOST);
  1406. thread t = thread([&] { svr.listen_after_bind(); });
  1407. auto se = detail::scope_exit([&] {
  1408. svr.stop();
  1409. t.join();
  1410. ASSERT_FALSE(svr.is_running());
  1411. });
  1412. svr.wait_until_ready();
  1413. UploadFormDataItems items = {
  1414. {"zulu", "1", "", ""},
  1415. {"alpha", "2", "", ""},
  1416. {"mike", "3", "", ""},
  1417. {"zebra", "z", "z.txt", "text/plain"},
  1418. {"apple", "a", "a.txt", "text/plain"},
  1419. };
  1420. Client cli(HOST, port);
  1421. auto res = cli.Post("/order", items);
  1422. ASSERT_TRUE(res);
  1423. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1424. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1425. }
  1426. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1427. Server svr;
  1428. std::vector<std::string> values;
  1429. std::string first, second, out_of_range, order;
  1430. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1431. values = req.form.get_fields("tag");
  1432. first = req.form.get_field("tag", 0);
  1433. second = req.form.get_field("tag", 1);
  1434. out_of_range = req.form.get_field("tag", 2);
  1435. for (const auto &field : req.form.fields) {
  1436. order += field.first + "=" + field.second.content + " ";
  1437. }
  1438. res.set_content("ok", "text/plain");
  1439. });
  1440. auto port = svr.bind_to_any_port(HOST);
  1441. thread t = thread([&] { svr.listen_after_bind(); });
  1442. auto se = detail::scope_exit([&] {
  1443. svr.stop();
  1444. t.join();
  1445. ASSERT_FALSE(svr.is_running());
  1446. });
  1447. svr.wait_until_ready();
  1448. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1449. // not adjacent in the container.
  1450. UploadFormDataItems items = {
  1451. {"tag", "first", "", ""},
  1452. {"other", "x", "", ""},
  1453. {"tag", "second", "", ""},
  1454. };
  1455. Client cli(HOST, port);
  1456. auto res = cli.Post("/repeated", items);
  1457. ASSERT_TRUE(res);
  1458. ASSERT_EQ(2U, values.size());
  1459. EXPECT_EQ("first", values[0]);
  1460. EXPECT_EQ("second", values[1]);
  1461. EXPECT_EQ("first", first);
  1462. EXPECT_EQ("second", second);
  1463. // std::multimap already kept entries sharing a name in insertion order, so
  1464. // everything above passes without this change too. The whole traversal is
  1465. // what tells the two apart: sorting by name would hoist "other" to the front
  1466. // and the two "tag" parts would end up adjacent.
  1467. EXPECT_EQ("tag=first other=x tag=second ", order);
  1468. // Advancing past the last entry of a name used to run off the container;
  1469. // the container's saturating increment makes it return the default instead.
  1470. EXPECT_EQ("", out_of_range);
  1471. }
  1472. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1473. Server svr;
  1474. std::string file_names;
  1475. svr.Post("/upload", [&](const Request &req, Response &res) {
  1476. for (const auto &file : req.form.files) {
  1477. file_names += file.first + "|" + file.second.filename + " ";
  1478. }
  1479. res.set_content("ok", "text/plain");
  1480. });
  1481. auto port = svr.bind_to_any_port(HOST);
  1482. thread t = thread([&] { svr.listen_after_bind(); });
  1483. auto se = detail::scope_exit([&] {
  1484. svr.stop();
  1485. t.join();
  1486. ASSERT_FALSE(svr.is_running());
  1487. });
  1488. svr.wait_until_ready();
  1489. // A trailing backslash would otherwise escape the closing quote.
  1490. UploadFormDataItems items = {
  1491. {"dir\\", "x", "a.txt", "text/plain"},
  1492. {"b", "y", "a\\\\b.txt", "text/plain"},
  1493. };
  1494. Client cli(HOST, port);
  1495. auto res = cli.Post("/upload", items);
  1496. ASSERT_TRUE(res);
  1497. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1498. }
  1499. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1500. // Server::read_content() keeps a FormFields::iterator alive across the
  1501. // content callbacks that fill the part it points at. The container is
  1502. // vector-backed, so a later emplace can reallocate and invalidate an older
  1503. // iterator; 64 parts grow the vector through seven reallocations, which
  1504. // checks that every part's content still lands in its own entry.
  1505. const size_t part_count = 64;
  1506. // One formula for both the parts sent and the values expected back, so the
  1507. // two cannot drift apart.
  1508. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1509. auto content_of = [](size_t i) {
  1510. return std::string(64, static_cast<char>('a' + (i % 26)));
  1511. };
  1512. Server svr;
  1513. std::vector<std::pair<std::string, std::string>> received;
  1514. svr.Post("/many", [&](const Request &req, Response &res) {
  1515. for (const auto &field : req.form.fields) {
  1516. received.emplace_back(field.first, field.second.content);
  1517. }
  1518. res.set_content("ok", "text/plain");
  1519. });
  1520. auto port = svr.bind_to_any_port(HOST);
  1521. thread t = thread([&] { svr.listen_after_bind(); });
  1522. auto se = detail::scope_exit([&] {
  1523. svr.stop();
  1524. t.join();
  1525. ASSERT_FALSE(svr.is_running());
  1526. });
  1527. svr.wait_until_ready();
  1528. UploadFormDataItems items;
  1529. for (size_t i = 0; i < part_count; i++) {
  1530. items.push_back({name_of(i), content_of(i), "", ""});
  1531. }
  1532. Client cli(HOST, port);
  1533. auto res = cli.Post("/many", items);
  1534. ASSERT_TRUE(res);
  1535. ASSERT_EQ(part_count, received.size());
  1536. for (size_t i = 0; i < part_count; i++) {
  1537. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1538. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1539. }
  1540. }
  1541. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1542. string content_type = "multipart/form-data; boundary=something";
  1543. string boundary;
  1544. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1545. EXPECT_TRUE(ret);
  1546. EXPECT_EQ(boundary, "something");
  1547. }
  1548. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1549. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1550. string boundary;
  1551. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1552. EXPECT_TRUE(ret);
  1553. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1554. }
  1555. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1556. string content_type =
  1557. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1558. string boundary;
  1559. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1560. EXPECT_TRUE(ret);
  1561. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1562. }
  1563. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1564. string content_type =
  1565. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1566. string boundary;
  1567. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1568. EXPECT_TRUE(ret);
  1569. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1570. }
  1571. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1572. const string boundary(70, 'a');
  1573. string content_type = "multipart/form-data; boundary=" + boundary;
  1574. string parsed;
  1575. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1576. EXPECT_TRUE(ret);
  1577. EXPECT_EQ(parsed, boundary);
  1578. }
  1579. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1580. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1581. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1582. string parsed;
  1583. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1584. EXPECT_FALSE(ret);
  1585. }
  1586. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1587. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1588. // is 72 characters on the wire and still valid.
  1589. const string boundary(70, 'a');
  1590. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1591. string parsed;
  1592. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1593. EXPECT_EQ(parsed, boundary);
  1594. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1595. parsed.clear();
  1596. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1597. }
  1598. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1599. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1600. // The parameter parser must not treat that '=' as the key/value separator.
  1601. string content_type =
  1602. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1603. "charset=UTF-8";
  1604. string parsed;
  1605. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1606. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1607. }
  1608. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1609. // A ';' inside the quoted-string is part of the value, not a parameter
  1610. // separator, so it must not truncate the boundary.
  1611. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1612. string parsed;
  1613. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1614. EXPECT_EQ(parsed, "a;b");
  1615. }
  1616. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1617. string parsed;
  1618. EXPECT_TRUE(detail::parse_multipart_boundary(
  1619. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1620. EXPECT_EQ("a\\b", parsed);
  1621. EXPECT_TRUE(detail::parse_multipart_boundary(
  1622. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1623. EXPECT_EQ("a\"b", parsed);
  1624. }
  1625. TEST(ParseDispositionParamsTest, QuotedValues) {
  1626. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1627. // ';' and '=' are ordinary characters inside one.
  1628. struct {
  1629. const char *value;
  1630. std::vector<std::pair<const char *, const char *>> expected;
  1631. } cases[] = {
  1632. {"name=\"file1\"; filename=\"a.txt\"",
  1633. {{"name", "file1"}, {"filename", "a.txt"}}},
  1634. // Whitespace around '=' and ';' is still trimmed
  1635. {"name=\"file2\" ;filename = \"a.html\"",
  1636. {{"name", "file2"}, {"filename", "a.html"}}},
  1637. // '=' inside the value used to leave only the text after the last one
  1638. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1639. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1640. {"name=\"x=y\"", {{"name", "x=y"}}},
  1641. // ';' inside the value used to truncate the pair and leave a bogus one
  1642. {"name=\"file3\"; filename=\"a;b.txt\"",
  1643. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1644. // An unquoted value keeps working, and so does filename*
  1645. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1646. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1647. // A parameter with no key is dropped rather than turned into one whose
  1648. // key is the value
  1649. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1650. // An escaped quote does not end the value
  1651. {"name=\"a\\\"; filename=evil.php\"",
  1652. {{"name", "a\"; filename=evil.php"}}},
  1653. // Other backslashes, as in a Windows path, are kept
  1654. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1655. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1656. };
  1657. for (const auto &c : cases) {
  1658. Params params;
  1659. detail::parse_disposition_params(c.value, params);
  1660. for (const auto &kv : c.expected) {
  1661. auto it = params.find(kv.first);
  1662. ASSERT_NE(it, params.end())
  1663. << "value: " << c.value << ", key: " << kv.first;
  1664. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1665. }
  1666. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1667. }
  1668. }
  1669. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1670. Server svr;
  1671. std::string filename;
  1672. std::string content;
  1673. svr.Post("/upload", [&](const Request &req, Response &) {
  1674. const auto &file = req.form.get_file("file");
  1675. filename = file.filename;
  1676. content = file.content;
  1677. });
  1678. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1679. auto se = detail::scope_exit([&] {
  1680. svr.stop();
  1681. thread.join();
  1682. ASSERT_FALSE(svr.is_running());
  1683. });
  1684. svr.wait_until_ready();
  1685. std::string body = "--B\r\n"
  1686. "Content-Disposition: form-data; name=\"file\"; "
  1687. "filename=\"a.txt\"\r\n"
  1688. "Content-Type: text/plain\r\n"
  1689. "\r\n"
  1690. "hello\r\n"
  1691. "--B--\r\n";
  1692. Client cli(HOST, PORT);
  1693. auto res = cli.Post(
  1694. "/upload",
  1695. [&](size_t offset, DataSink &sink) {
  1696. if (offset < body.size()) {
  1697. sink.write(&body[offset], 1);
  1698. } else {
  1699. sink.done();
  1700. }
  1701. return true;
  1702. },
  1703. "multipart/form-data; boundary=B");
  1704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1705. EXPECT_EQ(StatusCode::OK_200, res->status);
  1706. EXPECT_EQ("a.txt", filename);
  1707. EXPECT_EQ("hello", content);
  1708. }
  1709. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1710. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1711. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1712. Server svr;
  1713. std::string field_value, file_name, file_filename;
  1714. bool has_field = false, has_file = false;
  1715. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1716. has_field = req.form.has_field("x=y");
  1717. field_value = req.form.get_field("x=y");
  1718. has_file = req.form.has_file("file1");
  1719. const auto &file = req.form.get_file("file1");
  1720. file_name = file.name;
  1721. file_filename = file.filename;
  1722. res.set_content("ok", "text/plain");
  1723. });
  1724. auto port = svr.bind_to_any_port(HOST);
  1725. thread t = thread([&] { svr.listen_after_bind(); });
  1726. auto se = detail::scope_exit([&] {
  1727. svr.stop();
  1728. t.join();
  1729. ASSERT_FALSE(svr.is_running());
  1730. });
  1731. svr.wait_until_ready();
  1732. UploadFormDataItems items = {
  1733. {"x=y", "field-value", "", ""},
  1734. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1735. };
  1736. Client cli(HOST, port);
  1737. auto res = cli.Post("/quoted", items);
  1738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1739. ASSERT_EQ(StatusCode::OK_200, res->status);
  1740. EXPECT_TRUE(has_field);
  1741. EXPECT_EQ("field-value", field_value);
  1742. EXPECT_TRUE(has_file);
  1743. EXPECT_EQ("file1", file_name);
  1744. EXPECT_EQ("a;b=report.pdf", file_filename);
  1745. }
  1746. TEST(GetHeaderValueTest, DefaultValue) {
  1747. Headers headers = {{"Dummy", "Dummy"}};
  1748. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1749. EXPECT_STREQ("text/plain", val);
  1750. }
  1751. TEST(GetHeaderValueTest, DefaultValueInt) {
  1752. Headers headers = {{"Dummy", "Dummy"}};
  1753. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1754. EXPECT_EQ(100ull, val);
  1755. }
  1756. TEST(GetHeaderValueTest, RegularValue) {
  1757. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1758. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1759. EXPECT_STREQ("text/html", val);
  1760. }
  1761. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1762. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1763. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1764. EXPECT_STREQ("text/html", val);
  1765. }
  1766. TEST(GetHeaderValueTest, SetContent) {
  1767. Response res;
  1768. res.set_content("html", "text/html");
  1769. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1770. res.set_content("text", "text/plain");
  1771. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1772. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1773. }
  1774. TEST(GetHeaderValueTest, RegularValueInt) {
  1775. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1776. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1777. EXPECT_EQ(100ull, val);
  1778. }
  1779. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1780. Headers headers = {{"Content-Length", "x"}};
  1781. auto is_invalid_value = false;
  1782. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1783. is_invalid_value);
  1784. EXPECT_EQ(0ull, val);
  1785. EXPECT_TRUE(is_invalid_value);
  1786. }
  1787. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1788. // An all-digit value that overflows size_t must be reported as invalid, not
  1789. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1790. // a large length to a small one on 32-bit builds, leaving the framing length
  1791. // wrong while is_invalid_value stayed false.
  1792. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1793. auto is_invalid_value = false;
  1794. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1795. is_invalid_value);
  1796. EXPECT_TRUE(is_invalid_value);
  1797. // A well-formed length is unaffected.
  1798. Headers ok = {{"Content-Length", "1234"}};
  1799. is_invalid_value = false;
  1800. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1801. is_invalid_value);
  1802. EXPECT_EQ(1234ull, val);
  1803. EXPECT_FALSE(is_invalid_value);
  1804. }
  1805. TEST(GetHeaderValueTest, Range) {
  1806. {
  1807. Headers headers = {make_range_header({{1, -1}})};
  1808. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1809. EXPECT_STREQ("bytes=1-", val);
  1810. }
  1811. {
  1812. Headers headers = {make_range_header({{-1, 1}})};
  1813. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1814. EXPECT_STREQ("bytes=-1", val);
  1815. }
  1816. {
  1817. Headers headers = {make_range_header({{1, 10}})};
  1818. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1819. EXPECT_STREQ("bytes=1-10", val);
  1820. }
  1821. {
  1822. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1823. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1824. EXPECT_STREQ("bytes=1-10, 100-", val);
  1825. }
  1826. {
  1827. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1828. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1829. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1830. }
  1831. {
  1832. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1833. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1834. EXPECT_STREQ("bytes=0-0, -1", val);
  1835. }
  1836. }
  1837. TEST(BearerTokenAuthTest, SchemeValidation) {
  1838. // A value shorter than "Bearer " must not throw from the fixed-length
  1839. // substr, and a non-Bearer scheme must not be reported as a token.
  1840. struct {
  1841. const char *value;
  1842. const char *expected;
  1843. } cases[] = {
  1844. {"x", ""},
  1845. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1846. {"Bearer abc123", "abc123"},
  1847. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1848. };
  1849. for (const auto &c : cases) {
  1850. Request req;
  1851. req.set_header("Authorization", c.value);
  1852. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1853. }
  1854. }
  1855. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1856. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1857. // to depend on the standard library (libstdc++ handed back duplicates in
  1858. // reverse insertion order, libc++ in insertion order).
  1859. Request req;
  1860. req.set_header("Accept-Encoding", "gzip");
  1861. req.set_header("Accept-Encoding", "deflate");
  1862. req.set_header("Accept-Encoding", "br");
  1863. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1864. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1865. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1866. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1867. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1868. }
  1869. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1870. Request req;
  1871. req.set_header("X-Test", "only");
  1872. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1873. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1874. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1875. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1876. }
  1877. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1878. Request req;
  1879. req.set_header("X-First", "1");
  1880. req.set_header("X-Test", "2");
  1881. req.params.emplace("first", "1");
  1882. req.params.emplace("test", "2");
  1883. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1884. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1885. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1886. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1887. // The second one is negative when read as a signed value
  1888. const auto max_id = (std::numeric_limits<size_t>::max)();
  1889. for (auto id : {max_id / 2, max_id}) {
  1890. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1891. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1892. EXPECT_EQ("", req.get_param_value("test", id));
  1893. EXPECT_EQ("", req.form.get_field("test", id));
  1894. EXPECT_EQ("", req.form.get_file("test", id).content);
  1895. }
  1896. }
  1897. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1898. Headers headers;
  1899. headers.emplace("Host", "example.com");
  1900. headers.emplace("Accept-Encoding", "gzip");
  1901. headers.emplace("User-Agent", "test");
  1902. headers.emplace("Accept-Encoding", "deflate");
  1903. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1904. "Accept-Encoding=deflate ",
  1905. entries_to_string(headers));
  1906. }
  1907. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1908. Headers headers = {{"Content-Type", "text/html"},
  1909. {"CONTENT-TYPE", "text/xml"}};
  1910. EXPECT_EQ(2U, headers.count("content-type"));
  1911. auto it = headers.find("content-type");
  1912. ASSERT_TRUE(it != headers.end());
  1913. EXPECT_EQ("text/html", it->second);
  1914. }
  1915. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1916. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1917. // drop only those fields and leave everything positioned between them.
  1918. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1919. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1920. auto rng = headers.equal_range("a");
  1921. headers.erase(rng.first, rng.second);
  1922. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1923. }
  1924. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1925. Headers headers = {
  1926. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1927. EXPECT_EQ(3U, headers.erase("A"));
  1928. EXPECT_EQ(0U, headers.count("A"));
  1929. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1930. }
  1931. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1932. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1933. headers.emplace_front("Host", "example.com");
  1934. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1935. entries_to_string(headers));
  1936. }
  1937. TEST(ParseHeaderValueTest, Range) {
  1938. {
  1939. Ranges ranges;
  1940. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1941. EXPECT_TRUE(ret);
  1942. EXPECT_EQ(1u, ranges.size());
  1943. EXPECT_EQ(1u, ranges[0].first);
  1944. EXPECT_EQ(-1, ranges[0].second);
  1945. }
  1946. {
  1947. Ranges ranges;
  1948. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1949. EXPECT_TRUE(ret);
  1950. EXPECT_EQ(1u, ranges.size());
  1951. EXPECT_EQ(-1, ranges[0].first);
  1952. EXPECT_EQ(1u, ranges[0].second);
  1953. }
  1954. {
  1955. Ranges ranges;
  1956. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1957. EXPECT_TRUE(ret);
  1958. EXPECT_EQ(1u, ranges.size());
  1959. EXPECT_EQ(1u, ranges[0].first);
  1960. EXPECT_EQ(10u, ranges[0].second);
  1961. }
  1962. {
  1963. Ranges ranges;
  1964. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1965. EXPECT_FALSE(ret);
  1966. }
  1967. {
  1968. Ranges ranges;
  1969. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1970. EXPECT_TRUE(ret);
  1971. EXPECT_EQ(2u, ranges.size());
  1972. EXPECT_EQ(1u, ranges[0].first);
  1973. EXPECT_EQ(10u, ranges[0].second);
  1974. EXPECT_EQ(100u, ranges[1].first);
  1975. EXPECT_EQ(-1, ranges[1].second);
  1976. }
  1977. {
  1978. Ranges ranges;
  1979. auto ret =
  1980. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1981. EXPECT_TRUE(ret);
  1982. EXPECT_EQ(3u, ranges.size());
  1983. EXPECT_EQ(1u, ranges[0].first);
  1984. EXPECT_EQ(10u, ranges[0].second);
  1985. EXPECT_EQ(100u, ranges[1].first);
  1986. EXPECT_EQ(200u, ranges[1].second);
  1987. EXPECT_EQ(300u, ranges[2].first);
  1988. EXPECT_EQ(400u, ranges[2].second);
  1989. }
  1990. {
  1991. Ranges ranges;
  1992. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1993. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1994. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1995. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1996. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1997. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1998. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1999. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  2000. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  2001. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  2002. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  2003. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  2004. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  2005. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  2006. EXPECT_FALSE(
  2007. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2008. EXPECT_TRUE(ranges.empty());
  2009. }
  2010. {
  2011. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2012. // remainder of the representation, so it stays accepted.
  2013. Ranges ranges;
  2014. auto ret =
  2015. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2016. EXPECT_TRUE(ret);
  2017. ASSERT_EQ(1u, ranges.size());
  2018. EXPECT_EQ(0, ranges[0].first);
  2019. EXPECT_EQ(-1, ranges[0].second);
  2020. }
  2021. // RFC 9110 14.1: range unit names are case-insensitive.
  2022. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2023. Ranges ranges;
  2024. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2025. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2026. }
  2027. }
  2028. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2029. Request req;
  2030. req.set_header("Accept-Encoding", "gzip");
  2031. Response res;
  2032. res.set_header("Content-Type", "text/plain");
  2033. auto ret = detail::encoding_type(req, res);
  2034. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2035. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2036. #else
  2037. EXPECT_TRUE(ret == detail::EncodingType::None);
  2038. #endif
  2039. }
  2040. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2041. Request req;
  2042. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2043. Response res;
  2044. res.set_header("Content-Type", "text/plain");
  2045. auto ret = detail::encoding_type(req, res);
  2046. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2047. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2048. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2049. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2050. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2051. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2052. #else
  2053. EXPECT_TRUE(ret == detail::EncodingType::None);
  2054. #endif
  2055. }
  2056. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2057. Request req;
  2058. req.set_header("Accept-Encoding",
  2059. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2060. Response res;
  2061. res.set_header("Content-Type", "text/plain");
  2062. auto ret = detail::encoding_type(req, res);
  2063. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2064. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2065. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2066. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2067. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2068. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2069. #else
  2070. EXPECT_TRUE(ret == detail::EncodingType::None);
  2071. #endif
  2072. }
  2073. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2074. // All supported encodings rejected with q=0 should return None
  2075. Request req;
  2076. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2077. Response res;
  2078. res.set_header("Content-Type", "text/plain");
  2079. auto ret = detail::encoding_type(req, res);
  2080. EXPECT_TRUE(ret == detail::EncodingType::None);
  2081. }
  2082. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2083. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2084. Request req;
  2085. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2086. Response res;
  2087. res.set_header("Content-Type", "text/plain");
  2088. auto ret = detail::encoding_type(req, res);
  2089. EXPECT_TRUE(ret == detail::EncodingType::None);
  2090. }
  2091. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2092. Request req;
  2093. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2094. Response res;
  2095. res.set_header("Content-Type", "text/plain");
  2096. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2097. }
  2098. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2099. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2100. Request req;
  2101. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2102. Response res;
  2103. res.set_header("Content-Type", "text/plain");
  2104. auto ret = detail::encoding_type(req, res);
  2105. EXPECT_TRUE(ret == detail::EncodingType::None);
  2106. }
  2107. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2108. // RFC 7231: Accept-Encoding values are case-insensitive
  2109. Request req;
  2110. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2111. Response res;
  2112. res.set_header("Content-Type", "text/plain");
  2113. auto ret = detail::encoding_type(req, res);
  2114. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2115. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2116. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2117. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2118. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2119. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2120. #else
  2121. EXPECT_TRUE(ret == detail::EncodingType::None);
  2122. #endif
  2123. }
  2124. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2125. // q value should determine priority, not hardcoded order
  2126. Request req;
  2127. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2128. Response res;
  2129. res.set_header("Content-Type", "text/plain");
  2130. auto ret = detail::encoding_type(req, res);
  2131. // gzip has highest q=1.0, so it should be selected even though
  2132. // br and zstd are also supported
  2133. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2134. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2135. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2136. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2137. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2138. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2139. #else
  2140. EXPECT_TRUE(ret == detail::EncodingType::None);
  2141. #endif
  2142. }
  2143. TEST(BufferStreamTest, read) {
  2144. detail::BufferStream strm1;
  2145. Stream &strm = strm1;
  2146. EXPECT_EQ(5, strm.write("hello"));
  2147. char buf[512];
  2148. EXPECT_EQ(2, strm.read(buf, 2));
  2149. EXPECT_EQ('h', buf[0]);
  2150. EXPECT_EQ('e', buf[1]);
  2151. EXPECT_EQ(2, strm.read(buf, 2));
  2152. EXPECT_EQ('l', buf[0]);
  2153. EXPECT_EQ('l', buf[1]);
  2154. EXPECT_EQ(1, strm.read(buf, 1));
  2155. EXPECT_EQ('o', buf[0]);
  2156. EXPECT_EQ(0, strm.read(buf, 1));
  2157. }
  2158. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2159. auto host = "www.httpwatch.com";
  2160. auto ip = hosted_at(host);
  2161. EXPECT_EQ("23.96.13.243", ip);
  2162. std::vector<std::string> addrs;
  2163. hosted_at(host, addrs);
  2164. EXPECT_EQ(1u, addrs.size());
  2165. }
  2166. #if 0 // It depends on each test environment...
  2167. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2168. auto host = "www.youtube.com";
  2169. std::vector<std::string> addrs;
  2170. hosted_at(host, addrs);
  2171. EXPECT_EQ(20u, addrs.size());
  2172. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2173. EXPECT_TRUE(it != addrs.end());
  2174. }
  2175. #endif
  2176. class ChunkedEncodingTest : public ::testing::Test {
  2177. protected:
  2178. ChunkedEncodingTest()
  2179. : cli_(HOST, PORT)
  2180. #ifdef CPPHTTPLIB_SSL_ENABLED
  2181. ,
  2182. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2183. #endif
  2184. {
  2185. cli_.set_connection_timeout(2);
  2186. #ifdef CPPHTTPLIB_SSL_ENABLED
  2187. cli_.enable_server_certificate_verification(false);
  2188. #endif
  2189. }
  2190. virtual void SetUp() {
  2191. read_file("./image.jpg", image_data_);
  2192. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2193. res.set_content("Hello World!", "text/plain");
  2194. });
  2195. svr_.Get(
  2196. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2197. res.set_chunked_content_provider(
  2198. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2199. size_t remaining = image_data_.size() - offset;
  2200. if (remaining == 0) {
  2201. sink.done();
  2202. } else {
  2203. constexpr size_t CHUNK_SIZE = 1024;
  2204. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2205. sink.write(&image_data_[offset], send_size);
  2206. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2207. }
  2208. return true;
  2209. });
  2210. });
  2211. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2212. svr_.wait_until_ready();
  2213. }
  2214. virtual void TearDown() {
  2215. svr_.stop();
  2216. if (!request_threads_.empty()) {
  2217. std::this_thread::sleep_for(std::chrono::seconds(1));
  2218. for (auto &t : request_threads_) {
  2219. t.join();
  2220. }
  2221. }
  2222. t_.join();
  2223. }
  2224. #ifdef CPPHTTPLIB_SSL_ENABLED
  2225. SSLClient cli_;
  2226. SSLServer svr_;
  2227. #else
  2228. Client cli_;
  2229. Server svr_;
  2230. #endif
  2231. thread t_;
  2232. std::vector<thread> request_threads_;
  2233. std::string image_data_;
  2234. };
  2235. TEST_F(ChunkedEncodingTest, NormalGet) {
  2236. auto res = cli_.Get("/chunked");
  2237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2238. std::string out;
  2239. read_file("./image.jpg", out);
  2240. EXPECT_EQ(StatusCode::OK_200, res->status);
  2241. EXPECT_EQ(out, res->body);
  2242. }
  2243. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2244. std::string body;
  2245. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2246. body.append(data, data_length);
  2247. return true;
  2248. });
  2249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2250. std::string out;
  2251. read_file("./image.jpg", out);
  2252. EXPECT_EQ(StatusCode::OK_200, res->status);
  2253. EXPECT_EQ(out, body);
  2254. }
  2255. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2256. std::string body;
  2257. auto res = cli_.Get(
  2258. "/chunked",
  2259. [&](const Response &response) {
  2260. EXPECT_EQ(StatusCode::OK_200, response.status);
  2261. return true;
  2262. },
  2263. [&](const char *data, size_t data_length) {
  2264. body.append(data, data_length);
  2265. return true;
  2266. });
  2267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2268. std::string out;
  2269. read_file("./image.jpg", out);
  2270. EXPECT_EQ(StatusCode::OK_200, res->status);
  2271. EXPECT_EQ(out, body);
  2272. }
  2273. TEST(RangeTest, FromHTTPBin_Online) {
  2274. auto host = "httpbingo.org";
  2275. auto path = std::string{"/range/32"};
  2276. #ifdef CPPHTTPLIB_SSL_ENABLED
  2277. auto port = 443;
  2278. SSLClient cli(host, port);
  2279. #else
  2280. auto port = 80;
  2281. Client cli(host, port);
  2282. #endif
  2283. cli.set_connection_timeout(5);
  2284. {
  2285. auto res = cli.Get(path);
  2286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2287. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2288. EXPECT_EQ(StatusCode::OK_200, res->status);
  2289. }
  2290. {
  2291. Headers headers = {make_range_header({{1, -1}})};
  2292. auto res = cli.Get(path, headers);
  2293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2294. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2295. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2296. }
  2297. {
  2298. Headers headers = {make_range_header({{1, 10}})};
  2299. auto res = cli.Get(path, headers);
  2300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2301. EXPECT_EQ("bcdefghijk", res->body);
  2302. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2303. }
  2304. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2305. // entire resource, while the original httpbin returned 200. Both are
  2306. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2307. {
  2308. Headers headers = {make_range_header({{0, 31}})};
  2309. auto res = cli.Get(path, headers);
  2310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2311. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2312. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2313. res->status == StatusCode::PartialContent_206);
  2314. }
  2315. {
  2316. Headers headers = {make_range_header({{0, -1}})};
  2317. auto res = cli.Get(path, headers);
  2318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2319. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2320. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2321. res->status == StatusCode::PartialContent_206);
  2322. }
  2323. // go-httpbin returns 206 with clamped range for over-range requests,
  2324. // while the original httpbin returned 416. Both behaviors are observed
  2325. // in real servers, so we only verify the request succeeds.
  2326. {
  2327. Headers headers = {make_range_header({{0, 32}})};
  2328. auto res = cli.Get(path, headers);
  2329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2330. }
  2331. }
  2332. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2333. auto host = "unresolvableaddress.local";
  2334. auto path = std::string{"/"};
  2335. #ifdef CPPHTTPLIB_SSL_ENABLED
  2336. auto port = 443;
  2337. SSLClient cli(host, port);
  2338. #else
  2339. auto port = 80;
  2340. Client cli(host, port);
  2341. #endif
  2342. cli.set_connection_timeout(1);
  2343. {
  2344. auto res = cli.Get(path);
  2345. ASSERT_FALSE(res);
  2346. }
  2347. std::this_thread::sleep_for(std::chrono::seconds(8));
  2348. }
  2349. #if defined(__linux__) && defined(__GLIBC__) && \
  2350. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2351. // Forward declaration: in split builds split.py strips `inline` and moves the
  2352. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2353. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2354. // against the symbol in both header-only and split builds.
  2355. namespace httplib {
  2356. namespace detail {
  2357. int getaddrinfo_with_timeout(const char *node, const char *service,
  2358. const struct addrinfo *hints,
  2359. struct addrinfo **res, time_t timeout_sec);
  2360. } // namespace detail
  2361. } // namespace httplib
  2362. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2363. //
  2364. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2365. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2366. // gai_suspend() call hits the connection timeout the function calls
  2367. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2368. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2369. // still alive and still references the now-destroyed stack frame.
  2370. //
  2371. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2372. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2373. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2374. // and runs them in a container.
  2375. namespace {
  2376. bool should_run_issue_2431_tests() {
  2377. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2378. return v && *v && std::string(v) != "0";
  2379. }
  2380. std::string unique_unresolvable_host(int n) {
  2381. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2382. // glibc still asks the configured nameserver — which is exactly the path
  2383. // we want to exercise. A unique label per call avoids the resolver cache.
  2384. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2385. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2386. std::to_string(n) + ".invalid";
  2387. }
  2388. } // namespace
  2389. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2390. if (!should_run_issue_2431_tests()) {
  2391. GTEST_SKIP()
  2392. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2393. }
  2394. for (int i = 0; i < 8; ++i) {
  2395. struct addrinfo hints;
  2396. memset(&hints, 0, sizeof(hints));
  2397. hints.ai_family = AF_UNSPEC;
  2398. hints.ai_socktype = SOCK_STREAM;
  2399. auto host = unique_unresolvable_host(i);
  2400. struct addrinfo *result = nullptr;
  2401. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2402. &result, /*timeout_sec=*/1);
  2403. if (rc == 0 && result) { freeaddrinfo(result); }
  2404. }
  2405. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2406. // stack region they still believe holds their gaicb.
  2407. std::this_thread::sleep_for(std::chrono::seconds(3));
  2408. }
  2409. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2410. if (!should_run_issue_2431_tests()) {
  2411. GTEST_SKIP()
  2412. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2413. }
  2414. std::atomic<bool> stop{false};
  2415. std::vector<std::thread> threads;
  2416. for (int t = 0; t < 8; ++t) {
  2417. threads.emplace_back([t, &stop] {
  2418. int i = 0;
  2419. while (!stop.load(std::memory_order_relaxed)) {
  2420. struct addrinfo hints;
  2421. memset(&hints, 0, sizeof(hints));
  2422. hints.ai_family = AF_UNSPEC;
  2423. hints.ai_socktype = SOCK_STREAM;
  2424. auto host = unique_unresolvable_host(t * 100000 + i++);
  2425. struct addrinfo *result = nullptr;
  2426. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2427. &result, /*timeout_sec=*/1);
  2428. if (rc == 0 && result) { freeaddrinfo(result); }
  2429. }
  2430. });
  2431. }
  2432. std::this_thread::sleep_for(std::chrono::seconds(8));
  2433. stop.store(true, std::memory_order_relaxed);
  2434. for (auto &th : threads) {
  2435. th.join();
  2436. }
  2437. std::this_thread::sleep_for(std::chrono::seconds(3));
  2438. }
  2439. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2440. if (!should_run_issue_2431_tests()) {
  2441. GTEST_SKIP()
  2442. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2443. }
  2444. std::atomic<bool> stop{false};
  2445. std::vector<std::thread> threads;
  2446. for (int t = 0; t < 8; ++t) {
  2447. threads.emplace_back([t, &stop] {
  2448. int i = 0;
  2449. while (!stop.load(std::memory_order_relaxed)) {
  2450. auto host = unique_unresolvable_host(t * 100000 + i++);
  2451. Client cli(host, 80);
  2452. cli.set_connection_timeout(1, 0);
  2453. cli.set_read_timeout(1, 0);
  2454. cli.set_write_timeout(1, 0);
  2455. (void)cli.Get("/");
  2456. }
  2457. });
  2458. }
  2459. std::this_thread::sleep_for(std::chrono::seconds(8));
  2460. stop.store(true, std::memory_order_relaxed);
  2461. for (auto &th : threads) {
  2462. th.join();
  2463. }
  2464. std::this_thread::sleep_for(std::chrono::seconds(3));
  2465. }
  2466. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2467. TEST(ConnectionErrorTest, InvalidHost) {
  2468. auto host = "-abcde.com";
  2469. #ifdef CPPHTTPLIB_SSL_ENABLED
  2470. auto port = 443;
  2471. SSLClient cli(host, port);
  2472. #else
  2473. auto port = 80;
  2474. Client cli(host, port);
  2475. #endif
  2476. cli.set_connection_timeout(std::chrono::seconds(2));
  2477. auto res = cli.Get("/");
  2478. ASSERT_TRUE(!res);
  2479. EXPECT_EQ(Error::Connection, res.error());
  2480. }
  2481. TEST(ConnectionErrorTest, InvalidHost2) {
  2482. auto host = "httpcan.org/";
  2483. #ifdef CPPHTTPLIB_SSL_ENABLED
  2484. SSLClient cli(host);
  2485. #else
  2486. Client cli(host);
  2487. #endif
  2488. cli.set_connection_timeout(std::chrono::seconds(2));
  2489. auto res = cli.Get("/");
  2490. ASSERT_TRUE(!res);
  2491. EXPECT_EQ(Error::Connection, res.error());
  2492. }
  2493. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2494. auto host = "httpcan.org/";
  2495. #ifdef CPPHTTPLIB_SSL_ENABLED
  2496. SSLClient cli(host);
  2497. #else
  2498. Client cli(host);
  2499. #endif
  2500. cli.set_connection_timeout(std::chrono::seconds(2));
  2501. auto res = cli.Get("/");
  2502. ASSERT_TRUE(!res);
  2503. stringstream s;
  2504. s << "error code: " << res.error();
  2505. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2506. }
  2507. TEST(ConnectionErrorTest, InvalidPort) {
  2508. auto host = "localhost";
  2509. auto port = 44380;
  2510. #ifdef CPPHTTPLIB_SSL_ENABLED
  2511. SSLClient cli(host, port);
  2512. #else
  2513. Client cli(host, port);
  2514. #endif
  2515. cli.set_connection_timeout(std::chrono::seconds(2));
  2516. auto res = cli.Get("/");
  2517. ASSERT_TRUE(!res);
  2518. EXPECT_TRUE(Error::Connection == res.error() ||
  2519. Error::ConnectionTimeout == res.error());
  2520. }
  2521. TEST(ConnectionErrorTest, Timeout_Online) {
  2522. auto host = "google.com";
  2523. #ifdef CPPHTTPLIB_SSL_ENABLED
  2524. auto port = 44380;
  2525. SSLClient cli(host, port);
  2526. #else
  2527. auto port = 8080;
  2528. Client cli(host, port);
  2529. #endif
  2530. cli.set_connection_timeout(std::chrono::seconds(2));
  2531. // only probe one address type so that the error reason
  2532. // correlates to the timed-out IPv4, not the unsupported
  2533. // IPv6 connection attempt
  2534. cli.set_address_family(AF_INET);
  2535. auto res = cli.Get("/");
  2536. ASSERT_TRUE(!res);
  2537. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2538. }
  2539. TEST(CancelTest, NoCancel_Online) {
  2540. auto host = "httpbingo.org";
  2541. auto path = std::string{"/range/32"};
  2542. #ifdef CPPHTTPLIB_SSL_ENABLED
  2543. auto port = 443;
  2544. SSLClient cli(host, port);
  2545. #else
  2546. auto port = 80;
  2547. Client cli(host, port);
  2548. #endif
  2549. cli.set_connection_timeout(std::chrono::seconds(5));
  2550. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2552. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2553. EXPECT_EQ(StatusCode::OK_200, res->status);
  2554. }
  2555. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2556. // Use /bytes with a large payload so that the DownloadProgress callback
  2557. // (which only fires for Content-Length responses) is invoked before the
  2558. // entire body is received, giving cancellation a chance to fire.
  2559. auto host = "httpbingo.org";
  2560. auto path = std::string{"/bytes/524288"};
  2561. #ifdef CPPHTTPLIB_SSL_ENABLED
  2562. auto port = 443;
  2563. SSLClient cli(host, port);
  2564. #else
  2565. auto port = 80;
  2566. Client cli(host, port);
  2567. #endif
  2568. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2569. cli.set_connection_timeout(std::chrono::seconds(5));
  2570. ASSERT_TRUE(!res);
  2571. EXPECT_EQ(Error::Canceled, res.error());
  2572. }
  2573. TEST(CancelTest, WithCancelLargePayload_Online) {
  2574. auto host = "httpbingo.org";
  2575. auto path = std::string{"/bytes/524288"};
  2576. #ifdef CPPHTTPLIB_SSL_ENABLED
  2577. auto port = 443;
  2578. SSLClient cli(host, port);
  2579. #else
  2580. auto port = 80;
  2581. Client cli(host, port);
  2582. #endif
  2583. cli.set_connection_timeout(std::chrono::seconds(5));
  2584. uint32_t count = 0;
  2585. auto res =
  2586. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2587. ASSERT_TRUE(!res);
  2588. EXPECT_EQ(Error::Canceled, res.error());
  2589. }
  2590. TEST(CancelTest, NoCancelPost) {
  2591. Server svr;
  2592. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2593. res.set_content("Hello World!", "text/plain");
  2594. });
  2595. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2596. auto se = detail::scope_exit([&] {
  2597. svr.stop();
  2598. thread.join();
  2599. ASSERT_FALSE(svr.is_running());
  2600. });
  2601. svr.wait_until_ready();
  2602. Client cli(HOST, PORT);
  2603. cli.set_connection_timeout(std::chrono::seconds(5));
  2604. auto res =
  2605. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2606. "application/json", [](uint64_t, uint64_t) { return true; });
  2607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2608. EXPECT_EQ("Hello World!", res->body);
  2609. EXPECT_EQ(StatusCode::OK_200, res->status);
  2610. }
  2611. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2612. Server svr;
  2613. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2614. res.set_content("Hello World!", "text/plain");
  2615. });
  2616. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2617. auto se = detail::scope_exit([&] {
  2618. svr.stop();
  2619. thread.join();
  2620. ASSERT_FALSE(svr.is_running());
  2621. });
  2622. svr.wait_until_ready();
  2623. Client cli(HOST, PORT);
  2624. cli.set_connection_timeout(std::chrono::seconds(5));
  2625. auto res =
  2626. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2627. "application/json", [](uint64_t, uint64_t) { return false; });
  2628. ASSERT_TRUE(!res);
  2629. EXPECT_EQ(Error::Canceled, res.error());
  2630. }
  2631. TEST(CancelTest, WithCancelLargePayloadPost) {
  2632. Server svr;
  2633. svr.set_payload_max_length(200 * 1024 * 1024);
  2634. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2635. res.set_content(LARGE_DATA, "text/plain");
  2636. });
  2637. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2638. auto se = detail::scope_exit([&] {
  2639. svr.stop();
  2640. thread.join();
  2641. ASSERT_FALSE(svr.is_running());
  2642. });
  2643. svr.wait_until_ready();
  2644. Client cli(HOST, PORT);
  2645. cli.set_payload_max_length(200 * 1024 * 1024);
  2646. cli.set_connection_timeout(std::chrono::seconds(5));
  2647. auto res =
  2648. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2649. "application/json", [](uint64_t, uint64_t) { return false; });
  2650. ASSERT_TRUE(!res);
  2651. EXPECT_EQ(Error::Canceled, res.error());
  2652. }
  2653. TEST(CancelTest, NoCancelPut) {
  2654. Server svr;
  2655. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2656. res.set_content("Hello World!", "text/plain");
  2657. });
  2658. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2659. auto se = detail::scope_exit([&] {
  2660. svr.stop();
  2661. thread.join();
  2662. ASSERT_FALSE(svr.is_running());
  2663. });
  2664. svr.wait_until_ready();
  2665. Client cli(HOST, PORT);
  2666. cli.set_connection_timeout(std::chrono::seconds(5));
  2667. auto res =
  2668. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2669. "application/json", [](uint64_t, uint64_t) { return true; });
  2670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2671. EXPECT_EQ("Hello World!", res->body);
  2672. EXPECT_EQ(StatusCode::OK_200, res->status);
  2673. }
  2674. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2675. Server svr;
  2676. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2677. res.set_content("Hello World!", "text/plain");
  2678. });
  2679. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2680. auto se = detail::scope_exit([&] {
  2681. svr.stop();
  2682. thread.join();
  2683. ASSERT_FALSE(svr.is_running());
  2684. });
  2685. svr.wait_until_ready();
  2686. Client cli(HOST, PORT);
  2687. cli.set_connection_timeout(std::chrono::seconds(5));
  2688. auto res =
  2689. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2690. "application/json", [](uint64_t, uint64_t) { return false; });
  2691. ASSERT_TRUE(!res);
  2692. EXPECT_EQ(Error::Canceled, res.error());
  2693. }
  2694. TEST(CancelTest, WithCancelLargePayloadPut) {
  2695. Server svr;
  2696. svr.set_payload_max_length(200 * 1024 * 1024);
  2697. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2698. res.set_content(LARGE_DATA, "text/plain");
  2699. });
  2700. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2701. auto se = detail::scope_exit([&] {
  2702. svr.stop();
  2703. thread.join();
  2704. ASSERT_FALSE(svr.is_running());
  2705. });
  2706. svr.wait_until_ready();
  2707. Client cli(HOST, PORT);
  2708. cli.set_payload_max_length(200 * 1024 * 1024);
  2709. cli.set_connection_timeout(std::chrono::seconds(5));
  2710. auto res =
  2711. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2712. "application/json", [](uint64_t, uint64_t) { return false; });
  2713. ASSERT_TRUE(!res);
  2714. EXPECT_EQ(Error::Canceled, res.error());
  2715. }
  2716. TEST(CancelTest, NoCancelPatch) {
  2717. Server svr;
  2718. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2719. res.set_content("Hello World!", "text/plain");
  2720. });
  2721. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2722. auto se = detail::scope_exit([&] {
  2723. svr.stop();
  2724. thread.join();
  2725. ASSERT_FALSE(svr.is_running());
  2726. });
  2727. svr.wait_until_ready();
  2728. Client cli(HOST, PORT);
  2729. cli.set_connection_timeout(std::chrono::seconds(5));
  2730. auto res =
  2731. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2732. "application/json", [](uint64_t, uint64_t) { return true; });
  2733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2734. EXPECT_EQ("Hello World!", res->body);
  2735. EXPECT_EQ(StatusCode::OK_200, res->status);
  2736. }
  2737. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2738. Server svr;
  2739. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2740. res.set_content("Hello World!", "text/plain");
  2741. });
  2742. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2743. auto se = detail::scope_exit([&] {
  2744. svr.stop();
  2745. thread.join();
  2746. ASSERT_FALSE(svr.is_running());
  2747. });
  2748. svr.wait_until_ready();
  2749. Client cli(HOST, PORT);
  2750. cli.set_connection_timeout(std::chrono::seconds(5));
  2751. auto res =
  2752. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2753. "application/json", [](uint64_t, uint64_t) { return false; });
  2754. ASSERT_TRUE(!res);
  2755. EXPECT_EQ(Error::Canceled, res.error());
  2756. }
  2757. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2758. Server svr;
  2759. svr.set_payload_max_length(200 * 1024 * 1024);
  2760. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2761. res.set_content(LARGE_DATA, "text/plain");
  2762. });
  2763. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2764. auto se = detail::scope_exit([&] {
  2765. svr.stop();
  2766. thread.join();
  2767. ASSERT_FALSE(svr.is_running());
  2768. });
  2769. svr.wait_until_ready();
  2770. Client cli(HOST, PORT);
  2771. cli.set_payload_max_length(200 * 1024 * 1024);
  2772. cli.set_connection_timeout(std::chrono::seconds(5));
  2773. auto res =
  2774. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2775. "application/json", [](uint64_t, uint64_t) { return false; });
  2776. ASSERT_TRUE(!res);
  2777. EXPECT_EQ(Error::Canceled, res.error());
  2778. }
  2779. TEST(CancelTest, NoCancelDelete) {
  2780. Server svr;
  2781. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2782. res.set_content("Hello World!", "text/plain");
  2783. });
  2784. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2785. auto se = detail::scope_exit([&] {
  2786. svr.stop();
  2787. thread.join();
  2788. ASSERT_FALSE(svr.is_running());
  2789. });
  2790. svr.wait_until_ready();
  2791. Client cli(HOST, PORT);
  2792. cli.set_connection_timeout(std::chrono::seconds(5));
  2793. auto res =
  2794. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2795. "application/json", [](uint64_t, uint64_t) { return true; });
  2796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2797. EXPECT_EQ("Hello World!", res->body);
  2798. EXPECT_EQ(StatusCode::OK_200, res->status);
  2799. }
  2800. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2801. Server svr;
  2802. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2803. res.set_content("Hello World!", "text/plain");
  2804. });
  2805. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2806. auto se = detail::scope_exit([&] {
  2807. svr.stop();
  2808. thread.join();
  2809. ASSERT_FALSE(svr.is_running());
  2810. });
  2811. svr.wait_until_ready();
  2812. Client cli(HOST, PORT);
  2813. cli.set_connection_timeout(std::chrono::seconds(5));
  2814. auto res =
  2815. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2816. "application/json", [](uint64_t, uint64_t) { return false; });
  2817. ASSERT_TRUE(!res);
  2818. EXPECT_EQ(Error::Canceled, res.error());
  2819. }
  2820. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2821. Server svr;
  2822. svr.set_payload_max_length(200 * 1024 * 1024);
  2823. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2824. res.set_content(LARGE_DATA, "text/plain");
  2825. });
  2826. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2827. auto se = detail::scope_exit([&] {
  2828. svr.stop();
  2829. thread.join();
  2830. ASSERT_FALSE(svr.is_running());
  2831. });
  2832. svr.wait_until_ready();
  2833. Client cli(HOST, PORT);
  2834. cli.set_payload_max_length(200 * 1024 * 1024);
  2835. cli.set_connection_timeout(std::chrono::seconds(5));
  2836. auto res =
  2837. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2838. "application/json", [](uint64_t, uint64_t) { return false; });
  2839. ASSERT_TRUE(!res);
  2840. EXPECT_EQ(Error::Canceled, res.error());
  2841. }
  2842. static std::string remove_whitespace(const std::string &input) {
  2843. std::string output;
  2844. output.reserve(input.size());
  2845. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2846. [](unsigned char c) { return !std::isspace(c); });
  2847. return output;
  2848. }
  2849. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2850. auto host = "httpbingo.org";
  2851. auto path = std::string{"/basic-auth/hello/world"};
  2852. #ifdef CPPHTTPLIB_SSL_ENABLED
  2853. auto port = 443;
  2854. SSLClient cli(host, port);
  2855. #else
  2856. auto port = 80;
  2857. Client cli(host, port);
  2858. #endif
  2859. {
  2860. auto res = cli.Get(path);
  2861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2862. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2863. }
  2864. {
  2865. auto res = cli.Get(
  2866. path, Headers{make_basic_authentication_header("hello", "world")});
  2867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2868. auto body = remove_whitespace(res->body);
  2869. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2870. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2871. EXPECT_EQ(StatusCode::OK_200, res->status);
  2872. }
  2873. {
  2874. cli.set_basic_auth("hello", "world");
  2875. auto res = cli.Get(path);
  2876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2877. auto body = remove_whitespace(res->body);
  2878. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2879. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2880. EXPECT_EQ(StatusCode::OK_200, res->status);
  2881. }
  2882. {
  2883. cli.set_basic_auth("hello", "bad");
  2884. auto res = cli.Get(path);
  2885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2886. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2887. }
  2888. {
  2889. cli.set_basic_auth("bad", "world");
  2890. auto res = cli.Get(path);
  2891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2892. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2893. }
  2894. }
  2895. #ifdef CPPHTTPLIB_SSL_ENABLED
  2896. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2897. auto host = "httpbingo.org";
  2898. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2899. auto paths = std::vector<std::string>{
  2900. "/digest-auth/auth/hello/world/MD5",
  2901. "/digest-auth/auth/hello/world/SHA-256",
  2902. };
  2903. auto port = 443;
  2904. SSLClient cli(host, port);
  2905. {
  2906. auto res = cli.Get(unauth_path);
  2907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2908. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2909. }
  2910. {
  2911. cli.set_digest_auth("hello", "world");
  2912. for (const auto &path : paths) {
  2913. auto res = cli.Get(path.c_str());
  2914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2915. auto body = remove_whitespace(res->body);
  2916. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2917. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2918. EXPECT_EQ(StatusCode::OK_200, res->status);
  2919. }
  2920. cli.set_digest_auth("hello", "bad");
  2921. for (const auto &path : paths) {
  2922. auto res = cli.Get(path.c_str());
  2923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2924. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2925. }
  2926. }
  2927. }
  2928. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2929. // comma-separated list of challenges, and each challenge may itself carry a
  2930. // comma-separated auth-param list, so a server can legally offer Basic
  2931. // before Digest, either as two field lines or packed into one. Runs one 401
  2932. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2933. // value() joins them in receipt order) and checks that the retry carries a
  2934. // well-formed Digest Authorization header naming expected_realm.
  2935. static void
  2936. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2937. const std::string &expected_realm) {
  2938. std::atomic<int> hits{0};
  2939. Server svr;
  2940. svr.Get("/x", [&](const Request &req, Response &res) {
  2941. if (++hits == 1) {
  2942. res.status = StatusCode::Unauthorized_401;
  2943. for (const auto &challenge : challenges) {
  2944. res.set_header("WWW-Authenticate", challenge);
  2945. }
  2946. } else {
  2947. auto authorization = req.get_header_value("Authorization");
  2948. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2949. EXPECT_NE(std::string::npos,
  2950. authorization.find("realm=\"" + expected_realm + "\""));
  2951. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2952. res.set_content("ok", "text/plain");
  2953. }
  2954. });
  2955. auto port = svr.bind_to_any_port(HOST);
  2956. std::thread t([&]() { svr.listen_after_bind(); });
  2957. auto se = detail::scope_exit([&] {
  2958. svr.stop();
  2959. t.join();
  2960. });
  2961. svr.wait_until_ready();
  2962. Client cli(HOST, port);
  2963. cli.set_digest_auth("hello", "world");
  2964. auto res = cli.Get("/x");
  2965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2966. EXPECT_EQ(2, hits.load());
  2967. }
  2968. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2969. static const char *kDigestChallenge =
  2970. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2971. "algorithm=MD5";
  2972. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2973. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2974. "testrealm");
  2975. }
  2976. // Same challenge list with the schemes in the opposite order, to make sure
  2977. // the fix above didn't just special-case "Basic first".
  2978. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2979. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2980. "testrealm");
  2981. }
  2982. // A comma inside a quoted auth-param value must not be mistaken for the
  2983. // separator between two challenges (or two auth-params).
  2984. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2985. run_digest_challenge_list_test(
  2986. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2987. "algorithm=MD5"},
  2988. "test,realm");
  2989. }
  2990. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  2991. // the params and leaves out the fragment.
  2992. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  2993. Server svr;
  2994. std::string uri, target;
  2995. svr.Get("/a b", [&](const Request &req, Response &res) {
  2996. auto auth = req.get_header_value("Authorization");
  2997. if (auth.empty()) {
  2998. res.status = StatusCode::Unauthorized_401;
  2999. res.set_header("WWW-Authenticate",
  3000. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3001. return;
  3002. }
  3003. auto b = auth.find("uri=\"") + 5;
  3004. uri = auth.substr(b, auth.find('"', b) - b);
  3005. target = req.target;
  3006. });
  3007. auto port = svr.bind_to_any_port(HOST);
  3008. std::thread t([&]() { svr.listen_after_bind(); });
  3009. auto se = detail::scope_exit([&] {
  3010. svr.stop();
  3011. t.join();
  3012. });
  3013. svr.wait_until_ready();
  3014. Client cli(HOST, port);
  3015. cli.set_digest_auth("hello", "world");
  3016. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3018. EXPECT_EQ("/a%20b?x=1", target);
  3019. EXPECT_EQ(target, uri);
  3020. }
  3021. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3022. // make_digest_authentication_header() dereferences both unconditionally, so
  3023. // a server sending a challenge missing either one must not be treated as
  3024. // usable -- doing so used to crash the client with std::out_of_range.
  3025. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3026. Server svr;
  3027. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3028. res.status = StatusCode::Unauthorized_401;
  3029. res.set_header("WWW-Authenticate", challenge);
  3030. });
  3031. auto port = svr.bind_to_any_port(HOST);
  3032. std::thread t([&]() { svr.listen_after_bind(); });
  3033. auto se = detail::scope_exit([&] {
  3034. svr.stop();
  3035. t.join();
  3036. });
  3037. svr.wait_until_ready();
  3038. Client cli(HOST, port);
  3039. cli.set_digest_auth("hello", "world");
  3040. auto res = cli.Get("/x");
  3041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3042. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3043. }
  3044. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3045. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3046. }
  3047. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3048. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3049. }
  3050. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3051. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3052. }
  3053. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3054. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3055. // when storing the values, so the header builder has to re-escape them (and
  3056. // keep algorithm a bare token); otherwise the value breaks out of its
  3057. // quoted-string and injects extra auth-params into the client's Authorization.
  3058. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3059. std::atomic<int> hits{0};
  3060. std::string authorization;
  3061. Server svr;
  3062. svr.Get("/x", [&](const Request &req, Response &res) {
  3063. if (++hits == 1) {
  3064. res.status = StatusCode::Unauthorized_401;
  3065. // On the wire the quotes embedded in the values are backslash-escaped.
  3066. res.set_header("WWW-Authenticate",
  3067. "Digest realm=\"testrealm\", "
  3068. "nonce=\"n\\\"; injected=\\\"x\", "
  3069. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3070. } else {
  3071. authorization = req.get_header_value("Authorization");
  3072. res.set_content("ok", "text/plain");
  3073. }
  3074. });
  3075. auto port = svr.bind_to_any_port(HOST);
  3076. std::thread t([&]() { svr.listen_after_bind(); });
  3077. auto se = detail::scope_exit([&] {
  3078. svr.stop();
  3079. t.join();
  3080. });
  3081. svr.wait_until_ready();
  3082. Client cli(HOST, port);
  3083. cli.set_digest_auth("hello", "world");
  3084. auto res = cli.Get("/x");
  3085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3086. EXPECT_EQ(2, hits.load());
  3087. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3088. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3089. // inside its quoted-string rather than starting an "injected" auth-param.
  3090. EXPECT_NE(std::string::npos,
  3091. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3092. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3093. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3094. }
  3095. #endif
  3096. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3097. auto host = "google.com";
  3098. auto another_host = "example.com";
  3099. auto wrong_ip = "0.0.0.0";
  3100. #ifdef CPPHTTPLIB_SSL_ENABLED
  3101. SSLClient cli(host);
  3102. #else
  3103. Client cli(host);
  3104. #endif
  3105. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3106. auto res = cli.Get("/");
  3107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3108. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3109. }
  3110. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3111. auto host = "google.com";
  3112. auto wrong_ip = "0.0.0.0";
  3113. #ifdef CPPHTTPLIB_SSL_ENABLED
  3114. SSLClient cli(host);
  3115. #else
  3116. Client cli(host);
  3117. #endif
  3118. cli.set_hostname_addr_map({{host, wrong_ip}});
  3119. auto res = cli.Get("/");
  3120. ASSERT_TRUE(!res);
  3121. EXPECT_EQ(Error::Connection, res.error());
  3122. }
  3123. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3124. // A mapped value that is not an IP literal must be resolved. "localhost"
  3125. // resolves from the hosts file, so this test needs no external DNS.
  3126. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3127. auto host = "target.invalid";
  3128. Server svr;
  3129. std::string received_host;
  3130. svr.Get("/hi", [&](const Request &req, Response &res) {
  3131. received_host = req.get_header_value("Host");
  3132. res.set_content("Hello World!", "text/plain");
  3133. });
  3134. auto port = svr.bind_to_any_port(HOST);
  3135. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3136. auto se = detail::scope_exit([&] {
  3137. svr.stop();
  3138. thread.join();
  3139. ASSERT_FALSE(svr.is_running());
  3140. });
  3141. svr.wait_until_ready();
  3142. Client cli(host, port);
  3143. cli.set_hostname_addr_map({{host, HOST}});
  3144. auto res = cli.Get("/hi");
  3145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3146. EXPECT_EQ(StatusCode::OK_200, res->status);
  3147. // The mapping only redirects the connection; the identity stays host_.
  3148. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3149. }
  3150. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3151. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3152. auto host = "target.invalid";
  3153. Server svr;
  3154. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3155. res.set_content("Hello World!", "text/plain");
  3156. });
  3157. auto port = svr.bind_to_any_port("127.0.0.1");
  3158. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3159. auto se = detail::scope_exit([&] {
  3160. svr.stop();
  3161. thread.join();
  3162. ASSERT_FALSE(svr.is_running());
  3163. });
  3164. svr.wait_until_ready();
  3165. Client cli(host, port);
  3166. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3167. auto res = cli.Get("/hi");
  3168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3169. EXPECT_EQ(StatusCode::OK_200, res->status);
  3170. }
  3171. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3172. // An empty mapped value must leave host_ as the connection target. Without
  3173. // that guard the empty value would become the host argument, getaddrinfo
  3174. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3175. // loopback - silently connecting somewhere the caller never asked for.
  3176. // The server listens on loopback, so such a fallback would succeed and is
  3177. // therefore observable as a failure of this test.
  3178. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3179. Server svr;
  3180. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3181. res.set_content("Hello World!", "text/plain");
  3182. });
  3183. auto port = svr.bind_to_any_port(HOST);
  3184. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3185. auto se = detail::scope_exit([&] {
  3186. svr.stop();
  3187. thread.join();
  3188. ASSERT_FALSE(svr.is_running());
  3189. });
  3190. svr.wait_until_ready();
  3191. Client cli(blackhole, port);
  3192. cli.set_hostname_addr_map({{blackhole, ""}});
  3193. cli.set_connection_timeout(1);
  3194. auto res = cli.Get("/hi");
  3195. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3196. }
  3197. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3198. auto host = "httpbingo.org";
  3199. auto path = std::string{"/absolute-redirect/3"};
  3200. #ifdef CPPHTTPLIB_SSL_ENABLED
  3201. SSLClient cli(host);
  3202. #else
  3203. Client cli(host);
  3204. #endif
  3205. cli.set_follow_location(true);
  3206. auto res = cli.Get(path);
  3207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3208. EXPECT_EQ(StatusCode::OK_200, res->status);
  3209. }
  3210. TEST(RedirectTest, Redirect_Online) {
  3211. auto host = "httpbingo.org";
  3212. auto path = std::string{"/redirect/3"};
  3213. #ifdef CPPHTTPLIB_SSL_ENABLED
  3214. SSLClient cli(host);
  3215. #else
  3216. Client cli(host);
  3217. #endif
  3218. cli.set_follow_location(true);
  3219. auto res = cli.Get(path);
  3220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3221. EXPECT_EQ(StatusCode::OK_200, res->status);
  3222. }
  3223. TEST(RelativeRedirectTest, Redirect_Online) {
  3224. auto host = "httpbingo.org";
  3225. auto path = std::string{"/relative-redirect/3"};
  3226. #ifdef CPPHTTPLIB_SSL_ENABLED
  3227. SSLClient cli(host);
  3228. #else
  3229. Client cli(host);
  3230. #endif
  3231. cli.set_follow_location(true);
  3232. auto res = cli.Get(path);
  3233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3234. EXPECT_EQ(StatusCode::OK_200, res->status);
  3235. }
  3236. TEST(TooManyRedirectTest, Redirect_Online) {
  3237. auto host = "httpbingo.org";
  3238. auto path = std::string{"/redirect/21"};
  3239. #ifdef CPPHTTPLIB_SSL_ENABLED
  3240. SSLClient cli(host);
  3241. #else
  3242. Client cli(host);
  3243. #endif
  3244. cli.set_follow_location(true);
  3245. auto res = cli.Get(path);
  3246. ASSERT_TRUE(!res);
  3247. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3248. }
  3249. #ifdef CPPHTTPLIB_SSL_ENABLED
  3250. TEST(YahooRedirectTest, Redirect_Online) {
  3251. Client cli("yahoo.com");
  3252. auto res = cli.Get("/");
  3253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3254. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3255. cli.set_follow_location(true);
  3256. res = cli.Get("/");
  3257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3258. EXPECT_EQ(StatusCode::OK_200, res->status);
  3259. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3260. }
  3261. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3262. #define REDIR_HOST "httpbingo.org"
  3263. #define REDIR_PATH "/redirect-to"
  3264. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3265. SSLClient cli(REDIR_HOST);
  3266. cli.set_follow_location(true);
  3267. auto res =
  3268. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3270. EXPECT_EQ(StatusCode::OK_200, res->status);
  3271. }
  3272. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3273. SSLClient cli(REDIR_HOST);
  3274. cli.set_follow_location(true);
  3275. Params params;
  3276. params.emplace("url", "http://example.com");
  3277. params.emplace("status_code", "302");
  3278. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3280. EXPECT_EQ(StatusCode::OK_200, res->status);
  3281. }
  3282. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3283. SSLClient cli(REDIR_HOST);
  3284. cli.set_follow_location(true);
  3285. Params params;
  3286. params.emplace("url", "http://example.com");
  3287. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3289. EXPECT_EQ(StatusCode::OK_200, res->status);
  3290. }
  3291. TEST(UrlWithSpace, Redirect_Online) {
  3292. SSLClient cli("edge.forgecdn.net");
  3293. cli.set_follow_location(true);
  3294. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3296. EXPECT_EQ(StatusCode::OK_200, res->status);
  3297. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3298. }
  3299. #endif
  3300. #if !defined(_WIN32) && !defined(_WIN64)
  3301. TEST(ReceiveSignals, Signal) {
  3302. auto setupSignalHandlers = []() {
  3303. struct sigaction act;
  3304. sigemptyset(&act.sa_mask);
  3305. act.sa_flags = SA_SIGINFO;
  3306. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3307. switch (sig) {
  3308. case SIGINT:
  3309. default: break;
  3310. }
  3311. };
  3312. ::sigaction(SIGINT, &act, nullptr);
  3313. };
  3314. Server svr;
  3315. int port = 0;
  3316. auto thread = std::thread([&]() {
  3317. setupSignalHandlers();
  3318. port = svr.bind_to_any_port(HOST);
  3319. svr.listen_after_bind();
  3320. });
  3321. auto se = detail::scope_exit([&] {
  3322. svr.stop();
  3323. thread.join();
  3324. ASSERT_FALSE(svr.is_running());
  3325. });
  3326. svr.wait_until_ready();
  3327. ASSERT_TRUE(svr.is_running());
  3328. pthread_kill(thread.native_handle(), SIGINT);
  3329. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3330. ASSERT_TRUE(svr.is_running());
  3331. }
  3332. #endif
  3333. TEST(RedirectToDifferentPort, Redirect) {
  3334. Server svr1;
  3335. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3336. res.set_content("Hello World!", "text/plain");
  3337. });
  3338. int svr1_port = 0;
  3339. auto thread1 = std::thread([&]() {
  3340. svr1_port = svr1.bind_to_any_port(HOST);
  3341. svr1.listen_after_bind();
  3342. });
  3343. Server svr2;
  3344. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3345. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3346. });
  3347. int svr2_port = 0;
  3348. auto thread2 = std::thread([&]() {
  3349. svr2_port = svr2.bind_to_any_port(HOST);
  3350. svr2.listen_after_bind();
  3351. });
  3352. auto se = detail::scope_exit([&] {
  3353. svr2.stop();
  3354. thread2.join();
  3355. svr1.stop();
  3356. thread1.join();
  3357. ASSERT_FALSE(svr2.is_running());
  3358. ASSERT_FALSE(svr1.is_running());
  3359. });
  3360. svr1.wait_until_ready();
  3361. svr2.wait_until_ready();
  3362. Client cli("localhost", svr2_port);
  3363. cli.set_follow_location(true);
  3364. auto res = cli.Get("/2");
  3365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3366. EXPECT_EQ(StatusCode::OK_200, res->status);
  3367. EXPECT_EQ("Hello World!", res->body);
  3368. }
  3369. // GET /redir on one server redirects to /target on another port, so the
  3370. // client follows it with a new client.
  3371. static Result
  3372. GetThroughRedirectToDifferentPort(Server::Handler target,
  3373. const std::function<void(Client &)> &setup,
  3374. const Headers &headers = Headers()) {
  3375. Server target_svr;
  3376. target_svr.Get("/target", target);
  3377. int target_port = 0;
  3378. auto target_thread = std::thread([&]() {
  3379. target_port = target_svr.bind_to_any_port(HOST);
  3380. target_svr.listen_after_bind();
  3381. });
  3382. Server origin_svr;
  3383. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3384. res.set_redirect(
  3385. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3386. });
  3387. int origin_port = 0;
  3388. auto origin_thread = std::thread([&]() {
  3389. origin_port = origin_svr.bind_to_any_port(HOST);
  3390. origin_svr.listen_after_bind();
  3391. });
  3392. auto se = detail::scope_exit([&] {
  3393. origin_svr.stop();
  3394. origin_thread.join();
  3395. target_svr.stop();
  3396. target_thread.join();
  3397. });
  3398. target_svr.wait_until_ready();
  3399. origin_svr.wait_until_ready();
  3400. Client cli("localhost", origin_port);
  3401. cli.set_follow_location(true);
  3402. setup(cli);
  3403. return cli.Get("/redir", headers);
  3404. }
  3405. static void
  3406. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3407. std::string captured_authorization;
  3408. auto result = GetThroughRedirectToDifferentPort(
  3409. [&](const Request &req, Response &res) {
  3410. captured_authorization = req.get_header_value("Authorization");
  3411. res.set_content("OK", "text/plain");
  3412. },
  3413. set_auth);
  3414. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3415. EXPECT_EQ(StatusCode::OK_200, result->status);
  3416. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3417. EXPECT_TRUE(captured_authorization.empty());
  3418. }
  3419. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3420. TestDoNotForwardCredentialsOnRedirect(
  3421. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3422. }
  3423. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3424. TestDoNotForwardCredentialsOnRedirect(
  3425. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3426. }
  3427. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3428. std::string captured_cookie;
  3429. auto result = GetThroughRedirectToDifferentPort(
  3430. [&](const Request &req, Response &res) {
  3431. captured_cookie = req.get_header_value("Cookie");
  3432. res.set_content("OK", "text/plain");
  3433. },
  3434. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3435. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3436. EXPECT_EQ(StatusCode::OK_200, result->status);
  3437. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3438. EXPECT_TRUE(captured_cookie.empty());
  3439. }
  3440. TEST(RedirectToSamePort, ForwardCookie) {
  3441. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3442. // header so that ordinary session flows keep working.
  3443. Server svr;
  3444. std::string captured_cookie;
  3445. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3446. res.set_redirect("/target", 302);
  3447. });
  3448. svr.Get("/target", [&](const Request &req, Response &res) {
  3449. captured_cookie = req.get_header_value("Cookie");
  3450. res.set_content("OK", "text/plain");
  3451. });
  3452. auto port = svr.bind_to_any_port(HOST);
  3453. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3454. auto se = detail::scope_exit([&] {
  3455. svr.stop();
  3456. thread.join();
  3457. ASSERT_FALSE(svr.is_running());
  3458. });
  3459. svr.wait_until_ready();
  3460. Client cli(HOST, port);
  3461. cli.set_follow_location(true);
  3462. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3463. auto res = cli.Get("/redir", headers);
  3464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3465. EXPECT_EQ(StatusCode::OK_200, res->status);
  3466. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3467. }
  3468. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3469. std::string authorization;
  3470. std::string trace_id;
  3471. auto result = GetThroughRedirectToDifferentPort(
  3472. [&](const Request &req, Response &res) {
  3473. authorization = req.get_header_value("Authorization");
  3474. trace_id = req.get_header_value("X-Trace-Id");
  3475. res.set_content("OK", "text/plain");
  3476. },
  3477. [](Client &cli) {
  3478. cli.set_default_headers(
  3479. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3480. });
  3481. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3482. EXPECT_EQ(StatusCode::OK_200, result->status);
  3483. // Like a header given with the request, a default one goes along unless it
  3484. // carries credentials (RFC 9110 15.4).
  3485. EXPECT_TRUE(authorization.empty());
  3486. EXPECT_EQ("42", trace_id);
  3487. }
  3488. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3489. auto result = GetThroughRedirectToDifferentPort(
  3490. [](const Request &, Response &res) {
  3491. res.set_content(std::string(2048, 'x'), "text/plain");
  3492. },
  3493. [](Client &cli) { cli.set_payload_max_length(1024); });
  3494. EXPECT_FALSE(result);
  3495. }
  3496. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3497. auto result = GetThroughRedirectToDifferentPort(
  3498. [](const Request &req, Response &res) {
  3499. // Answer after a second, or once the client gives up.
  3500. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3501. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3502. }
  3503. res.set_content("late", "text/plain");
  3504. },
  3505. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3506. ASSERT_FALSE(result);
  3507. EXPECT_EQ(Error::Read, result.error());
  3508. }
  3509. #ifdef CPPHTTPLIB_SSL_ENABLED
  3510. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3511. auto result = GetThroughRedirectToDifferentPort(
  3512. [](const Request &, Response &res) {
  3513. res.status = StatusCode::Unauthorized_401;
  3514. res.set_header("WWW-Authenticate",
  3515. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3516. },
  3517. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3518. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3519. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3520. }
  3521. #endif
  3522. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3523. Server svr;
  3524. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3525. // Port number that overflows int — should not crash
  3526. res.set_redirect("http://localhost:99999999999999999999/target");
  3527. });
  3528. auto port = svr.bind_to_any_port(HOST);
  3529. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3530. auto se = detail::scope_exit([&] {
  3531. svr.stop();
  3532. thread.join();
  3533. ASSERT_FALSE(svr.is_running());
  3534. });
  3535. svr.wait_until_ready();
  3536. Client cli(HOST, port);
  3537. cli.set_follow_location(true);
  3538. auto res = cli.Get("/redir");
  3539. // Should fail gracefully, not crash (no valid response due to bad port)
  3540. EXPECT_FALSE(res);
  3541. }
  3542. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3543. Server svr;
  3544. auto port = svr.bind_to_any_port(HOST);
  3545. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3546. // The server's own port followed by junk must not be followed
  3547. res.set_redirect("http://" + std::string(HOST) + ":" +
  3548. std::to_string(port) + "junk/target");
  3549. });
  3550. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3551. res.set_content("target", "text/plain");
  3552. });
  3553. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3554. auto se = detail::scope_exit([&] {
  3555. svr.stop();
  3556. thread.join();
  3557. ASSERT_FALSE(svr.is_running());
  3558. });
  3559. svr.wait_until_ready();
  3560. Client cli(HOST, port);
  3561. cli.set_follow_location(true);
  3562. auto res = cli.Get("/redir");
  3563. EXPECT_FALSE(res);
  3564. }
  3565. TEST(RedirectFromPageWithContent, Redirect) {
  3566. Server svr;
  3567. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3568. res.set_content("___", "text/plain");
  3569. res.set_redirect("/2");
  3570. });
  3571. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3572. res.set_content("Hello World!", "text/plain");
  3573. });
  3574. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3575. auto se = detail::scope_exit([&] {
  3576. svr.stop();
  3577. th.join();
  3578. ASSERT_FALSE(svr.is_running());
  3579. });
  3580. svr.wait_until_ready();
  3581. {
  3582. Client cli("localhost", PORT);
  3583. cli.set_follow_location(true);
  3584. std::string body;
  3585. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3586. body.append(data, data_length);
  3587. return true;
  3588. });
  3589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3590. EXPECT_EQ(StatusCode::OK_200, res->status);
  3591. EXPECT_EQ("Hello World!", body);
  3592. }
  3593. {
  3594. Client cli("localhost", PORT);
  3595. std::string body;
  3596. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3597. body.append(data, data_length);
  3598. return true;
  3599. });
  3600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3601. EXPECT_EQ(StatusCode::Found_302, res->status);
  3602. EXPECT_EQ("___", body);
  3603. }
  3604. }
  3605. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3606. Server svr;
  3607. auto port_str = std::to_string(PORT);
  3608. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3609. auto expected_host = "[::1]:" + port_str;
  3610. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3611. res.set_content("___", "text/plain");
  3612. // res.set_redirect("/2");
  3613. res.set_redirect(redirect_url);
  3614. });
  3615. svr.Get("/2", [&](const Request &req, Response &res) {
  3616. auto host_header = req.headers.find("Host");
  3617. ASSERT_TRUE(host_header != req.headers.end());
  3618. EXPECT_EQ(expected_host, host_header->second);
  3619. res.set_content("Hello World!", "text/plain");
  3620. });
  3621. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3622. auto se = detail::scope_exit([&] {
  3623. svr.stop();
  3624. th.join();
  3625. ASSERT_FALSE(svr.is_running());
  3626. });
  3627. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3628. // actually starts anything, so the condition !svr.is_running() will
  3629. // always remain true, and the loop never stops.
  3630. // This basically counts how many milliseconds have passed since the
  3631. // call to svr.listen(), and if after 5 seconds nothing started yet
  3632. // aborts the test.
  3633. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3634. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3635. ASSERT_LT(milliseconds, 5000U);
  3636. }
  3637. {
  3638. Client cli("::1", PORT);
  3639. cli.set_follow_location(true);
  3640. std::string body;
  3641. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3642. body.append(data, data_length);
  3643. return true;
  3644. });
  3645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3646. EXPECT_EQ(StatusCode::OK_200, res->status);
  3647. EXPECT_EQ("Hello World!", body);
  3648. }
  3649. {
  3650. Client cli("::1", PORT);
  3651. std::string body;
  3652. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3653. body.append(data, data_length);
  3654. return true;
  3655. });
  3656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3657. EXPECT_EQ(StatusCode::Found_302, res->status);
  3658. EXPECT_EQ("___", body);
  3659. }
  3660. }
  3661. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3662. Server svr;
  3663. svr.Get("/foo", [](const Request &req, Response &res) {
  3664. auto a = req.params.find("a");
  3665. if (a != req.params.end()) {
  3666. res.set_content((*a).second, "text/plain");
  3667. res.status = StatusCode::OK_200;
  3668. } else {
  3669. res.status = StatusCode::BadRequest_400;
  3670. }
  3671. });
  3672. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3673. auto se = detail::scope_exit([&] {
  3674. svr.stop();
  3675. thread.join();
  3676. ASSERT_FALSE(svr.is_running());
  3677. });
  3678. svr.wait_until_ready();
  3679. {
  3680. Client cli(HOST, PORT);
  3681. cli.set_path_encode(false);
  3682. auto res = cli.Get("/foo?a=explicitly+encoded");
  3683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3684. EXPECT_EQ(StatusCode::OK_200, res->status);
  3685. // This expects it back with a space, as the `+` won't have been
  3686. // url-encoded, and server-side the params get decoded turning `+`
  3687. // into spaces.
  3688. EXPECT_EQ("explicitly encoded", res->body);
  3689. }
  3690. }
  3691. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3692. // When path encoding is disabled the client must transmit the supplied
  3693. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3694. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3695. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3696. // than a space (0x20). Assert on the raw wire target to catch this.
  3697. Server svr;
  3698. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3699. svr.Get("/foo", [&](const Request &req, Response &res) {
  3700. EXPECT_EQ(expected_target, req.target);
  3701. res.status = StatusCode::OK_200;
  3702. });
  3703. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3704. auto se = detail::scope_exit([&] {
  3705. svr.stop();
  3706. thread.join();
  3707. ASSERT_FALSE(svr.is_running());
  3708. });
  3709. svr.wait_until_ready();
  3710. {
  3711. Client cli(HOST, PORT);
  3712. cli.set_path_encode(false);
  3713. auto res = cli.Get(expected_target.c_str());
  3714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3715. EXPECT_EQ(StatusCode::OK_200, res->status);
  3716. }
  3717. }
  3718. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3719. // `open_stream()` used to skip the path encoding that the buffered send
  3720. // path applies, so the same `path` produced different bytes in the request
  3721. // line depending on which API was used. Assert the two agree.
  3722. Server svr;
  3723. std::string target;
  3724. svr.Get(".*", [&](const Request &req, Response &res) {
  3725. target = req.target;
  3726. res.status = StatusCode::OK_200;
  3727. });
  3728. auto port = svr.bind_to_any_port(HOST);
  3729. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3730. auto se = detail::scope_exit([&] {
  3731. svr.stop();
  3732. thread.join();
  3733. ASSERT_FALSE(svr.is_running());
  3734. });
  3735. svr.wait_until_ready();
  3736. struct {
  3737. const char *path;
  3738. const char *expected;
  3739. } cases[] = {
  3740. {"/a b?x=1", "/a%20b?x=1"},
  3741. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3742. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3743. };
  3744. for (const auto &c : cases) {
  3745. Client cli(HOST, port);
  3746. target.clear();
  3747. auto res = cli.Get(c.path);
  3748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3749. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3750. auto buffered_target = target;
  3751. target.clear();
  3752. auto handle = cli.open_stream("GET", c.path);
  3753. EXPECT_TRUE(handle.is_valid())
  3754. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3755. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3756. }
  3757. }
  3758. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3759. // The `set_path_encode(false)` contract — transmit the supplied target
  3760. // verbatim — must hold for the streaming API too.
  3761. Server svr;
  3762. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3763. std::string target;
  3764. svr.Get("/foo", [&](const Request &req, Response &res) {
  3765. target = req.target;
  3766. res.status = StatusCode::OK_200;
  3767. });
  3768. auto port = svr.bind_to_any_port(HOST);
  3769. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3770. auto se = detail::scope_exit([&] {
  3771. svr.stop();
  3772. thread.join();
  3773. ASSERT_FALSE(svr.is_running());
  3774. });
  3775. svr.wait_until_ready();
  3776. {
  3777. Client cli(HOST, port);
  3778. cli.set_path_encode(false);
  3779. auto handle = cli.open_stream("GET", expected_target);
  3780. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3781. EXPECT_EQ(expected_target, target);
  3782. }
  3783. }
  3784. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3785. // With path encoding enabled a CR/LF in the target is percent-encoded
  3786. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3787. // write_request_line still backstops `set_path_encode(false)`, which is
  3788. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3789. Server svr;
  3790. // Captured before routing: the decoded path contains a newline, which a
  3791. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3792. std::string target;
  3793. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3794. target = req.target;
  3795. res.status = StatusCode::OK_200;
  3796. return Server::HandlerResponse::Handled;
  3797. });
  3798. auto port = svr.bind_to_any_port(HOST);
  3799. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3800. auto se = detail::scope_exit([&] {
  3801. svr.stop();
  3802. thread.join();
  3803. ASSERT_FALSE(svr.is_running());
  3804. });
  3805. svr.wait_until_ready();
  3806. {
  3807. Client cli(HOST, port);
  3808. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3809. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3810. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3811. }
  3812. }
  3813. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3814. // Every control character is percent-encoded, not just CR/LF, so the target
  3815. // passes the request-target check in write_request_line.
  3816. Server svr;
  3817. std::string target;
  3818. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3819. target = req.target;
  3820. res.status = StatusCode::OK_200;
  3821. return Server::HandlerResponse::Handled;
  3822. });
  3823. auto port = svr.bind_to_any_port(HOST);
  3824. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3825. auto se = detail::scope_exit([&] {
  3826. svr.stop();
  3827. thread.join();
  3828. ASSERT_FALSE(svr.is_running());
  3829. });
  3830. svr.wait_until_ready();
  3831. {
  3832. Client cli(HOST, port);
  3833. auto res = cli.Get("/a\tb\x1b\x7f");
  3834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3835. EXPECT_EQ("/a%09b%1B%7F", target);
  3836. }
  3837. }
  3838. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3839. // Nothing may reach the wire: a raw CR/LF target would split the request
  3840. // line and inject headers.
  3841. Server svr;
  3842. // Pre-routing so that "not called" means nothing reached the server at all,
  3843. // rather than merely failing to match a handler pattern.
  3844. auto handler_called = false;
  3845. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3846. handler_called = true;
  3847. res.status = StatusCode::OK_200;
  3848. return Server::HandlerResponse::Handled;
  3849. });
  3850. auto port = svr.bind_to_any_port(HOST);
  3851. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3852. auto se = detail::scope_exit([&] {
  3853. svr.stop();
  3854. thread.join();
  3855. ASSERT_FALSE(svr.is_running());
  3856. });
  3857. svr.wait_until_ready();
  3858. {
  3859. Client cli(HOST, port);
  3860. cli.set_path_encode(false);
  3861. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3862. EXPECT_FALSE(handle.is_valid());
  3863. EXPECT_EQ(Error::Write, handle.error);
  3864. EXPECT_FALSE(handler_called);
  3865. }
  3866. }
  3867. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3868. // Which of the two branches runs is decided by whether the query component
  3869. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3870. // an empty query and must still fall back to building one from
  3871. // `req.params`, while a non-empty query must win over `req.params`.
  3872. Server svr;
  3873. std::string target;
  3874. svr.Get("/foo", [&](const Request &req, Response &res) {
  3875. target = req.target;
  3876. res.status = StatusCode::OK_200;
  3877. });
  3878. auto port = svr.bind_to_any_port(HOST);
  3879. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3880. auto se = detail::scope_exit([&] {
  3881. svr.stop();
  3882. thread.join();
  3883. ASSERT_FALSE(svr.is_running());
  3884. });
  3885. svr.wait_until_ready();
  3886. {
  3887. // Trailing `?` -> empty query component -> `req.params` is used.
  3888. Client cli(HOST, port);
  3889. Request req;
  3890. req.method = "GET";
  3891. req.path = "/foo?";
  3892. req.params.emplace("a", "1");
  3893. target.clear();
  3894. auto res = cli.send(req);
  3895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3896. EXPECT_EQ("/foo?a=1", target);
  3897. }
  3898. {
  3899. // Non-empty query in `req.path` -> `req.params` is not appended.
  3900. Client cli(HOST, port);
  3901. Request req;
  3902. req.method = "GET";
  3903. req.path = "/foo?b=2";
  3904. req.params.emplace("a", "1");
  3905. target.clear();
  3906. auto res = cli.send(req);
  3907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3908. EXPECT_EQ("/foo?b=2", target);
  3909. }
  3910. }
  3911. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3912. Server svr;
  3913. svr.Get("/", [](const Request &req, Response &) {
  3914. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3915. });
  3916. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3917. auto se = detail::scope_exit([&] {
  3918. svr.stop();
  3919. thread.join();
  3920. ASSERT_FALSE(svr.is_running());
  3921. });
  3922. svr.wait_until_ready();
  3923. {
  3924. Client cli(HOST, PORT);
  3925. cli.set_path_encode(false);
  3926. auto res = cli.Get("/?something=%0A");
  3927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3928. EXPECT_EQ(StatusCode::OK_200, res->status);
  3929. }
  3930. }
  3931. TEST(BindServerTest, BindDualStack) {
  3932. Server svr;
  3933. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3934. res.set_content("Hello World!", "text/plain");
  3935. });
  3936. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3937. auto se = detail::scope_exit([&] {
  3938. svr.stop();
  3939. thread.join();
  3940. ASSERT_FALSE(svr.is_running());
  3941. });
  3942. svr.wait_until_ready();
  3943. {
  3944. Client cli("127.0.0.1", PORT);
  3945. auto res = cli.Get("/1");
  3946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3947. EXPECT_EQ(StatusCode::OK_200, res->status);
  3948. EXPECT_EQ("Hello World!", res->body);
  3949. }
  3950. {
  3951. Client cli("::1", PORT);
  3952. auto res = cli.Get("/1");
  3953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3954. EXPECT_EQ(StatusCode::OK_200, res->status);
  3955. EXPECT_EQ("Hello World!", res->body);
  3956. }
  3957. }
  3958. TEST(BindServerTest, BindAndListenSeparately) {
  3959. Server svr;
  3960. int port = svr.bind_to_any_port("0.0.0.0");
  3961. ASSERT_TRUE(svr.is_valid());
  3962. ASSERT_TRUE(port > 0);
  3963. svr.stop();
  3964. }
  3965. // Reports whether anything is still listening on a loopback port. A plain
  3966. // connect() is used instead of a Client request because a socket left bound by
  3967. // mistake accepts the connection into its backlog and never answers, which
  3968. // would hang the test instead of failing it.
  3969. static bool is_loopback_port_accepting(int port) {
  3970. sockaddr_in addr{};
  3971. addr.sin_family = AF_INET;
  3972. addr.sin_port = htons(static_cast<uint16_t>(port));
  3973. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3974. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3975. EXPECT_NE(sock, INVALID_SOCKET);
  3976. if (sock == INVALID_SOCKET) { return false; }
  3977. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3978. static_cast<socklen_t>(sizeof(addr)));
  3979. detail::close_socket(sock);
  3980. return ret == 0;
  3981. }
  3982. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3983. Server svr;
  3984. auto port = svr.bind_to_any_port("127.0.0.1");
  3985. ASSERT_TRUE(port > 0);
  3986. svr.stop();
  3987. // bind_to_any_port() already called listen(2), so until stop() closed the
  3988. // descriptor the port kept accepting connections into the backlog. ASSERT
  3989. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3990. // below blocks forever in the accept loop.
  3991. ASSERT_FALSE(is_loopback_port_accepting(port));
  3992. // Nothing is left to accept on, so listen_after_bind() must report failure
  3993. // instead of returning success without ever serving.
  3994. EXPECT_FALSE(svr.listen_after_bind());
  3995. // The failed listen marks the server decommissioned, so a waiter returns
  3996. // instead of spinning forever.
  3997. svr.wait_until_ready();
  3998. }
  3999. #ifdef CPPHTTPLIB_SSL_ENABLED
  4000. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4001. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4002. CLIENT_CA_CERT_DIR);
  4003. int port = svr.bind_to_any_port("0.0.0.0");
  4004. ASSERT_TRUE(svr.is_valid());
  4005. ASSERT_TRUE(port > 0);
  4006. svr.stop();
  4007. }
  4008. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4009. // or a rejected CustomRoute() registration would not stop the server binding.
  4010. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4011. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4012. CLIENT_CA_CERT_DIR);
  4013. ASSERT_TRUE(svr.is_valid());
  4014. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4015. EXPECT_FALSE(svr.is_valid());
  4016. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4017. }
  4018. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4019. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4020. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4021. int port = svr.bind_to_any_port("0.0.0.0");
  4022. ASSERT_TRUE(svr.is_valid());
  4023. ASSERT_TRUE(port > 0);
  4024. svr.stop();
  4025. }
  4026. TEST(BindServerTest, UpdateCertsPem) {
  4027. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4028. int port = svr.bind_to_any_port("0.0.0.0");
  4029. ASSERT_TRUE(svr.is_valid());
  4030. ASSERT_TRUE(port > 0);
  4031. // Read PEM files
  4032. std::string cert_pem, key_pem, ca_pem;
  4033. read_file(SERVER_CERT_FILE, cert_pem);
  4034. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4035. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4036. // Update server certificates using PEM API
  4037. ASSERT_TRUE(
  4038. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4039. ASSERT_TRUE(svr.is_valid());
  4040. svr.stop();
  4041. }
  4042. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4043. // Start server with client CA (enables client auth)
  4044. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4045. ASSERT_TRUE(svr.is_valid());
  4046. bool handler_called = false;
  4047. svr.Get("/test", [&](const Request &req, Response &res) {
  4048. handler_called = true;
  4049. // Verify client certificate is present
  4050. auto cert = req.peer_cert();
  4051. EXPECT_TRUE(static_cast<bool>(cert));
  4052. res.set_content("ok", "text/plain");
  4053. });
  4054. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4055. auto se = detail::scope_exit([&] {
  4056. svr.stop();
  4057. t.join();
  4058. ASSERT_FALSE(svr.is_running());
  4059. });
  4060. svr.wait_until_ready();
  4061. // Read PEM files
  4062. std::string cert_pem, key_pem, ca_pem;
  4063. read_file(SERVER_CERT_FILE, cert_pem);
  4064. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4065. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4066. // Update server certificates and client CA using PEM API while server running
  4067. ASSERT_TRUE(
  4068. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4069. // Connect with client certificate
  4070. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4071. cli.enable_server_certificate_verification(false);
  4072. cli.set_connection_timeout(30);
  4073. auto res = cli.Get("/test");
  4074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4075. ASSERT_EQ(StatusCode::OK_200, res->status);
  4076. ASSERT_TRUE(handler_called);
  4077. EXPECT_EQ("ok", res->body);
  4078. }
  4079. // Puts a CA that did not sign the client's certificate in the old one's place.
  4080. static bool replace_client_ca(SSLServer &svr) {
  4081. std::string cert_pem, key_pem, ca_pem;
  4082. read_file(SERVER_CERT_FILE, cert_pem);
  4083. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4084. read_file(SERVER_CERT2_FILE, ca_pem);
  4085. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4086. ca_pem.c_str());
  4087. }
  4088. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4089. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4090. ASSERT_TRUE(svr.is_valid());
  4091. svr.Get("/test", [](const Request &, Response &res) {
  4092. res.set_content("ok", "text/plain");
  4093. });
  4094. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4095. auto se = detail::scope_exit([&] {
  4096. svr.stop();
  4097. t.join();
  4098. ASSERT_FALSE(svr.is_running());
  4099. });
  4100. svr.wait_until_ready();
  4101. auto get = [] {
  4102. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4103. cli.enable_server_certificate_verification(false);
  4104. return cli.Get("/test");
  4105. };
  4106. ASSERT_TRUE(get());
  4107. ASSERT_TRUE(replace_client_ca(svr));
  4108. EXPECT_FALSE(get());
  4109. }
  4110. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4111. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4112. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4113. ASSERT_TRUE(svr.is_valid());
  4114. tls::set_verify_callback(svr.tls_context(),
  4115. [](const tls::VerifyContext &) -> bool {
  4116. throw std::runtime_error("verify");
  4117. });
  4118. svr.Get("/test", [](const Request &, Response &res) {
  4119. res.set_content("ok", "text/plain");
  4120. });
  4121. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4122. auto se = detail::scope_exit([&] {
  4123. svr.stop();
  4124. t.join();
  4125. ASSERT_FALSE(svr.is_running());
  4126. });
  4127. svr.wait_until_ready();
  4128. auto get = [] {
  4129. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4130. cli.enable_server_certificate_verification(false);
  4131. return cli.Get("/test");
  4132. };
  4133. EXPECT_FALSE(get());
  4134. // The handshake is over, so an update does not wait for it.
  4135. std::string cert_pem, key_pem;
  4136. read_file(SERVER_CERT_FILE, cert_pem);
  4137. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4138. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4139. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4140. return v.preverify_ok;
  4141. });
  4142. auto res = get();
  4143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4144. EXPECT_EQ("ok", res->body);
  4145. }
  4146. #endif
  4147. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4148. // Sends each request over a new connection with a client certificate,
  4149. // resuming the session of the one before when there is one.
  4150. class ResumingClient {
  4151. public:
  4152. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4153. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4154. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4155. SSL_FILETYPE_PEM);
  4156. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4157. // callback, not through SSL_get1_session().
  4158. SSL_CTX_set_app_data(ctx_, this);
  4159. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4160. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4161. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4162. auto self = static_cast<ResumingClient *>(
  4163. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4164. SSL_SESSION_free(self->session_);
  4165. self->session_ = session;
  4166. return 1; // Keeps the reference
  4167. });
  4168. }
  4169. ~ResumingClient() {
  4170. SSL_SESSION_free(session_);
  4171. SSL_CTX_free(ctx_);
  4172. }
  4173. // Tells whether the request was answered.
  4174. bool get() {
  4175. auto error = Error::Success;
  4176. auto sock = detail::create_client_socket(
  4177. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4178. /*connection_timeout_sec=*/5, 0,
  4179. /*read_timeout_sec=*/5, 0,
  4180. /*write_timeout_sec=*/5, 0, std::string(), error);
  4181. if (sock == INVALID_SOCKET) { return false; }
  4182. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4183. auto ssl = SSL_new(ctx_);
  4184. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4185. SSL_set_fd(ssl, static_cast<int>(sock));
  4186. if (session_) { SSL_set_session(ssl, session_); }
  4187. if (SSL_connect(ssl) != 1) { return false; }
  4188. reused_ = SSL_session_reused(ssl) == 1;
  4189. // Reading the response also takes in a TLS 1.3 session ticket.
  4190. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4191. "Connection: close\r\n\r\n";
  4192. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4193. std::string res;
  4194. char buf[256];
  4195. int n;
  4196. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4197. res.append(buf, static_cast<size_t>(n));
  4198. }
  4199. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4200. SSL_shutdown(ssl);
  4201. return res.find("200 OK") != std::string::npos;
  4202. }
  4203. // Whether the last connection resumed a session
  4204. bool reused() const { return reused_; }
  4205. private:
  4206. SSL_CTX *ctx_;
  4207. SSL_SESSION *session_ = nullptr;
  4208. bool reused_ = false;
  4209. };
  4210. // A client that resumes its session gets through, but not once the client CA
  4211. // has changed, as a resumed session does not show the certificate again.
  4212. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4213. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4214. ASSERT_TRUE(svr.is_valid());
  4215. svr.Get("/test", [](const Request &, Response &res) {
  4216. res.set_content("ok", "text/plain");
  4217. });
  4218. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4219. auto se = detail::scope_exit([&] {
  4220. svr.stop();
  4221. t.join();
  4222. ASSERT_FALSE(svr.is_running());
  4223. });
  4224. svr.wait_until_ready();
  4225. ResumingClient cli;
  4226. ASSERT_TRUE(cli.get());
  4227. ASSERT_TRUE(cli.get());
  4228. EXPECT_TRUE(cli.reused());
  4229. ASSERT_TRUE(replace_client_ca(svr));
  4230. EXPECT_FALSE(cli.get());
  4231. }
  4232. // A resumed session does not show the certificate again, so the server does
  4233. // not resume one with a verify callback to run on it.
  4234. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4235. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4236. ASSERT_TRUE(svr.is_valid());
  4237. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4238. return v.preverify_ok;
  4239. });
  4240. svr.Get("/test", [](const Request &, Response &res) {
  4241. res.set_content("ok", "text/plain");
  4242. });
  4243. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4244. auto se = detail::scope_exit([&] {
  4245. svr.stop();
  4246. t.join();
  4247. ASSERT_FALSE(svr.is_running());
  4248. });
  4249. svr.wait_until_ready();
  4250. ResumingClient cli;
  4251. ASSERT_TRUE(cli.get());
  4252. ASSERT_TRUE(cli.get());
  4253. EXPECT_FALSE(cli.reused());
  4254. }
  4255. #endif
  4256. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4257. // wolfSSL shares its session cache between contexts, so a resumed session
  4258. // could carry a client certificate checked against another server's CA, or
  4259. // against a client CA since replaced.
  4260. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4261. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4262. ASSERT_TRUE(svr.is_valid());
  4263. // Trusts a CA that did not sign the client's certificate.
  4264. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4265. ASSERT_TRUE(other.is_valid());
  4266. for (auto s : {&svr, &other}) {
  4267. s->Get("/test", [](const Request &, Response &res) {
  4268. res.set_content("ok", "text/plain");
  4269. });
  4270. }
  4271. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4272. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4273. auto se = detail::scope_exit([&] {
  4274. other.stop();
  4275. svr.stop();
  4276. t2.join();
  4277. t.join();
  4278. });
  4279. svr.wait_until_ready();
  4280. other.wait_until_ready();
  4281. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4282. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4283. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4284. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4285. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4286. ASSERT_EQ(WOLFSSL_SUCCESS,
  4287. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4288. WOLFSSL_FILETYPE_PEM));
  4289. WOLFSSL_SESSION *session = nullptr;
  4290. auto session_se = detail::scope_exit([&] {
  4291. if (session) { wolfSSL_SESSION_free(session); }
  4292. });
  4293. // A request over a new connection, resuming `session` when there is one and
  4294. // keeping the connection's own in its place. Tells whether it was answered.
  4295. auto get = [&](int port) {
  4296. auto error = Error::Success;
  4297. auto sock = detail::create_client_socket(
  4298. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4299. /*connection_timeout_sec=*/5, 0,
  4300. /*read_timeout_sec=*/5, 0,
  4301. /*write_timeout_sec=*/5, 0, std::string(), error);
  4302. if (sock == INVALID_SOCKET) { return false; }
  4303. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4304. auto ssl = wolfSSL_new(ctx);
  4305. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4306. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4307. if (session) { wolfSSL_set_session(ssl, session); }
  4308. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4309. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4310. "Connection: close\r\n\r\n";
  4311. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4312. std::string res;
  4313. char buf[256];
  4314. int n;
  4315. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4316. res.append(buf, static_cast<size_t>(n));
  4317. }
  4318. wolfSSL_shutdown(ssl);
  4319. if (session) { wolfSSL_SESSION_free(session); }
  4320. session = wolfSSL_get1_session(ssl);
  4321. return res.find("200 OK") != std::string::npos;
  4322. };
  4323. ASSERT_TRUE(get(PORT));
  4324. EXPECT_FALSE(get(PORT + 1));
  4325. ASSERT_TRUE(get(PORT));
  4326. ASSERT_TRUE(replace_client_ca(svr));
  4327. EXPECT_FALSE(get(PORT));
  4328. }
  4329. #endif
  4330. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4331. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4332. ASSERT_TRUE(svr.is_valid());
  4333. svr.Get("/test", [](const Request &, Response &res) {
  4334. res.set_content("ok", "text/plain");
  4335. });
  4336. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4337. auto se = detail::scope_exit([&] {
  4338. svr.stop();
  4339. t.join();
  4340. ASSERT_FALSE(svr.is_running());
  4341. });
  4342. svr.wait_until_ready();
  4343. // A connection that sends no ClientHello keeps its handshake in progress,
  4344. // once the server has had a moment to start it.
  4345. auto error = Error::Success;
  4346. auto sock = detail::create_client_socket(
  4347. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4348. /*connection_timeout_sec=*/5, 0,
  4349. /*read_timeout_sec=*/5, 0,
  4350. /*write_timeout_sec=*/5, 0, std::string(), error);
  4351. ASSERT_NE(INVALID_SOCKET, sock);
  4352. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4353. std::string cert_pem, key_pem;
  4354. read_file(SERVER_CERT_FILE, cert_pem);
  4355. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4356. auto update = std::async(std::launch::async, [&]() {
  4357. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4358. });
  4359. EXPECT_EQ(std::future_status::timeout,
  4360. update.wait_for(std::chrono::milliseconds(200)));
  4361. detail::close_socket(sock);
  4362. EXPECT_TRUE(update.get());
  4363. SSLClient cli(HOST, PORT);
  4364. cli.enable_server_certificate_verification(false);
  4365. auto res = cli.Get("/test");
  4366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4367. EXPECT_EQ(StatusCode::OK_200, res->status);
  4368. }
  4369. #endif
  4370. TEST(ErrorHandlerTest, ContentLength) {
  4371. Server svr;
  4372. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4373. res.status = StatusCode::OK_200;
  4374. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4375. "text/html"); // <= Content-Length still 13
  4376. });
  4377. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4378. res.set_content("Hello World!\n", "text/plain");
  4379. res.status = 524;
  4380. });
  4381. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4382. auto se = detail::scope_exit([&] {
  4383. svr.stop();
  4384. thread.join();
  4385. ASSERT_FALSE(svr.is_running());
  4386. });
  4387. svr.wait_until_ready();
  4388. {
  4389. Client cli(HOST, PORT);
  4390. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4392. EXPECT_EQ(StatusCode::OK_200, res->status);
  4393. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4394. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4395. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4396. }
  4397. }
  4398. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4399. TEST(ExceptionTest, WithoutExceptionHandler) {
  4400. Server svr;
  4401. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4402. throw std::runtime_error("exception...");
  4403. });
  4404. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4405. throw std::runtime_error("exception\r\n...");
  4406. });
  4407. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4408. auto se = detail::scope_exit([&] {
  4409. svr.stop();
  4410. listen_thread.join();
  4411. ASSERT_FALSE(svr.is_running());
  4412. });
  4413. svr.wait_until_ready();
  4414. Client cli("localhost", PORT);
  4415. {
  4416. auto res = cli.Get("/exception");
  4417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4418. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4419. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4420. }
  4421. {
  4422. auto res = cli.Get("/unknown");
  4423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4424. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4425. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4426. }
  4427. }
  4428. TEST(ExceptionTest, WithExceptionHandler) {
  4429. Server svr;
  4430. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4431. std::exception_ptr ep) {
  4432. EXPECT_FALSE(ep == nullptr);
  4433. try {
  4434. std::rethrow_exception(ep);
  4435. } catch (std::exception &e) {
  4436. EXPECT_EQ("abc", std::string(e.what()));
  4437. } catch (...) {}
  4438. res.status = StatusCode::InternalServerError_500;
  4439. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4440. "text/html"); // <= Content-Length still 13 at this point
  4441. });
  4442. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4443. res.set_content("Hello World!\n", "text/plain");
  4444. throw std::runtime_error("abc");
  4445. });
  4446. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4447. auto se = detail::scope_exit([&] {
  4448. svr.stop();
  4449. thread.join();
  4450. ASSERT_FALSE(svr.is_running());
  4451. });
  4452. svr.wait_until_ready();
  4453. for (size_t i = 0; i < 10; i++) {
  4454. Client cli(HOST, PORT);
  4455. for (size_t j = 0; j < 100; j++) {
  4456. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4458. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4459. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4460. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4461. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4462. }
  4463. cli.set_keep_alive(true);
  4464. for (size_t j = 0; j < 100; j++) {
  4465. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4467. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4468. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4469. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4470. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4471. }
  4472. }
  4473. }
  4474. TEST(ExceptionTest, AndErrorHandler) {
  4475. Server svr;
  4476. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4477. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4478. });
  4479. svr.set_exception_handler(
  4480. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4481. EXPECT_FALSE(ep == nullptr);
  4482. try {
  4483. std::rethrow_exception(ep);
  4484. } catch (std::exception &e) {
  4485. res.set_content(e.what(), "text/html");
  4486. } catch (...) {}
  4487. res.status = StatusCode::InternalServerError_500;
  4488. });
  4489. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4490. throw std::runtime_error("EXCEPTION");
  4491. });
  4492. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4493. res.set_content("ERROR", "text/html");
  4494. res.status = StatusCode::InternalServerError_500;
  4495. });
  4496. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4497. auto se = detail::scope_exit([&] {
  4498. svr.stop();
  4499. thread.join();
  4500. ASSERT_FALSE(svr.is_running());
  4501. });
  4502. svr.wait_until_ready();
  4503. Client cli(HOST, PORT);
  4504. {
  4505. auto res = cli.Get("/exception");
  4506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4507. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4508. EXPECT_EQ("EXCEPTION", res->body);
  4509. }
  4510. {
  4511. auto res = cli.Get("/error");
  4512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4513. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4514. EXPECT_EQ("ERROR", res->body);
  4515. }
  4516. {
  4517. auto res = cli.Get("/invalid");
  4518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4519. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4520. EXPECT_EQ("NOT_FOUND", res->body);
  4521. }
  4522. }
  4523. #endif
  4524. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4525. // process_request() wraps only routing() in a try/catch, so an exception from
  4526. // any other user callback used to unwind into the task queue - which does not
  4527. // catch - and terminate the process. Each test below runs the server on a
  4528. // single worker thread: a guard that catches the exception but still loses the
  4529. // thread would otherwise be hidden by a spare worker serving the follow-up
  4530. // request. Note that a regression here aborts the whole test binary rather
  4531. // than failing one test.
  4532. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4533. Server svr;
  4534. svr.new_task_queue = [] { return new ThreadPool(1); };
  4535. std::atomic<int> reported{0};
  4536. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4537. if (err == Error::UserCallbackException) { reported++; }
  4538. });
  4539. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4540. res.set_content_provider(
  4541. 1024, "text/plain",
  4542. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4543. sink.write("hello", 5);
  4544. throw std::runtime_error("from the content provider");
  4545. });
  4546. });
  4547. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4548. res.set_content("ok", "text/plain");
  4549. });
  4550. auto port = svr.bind_to_any_port(HOST);
  4551. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4552. auto se = detail::scope_exit([&] {
  4553. svr.stop();
  4554. listen_thread.join();
  4555. ASSERT_FALSE(svr.is_running());
  4556. });
  4557. svr.wait_until_ready();
  4558. {
  4559. Client cli(HOST, port);
  4560. cli.set_read_timeout(5, 0);
  4561. EXPECT_FALSE(cli.Get("/throw"));
  4562. }
  4563. EXPECT_TRUE(svr.is_running());
  4564. EXPECT_EQ(1, reported.load());
  4565. // A request on a fresh connection is still served.
  4566. {
  4567. Client cli(HOST, port);
  4568. auto res = cli.Get("/ok");
  4569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4570. EXPECT_EQ(StatusCode::OK_200, res->status);
  4571. EXPECT_EQ("ok", res->body);
  4572. }
  4573. }
  4574. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4575. Server svr;
  4576. svr.new_task_queue = [] { return new ThreadPool(1); };
  4577. std::atomic<bool> should_throw{true};
  4578. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4579. res.set_content("hi", "text/plain");
  4580. });
  4581. svr.set_post_routing_handler(
  4582. [&](const Request & /*req*/, Response & /*res*/) {
  4583. if (should_throw) {
  4584. throw std::runtime_error("from the post-routing handler");
  4585. }
  4586. });
  4587. auto port = svr.bind_to_any_port(HOST);
  4588. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4589. auto se = detail::scope_exit([&] {
  4590. svr.stop();
  4591. listen_thread.join();
  4592. ASSERT_FALSE(svr.is_running());
  4593. });
  4594. svr.wait_until_ready();
  4595. {
  4596. Client cli(HOST, port);
  4597. cli.set_read_timeout(5, 0);
  4598. EXPECT_FALSE(cli.Get("/hi"));
  4599. }
  4600. EXPECT_TRUE(svr.is_running());
  4601. should_throw = false;
  4602. {
  4603. Client cli(HOST, port);
  4604. auto res = cli.Get("/hi");
  4605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4606. EXPECT_EQ(StatusCode::OK_200, res->status);
  4607. EXPECT_EQ("hi", res->body);
  4608. }
  4609. }
  4610. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4611. // The guard reports the caught exception through the error logger, which is
  4612. // a user callback too. A logger that throws has to be contained as well, or
  4613. // the process would terminate from inside the catch.
  4614. Server svr;
  4615. svr.new_task_queue = [] { return new ThreadPool(1); };
  4616. std::atomic<int> reported{0};
  4617. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4618. if (err == Error::UserCallbackException) {
  4619. reported++;
  4620. throw std::runtime_error("from the error logger");
  4621. }
  4622. });
  4623. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4624. res.set_content_provider(
  4625. 1024, "text/plain",
  4626. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4627. sink.write("hello", 5);
  4628. throw std::runtime_error("from the content provider");
  4629. });
  4630. });
  4631. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4632. res.set_content("ok", "text/plain");
  4633. });
  4634. auto port = svr.bind_to_any_port(HOST);
  4635. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4636. auto se = detail::scope_exit([&] {
  4637. svr.stop();
  4638. listen_thread.join();
  4639. ASSERT_FALSE(svr.is_running());
  4640. });
  4641. svr.wait_until_ready();
  4642. {
  4643. Client cli(HOST, port);
  4644. cli.set_read_timeout(5, 0);
  4645. EXPECT_FALSE(cli.Get("/throw"));
  4646. }
  4647. EXPECT_TRUE(svr.is_running());
  4648. EXPECT_EQ(1, reported.load());
  4649. {
  4650. Client cli(HOST, port);
  4651. auto res = cli.Get("/ok");
  4652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4653. EXPECT_EQ(StatusCode::OK_200, res->status);
  4654. EXPECT_EQ("ok", res->body);
  4655. }
  4656. }
  4657. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4658. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4659. // so the exception unwinds through the ws::WebSocket object on its way to
  4660. // the guard. None of the HTTP cases above cross that.
  4661. Server svr;
  4662. svr.new_task_queue = [] { return new ThreadPool(1); };
  4663. std::atomic<int> reported{0};
  4664. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4665. if (err == Error::UserCallbackException) { reported++; }
  4666. });
  4667. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4668. throw std::runtime_error("from the WebSocket handler");
  4669. });
  4670. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4671. res.set_content("ok", "text/plain");
  4672. });
  4673. auto port = svr.bind_to_any_port(HOST);
  4674. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4675. auto se = detail::scope_exit([&] {
  4676. svr.stop();
  4677. listen_thread.join();
  4678. ASSERT_FALSE(svr.is_running());
  4679. });
  4680. svr.wait_until_ready();
  4681. {
  4682. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4683. "/ws");
  4684. auto res = client.connect();
  4685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4686. // The server dropped the connection instead of dying.
  4687. std::string msg;
  4688. EXPECT_FALSE(client.read(msg));
  4689. client.close();
  4690. }
  4691. EXPECT_TRUE(svr.is_running());
  4692. EXPECT_EQ(1, reported.load());
  4693. {
  4694. Client cli(HOST, port);
  4695. auto res = cli.Get("/ok");
  4696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4697. EXPECT_EQ(StatusCode::OK_200, res->status);
  4698. EXPECT_EQ("ok", res->body);
  4699. }
  4700. }
  4701. #ifdef CPPHTTPLIB_SSL_ENABLED
  4702. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4703. // SSLServer::process_and_close_socket() is a separate overload with its own
  4704. // guard, so it is exercised on its own.
  4705. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4706. ASSERT_TRUE(svr.is_valid());
  4707. svr.new_task_queue = [] { return new ThreadPool(1); };
  4708. std::atomic<int> reported{0};
  4709. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4710. if (err == Error::UserCallbackException) { reported++; }
  4711. });
  4712. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4713. res.set_content_provider(
  4714. 1024, "text/plain",
  4715. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4716. sink.write("hello", 5);
  4717. throw std::runtime_error("from the content provider");
  4718. });
  4719. });
  4720. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4721. res.set_content("ok", "text/plain");
  4722. });
  4723. auto port = svr.bind_to_any_port(HOST);
  4724. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4725. auto se = detail::scope_exit([&] {
  4726. svr.stop();
  4727. listen_thread.join();
  4728. ASSERT_FALSE(svr.is_running());
  4729. });
  4730. svr.wait_until_ready();
  4731. {
  4732. SSLClient cli(HOST, port);
  4733. cli.enable_server_certificate_verification(false);
  4734. cli.set_read_timeout(5, 0);
  4735. EXPECT_FALSE(cli.Get("/throw"));
  4736. }
  4737. EXPECT_TRUE(svr.is_running());
  4738. EXPECT_EQ(1, reported.load());
  4739. {
  4740. SSLClient cli(HOST, port);
  4741. cli.enable_server_certificate_verification(false);
  4742. auto res = cli.Get("/ok");
  4743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4744. EXPECT_EQ(StatusCode::OK_200, res->status);
  4745. EXPECT_EQ("ok", res->body);
  4746. }
  4747. }
  4748. #endif
  4749. #endif
  4750. TEST(NoContentTest, ContentLength) {
  4751. Server svr;
  4752. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4753. res.status = StatusCode::NoContent_204;
  4754. });
  4755. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4756. auto se = detail::scope_exit([&] {
  4757. svr.stop();
  4758. thread.join();
  4759. ASSERT_FALSE(svr.is_running());
  4760. });
  4761. svr.wait_until_ready();
  4762. {
  4763. Client cli(HOST, PORT);
  4764. auto res = cli.Get("/hi");
  4765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4766. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4767. // RFC 9110 8.6: none in a 204 response
  4768. EXPECT_FALSE(res->has_header("Content-Length"));
  4769. }
  4770. }
  4771. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4772. Server svr;
  4773. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4774. res.set_header("Content-Length", "5");
  4775. res.set_content("hello world", "text/plain");
  4776. });
  4777. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4778. // A body that reads as the last chunk, were it taken as chunked
  4779. res.set_header("Transfer-Encoding", "chunked");
  4780. res.set_content("0\r\n\r\n", "text/plain");
  4781. });
  4782. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4783. res.set_header("Content-Length", "2");
  4784. res.set_content_provider(5, "text/plain",
  4785. [](size_t offset, size_t length, DataSink &sink) {
  4786. sink.write(&"hello"[offset], length);
  4787. return true;
  4788. });
  4789. });
  4790. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4791. res.set_header("Content-Length", "1234");
  4792. });
  4793. thread t = thread([&] { svr.listen(HOST, PORT); });
  4794. auto se = detail::scope_exit([&] {
  4795. svr.stop();
  4796. t.join();
  4797. ASSERT_FALSE(svr.is_running());
  4798. });
  4799. svr.wait_until_ready();
  4800. Client cli(HOST, PORT);
  4801. cli.set_read_timeout(1, 0);
  4802. auto expect_body = [&](const Result &res, const std::string &body) {
  4803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4804. EXPECT_EQ(body, res->body);
  4805. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4806. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4807. };
  4808. Headers identity{{"Accept-Encoding", ""}};
  4809. expect_body(cli.Get("/body", identity), "hello world");
  4810. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4811. expect_body(cli.Get("/body",
  4812. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4813. "he");
  4814. expect_body(cli.Get("/provider", identity), "hello");
  4815. expect_body(cli.Get("/empty", identity), "");
  4816. // A HEAD response may give the length of the body a GET would get.
  4817. auto res = cli.Head("/empty");
  4818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4819. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4820. }
  4821. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4822. Server svr;
  4823. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4824. res.set_content("short", "text/plain");
  4825. });
  4826. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4827. res.body += " with a footer";
  4828. res.set_header("Transfer-Encoding", "chunked");
  4829. });
  4830. thread t = thread([&] { svr.listen(HOST, PORT); });
  4831. auto se = detail::scope_exit([&] {
  4832. svr.stop();
  4833. t.join();
  4834. ASSERT_FALSE(svr.is_running());
  4835. });
  4836. svr.wait_until_ready();
  4837. Client cli(HOST, PORT);
  4838. cli.set_read_timeout(1, 0);
  4839. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  4840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4841. EXPECT_EQ("short with a footer", res->body);
  4842. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4843. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4844. }
  4845. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  4846. Server svr;
  4847. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4848. res.set_header("Content-Length", "3");
  4849. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  4850. sink.write("abc", 3);
  4851. sink.done();
  4852. return true;
  4853. });
  4854. });
  4855. thread t = thread([&] { svr.listen(HOST, PORT); });
  4856. auto se = detail::scope_exit([&] {
  4857. svr.stop();
  4858. t.join();
  4859. ASSERT_FALSE(svr.is_running());
  4860. });
  4861. svr.wait_until_ready();
  4862. Client cli(HOST, PORT);
  4863. cli.set_keep_alive(true);
  4864. auto res = cli.Get("/");
  4865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4866. EXPECT_EQ("abc", res->body);
  4867. EXPECT_FALSE(res->has_header("Content-Length"));
  4868. EXPECT_EQ("close", res->get_header_value("Connection"));
  4869. EXPECT_FALSE(res->has_header("Keep-Alive"));
  4870. // No body to delimit
  4871. auto head = cli.Head("/");
  4872. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  4873. EXPECT_FALSE(head->has_header("Connection"));
  4874. }
  4875. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4876. #ifdef CPPHTTPLIB_SSL_ENABLED
  4877. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4878. ASSERT_TRUE(svr.is_valid());
  4879. #else
  4880. Server svr;
  4881. #endif
  4882. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4883. if (req.path == "/routing_handler") {
  4884. res.set_header("PRE_ROUTING", "on");
  4885. res.set_content("Routing Handler", "text/plain");
  4886. return httplib::Server::HandlerResponse::Handled;
  4887. }
  4888. return httplib::Server::HandlerResponse::Unhandled;
  4889. });
  4890. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4891. res.set_content("Error", "text/html");
  4892. });
  4893. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4894. if (req.path == "/routing_handler") {
  4895. res.set_header("POST_ROUTING", "on");
  4896. }
  4897. });
  4898. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4899. res.set_content("Hello World!\n", "text/plain");
  4900. });
  4901. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4902. auto se = detail::scope_exit([&] {
  4903. svr.stop();
  4904. thread.join();
  4905. ASSERT_FALSE(svr.is_running());
  4906. });
  4907. svr.wait_until_ready();
  4908. {
  4909. #ifdef CPPHTTPLIB_SSL_ENABLED
  4910. SSLClient cli(HOST, PORT);
  4911. cli.enable_server_certificate_verification(false);
  4912. #else
  4913. Client cli(HOST, PORT);
  4914. #endif
  4915. auto res = cli.Get("/routing_handler");
  4916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4917. EXPECT_EQ(StatusCode::OK_200, res->status);
  4918. EXPECT_EQ("Routing Handler", res->body);
  4919. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4920. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4921. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4922. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4923. }
  4924. {
  4925. #ifdef CPPHTTPLIB_SSL_ENABLED
  4926. SSLClient cli(HOST, PORT);
  4927. cli.enable_server_certificate_verification(false);
  4928. #else
  4929. Client cli(HOST, PORT);
  4930. #endif
  4931. auto res = cli.Get("/hi");
  4932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4933. EXPECT_EQ(StatusCode::OK_200, res->status);
  4934. EXPECT_EQ("Hello World!\n", res->body);
  4935. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4936. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4937. }
  4938. {
  4939. #ifdef CPPHTTPLIB_SSL_ENABLED
  4940. SSLClient cli(HOST, PORT);
  4941. cli.enable_server_certificate_verification(false);
  4942. #else
  4943. Client cli(HOST, PORT);
  4944. #endif
  4945. auto res = cli.Get("/aaa");
  4946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4947. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4948. EXPECT_EQ("Error", res->body);
  4949. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4950. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4951. }
  4952. }
  4953. TEST(RequestHandlerTest, PreRequestHandler) {
  4954. auto route_path = "/user/:user";
  4955. Server svr;
  4956. svr.Get("/hi", [](const Request &, Response &res) {
  4957. res.set_content("hi", "text/plain");
  4958. });
  4959. svr.Get(route_path, [](const Request &req, Response &res) {
  4960. res.set_content(req.path_params.at("user"), "text/plain");
  4961. });
  4962. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4963. if (req.matched_route == route_path) {
  4964. auto user = req.path_params.at("user");
  4965. if (user != "john") {
  4966. res.status = StatusCode::Forbidden_403;
  4967. res.set_content("error", "text/html");
  4968. return Server::HandlerResponse::Handled;
  4969. }
  4970. }
  4971. return Server::HandlerResponse::Unhandled;
  4972. });
  4973. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4974. auto se = detail::scope_exit([&] {
  4975. svr.stop();
  4976. thread.join();
  4977. ASSERT_FALSE(svr.is_running());
  4978. });
  4979. svr.wait_until_ready();
  4980. Client cli(HOST, PORT);
  4981. {
  4982. auto res = cli.Get("/hi");
  4983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4984. EXPECT_EQ(StatusCode::OK_200, res->status);
  4985. EXPECT_EQ("hi", res->body);
  4986. }
  4987. {
  4988. auto res = cli.Get("/user/john");
  4989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4990. EXPECT_EQ(StatusCode::OK_200, res->status);
  4991. EXPECT_EQ("john", res->body);
  4992. }
  4993. {
  4994. auto res = cli.Get("/user/invalid-user");
  4995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4996. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4997. EXPECT_EQ("error", res->body);
  4998. }
  4999. }
  5000. // The pre-request handler must run before the request body is read, so a
  5001. // rejected request never forces the server to buffer a (potentially large)
  5002. // body. Here the posted body is larger than the payload limit: if the body
  5003. // were read first the server would answer 413, but because the pre-request
  5004. // handler runs first it answers 403 and the body is never read.
  5005. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5006. Server svr;
  5007. svr.set_payload_max_length(8);
  5008. auto handler_ran = false;
  5009. svr.Post("/reject", [&](const Request &req, Response &res) {
  5010. handler_ran = true;
  5011. res.set_content(req.body, "text/plain");
  5012. });
  5013. svr.Post("/accept", [](const Request &req, Response &res) {
  5014. res.set_content(req.body, "text/plain");
  5015. });
  5016. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5017. if (req.matched_route == "/reject") {
  5018. res.status = StatusCode::Forbidden_403;
  5019. res.set_content("denied", "text/plain");
  5020. return Server::HandlerResponse::Handled;
  5021. }
  5022. return Server::HandlerResponse::Unhandled;
  5023. });
  5024. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5025. auto se = detail::scope_exit([&] {
  5026. svr.stop();
  5027. thread.join();
  5028. ASSERT_FALSE(svr.is_running());
  5029. });
  5030. svr.wait_until_ready();
  5031. Client cli(HOST, PORT);
  5032. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5033. // rejects with 403 before the body is read, so 413 is never reached.
  5034. {
  5035. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5037. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5038. EXPECT_EQ("denied", res->body);
  5039. EXPECT_FALSE(handler_ran);
  5040. }
  5041. // An approved route still reads the body and enforces the payload limit.
  5042. {
  5043. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5045. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5046. }
  5047. }
  5048. TEST(UserDataTest, BasicOperations) {
  5049. httplib::UserData ud;
  5050. // Initially empty
  5051. EXPECT_FALSE(ud.has("key"));
  5052. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5053. // set and get
  5054. ud.set("key", 42);
  5055. EXPECT_TRUE(ud.has("key"));
  5056. auto *p = ud.get<int>("key");
  5057. ASSERT_NE(nullptr, p);
  5058. EXPECT_EQ(42, *p);
  5059. // Type mismatch → nullptr
  5060. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5061. // Overwrite with different type
  5062. ud.set("key", std::string("hello"));
  5063. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5064. auto *s = ud.get<std::string>("key");
  5065. ASSERT_NE(nullptr, s);
  5066. EXPECT_EQ("hello", *s);
  5067. // erase
  5068. ud.erase("key");
  5069. EXPECT_FALSE(ud.has("key"));
  5070. // clear
  5071. ud.set("a", 1);
  5072. ud.set("b", 2);
  5073. ud.clear();
  5074. EXPECT_FALSE(ud.has("a"));
  5075. EXPECT_FALSE(ud.has("b"));
  5076. }
  5077. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5078. struct AuthCtx {
  5079. std::string user_id;
  5080. };
  5081. Server svr;
  5082. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5083. res.user_data.set("auth", AuthCtx{"alice"});
  5084. return Server::HandlerResponse::Unhandled;
  5085. });
  5086. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5087. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5088. ASSERT_NE(nullptr, ctx);
  5089. res.set_content("Hello " + ctx->user_id, "text/plain");
  5090. });
  5091. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5092. auto se = detail::scope_exit([&] {
  5093. svr.stop();
  5094. thread.join();
  5095. ASSERT_FALSE(svr.is_running());
  5096. });
  5097. svr.wait_until_ready();
  5098. Client cli(HOST, PORT);
  5099. auto res = cli.Get("/me");
  5100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5101. EXPECT_EQ(StatusCode::OK_200, res->status);
  5102. EXPECT_EQ("Hello alice", res->body);
  5103. }
  5104. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5105. struct RoleCtx {
  5106. std::string role;
  5107. };
  5108. Server svr;
  5109. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5110. res.user_data.set("role", RoleCtx{"admin"});
  5111. return Server::HandlerResponse::Unhandled;
  5112. });
  5113. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5114. auto *ctx = res.user_data.get<RoleCtx>("role");
  5115. ASSERT_NE(nullptr, ctx);
  5116. res.set_content(ctx->role, "text/plain");
  5117. });
  5118. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5119. auto se = detail::scope_exit([&] {
  5120. svr.stop();
  5121. thread.join();
  5122. ASSERT_FALSE(svr.is_running());
  5123. });
  5124. svr.wait_until_ready();
  5125. Client cli(HOST, PORT);
  5126. auto res = cli.Get("/role");
  5127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5128. EXPECT_EQ(StatusCode::OK_200, res->status);
  5129. EXPECT_EQ("admin", res->body);
  5130. }
  5131. TEST(InvalidFormatTest, StatusCode) {
  5132. Server svr;
  5133. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5134. res.set_content("Hello World!\n", "text/plain");
  5135. res.status = 9999; // Status should be a three-digit code...
  5136. });
  5137. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5138. auto se = detail::scope_exit([&] {
  5139. svr.stop();
  5140. thread.join();
  5141. ASSERT_FALSE(svr.is_running());
  5142. });
  5143. svr.wait_until_ready();
  5144. {
  5145. Client cli(HOST, PORT);
  5146. auto res = cli.Get("/hi");
  5147. ASSERT_FALSE(res);
  5148. }
  5149. }
  5150. TEST(URLFragmentTest, WithFragment) {
  5151. Server svr;
  5152. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5153. EXPECT_TRUE(req.target == "/hi");
  5154. });
  5155. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5156. auto se = detail::scope_exit([&] {
  5157. svr.stop();
  5158. thread.join();
  5159. ASSERT_FALSE(svr.is_running());
  5160. });
  5161. svr.wait_until_ready();
  5162. {
  5163. Client cli(HOST, PORT);
  5164. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5165. EXPECT_TRUE(res);
  5166. EXPECT_EQ(StatusCode::OK_200, res->status);
  5167. res = cli.Get("/hi%23key1=val1=key2=val2");
  5168. EXPECT_TRUE(res);
  5169. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5170. }
  5171. }
  5172. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5173. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5174. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5175. Server svr;
  5176. std::vector<std::string> targets;
  5177. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5178. targets.push_back(req.target);
  5179. });
  5180. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5181. auto se = detail::scope_exit([&] {
  5182. svr.stop();
  5183. thread.join();
  5184. ASSERT_FALSE(svr.is_running());
  5185. });
  5186. svr.wait_until_ready();
  5187. Client cli(HOST, PORT);
  5188. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5189. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5190. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5191. // A '?' after the '#' belongs to the fragment, not to the query.
  5192. Request req;
  5193. req.method = "GET";
  5194. req.path = "/hi#f?x=1";
  5195. req.params.emplace("a", "1");
  5196. Response res;
  5197. auto error = Error::Success;
  5198. EXPECT_TRUE(cli.send(req, res, error));
  5199. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5200. "/hi?a=1"}),
  5201. targets);
  5202. }
  5203. TEST(HeaderWriter, SetHeaderWriter) {
  5204. Server svr;
  5205. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5206. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5207. return detail::write_headers(strm, hdrs);
  5208. });
  5209. svr.Get("/hi", [](const Request &req, Response &res) {
  5210. auto it = req.headers.find("CustomClientHeader");
  5211. EXPECT_TRUE(it != req.headers.end());
  5212. EXPECT_EQ(it->second, "CustomClientValue");
  5213. res.set_content("Hello World!\n", "text/plain");
  5214. });
  5215. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5216. auto se = detail::scope_exit([&] {
  5217. svr.stop();
  5218. thread.join();
  5219. ASSERT_FALSE(svr.is_running());
  5220. });
  5221. svr.wait_until_ready();
  5222. {
  5223. Client cli(HOST, PORT);
  5224. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5225. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5226. return detail::write_headers(strm, hdrs);
  5227. });
  5228. auto res = cli.Get("/hi");
  5229. EXPECT_TRUE(res);
  5230. EXPECT_EQ(StatusCode::OK_200, res->status);
  5231. auto it = res->headers.find("CustomServerHeader");
  5232. EXPECT_TRUE(it != res->headers.end());
  5233. EXPECT_EQ(it->second, "CustomServerValue");
  5234. }
  5235. }
  5236. class ServerTest : public ::testing::Test {
  5237. protected:
  5238. ServerTest()
  5239. : cli_(HOST, PORT)
  5240. #ifdef CPPHTTPLIB_SSL_ENABLED
  5241. ,
  5242. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5243. #endif
  5244. {
  5245. #ifdef CPPHTTPLIB_SSL_ENABLED
  5246. cli_.enable_server_certificate_verification(false);
  5247. #endif
  5248. // Allow LARGE_DATA (100MB) responses
  5249. cli_.set_payload_max_length(200 * 1024 * 1024);
  5250. }
  5251. virtual void SetUp() {
  5252. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5253. svr_.set_payload_max_length(200 * 1024 * 1024);
  5254. svr_.set_mount_point("/", "./www");
  5255. svr_.set_mount_point("/mount", "./www2");
  5256. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5257. svr_.Get("/hi",
  5258. [&](const Request & /*req*/, Response &res) {
  5259. res.set_content("Hello World!", "text/plain");
  5260. })
  5261. .Get("/file_content",
  5262. [&](const Request & /*req*/, Response &res) {
  5263. res.set_file_content("./www/dir/test.html");
  5264. })
  5265. .Get("/file_content_with_content_type",
  5266. [&](const Request & /*req*/, Response &res) {
  5267. res.set_file_content("./www/file", "text/plain");
  5268. })
  5269. .Get("/invalid_file_content",
  5270. [&](const Request & /*req*/, Response &res) {
  5271. res.set_file_content("./www/dir/invalid_file_path");
  5272. })
  5273. .Get("/http_response_splitting",
  5274. [&](const Request & /*req*/, Response &res) {
  5275. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5276. EXPECT_EQ(0U, res.headers.size());
  5277. EXPECT_FALSE(res.has_header("a"));
  5278. res.set_header("a", "1\nSet-Cookie: a=1");
  5279. EXPECT_EQ(0U, res.headers.size());
  5280. EXPECT_FALSE(res.has_header("a"));
  5281. res.set_header("a", "1\rSet-Cookie: a=1");
  5282. EXPECT_EQ(0U, res.headers.size());
  5283. EXPECT_FALSE(res.has_header("a"));
  5284. res.set_header("a\r\nb", "0");
  5285. EXPECT_EQ(0U, res.headers.size());
  5286. EXPECT_FALSE(res.has_header("a"));
  5287. res.set_header("a\rb", "0");
  5288. EXPECT_EQ(0U, res.headers.size());
  5289. EXPECT_FALSE(res.has_header("a"));
  5290. res.set_header("a\nb", "0");
  5291. EXPECT_EQ(0U, res.headers.size());
  5292. EXPECT_FALSE(res.has_header("a"));
  5293. res.set_redirect("1\r\nSet-Cookie: a=1");
  5294. EXPECT_EQ(0U, res.headers.size());
  5295. EXPECT_FALSE(res.has_header("Location"));
  5296. })
  5297. .Get("/slow",
  5298. [&](const Request & /*req*/, Response &res) {
  5299. std::this_thread::sleep_for(std::chrono::seconds(4));
  5300. res.set_content("slow", "text/plain");
  5301. })
  5302. #if 0
  5303. .Post("/slowpost",
  5304. [&](const Request & /*req*/, Response &res) {
  5305. std::this_thread::sleep_for(std::chrono::seconds(2));
  5306. res.set_content("slow", "text/plain");
  5307. })
  5308. #endif
  5309. .Get("/remote_addr",
  5310. [&](const Request &req, Response &res) {
  5311. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5312. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5313. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5314. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5315. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5316. #endif
  5317. res.set_content(req.remote_addr, "text/plain");
  5318. })
  5319. .Get("/local_addr",
  5320. [&](const Request &req, Response &res) {
  5321. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5322. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5323. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5324. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5325. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5326. #endif
  5327. auto local_addr = req.local_addr;
  5328. auto local_port = std::to_string(req.local_port);
  5329. res.set_content(local_addr.append(":").append(local_port),
  5330. "text/plain");
  5331. })
  5332. .Get("/endwith%",
  5333. [&](const Request & /*req*/, Response &res) {
  5334. res.set_content("Hello World!", "text/plain");
  5335. })
  5336. .Get("/a\\+\\+b",
  5337. [&](const Request &req, Response &res) {
  5338. ASSERT_TRUE(req.has_param("a +b"));
  5339. auto val = req.get_param_value("a +b");
  5340. res.set_content(val, "text/plain");
  5341. })
  5342. .Get("/", [&](const Request & /*req*/,
  5343. Response &res) { res.set_redirect("/hi"); })
  5344. .Post("/1",
  5345. [](const Request & /*req*/, Response &res) {
  5346. res.set_redirect("/2", StatusCode::SeeOther_303);
  5347. })
  5348. .Get("/2",
  5349. [](const Request & /*req*/, Response &res) {
  5350. res.set_content("redirected.", "text/plain");
  5351. res.status = StatusCode::OK_200;
  5352. })
  5353. .Post("/person",
  5354. [&](const Request &req, Response &res) {
  5355. if (req.has_param("name") && req.has_param("note")) {
  5356. persons_[req.get_param_value("name")] =
  5357. req.get_param_value("note");
  5358. } else {
  5359. res.status = StatusCode::BadRequest_400;
  5360. }
  5361. })
  5362. .Put("/person",
  5363. [&](const Request &req, Response &res) {
  5364. if (req.has_param("name") && req.has_param("note")) {
  5365. persons_[req.get_param_value("name")] =
  5366. req.get_param_value("note");
  5367. } else {
  5368. res.status = StatusCode::BadRequest_400;
  5369. }
  5370. })
  5371. .Get("/person/(.*)",
  5372. [&](const Request &req, Response &res) {
  5373. string name = req.matches[1];
  5374. if (persons_.find(name) != persons_.end()) {
  5375. auto note = persons_[name];
  5376. res.set_content(note, "text/plain");
  5377. } else {
  5378. res.status = StatusCode::NotFound_404;
  5379. }
  5380. })
  5381. .Delete("/person",
  5382. [&](const Request &req, Response &res) {
  5383. if (req.has_param("name")) {
  5384. string name = req.get_param_value("name");
  5385. if (persons_.find(name) != persons_.end()) {
  5386. persons_.erase(name);
  5387. res.set_content("DELETED", "text/plain");
  5388. } else {
  5389. res.status = StatusCode::NotFound_404;
  5390. }
  5391. } else {
  5392. res.status = StatusCode::BadRequest_400;
  5393. }
  5394. })
  5395. .Post("/x-www-form-urlencoded-json",
  5396. [&](const Request &req, Response &res) {
  5397. auto json = req.get_param_value("json");
  5398. ASSERT_EQ(JSON_DATA, json);
  5399. res.set_content(json, "appliation/json");
  5400. res.status = StatusCode::OK_200;
  5401. })
  5402. .Get("/streamed-chunked",
  5403. [&](const Request & /*req*/, Response &res) {
  5404. res.set_chunked_content_provider(
  5405. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5406. sink.os << "123";
  5407. sink.os << "456";
  5408. sink.os << "789";
  5409. sink.done();
  5410. return true;
  5411. });
  5412. })
  5413. .Get("/streamed-chunked-with-prohibited-trailer",
  5414. [&](const Request & /*req*/, Response &res) {
  5415. auto i = new int(0);
  5416. // Declare both a prohibited trailer (Content-Length) and an
  5417. // allowed one
  5418. res.set_header("Trailer", "Content-Length, X-Allowed");
  5419. res.set_chunked_content_provider(
  5420. "text/plain",
  5421. [i](size_t /*offset*/, DataSink &sink) {
  5422. switch (*i) {
  5423. case 0: sink.os << "123"; break;
  5424. case 1: sink.os << "456"; break;
  5425. case 2: sink.os << "789"; break;
  5426. case 3: {
  5427. sink.done_with_trailer(
  5428. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5429. } break;
  5430. }
  5431. (*i)++;
  5432. return true;
  5433. },
  5434. [i](bool success) {
  5435. EXPECT_TRUE(success);
  5436. delete i;
  5437. });
  5438. })
  5439. .Get("/streamed-chunked2",
  5440. [&](const Request & /*req*/, Response &res) {
  5441. auto i = new int(0);
  5442. res.set_chunked_content_provider(
  5443. "text/plain",
  5444. [i](size_t /*offset*/, DataSink &sink) {
  5445. switch (*i) {
  5446. case 0: sink.os << "123"; break;
  5447. case 1: sink.os << "456"; break;
  5448. case 2: sink.os << "789"; break;
  5449. case 3: sink.done(); break;
  5450. }
  5451. (*i)++;
  5452. return true;
  5453. },
  5454. [i](bool success) {
  5455. EXPECT_TRUE(success);
  5456. delete i;
  5457. });
  5458. })
  5459. .Get("/streamed-chunked-with-trailer",
  5460. [&](const Request & /*req*/, Response &res) {
  5461. auto i = new int(0);
  5462. res.set_header("Trailer", "Dummy1, Dummy2");
  5463. res.set_chunked_content_provider(
  5464. "text/plain",
  5465. [i](size_t /*offset*/, DataSink &sink) {
  5466. switch (*i) {
  5467. case 0: sink.os << "123"; break;
  5468. case 1: sink.os << "456"; break;
  5469. case 2: sink.os << "789"; break;
  5470. case 3: {
  5471. sink.done_with_trailer(
  5472. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5473. } break;
  5474. }
  5475. (*i)++;
  5476. return true;
  5477. },
  5478. [i](bool success) {
  5479. EXPECT_TRUE(success);
  5480. delete i;
  5481. });
  5482. })
  5483. .Get("/streamed",
  5484. [&](const Request & /*req*/, Response &res) {
  5485. res.set_content_provider(
  5486. 6, "text/plain",
  5487. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5488. sink.os << (offset < 3 ? "a" : "b");
  5489. return true;
  5490. });
  5491. })
  5492. .Get("/streamed-without-length",
  5493. [&](const Request & /*req*/, Response &res) {
  5494. auto data = new std::string("abcdefg");
  5495. res.set_content_provider(
  5496. "text/plain",
  5497. [data](size_t offset, DataSink &sink) {
  5498. if (offset < data->size()) {
  5499. sink.os << data->substr(offset);
  5500. }
  5501. sink.done();
  5502. return true;
  5503. },
  5504. [data](bool success) {
  5505. EXPECT_TRUE(success);
  5506. delete data;
  5507. });
  5508. })
  5509. .Get("/streamed-with-range",
  5510. [&](const Request &req, Response &res) {
  5511. auto data = new std::string("abcdefg");
  5512. // An explicit status keeps the server from picking the 206 it
  5513. // would otherwise choose for a ranged request, so the response
  5514. // is not a partial representation.
  5515. auto status = req.get_param_value("status");
  5516. if (status == "200") {
  5517. res.status = StatusCode::OK_200;
  5518. } else if (status == "403") {
  5519. res.status = StatusCode::Forbidden_403;
  5520. }
  5521. res.set_content_provider(
  5522. data->size(), "text/plain",
  5523. [data](size_t offset, size_t length, DataSink &sink) {
  5524. size_t DATA_CHUNK_SIZE = 4;
  5525. const auto &d = *data;
  5526. auto out_len =
  5527. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5528. auto ret =
  5529. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5530. EXPECT_TRUE(ret);
  5531. return true;
  5532. },
  5533. [data, &req](bool success) {
  5534. EXPECT_EQ(success, !req.has_param("error"));
  5535. delete data;
  5536. });
  5537. })
  5538. .Get("/streamed-cancel",
  5539. [&](const Request & /*req*/, Response &res) {
  5540. res.set_content_provider(
  5541. size_t(-1), "text/plain",
  5542. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5543. sink.os << "data_chunk";
  5544. return true;
  5545. });
  5546. })
  5547. .Get("/regex-with-delimiter",
  5548. [&](const Request &req, Response & /*res*/) {
  5549. ASSERT_TRUE(req.has_param("key"));
  5550. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5551. })
  5552. .Get("/with-range",
  5553. [&](const Request & /*req*/, Response &res) {
  5554. res.set_content("abcdefg", "text/plain");
  5555. })
  5556. .Get("/test-start-time",
  5557. [&](const Request &req, Response & /*res*/) {
  5558. EXPECT_NE(req.start_time_,
  5559. std::chrono::steady_clock::time_point::min());
  5560. })
  5561. .Get("/with-range-customized-response",
  5562. [&](const Request & /*req*/, Response &res) {
  5563. res.status = StatusCode::BadRequest_400;
  5564. res.set_content(JSON_DATA, "application/json");
  5565. })
  5566. .Post("/chunked",
  5567. [&](const Request &req, Response & /*res*/) {
  5568. EXPECT_EQ(req.body, "dechunked post body");
  5569. })
  5570. .Post("/large-chunked",
  5571. [&](const Request &req, Response & /*res*/) {
  5572. std::string expected(6 * 30 * 1024u, 'a');
  5573. EXPECT_EQ(req.body, expected);
  5574. })
  5575. .Post("/multipart",
  5576. [&](const Request &req, Response & /*res*/) {
  5577. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5578. req.form.get_field_count("text2") +
  5579. req.form.get_field_count("file3") +
  5580. req.form.get_field_count("file4"));
  5581. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5582. req.form.get_file_count("file2"));
  5583. ASSERT_TRUE(!req.form.has_file("???"));
  5584. ASSERT_TRUE(!req.form.has_field("???"));
  5585. ASSERT_TRUE(req.body.empty());
  5586. {
  5587. const auto &text = req.form.get_field("text1");
  5588. EXPECT_EQ("text default", text);
  5589. }
  5590. {
  5591. const auto &text = req.form.get_field("text2");
  5592. EXPECT_EQ("aωb", text);
  5593. }
  5594. {
  5595. const auto &file = req.form.get_file("file1");
  5596. EXPECT_EQ("hello.txt", file.filename);
  5597. EXPECT_EQ("text/plain", file.content_type);
  5598. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5599. }
  5600. {
  5601. const auto &file = req.form.get_file("file2");
  5602. EXPECT_EQ("world.json", file.filename);
  5603. EXPECT_EQ("application/json", file.content_type);
  5604. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5605. }
  5606. {
  5607. const auto &text = req.form.get_field("file3");
  5608. EXPECT_EQ(0u, text.size());
  5609. }
  5610. {
  5611. const auto &text = req.form.get_field("file4");
  5612. EXPECT_EQ(0u, text.size());
  5613. }
  5614. })
  5615. .Post("/multipart/multi_file_values",
  5616. [&](const Request &req, Response & /*res*/) {
  5617. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5618. req.form.get_field_count("multi_text1"));
  5619. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5620. ASSERT_TRUE(!req.form.has_file("???"));
  5621. ASSERT_TRUE(!req.form.has_field("???"));
  5622. ASSERT_TRUE(req.body.empty());
  5623. {
  5624. const auto &text = req.form.get_field("text");
  5625. EXPECT_EQ("default text", text);
  5626. }
  5627. {
  5628. const auto &text1_values = req.form.get_fields("multi_text1");
  5629. EXPECT_EQ(2u, text1_values.size());
  5630. EXPECT_EQ("aaaaa", text1_values[0]);
  5631. EXPECT_EQ("bbbbb", text1_values[1]);
  5632. }
  5633. {
  5634. const auto &file1_values = req.form.get_files("multi_file1");
  5635. EXPECT_EQ(2u, file1_values.size());
  5636. auto file1 = file1_values[0];
  5637. EXPECT_EQ(file1.filename, "hello.txt");
  5638. EXPECT_EQ(file1.content_type, "text/plain");
  5639. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5640. auto file2 = file1_values[1];
  5641. EXPECT_EQ(file2.filename, "world.json");
  5642. EXPECT_EQ(file2.content_type, "application/json");
  5643. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5644. }
  5645. })
  5646. .Post("/empty",
  5647. [&](const Request &req, Response &res) {
  5648. EXPECT_EQ(req.body, "");
  5649. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5650. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5651. res.set_content("empty", "text/plain");
  5652. })
  5653. .Post("/empty-no-content-type",
  5654. [&](const Request &req, Response &res) {
  5655. EXPECT_EQ(req.body, "");
  5656. EXPECT_FALSE(req.has_header("Content-Type"));
  5657. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5658. res.set_content("empty-no-content-type", "text/plain");
  5659. })
  5660. .Post("/path-only",
  5661. [&](const Request &req, Response &res) {
  5662. EXPECT_EQ(req.body, "");
  5663. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5664. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5665. res.set_content("path-only", "text/plain");
  5666. })
  5667. .Post("/path-headers-only",
  5668. [&](const Request &req, Response &res) {
  5669. EXPECT_EQ(req.body, "");
  5670. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5671. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5672. EXPECT_EQ("world", req.get_header_value("hello"));
  5673. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5674. res.set_content("path-headers-only", "text/plain");
  5675. })
  5676. .Post("/post-large",
  5677. [&](const Request &req, Response &res) {
  5678. EXPECT_EQ(req.body, LARGE_DATA);
  5679. res.set_content(req.body, "text/plain");
  5680. })
  5681. .Post("/post-loopback",
  5682. [&](const Request &, Response &res,
  5683. ContentReader const &content_reader) {
  5684. std::string body;
  5685. content_reader([&](const char *data, size_t data_length) {
  5686. body.append(data, data_length);
  5687. return true;
  5688. });
  5689. res.set_content(body, "text/plain");
  5690. })
  5691. .Put("/put-loopback",
  5692. [&](const Request &, Response &res,
  5693. ContentReader const &content_reader) {
  5694. std::string body;
  5695. content_reader([&](const char *data, size_t data_length) {
  5696. body.append(data, data_length);
  5697. return true;
  5698. });
  5699. res.set_content(body, "text/plain");
  5700. })
  5701. .Patch("/patch-loopback",
  5702. [&](const Request &, Response &res,
  5703. ContentReader const &content_reader) {
  5704. std::string body;
  5705. content_reader([&](const char *data, size_t data_length) {
  5706. body.append(data, data_length);
  5707. return true;
  5708. });
  5709. res.set_content(body, "text/plain");
  5710. })
  5711. .Put("/empty-no-content-type",
  5712. [&](const Request &req, Response &res) {
  5713. EXPECT_EQ(req.body, "");
  5714. EXPECT_FALSE(req.has_header("Content-Type"));
  5715. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5716. res.set_content("empty-no-content-type", "text/plain");
  5717. })
  5718. .Put("/put",
  5719. [&](const Request &req, Response &res) {
  5720. EXPECT_EQ(req.body, "PUT");
  5721. res.set_content(req.body, "text/plain");
  5722. })
  5723. .Put("/put-large",
  5724. [&](const Request &req, Response &res) {
  5725. EXPECT_EQ(req.body, LARGE_DATA);
  5726. res.set_content(req.body, "text/plain");
  5727. })
  5728. .Patch("/patch",
  5729. [&](const Request &req, Response &res) {
  5730. EXPECT_EQ(req.body, "PATCH");
  5731. res.set_content(req.body, "text/plain");
  5732. })
  5733. .Delete("/delete",
  5734. [&](const Request & /*req*/, Response &res) {
  5735. res.set_content("DELETE", "text/plain");
  5736. })
  5737. .Delete("/delete-body",
  5738. [&](const Request &req, Response &res) {
  5739. EXPECT_EQ(req.body, "content");
  5740. res.set_content(req.body, "text/plain");
  5741. })
  5742. .Options(R"(\*)",
  5743. [&](const Request & /*req*/, Response &res) {
  5744. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5745. })
  5746. .CustomRoute("PROPFIND", "/dav/:id",
  5747. [&](const Request &req, Response &res) {
  5748. res.set_header("x-body-size",
  5749. std::to_string(req.body.size()));
  5750. res.set_header("x-matched-route", req.matched_route);
  5751. res.set_header("x-dav-id", req.path_params.at("id"));
  5752. res.status = StatusCode::MultiStatus_207;
  5753. res.set_content(req.body, "application/xml");
  5754. })
  5755. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5756. [&](const Request &req, Response &res) {
  5757. res.set_header("x-dav-match", req.matches[1]);
  5758. res.status = StatusCode::MultiStatus_207;
  5759. })
  5760. .CustomRoute("MKCOL", "/dav-mkcol",
  5761. [&](const Request &req, Response &res) {
  5762. EXPECT_TRUE(req.body.empty());
  5763. res.status = StatusCode::Created_201;
  5764. })
  5765. .CustomRoute(
  5766. "REPORT", "/dav-report",
  5767. [&](const Request & /*req*/, Response &res,
  5768. const ContentReader &content_reader) {
  5769. std::string body;
  5770. content_reader([&](const char *data, size_t data_length) {
  5771. body.append(data, data_length);
  5772. return true;
  5773. });
  5774. res.set_header("x-body-size", std::to_string(body.size()));
  5775. res.status = StatusCode::MultiStatus_207;
  5776. res.set_content(body, "application/xml");
  5777. })
  5778. .Get("/request-target",
  5779. [&](const Request &req, Response & /*res*/) {
  5780. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5781. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5782. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5783. })
  5784. .Get("/long-query-value",
  5785. [&](const Request &req, Response & /*res*/) {
  5786. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5787. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5788. })
  5789. .Get("/too-long-query-value",
  5790. [&](const Request &req, Response & /*res*/) {
  5791. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5792. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5793. })
  5794. .Get("/array-param",
  5795. [&](const Request &req, Response & /*res*/) {
  5796. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5797. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5798. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5799. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5800. })
  5801. .Get("/array-param-values",
  5802. [&](const Request &req, Response & /*res*/) {
  5803. auto values = req.get_param_values("array");
  5804. EXPECT_EQ(3u, values.size());
  5805. EXPECT_EQ("value1", values[0]);
  5806. EXPECT_EQ("value2", values[1]);
  5807. EXPECT_EQ("value3", values[2]);
  5808. auto empty = req.get_param_values("nonexistent");
  5809. EXPECT_TRUE(empty.empty());
  5810. })
  5811. .Post("/validate-no-multiple-headers",
  5812. [&](const Request &req, Response & /*res*/) {
  5813. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5814. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5815. })
  5816. .Post("/content_receiver",
  5817. [&](const Request &req, Response &res,
  5818. const ContentReader &content_reader) {
  5819. if (req.is_multipart_form_data()) {
  5820. std::vector<FormData> items;
  5821. content_reader(
  5822. [&](const FormData &file) {
  5823. items.push_back(file);
  5824. return true;
  5825. },
  5826. [&](const char *data, size_t data_length) {
  5827. items.back().content.append(data, data_length);
  5828. return true;
  5829. });
  5830. EXPECT_EQ(5u, items.size());
  5831. {
  5832. const auto &file = get_file_value(items, "text1");
  5833. EXPECT_TRUE(file.filename.empty());
  5834. EXPECT_EQ("text default", file.content);
  5835. }
  5836. {
  5837. const auto &file = get_file_value(items, "text2");
  5838. EXPECT_TRUE(file.filename.empty());
  5839. EXPECT_EQ("aωb", file.content);
  5840. }
  5841. {
  5842. const auto &file = get_file_value(items, "file1");
  5843. EXPECT_EQ("hello.txt", file.filename);
  5844. EXPECT_EQ("text/plain", file.content_type);
  5845. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5846. }
  5847. {
  5848. const auto &file = get_file_value(items, "file2");
  5849. EXPECT_EQ("world.json", file.filename);
  5850. EXPECT_EQ("application/json", file.content_type);
  5851. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5852. }
  5853. {
  5854. const auto &file = get_file_value(items, "file3");
  5855. EXPECT_TRUE(file.filename.empty());
  5856. EXPECT_EQ("application/octet-stream", file.content_type);
  5857. EXPECT_EQ(0u, file.content.size());
  5858. }
  5859. } else {
  5860. std::string body;
  5861. content_reader([&](const char *data, size_t data_length) {
  5862. EXPECT_EQ(7U, data_length);
  5863. body.append(data, data_length);
  5864. return true;
  5865. });
  5866. EXPECT_EQ(body, "content");
  5867. res.set_content(body, "text/plain");
  5868. }
  5869. })
  5870. .Put("/content_receiver",
  5871. [&](const Request & /*req*/, Response &res,
  5872. const ContentReader &content_reader) {
  5873. std::string body;
  5874. content_reader([&](const char *data, size_t data_length) {
  5875. body.append(data, data_length);
  5876. return true;
  5877. });
  5878. EXPECT_EQ(body, "content");
  5879. res.set_content(body, "text/plain");
  5880. })
  5881. .Patch("/content_receiver",
  5882. [&](const Request & /*req*/, Response &res,
  5883. const ContentReader &content_reader) {
  5884. std::string body;
  5885. content_reader([&](const char *data, size_t data_length) {
  5886. body.append(data, data_length);
  5887. return true;
  5888. });
  5889. EXPECT_EQ(body, "content");
  5890. res.set_content(body, "text/plain");
  5891. })
  5892. .Post("/query-string-and-body",
  5893. [&](const Request &req, Response & /*res*/) {
  5894. ASSERT_TRUE(req.has_param("key"));
  5895. EXPECT_EQ(req.get_param_value("key"), "value");
  5896. EXPECT_EQ(req.body, "content");
  5897. })
  5898. .Get("/last-request",
  5899. [&](const Request &req, Response & /*res*/) {
  5900. EXPECT_EQ("close", req.get_header_value("Connection"));
  5901. })
  5902. .Get(R"(/redirect/(\d+))",
  5903. [&](const Request &req, Response &res) {
  5904. auto num = std::stoi(req.matches[1]) + 1;
  5905. std::string url = "/redirect/" + std::to_string(num);
  5906. res.set_redirect(url);
  5907. })
  5908. .Post("/binary",
  5909. [&](const Request &req, Response &res) {
  5910. EXPECT_EQ(4U, req.body.size());
  5911. EXPECT_EQ("application/octet-stream",
  5912. req.get_header_value("Content-Type"));
  5913. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5914. res.set_content(req.body, "application/octet-stream");
  5915. })
  5916. .Put("/binary",
  5917. [&](const Request &req, Response &res) {
  5918. EXPECT_EQ(4U, req.body.size());
  5919. EXPECT_EQ("application/octet-stream",
  5920. req.get_header_value("Content-Type"));
  5921. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5922. res.set_content(req.body, "application/octet-stream");
  5923. })
  5924. .Patch("/binary",
  5925. [&](const Request &req, Response &res) {
  5926. EXPECT_EQ(4U, req.body.size());
  5927. EXPECT_EQ("application/octet-stream",
  5928. req.get_header_value("Content-Type"));
  5929. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5930. res.set_content(req.body, "application/octet-stream");
  5931. })
  5932. .Delete("/binary",
  5933. [&](const Request &req, Response &res) {
  5934. EXPECT_EQ(4U, req.body.size());
  5935. EXPECT_EQ("application/octet-stream",
  5936. req.get_header_value("Content-Type"));
  5937. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5938. res.set_content(req.body, "application/octet-stream");
  5939. })
  5940. .Get("/issue1772",
  5941. [&](const Request & /*req*/, Response &res) {
  5942. res.status = 401;
  5943. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5944. })
  5945. .Delete("/issue609",
  5946. [](const httplib::Request &, httplib::Response &res,
  5947. const httplib::ContentReader &) {
  5948. res.set_content("ok", "text/plain");
  5949. })
  5950. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5951. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5952. .Get("/compress",
  5953. [&](const Request & /*req*/, Response &res) {
  5954. res.set_content(
  5955. "12345678901234567890123456789012345678901234567890123456789"
  5956. "01234567890123456789012345678901234567890",
  5957. "text/plain");
  5958. })
  5959. .Get("/compress-with-charset",
  5960. [&](const Request & /*req*/, Response &res) {
  5961. res.set_content(
  5962. "12345678901234567890123456789012345678901234567890123456789"
  5963. "01234567890123456789012345678901234567890",
  5964. "application/json; charset=utf-8");
  5965. })
  5966. .Get("/nocompress",
  5967. [&](const Request & /*req*/, Response &res) {
  5968. res.set_content(
  5969. "12345678901234567890123456789012345678901234567890123456789"
  5970. "01234567890123456789012345678901234567890",
  5971. "application/octet-stream");
  5972. })
  5973. .Post("/compress-multipart",
  5974. [&](const Request &req, Response & /*res*/) {
  5975. EXPECT_EQ(2u, req.form.fields.size());
  5976. ASSERT_TRUE(!req.form.has_field("???"));
  5977. {
  5978. const auto &text = req.form.get_field("key1");
  5979. EXPECT_EQ("test", text);
  5980. }
  5981. {
  5982. const auto &text = req.form.get_field("key2");
  5983. EXPECT_EQ("--abcdefg123", text);
  5984. }
  5985. })
  5986. #endif
  5987. ;
  5988. persons_["john"] = "programmer";
  5989. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5990. svr_.wait_until_ready();
  5991. }
  5992. virtual void TearDown() {
  5993. svr_.stop();
  5994. if (!request_threads_.empty()) {
  5995. std::this_thread::sleep_for(std::chrono::seconds(1));
  5996. for (auto &t : request_threads_) {
  5997. t.join();
  5998. }
  5999. }
  6000. t_.join();
  6001. }
  6002. map<string, string> persons_;
  6003. #ifdef CPPHTTPLIB_SSL_ENABLED
  6004. SSLClient cli_;
  6005. SSLServer svr_;
  6006. #else
  6007. Client cli_;
  6008. Server svr_;
  6009. #endif
  6010. thread t_;
  6011. std::vector<thread> request_threads_;
  6012. };
  6013. TEST_F(ServerTest, GetMethod200) {
  6014. auto res = cli_.Get("/hi");
  6015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6016. EXPECT_EQ("HTTP/1.1", res->version);
  6017. EXPECT_EQ(StatusCode::OK_200, res->status);
  6018. EXPECT_EQ("OK", res->reason);
  6019. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6020. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6021. EXPECT_EQ("Hello World!", res->body);
  6022. }
  6023. TEST_F(ServerTest, GetEmptyFile) {
  6024. auto res = cli_.Get("/empty_file");
  6025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6026. EXPECT_EQ(StatusCode::OK_200, res->status);
  6027. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6028. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6029. EXPECT_EQ("", res->body);
  6030. }
  6031. TEST_F(ServerTest, GetFileContent) {
  6032. auto res = cli_.Get("/file_content");
  6033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6034. EXPECT_EQ(StatusCode::OK_200, res->status);
  6035. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6036. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6037. EXPECT_EQ("test.html", res->body);
  6038. }
  6039. TEST_F(ServerTest, GetFileContentWithRange) {
  6040. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6042. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6043. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6044. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6045. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6046. EXPECT_EQ("est", res->body);
  6047. }
  6048. TEST_F(ServerTest, GetFileContentWithContentType) {
  6049. auto res = cli_.Get("/file_content_with_content_type");
  6050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6051. EXPECT_EQ(StatusCode::OK_200, res->status);
  6052. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6053. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6054. EXPECT_EQ("file\n", res->body);
  6055. }
  6056. TEST_F(ServerTest, GetInvalidFileContent) {
  6057. auto res = cli_.Get("/invalid_file_content");
  6058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6059. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6060. }
  6061. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6062. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6064. EXPECT_EQ("HTTP/1.1", res->version);
  6065. EXPECT_EQ(StatusCode::OK_200, res->status);
  6066. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6067. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6068. EXPECT_EQ("Hello World!", res->body);
  6069. }
  6070. TEST_F(ServerTest, GetMethod302) {
  6071. auto res = cli_.Get("/");
  6072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6073. EXPECT_EQ(StatusCode::Found_302, res->status);
  6074. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6075. }
  6076. TEST_F(ServerTest, GetMethod302Redirect) {
  6077. cli_.set_follow_location(true);
  6078. auto res = cli_.Get("/");
  6079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6080. EXPECT_EQ(StatusCode::OK_200, res->status);
  6081. EXPECT_EQ("Hello World!", res->body);
  6082. EXPECT_EQ("/hi", res->location);
  6083. }
  6084. TEST_F(ServerTest, GetMethod404) {
  6085. auto res = cli_.Get("/invalid");
  6086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6087. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6088. }
  6089. TEST_F(ServerTest, HeadMethod200) {
  6090. auto res = cli_.Head("/hi");
  6091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6092. EXPECT_EQ(StatusCode::OK_200, res->status);
  6093. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6094. EXPECT_TRUE(res->body.empty());
  6095. }
  6096. TEST_F(ServerTest, HeadMethod200Static) {
  6097. auto res = cli_.Head("/mount/dir/index.html");
  6098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6099. EXPECT_EQ(StatusCode::OK_200, res->status);
  6100. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6101. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6102. EXPECT_TRUE(res->body.empty());
  6103. }
  6104. TEST_F(ServerTest, HeadMethod404) {
  6105. auto res = cli_.Head("/invalid");
  6106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6107. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6108. EXPECT_TRUE(res->body.empty());
  6109. }
  6110. TEST_F(ServerTest, GetMethodPersonJohn) {
  6111. auto res = cli_.Get("/person/john");
  6112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6113. EXPECT_EQ(StatusCode::OK_200, res->status);
  6114. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6115. EXPECT_EQ("programmer", res->body);
  6116. }
  6117. TEST_F(ServerTest, PostMethod1) {
  6118. auto res = cli_.Get("/person/john1");
  6119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6120. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6121. res = cli_.Post("/person", "name=john1&note=coder",
  6122. "application/x-www-form-urlencoded");
  6123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6124. ASSERT_EQ(StatusCode::OK_200, res->status);
  6125. res = cli_.Get("/person/john1");
  6126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6127. ASSERT_EQ(StatusCode::OK_200, res->status);
  6128. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6129. ASSERT_EQ("coder", res->body);
  6130. }
  6131. TEST_F(ServerTest, PostMethod2) {
  6132. auto res = cli_.Get("/person/john2");
  6133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6134. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6135. Params params;
  6136. params.emplace("name", "john2");
  6137. params.emplace("note", "coder");
  6138. res = cli_.Post("/person", params);
  6139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6140. ASSERT_EQ(StatusCode::OK_200, res->status);
  6141. res = cli_.Get("/person/john2");
  6142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6143. ASSERT_EQ(StatusCode::OK_200, res->status);
  6144. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6145. ASSERT_EQ("coder", res->body);
  6146. }
  6147. TEST_F(ServerTest, PutMethod3) {
  6148. auto res = cli_.Get("/person/john3");
  6149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6150. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6151. Params params;
  6152. params.emplace("name", "john3");
  6153. params.emplace("note", "coder");
  6154. res = cli_.Put("/person", params);
  6155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6156. ASSERT_EQ(StatusCode::OK_200, res->status);
  6157. res = cli_.Get("/person/john3");
  6158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6159. ASSERT_EQ(StatusCode::OK_200, res->status);
  6160. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6161. ASSERT_EQ("coder", res->body);
  6162. }
  6163. TEST_F(ServerTest, DeleteMethod1) {
  6164. auto res = cli_.Get("/person/john4");
  6165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6166. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6167. Params params;
  6168. params.emplace("name", "john4");
  6169. params.emplace("note", "coder");
  6170. res = cli_.Post("/person", params);
  6171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6172. ASSERT_EQ(StatusCode::OK_200, res->status);
  6173. res = cli_.Get("/person/john4");
  6174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6175. ASSERT_EQ(StatusCode::OK_200, res->status);
  6176. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6177. ASSERT_EQ("coder", res->body);
  6178. Params delete_params;
  6179. delete_params.emplace("name", "john4");
  6180. res = cli_.Delete("/person", delete_params);
  6181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6182. ASSERT_EQ(StatusCode::OK_200, res->status);
  6183. ASSERT_EQ("DELETED", res->body);
  6184. res = cli_.Get("/person/john4");
  6185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6186. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6187. }
  6188. TEST_F(ServerTest, DeleteMethod2) {
  6189. auto res = cli_.Get("/person/john5");
  6190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6191. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6192. Params params;
  6193. params.emplace("name", "john5");
  6194. params.emplace("note", "developer");
  6195. res = cli_.Post("/person", params);
  6196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6197. ASSERT_EQ(StatusCode::OK_200, res->status);
  6198. res = cli_.Get("/person/john5");
  6199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6200. ASSERT_EQ(StatusCode::OK_200, res->status);
  6201. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6202. ASSERT_EQ("developer", res->body);
  6203. Params delete_params;
  6204. delete_params.emplace("name", "john5");
  6205. Headers headers;
  6206. headers.emplace("Custom-Header", "test-value");
  6207. res = cli_.Delete("/person", headers, delete_params);
  6208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6209. ASSERT_EQ(StatusCode::OK_200, res->status);
  6210. ASSERT_EQ("DELETED", res->body);
  6211. res = cli_.Get("/person/john5");
  6212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6213. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6214. }
  6215. TEST_F(ServerTest, DeleteMethod3) {
  6216. auto res = cli_.Get("/person/john6");
  6217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6218. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6219. Params params;
  6220. params.emplace("name", "john6");
  6221. params.emplace("note", "tester");
  6222. res = cli_.Post("/person", params);
  6223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6224. ASSERT_EQ(StatusCode::OK_200, res->status);
  6225. res = cli_.Get("/person/john6");
  6226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6227. ASSERT_EQ(StatusCode::OK_200, res->status);
  6228. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6229. ASSERT_EQ("tester", res->body);
  6230. Params delete_params;
  6231. delete_params.emplace("name", "john6");
  6232. Headers headers;
  6233. headers.emplace("Custom-Header", "test-value");
  6234. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6236. ASSERT_EQ(StatusCode::OK_200, res->status);
  6237. ASSERT_EQ("DELETED", res->body);
  6238. res = cli_.Get("/person/john6");
  6239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6240. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6241. }
  6242. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6243. Params params;
  6244. params.emplace("json", JSON_DATA);
  6245. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6247. ASSERT_EQ(StatusCode::OK_200, res->status);
  6248. ASSERT_EQ(JSON_DATA, res->body);
  6249. }
  6250. TEST_F(ServerTest, PostEmptyContent) {
  6251. auto res = cli_.Post("/empty", "", "text/plain");
  6252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6253. ASSERT_EQ(StatusCode::OK_200, res->status);
  6254. ASSERT_EQ("empty", res->body);
  6255. }
  6256. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6257. auto res = cli_.Post("/empty-no-content-type");
  6258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6259. ASSERT_EQ(StatusCode::OK_200, res->status);
  6260. ASSERT_EQ("empty-no-content-type", res->body);
  6261. }
  6262. TEST_F(ServerTest, PostPathOnly) {
  6263. auto res = cli_.Post("/path-only");
  6264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6265. ASSERT_EQ(StatusCode::OK_200, res->status);
  6266. ASSERT_EQ("path-only", res->body);
  6267. }
  6268. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6269. auto res = cli_.Post("/path-headers-only",
  6270. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6272. ASSERT_EQ(StatusCode::OK_200, res->status);
  6273. ASSERT_EQ("path-headers-only", res->body);
  6274. }
  6275. TEST_F(ServerTest, PostLarge) {
  6276. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6278. ASSERT_EQ(StatusCode::OK_200, res->status);
  6279. EXPECT_EQ(LARGE_DATA, res->body);
  6280. }
  6281. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6282. auto res = cli_.Put("/empty-no-content-type");
  6283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6284. ASSERT_EQ(StatusCode::OK_200, res->status);
  6285. ASSERT_EQ("empty-no-content-type", res->body);
  6286. }
  6287. TEST_F(ServerTest, GetMethodDir) {
  6288. auto res = cli_.Get("/dir/");
  6289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6290. EXPECT_EQ(StatusCode::OK_200, res->status);
  6291. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6292. auto body = R"(<html>
  6293. <head>
  6294. </head>
  6295. <body>
  6296. <a href="/dir/test.html">Test</a>
  6297. <a href="/hi">hi</a>
  6298. </body>
  6299. </html>
  6300. )";
  6301. EXPECT_EQ(body, res->body);
  6302. }
  6303. TEST_F(ServerTest, GetMethodDirTest) {
  6304. auto res = cli_.Get("/dir/test.html");
  6305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6306. EXPECT_EQ(StatusCode::OK_200, res->status);
  6307. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6308. EXPECT_EQ("test.html", res->body);
  6309. }
  6310. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6311. auto res = cli_.Get("/dir/../dir/test.html");
  6312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6313. EXPECT_EQ(StatusCode::OK_200, res->status);
  6314. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6315. EXPECT_EQ("test.html", res->body);
  6316. }
  6317. TEST_F(ServerTest, GetMethodInvalidPath) {
  6318. auto res = cli_.Get("/dir/../test.html");
  6319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6320. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6321. }
  6322. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6323. auto res = cli_.Get("/../www/dir/test.html");
  6324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6325. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6326. }
  6327. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6328. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6330. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6331. }
  6332. TEST_F(ServerTest, GetMethodDirMountTest) {
  6333. auto res = cli_.Get("/mount/dir/test.html");
  6334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6335. EXPECT_EQ(StatusCode::OK_200, res->status);
  6336. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6337. EXPECT_EQ("test.html", res->body);
  6338. }
  6339. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6340. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6342. EXPECT_EQ(StatusCode::OK_200, res->status);
  6343. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6344. EXPECT_EQ("test.html", res->body);
  6345. }
  6346. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6347. auto res = cli_.Get("/mount/dir/../test.html");
  6348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6349. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6350. }
  6351. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6352. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6354. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6355. }
  6356. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6357. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6359. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6360. }
  6361. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6362. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6364. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6365. }
  6366. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6367. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6369. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6370. }
  6371. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6372. auto res = cli_.Get("/mount/dir");
  6373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6374. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6375. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6376. }
  6377. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6378. auto res = cli_.Get("//dir");
  6379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6380. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6381. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6382. }
  6383. TEST_F(ServerTest, PostMethod303) {
  6384. auto res = cli_.Post("/1", "body", "text/plain");
  6385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6386. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6387. EXPECT_EQ("/2", res->get_header_value("Location"));
  6388. }
  6389. TEST_F(ServerTest, PostMethod303Redirect) {
  6390. cli_.set_follow_location(true);
  6391. auto res = cli_.Post("/1", "body", "text/plain");
  6392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6393. EXPECT_EQ(StatusCode::OK_200, res->status);
  6394. EXPECT_EQ("redirected.", res->body);
  6395. EXPECT_EQ("/2", res->location);
  6396. }
  6397. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6398. auto res = cli_.Get("/dir/test.abcde");
  6399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6400. EXPECT_EQ(StatusCode::OK_200, res->status);
  6401. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6402. EXPECT_EQ("abcde", res->body);
  6403. }
  6404. TEST_F(ServerTest, StaticFileRange) {
  6405. auto res =
  6406. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6408. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6409. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6410. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6411. EXPECT_EQ(true, res->has_header("Content-Range"));
  6412. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6413. EXPECT_EQ(std::string("cd"), res->body);
  6414. }
  6415. TEST_F(ServerTest, StaticFileRanges) {
  6416. auto res = cli_.Get("/dir/test.abcde",
  6417. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6419. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6420. EXPECT_TRUE(
  6421. res->get_header_value("Content-Type")
  6422. .find(
  6423. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6424. 0);
  6425. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6426. }
  6427. TEST_F(ServerTest, StaticFileRangeHead) {
  6428. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6430. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6431. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6432. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6433. EXPECT_EQ(true, res->has_header("Content-Range"));
  6434. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6435. }
  6436. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6437. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6439. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6440. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6441. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6442. EXPECT_EQ(true, res->has_header("Content-Range"));
  6443. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6444. res->get_header_value("Content-Range"));
  6445. EXPECT_EQ("LAST\n", res->body);
  6446. }
  6447. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6448. auto res =
  6449. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6451. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6452. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6453. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6454. EXPECT_EQ(true, res->has_header("Content-Range"));
  6455. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6456. }
  6457. TEST_F(ServerTest, StaticFileBigFile) {
  6458. auto res = cli_.Get("/dir/1MB.txt");
  6459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6460. EXPECT_EQ(StatusCode::OK_200, res->status);
  6461. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6462. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6463. }
  6464. TEST_F(ServerTest, InvalidBaseDirMount) {
  6465. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6466. }
  6467. TEST_F(ServerTest, Binary) {
  6468. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6469. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6470. "application/octet-stream");
  6471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6472. ASSERT_EQ(StatusCode::OK_200, res->status);
  6473. ASSERT_EQ(4U, res->body.size());
  6474. res = cli_.Put("/binary", binary.data(), binary.size(),
  6475. "application/octet-stream");
  6476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6477. ASSERT_EQ(StatusCode::OK_200, res->status);
  6478. ASSERT_EQ(4U, res->body.size());
  6479. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6480. "application/octet-stream");
  6481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6482. ASSERT_EQ(StatusCode::OK_200, res->status);
  6483. ASSERT_EQ(4U, res->body.size());
  6484. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6485. "application/octet-stream");
  6486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6487. ASSERT_EQ(StatusCode::OK_200, res->status);
  6488. ASSERT_EQ(4U, res->body.size());
  6489. }
  6490. TEST_F(ServerTest, BinaryString) {
  6491. auto binary = std::string("\x00\x01\x02\x03", 4);
  6492. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6494. ASSERT_EQ(StatusCode::OK_200, res->status);
  6495. ASSERT_EQ(4U, res->body.size());
  6496. res = cli_.Put("/binary", binary, "application/octet-stream");
  6497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6498. ASSERT_EQ(StatusCode::OK_200, res->status);
  6499. ASSERT_EQ(4U, res->body.size());
  6500. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6502. ASSERT_EQ(StatusCode::OK_200, res->status);
  6503. ASSERT_EQ(4U, res->body.size());
  6504. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6506. ASSERT_EQ(StatusCode::OK_200, res->status);
  6507. ASSERT_EQ(4U, res->body.size());
  6508. }
  6509. TEST_F(ServerTest, EmptyRequest) {
  6510. auto res = cli_.Get("");
  6511. ASSERT_TRUE(!res);
  6512. EXPECT_EQ(Error::Connection, res.error());
  6513. }
  6514. TEST_F(ServerTest, LongRequest) {
  6515. std::string request;
  6516. for (size_t i = 0; i < 545; i++) {
  6517. request += "/TooLongRequest";
  6518. }
  6519. request += "OK";
  6520. auto res = cli_.Get(request.c_str());
  6521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6522. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6523. }
  6524. TEST_F(ServerTest, TooLongRequest) {
  6525. std::string request;
  6526. for (size_t i = 0; i < 546; i++) {
  6527. request += "/TooLongRequest";
  6528. }
  6529. request += "_NG";
  6530. auto start = std::chrono::high_resolution_clock::now();
  6531. cli_.set_keep_alive(true);
  6532. auto res = cli_.Get(request.c_str());
  6533. auto end = std::chrono::high_resolution_clock::now();
  6534. auto elapsed =
  6535. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6536. .count();
  6537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6538. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6539. EXPECT_LE(elapsed, 1000);
  6540. EXPECT_EQ("close", res->get_header_value("Connection"));
  6541. EXPECT_FALSE(cli_.is_socket_open());
  6542. }
  6543. TEST_F(ServerTest, AlmostTooLongRequest) {
  6544. // test for #2046 - URI length check shouldn't include other content on req
  6545. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6546. // leading /, space, HTTP/1.1)
  6547. std::string request =
  6548. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6549. auto res = cli_.Get(request.c_str());
  6550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6551. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6552. }
  6553. TEST_F(ServerTest, LongHeader) {
  6554. Request req;
  6555. req.method = "GET";
  6556. req.path = "/hi";
  6557. std::string host_and_port;
  6558. host_and_port += HOST;
  6559. host_and_port += ":";
  6560. host_and_port += std::to_string(PORT);
  6561. req.headers.emplace("Host", host_and_port.c_str());
  6562. req.headers.emplace("Accept", "*/*");
  6563. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6564. req.headers.emplace(
  6565. "Header-Name",
  6566. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6567. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6568. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6569. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6570. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6571. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6572. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6573. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6574. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6575. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6576. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6577. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6578. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6579. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6580. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6581. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6582. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6583. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6584. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6585. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6586. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6587. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6588. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6589. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6590. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6591. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6592. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6593. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6594. "@@@@@@@@@@@@@@@@");
  6595. auto res = std::make_shared<Response>();
  6596. auto error = Error::Success;
  6597. auto ret = cli_.send(req, *res, error);
  6598. ASSERT_TRUE(ret);
  6599. EXPECT_EQ(StatusCode::OK_200, res->status);
  6600. }
  6601. TEST_F(ServerTest, LongQueryValue) {
  6602. auto start = std::chrono::high_resolution_clock::now();
  6603. cli_.set_keep_alive(true);
  6604. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6605. auto end = std::chrono::high_resolution_clock::now();
  6606. auto elapsed =
  6607. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6608. .count();
  6609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6610. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6611. EXPECT_LE(elapsed, 1000);
  6612. EXPECT_EQ("close", res->get_header_value("Connection"));
  6613. EXPECT_FALSE(cli_.is_socket_open());
  6614. }
  6615. TEST_F(ServerTest, TooLongQueryValue) {
  6616. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6617. ASSERT_FALSE(res);
  6618. EXPECT_EQ(Error::Read, res.error());
  6619. }
  6620. TEST_F(ServerTest, TooLongHeader) {
  6621. Request req;
  6622. req.method = "GET";
  6623. req.path = "/hi";
  6624. std::string host_and_port;
  6625. host_and_port += HOST;
  6626. host_and_port += ":";
  6627. host_and_port += std::to_string(PORT);
  6628. req.headers.emplace("Host", host_and_port.c_str());
  6629. req.headers.emplace("Accept", "*/*");
  6630. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6631. req.headers.emplace(
  6632. "Header-Name",
  6633. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6634. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6635. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6636. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6637. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6638. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6639. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6640. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6641. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6642. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6643. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6644. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6645. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6646. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6647. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6648. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6649. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6650. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6651. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6652. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6653. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6654. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6655. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6656. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6657. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6658. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6659. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6660. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6661. "@@@@@@@@@@@@@@@@@");
  6662. auto res = std::make_shared<Response>();
  6663. auto error = Error::Success;
  6664. auto ret = cli_.send(req, *res, error);
  6665. ASSERT_TRUE(ret);
  6666. EXPECT_EQ(StatusCode::OK_200, res->status);
  6667. }
  6668. TEST_F(ServerTest, HeaderCountAtLimit) {
  6669. // Test with headers just under the 100 limit
  6670. httplib::Headers headers;
  6671. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6672. // This should keep us just under the 100 header limit
  6673. for (int i = 0; i < 95; i++) {
  6674. std::string name = "X-Test-Header-" + std::to_string(i);
  6675. std::string value = "value" + std::to_string(i);
  6676. headers.emplace(name, value);
  6677. }
  6678. // This should work fine as we're under the limit
  6679. auto res = cli_.Get("/hi", headers);
  6680. EXPECT_TRUE(res);
  6681. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6682. }
  6683. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6684. // Test with many headers to exceed the 100 limit
  6685. httplib::Headers headers;
  6686. // Add 150 headers to definitely exceed the 100 limit
  6687. for (int i = 0; i < 150; i++) {
  6688. std::string name = "X-Test-Header-" + std::to_string(i);
  6689. std::string value = "value" + std::to_string(i);
  6690. headers.emplace(name, value);
  6691. }
  6692. // This should fail due to exceeding header count limit
  6693. cli_.set_keep_alive(true);
  6694. auto res = cli_.Get("/hi", headers);
  6695. // The server should respond with 400 Bad Request
  6696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6697. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6698. EXPECT_EQ("close", res->get_header_value("Connection"));
  6699. EXPECT_FALSE(cli_.is_socket_open());
  6700. }
  6701. TEST_F(ServerTest, PercentEncoding) {
  6702. auto res = cli_.Get("/e%6edwith%");
  6703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6704. EXPECT_EQ(StatusCode::OK_200, res->status);
  6705. }
  6706. TEST_F(ServerTest, PercentEncodingUnicode) {
  6707. auto res = cli_.Get("/e%u006edwith%");
  6708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6709. EXPECT_EQ(StatusCode::OK_200, res->status);
  6710. }
  6711. TEST_F(ServerTest, InvalidPercentEncoding) {
  6712. auto res = cli_.Get("/%endwith%");
  6713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6714. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6715. }
  6716. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6717. auto res = cli_.Get("/%uendwith%");
  6718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6719. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6720. }
  6721. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6722. auto res = cli_.Get("/hello?aaa=bbb%");
  6723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6724. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6725. }
  6726. TEST_F(ServerTest, PlusSignEncoding) {
  6727. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6729. EXPECT_EQ(StatusCode::OK_200, res->status);
  6730. EXPECT_EQ("a +b", res->body);
  6731. }
  6732. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6733. // This test simulates a potential DoS attack using many headers
  6734. // to verify our security fix prevents memory exhaustion
  6735. httplib::Headers attack_headers;
  6736. // Attempt to add many headers like an attacker would (200 headers to far
  6737. // exceed limit)
  6738. for (int i = 0; i < 200; i++) {
  6739. std::string name = "X-Attack-Header-" + std::to_string(i);
  6740. std::string value = "attack_payload_" + std::to_string(i);
  6741. attack_headers.emplace(name, value);
  6742. }
  6743. // Try to POST with excessive headers
  6744. cli_.set_keep_alive(true);
  6745. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6746. // Should either fail or return 400 Bad Request due to security limit
  6747. if (res) {
  6748. // If we get a response, it should be 400 Bad Request
  6749. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6750. EXPECT_EQ("close", res->get_header_value("Connection"));
  6751. }
  6752. EXPECT_FALSE(cli_.is_socket_open());
  6753. }
  6754. TEST_F(ServerTest, MultipartFormData) {
  6755. UploadFormDataItems items = {
  6756. {"text1", "text default", "", ""},
  6757. {"text2", "aωb", "", ""},
  6758. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6759. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6760. {"file3", "", "", "application/octet-stream"},
  6761. {"file4", "", "", " application/json tmp-string "}};
  6762. auto res = cli_.Post("/multipart", items);
  6763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6764. EXPECT_EQ(StatusCode::OK_200, res->status);
  6765. }
  6766. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6767. UploadFormDataItems items = {
  6768. {"text", "default text", "", ""},
  6769. {"multi_text1", "aaaaa", "", ""},
  6770. {"multi_text1", "bbbbb", "", ""},
  6771. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6772. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6773. "application/json"},
  6774. };
  6775. auto res = cli_.Post("/multipart/multi_file_values", items);
  6776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6777. EXPECT_EQ(StatusCode::OK_200, res->status);
  6778. }
  6779. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6780. auto res = cli_.Get("/hi");
  6781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6782. EXPECT_EQ(StatusCode::OK_200, res->status);
  6783. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6784. EXPECT_EQ("Hello World!", res->body);
  6785. }
  6786. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6787. Request req;
  6788. req.method = "POST";
  6789. req.path = "/chunked";
  6790. std::string host_and_port;
  6791. host_and_port += HOST;
  6792. host_and_port += ":";
  6793. host_and_port += std::to_string(PORT);
  6794. req.headers.emplace("Host", host_and_port.c_str());
  6795. req.headers.emplace("Accept", "*/*");
  6796. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6797. req.headers.emplace("Content-Type", "text/plain");
  6798. req.headers.emplace("Content-Length", "0");
  6799. req.headers.emplace(
  6800. "Transfer-Encoding",
  6801. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6802. // Client does not chunk, so make a chunked body manually.
  6803. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6804. auto res = std::make_shared<Response>();
  6805. auto error = Error::Success;
  6806. auto ret = cli_.send(req, *res, error);
  6807. ASSERT_TRUE(ret);
  6808. EXPECT_EQ(StatusCode::OK_200, res->status);
  6809. }
  6810. template <typename ClientT>
  6811. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6812. int expected_status) {
  6813. Request req;
  6814. req.method = "POST";
  6815. req.path = "/chunked";
  6816. std::string host_and_port;
  6817. host_and_port += HOST;
  6818. host_and_port += ":";
  6819. host_and_port += std::to_string(PORT);
  6820. req.headers.emplace("Host", host_and_port.c_str());
  6821. req.headers.emplace("Content-Length", "0");
  6822. req.headers.emplace("Transfer-Encoding", "chunked");
  6823. req.body = body;
  6824. auto res = std::make_shared<Response>();
  6825. auto error = Error::Success;
  6826. ASSERT_TRUE(cli.send(req, *res, error));
  6827. EXPECT_EQ(expected_status, res->status);
  6828. }
  6829. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6830. // rather than treat them as valid lengths.
  6831. template <typename ClientT>
  6832. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6833. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6834. }
  6835. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6836. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6837. }
  6838. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6839. expect_chunked_body_rejected(
  6840. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6841. }
  6842. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6843. // chunk-size line carries no CR, LF or other control character ahead of its
  6844. // terminator. Such a line must be refused rather than read as extension text.
  6845. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6846. expect_chunked_body_rejected(
  6847. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6848. }
  6849. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6850. expect_chunked_body_rejected(
  6851. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6852. }
  6853. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6854. expect_chunked_body_rejected(
  6855. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6856. }
  6857. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6858. // The literal stays split: a hex escape consumes every hex digit that
  6859. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6860. expect_chunked_body_rejected(
  6861. cli_, "4;a\x01"
  6862. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6863. }
  6864. TEST_F(ServerTest, AcceptsChunkExtension) {
  6865. expect_chunked_body_status(cli_,
  6866. "4;name=value\r\ndech\r\n"
  6867. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6868. "0;last\r\n\r\n",
  6869. StatusCode::OK_200);
  6870. }
  6871. TEST_F(ServerTest, GetStreamed2) {
  6872. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6874. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6875. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6876. EXPECT_EQ(true, res->has_header("Content-Range"));
  6877. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6878. EXPECT_EQ(std::string("ab"), res->body);
  6879. }
  6880. TEST_F(ServerTest, GetStreamed) {
  6881. auto res = cli_.Get("/streamed");
  6882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6883. EXPECT_EQ(StatusCode::OK_200, res->status);
  6884. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6885. EXPECT_EQ(std::string("aaabbb"), res->body);
  6886. }
  6887. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6888. auto res = cli_.Get("/streamed-without-length",
  6889. Headers{make_range_header({{0, -1}})});
  6890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6891. EXPECT_EQ(StatusCode::OK_200, res->status);
  6892. EXPECT_EQ(false, res->has_header("Content-Length"));
  6893. EXPECT_EQ(false, res->has_header("Content-Range"));
  6894. EXPECT_EQ(std::string("abcdefg"), res->body);
  6895. }
  6896. TEST_F(ServerTest, GetStreamedWithRange1) {
  6897. auto res =
  6898. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6900. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6901. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6902. EXPECT_EQ(true, res->has_header("Content-Range"));
  6903. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6904. EXPECT_EQ(std::string("def"), res->body);
  6905. }
  6906. TEST_F(ServerTest, GetStreamedWithRange2) {
  6907. auto res =
  6908. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6910. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6911. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6912. EXPECT_EQ(true, res->has_header("Content-Range"));
  6913. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6914. EXPECT_EQ(std::string("bcdefg"), res->body);
  6915. }
  6916. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6917. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6919. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6920. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6921. EXPECT_EQ(true, res->has_header("Content-Range"));
  6922. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6923. EXPECT_EQ(std::string("efg"), res->body);
  6924. }
  6925. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6926. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6927. // the entire representation.
  6928. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6929. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6931. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6932. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6933. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6934. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6935. }
  6936. }
  6937. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6938. auto res =
  6939. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6941. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6942. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6943. EXPECT_EQ(false, res->has_header("Content-Range"));
  6944. EXPECT_EQ(0U, res->body.size());
  6945. }
  6946. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6947. // Only a 206 is served as a partial representation. Under any other status
  6948. // `apply_ranges()` reported the full content length, so the body must match
  6949. // that header, and the content provider must never be asked for an offset
  6950. // outside the representation.
  6951. auto check = [&](int status, const char *range) {
  6952. auto path =
  6953. std::string("/streamed-with-range?status=") + std::to_string(status);
  6954. auto ctx = path + " Range: " + range;
  6955. auto res = cli_.Get(path, Headers{{"Range", range}});
  6956. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6957. EXPECT_EQ(status, res->status) << ctx;
  6958. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6959. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6960. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6961. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6962. };
  6963. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6964. check(403, "bytes=3-5");
  6965. // The offset is far past the representation.
  6966. check(403, "bytes=100000-100200");
  6967. // `first_pos` is still -1 here, and the bounds asserts in
  6968. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6969. check(403, "bytes=-3");
  6970. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6971. // multipart branch would have written one that is empty.
  6972. check(403, "bytes=1-2, 4-5");
  6973. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6974. // covers the whole representation.
  6975. check(200, "bytes=3-5");
  6976. check(200, "bytes=1-2, 4-5");
  6977. }
  6978. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6979. auto res =
  6980. cli_.Get("/streamed-with-range",
  6981. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6982. "92233720368547758079223372036854775807"}});
  6983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6984. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6985. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6986. EXPECT_EQ(false, res->has_header("Content-Range"));
  6987. EXPECT_EQ(0U, res->body.size());
  6988. }
  6989. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6990. auto res = cli_.Get(
  6991. "/with-range",
  6992. Headers{{"Range",
  6993. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6994. {"Accept-Encoding", ""}});
  6995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6996. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6997. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6998. EXPECT_EQ(true, res->has_header("Content-Range"));
  6999. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7000. EXPECT_EQ(std::string("abcdefg"), res->body);
  7001. }
  7002. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7003. auto res = cli_.Get("/with-range", Headers{
  7004. {"Range", "bytes=0-"},
  7005. {"Accept-Encoding", ""},
  7006. });
  7007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7008. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7009. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7010. EXPECT_EQ(true, res->has_header("Content-Range"));
  7011. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7012. EXPECT_EQ(std::string("abcdefg"), res->body);
  7013. }
  7014. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7015. auto res = cli_.Get("/streamed-with-range",
  7016. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7018. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7019. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7020. EXPECT_EQ(false, res->has_header("Content-Range"));
  7021. EXPECT_EQ(267U, res->body.size());
  7022. // Check that both range contents are present
  7023. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7024. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7025. // Check that Content-Range headers are present for both ranges
  7026. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7027. std::string::npos);
  7028. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7029. std::string::npos);
  7030. }
  7031. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7032. Ranges ranges;
  7033. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7034. ranges.emplace_back(0, -1);
  7035. }
  7036. auto res = cli_.Get("/streamed-with-range?error",
  7037. Headers{{make_range_header(ranges)}});
  7038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7039. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7040. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7041. EXPECT_EQ(false, res->has_header("Content-Range"));
  7042. EXPECT_EQ(0U, res->body.size());
  7043. }
  7044. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7045. auto res = cli_.Get("/streamed-with-range",
  7046. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7048. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7049. EXPECT_EQ(5U, res->body.size());
  7050. // Check that overlapping ranges are coalesced into a single range
  7051. EXPECT_EQ("bcdef", res->body);
  7052. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7053. // Should be single range, not multipart
  7054. EXPECT_TRUE(res->has_header("Content-Range"));
  7055. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7056. }
  7057. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7058. auto res = cli_.Get("/streamed-with-range",
  7059. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7061. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7062. EXPECT_EQ(268U, res->body.size());
  7063. // Check that both range contents are present
  7064. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7065. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7066. // Check that Content-Range headers are present for both ranges
  7067. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7068. std::string::npos);
  7069. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7070. std::string::npos);
  7071. }
  7072. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7073. auto res = cli_.Get("/streamed-with-range",
  7074. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7076. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7077. EXPECT_EQ(269U, res->body.size());
  7078. // Check that both duplicate range contents are present
  7079. size_t first_abc = res->body.find("abc\r\n");
  7080. EXPECT_TRUE(first_abc != std::string::npos);
  7081. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7082. EXPECT_TRUE(second_abc != std::string::npos);
  7083. // Check that Content-Range headers are present for both ranges
  7084. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7085. EXPECT_TRUE(first_range != std::string::npos);
  7086. size_t second_range =
  7087. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7088. EXPECT_TRUE(second_range != std::string::npos);
  7089. }
  7090. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7091. auto res =
  7092. cli_.Get("/streamed-with-range?error",
  7093. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7095. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7096. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7097. EXPECT_EQ(false, res->has_header("Content-Range"));
  7098. EXPECT_EQ(0U, res->body.size());
  7099. }
  7100. TEST_F(ServerTest, GetStreamedEndless) {
  7101. uint64_t offset = 0;
  7102. auto res = cli_.Get("/streamed-cancel",
  7103. [&](const char * /*data*/, uint64_t data_length) {
  7104. if (offset < 100) {
  7105. offset += data_length;
  7106. return true;
  7107. }
  7108. return false;
  7109. });
  7110. ASSERT_TRUE(!res);
  7111. EXPECT_EQ(Error::Canceled, res.error());
  7112. }
  7113. TEST_F(ServerTest, ClientStop) {
  7114. std::atomic_size_t count{4};
  7115. std::vector<std::thread> threads;
  7116. for (auto i = count.load(); i != 0; --i) {
  7117. threads.emplace_back([&]() {
  7118. auto res = cli_.Get("/streamed-cancel",
  7119. [&](const char *, uint64_t) { return true; });
  7120. --count;
  7121. ASSERT_TRUE(!res);
  7122. EXPECT_TRUE(res.error() == Error::Canceled ||
  7123. res.error() == Error::Read || res.error() == Error::Write);
  7124. });
  7125. }
  7126. std::this_thread::sleep_for(std::chrono::seconds(2));
  7127. while (count != 0) {
  7128. cli_.stop();
  7129. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7130. }
  7131. for (auto &t : threads) {
  7132. t.join();
  7133. }
  7134. }
  7135. TEST_F(ServerTest, GetWithRange1) {
  7136. auto res = cli_.Get("/with-range", Headers{
  7137. make_range_header({{3, 5}}),
  7138. {"Accept-Encoding", ""},
  7139. });
  7140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7141. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7142. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7143. EXPECT_EQ(true, res->has_header("Content-Range"));
  7144. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7145. EXPECT_EQ(std::string("def"), res->body);
  7146. }
  7147. TEST_F(ServerTest, GetWithRange2) {
  7148. auto res = cli_.Get("/with-range", Headers{
  7149. make_range_header({{1, -1}}),
  7150. {"Accept-Encoding", ""},
  7151. });
  7152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7153. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7154. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7155. EXPECT_EQ(true, res->has_header("Content-Range"));
  7156. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7157. EXPECT_EQ(std::string("bcdefg"), res->body);
  7158. }
  7159. TEST_F(ServerTest, GetWithRange3) {
  7160. auto res = cli_.Get("/with-range", Headers{
  7161. make_range_header({{0, 0}}),
  7162. {"Accept-Encoding", ""},
  7163. });
  7164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7165. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7166. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7167. EXPECT_EQ(true, res->has_header("Content-Range"));
  7168. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7169. EXPECT_EQ(std::string("a"), res->body);
  7170. }
  7171. TEST_F(ServerTest, GetWithRange4) {
  7172. auto res = cli_.Get("/with-range", Headers{
  7173. make_range_header({{-1, 2}}),
  7174. {"Accept-Encoding", ""},
  7175. });
  7176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7177. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7178. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7179. EXPECT_EQ(true, res->has_header("Content-Range"));
  7180. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7181. EXPECT_EQ(std::string("fg"), res->body);
  7182. }
  7183. TEST_F(ServerTest, GetWithRange5) {
  7184. auto res = cli_.Get("/with-range", Headers{
  7185. make_range_header({{0, 5}}),
  7186. {"Accept-Encoding", ""},
  7187. });
  7188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7189. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7190. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7191. EXPECT_EQ(true, res->has_header("Content-Range"));
  7192. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7193. EXPECT_EQ(std::string("abcdef"), res->body);
  7194. }
  7195. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7196. auto res =
  7197. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7199. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7200. }
  7201. TEST_F(ServerTest, GetWithRangeMultipart) {
  7202. auto res =
  7203. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7205. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7206. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7207. EXPECT_EQ(false, res->has_header("Content-Range"));
  7208. EXPECT_EQ(267U, res->body.size());
  7209. }
  7210. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7211. auto res = cli_.Get("/with-range",
  7212. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7214. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7215. }
  7216. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7217. auto res = cli_.Get("/with-range-customized-response",
  7218. Headers{{make_range_header({{1, 2}})}});
  7219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7220. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7221. EXPECT_EQ(true, res->has_header("Content-Length"));
  7222. EXPECT_EQ(false, res->has_header("Content-Range"));
  7223. EXPECT_EQ(JSON_DATA, res->body);
  7224. }
  7225. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7226. auto res = cli_.Get("/with-range-customized-response",
  7227. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7229. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7230. EXPECT_EQ(true, res->has_header("Content-Length"));
  7231. EXPECT_EQ(false, res->has_header("Content-Range"));
  7232. EXPECT_EQ(JSON_DATA, res->body);
  7233. }
  7234. TEST_F(ServerTest, Issue1772) {
  7235. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7237. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7238. }
  7239. TEST_F(ServerTest, Issue609) {
  7240. auto res = cli_.Delete("/issue609");
  7241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7242. EXPECT_EQ(StatusCode::OK_200, res->status);
  7243. EXPECT_EQ(std::string("ok"), res->body);
  7244. }
  7245. TEST_F(ServerTest, GetStreamedChunked) {
  7246. auto res = cli_.Get("/streamed-chunked");
  7247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7248. EXPECT_EQ(StatusCode::OK_200, res->status);
  7249. EXPECT_EQ(std::string("123456789"), res->body);
  7250. }
  7251. TEST_F(ServerTest, GetStreamedChunked2) {
  7252. auto res = cli_.Get("/streamed-chunked2");
  7253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7254. EXPECT_EQ(StatusCode::OK_200, res->status);
  7255. EXPECT_EQ(std::string("123456789"), res->body);
  7256. }
  7257. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7258. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7260. EXPECT_EQ(StatusCode::OK_200, res->status);
  7261. EXPECT_EQ(std::string("123456789"), res->body);
  7262. EXPECT_TRUE(res->has_header("Trailer"));
  7263. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7264. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7265. // Trailers are now stored separately from headers (security fix)
  7266. EXPECT_EQ(2U, res->trailers.size());
  7267. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7268. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7269. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7270. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7271. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7272. // Verify trailers are NOT in headers (security verification)
  7273. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7274. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7275. }
  7276. TEST_F(ServerTest, LargeChunkedPost) {
  7277. Request req;
  7278. req.method = "POST";
  7279. req.path = "/large-chunked";
  7280. std::string host_and_port;
  7281. host_and_port += HOST;
  7282. host_and_port += ":";
  7283. host_and_port += std::to_string(PORT);
  7284. req.headers.emplace("Host", host_and_port.c_str());
  7285. req.headers.emplace("Accept", "*/*");
  7286. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7287. req.headers.emplace("Content-Type", "text/plain");
  7288. req.headers.emplace("Content-Length", "0");
  7289. req.headers.emplace("Transfer-Encoding", "chunked");
  7290. std::string long_string(30 * 1024u, 'a');
  7291. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7292. // Attempt to make a large enough post to exceed OS buffers, to test that
  7293. // the server handles short reads if the full chunk data isn't available.
  7294. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7295. auto res = std::make_shared<Response>();
  7296. auto error = Error::Success;
  7297. auto ret = cli_.send(req, *res, error);
  7298. ASSERT_TRUE(ret);
  7299. EXPECT_EQ(StatusCode::OK_200, res->status);
  7300. }
  7301. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7302. auto res = cli_.Get("/remote_addr");
  7303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7304. EXPECT_EQ(StatusCode::OK_200, res->status);
  7305. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7306. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7307. }
  7308. TEST_F(ServerTest, GetMethodLocalAddr) {
  7309. auto res = cli_.Get("/local_addr");
  7310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7311. EXPECT_EQ(StatusCode::OK_200, res->status);
  7312. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7313. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7314. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7315. }
  7316. TEST_F(ServerTest, HTTPResponseSplitting) {
  7317. auto res = cli_.Get("/http_response_splitting");
  7318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7319. EXPECT_EQ(StatusCode::OK_200, res->status);
  7320. }
  7321. TEST_F(ServerTest, SlowRequest) {
  7322. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7323. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7324. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7325. }
  7326. #if 0
  7327. TEST_F(ServerTest, SlowPost) {
  7328. char buffer[64 * 1024];
  7329. memset(buffer, 0x42, sizeof(buffer));
  7330. auto res = cli_.Post(
  7331. "/slowpost", 64 * 1024 * 1024,
  7332. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7333. auto ret = sink.write(buffer, sizeof(buffer));
  7334. EXPECT_TRUE(ret);
  7335. return true;
  7336. },
  7337. "text/plain");
  7338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7339. EXPECT_EQ(StatusCode::OK_200, res->status);
  7340. }
  7341. TEST_F(ServerTest, SlowPostFail) {
  7342. char buffer[64 * 1024];
  7343. memset(buffer, 0x42, sizeof(buffer));
  7344. cli_.set_write_timeout(std::chrono::seconds(0));
  7345. auto res = cli_.Post(
  7346. "/slowpost", 64 * 1024 * 1024,
  7347. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7348. sink.write(buffer, sizeof(buffer));
  7349. return true;
  7350. },
  7351. "text/plain");
  7352. ASSERT_TRUE(!res);
  7353. EXPECT_EQ(Error::Write, res.error());
  7354. }
  7355. #endif
  7356. TEST_F(ServerTest, Put) {
  7357. auto res = cli_.Put("/put", "PUT", "text/plain");
  7358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7359. EXPECT_EQ(StatusCode::OK_200, res->status);
  7360. EXPECT_EQ("PUT", res->body);
  7361. }
  7362. TEST_F(ServerTest, PutWithContentProvider) {
  7363. auto res = cli_.Put(
  7364. "/put", 3,
  7365. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7366. sink.os << "PUT";
  7367. return true;
  7368. },
  7369. "text/plain");
  7370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7371. EXPECT_EQ(StatusCode::OK_200, res->status);
  7372. EXPECT_EQ("PUT", res->body);
  7373. }
  7374. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7375. auto res = cli_.Post(
  7376. "/post", 42,
  7377. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7378. return false;
  7379. },
  7380. "text/plain");
  7381. ASSERT_TRUE(!res);
  7382. EXPECT_EQ(Error::Canceled, res.error());
  7383. }
  7384. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7385. auto res = cli_.Put(
  7386. "/put",
  7387. [](size_t /*offset*/, DataSink &sink) {
  7388. sink.os << "PUT";
  7389. sink.done();
  7390. return true;
  7391. },
  7392. "text/plain");
  7393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7394. EXPECT_EQ(StatusCode::OK_200, res->status);
  7395. EXPECT_EQ("PUT", res->body);
  7396. }
  7397. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7398. auto res = cli_.Post(
  7399. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7400. "text/plain");
  7401. ASSERT_TRUE(!res);
  7402. EXPECT_EQ(Error::Canceled, res.error());
  7403. }
  7404. TEST_F(ServerTest, PostLoopBack) {
  7405. std::string body;
  7406. auto res = cli_.Post(
  7407. "/post-loopback", 9,
  7408. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7409. EXPECT_EQ(9u, length);
  7410. sink.write("123", 3);
  7411. sink.write("456", 3);
  7412. sink.write("789", 3);
  7413. return true;
  7414. },
  7415. "text/plain",
  7416. [&body](const char *data, size_t data_length) {
  7417. body.append(data, data_length);
  7418. return true;
  7419. });
  7420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7421. EXPECT_EQ(StatusCode::OK_200, res->status);
  7422. EXPECT_EQ("123456789", body);
  7423. }
  7424. TEST_F(ServerTest, PutLoopBack) {
  7425. std::string body;
  7426. auto res = cli_.Put(
  7427. "/put-loopback", 9,
  7428. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7429. EXPECT_EQ(9u, length);
  7430. sink.write("123", 3);
  7431. sink.write("456", 3);
  7432. sink.write("789", 3);
  7433. return true;
  7434. },
  7435. "text/plain",
  7436. [&body](const char *data, size_t data_length) {
  7437. body.append(data, data_length);
  7438. return true;
  7439. });
  7440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7441. EXPECT_EQ(StatusCode::OK_200, res->status);
  7442. EXPECT_EQ("123456789", body);
  7443. }
  7444. TEST_F(ServerTest, PatchLoopBack) {
  7445. std::string body;
  7446. auto res = cli_.Patch(
  7447. "/patch-loopback", 9,
  7448. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7449. EXPECT_EQ(9u, length);
  7450. sink.write("123", 3);
  7451. sink.write("456", 3);
  7452. sink.write("789", 3);
  7453. return true;
  7454. },
  7455. "text/plain",
  7456. [&body](const char *data, size_t data_length) {
  7457. body.append(data, data_length);
  7458. return true;
  7459. });
  7460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7461. EXPECT_EQ(StatusCode::OK_200, res->status);
  7462. EXPECT_EQ("123456789", body);
  7463. }
  7464. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7465. std::string body;
  7466. auto res = cli_.Post(
  7467. "/post-loopback",
  7468. [](size_t /*offset*/, DataSink &sink) {
  7469. sink.write("123", 3);
  7470. sink.write("456", 3);
  7471. sink.write("789", 3);
  7472. sink.done();
  7473. return true;
  7474. },
  7475. "text/plain",
  7476. [&body](const char *data, size_t data_length) {
  7477. body.append(data, data_length);
  7478. return true;
  7479. });
  7480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7481. EXPECT_EQ(StatusCode::OK_200, res->status);
  7482. EXPECT_EQ("123456789", body);
  7483. }
  7484. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7485. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7486. cli_.set_compress(true);
  7487. auto res = cli_.Put(
  7488. "/put", 3,
  7489. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7490. sink.os << "PUT";
  7491. return true;
  7492. },
  7493. "text/plain");
  7494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7495. EXPECT_EQ(StatusCode::OK_200, res->status);
  7496. EXPECT_EQ("PUT", res->body);
  7497. }
  7498. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7499. cli_.set_compress(true);
  7500. auto res = cli_.Post(
  7501. "/post", 42,
  7502. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7503. return false;
  7504. },
  7505. "text/plain");
  7506. ASSERT_TRUE(!res);
  7507. EXPECT_EQ(Error::Canceled, res.error());
  7508. }
  7509. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7510. cli_.set_compress(true);
  7511. auto res = cli_.Put(
  7512. "/put",
  7513. [](size_t /*offset*/, DataSink &sink) {
  7514. sink.os << "PUT";
  7515. sink.done();
  7516. return true;
  7517. },
  7518. "text/plain");
  7519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7520. EXPECT_EQ(StatusCode::OK_200, res->status);
  7521. EXPECT_EQ("PUT", res->body);
  7522. }
  7523. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7524. cli_.set_compress(true);
  7525. auto res = cli_.Post(
  7526. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7527. "text/plain");
  7528. ASSERT_TRUE(!res);
  7529. EXPECT_EQ(Error::Canceled, res.error());
  7530. }
  7531. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7532. cli_.set_compress(true);
  7533. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7535. EXPECT_EQ(StatusCode::OK_200, res->status);
  7536. EXPECT_EQ(LARGE_DATA, res->body);
  7537. }
  7538. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7539. #ifdef CPPHTTPLIB_SSL_ENABLED
  7540. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7541. Client cli(s.c_str());
  7542. cli.enable_server_certificate_verification(false);
  7543. #else
  7544. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7545. Client cli(s.c_str());
  7546. #endif
  7547. cli.set_compress(true);
  7548. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7550. EXPECT_EQ(StatusCode::OK_200, res->status);
  7551. EXPECT_EQ(LARGE_DATA, res->body);
  7552. // The compressed size should be less than a 10th of the original. May vary
  7553. // depending on the zlib library.
  7554. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7555. static_cast<uint64_t>(10 * 1024 * 1024));
  7556. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7557. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7558. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7559. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7560. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7561. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7562. #endif
  7563. }
  7564. TEST_F(ServerTest, PutContentWithDeflate) {
  7565. cli_.set_compress(false);
  7566. Headers headers;
  7567. headers.emplace("Content-Encoding", "deflate");
  7568. // PUT in deflate format:
  7569. auto res = cli_.Put("/put", headers,
  7570. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7572. EXPECT_EQ(StatusCode::OK_200, res->status);
  7573. EXPECT_EQ("PUT", res->body);
  7574. }
  7575. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7576. Headers headers;
  7577. headers.emplace("Accept-Encoding", "gzip, deflate");
  7578. auto res = cli_.Get("/streamed-chunked", headers);
  7579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7580. EXPECT_EQ(StatusCode::OK_200, res->status);
  7581. EXPECT_EQ(std::string("123456789"), res->body);
  7582. }
  7583. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7584. Headers headers;
  7585. headers.emplace("Accept-Encoding", "gzip, deflate");
  7586. auto res = cli_.Get("/streamed-chunked2", headers);
  7587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7588. EXPECT_EQ(StatusCode::OK_200, res->status);
  7589. EXPECT_EQ(std::string("123456789"), res->body);
  7590. }
  7591. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7592. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7594. EXPECT_EQ(StatusCode::OK_200, res->status);
  7595. }
  7596. TEST(GzipDecompressor, ChunkedDecompression) {
  7597. std::string data;
  7598. for (size_t i = 0; i < 32 * 1024; ++i) {
  7599. data.push_back(static_cast<char>('a' + i % 26));
  7600. }
  7601. std::string compressed_data;
  7602. {
  7603. httplib::detail::gzip_compressor compressor;
  7604. bool result = compressor.compress(
  7605. data.data(), data.size(),
  7606. /*last=*/true,
  7607. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7608. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7609. compressed_data_size);
  7610. return true;
  7611. });
  7612. ASSERT_TRUE(result);
  7613. }
  7614. std::string decompressed_data;
  7615. {
  7616. httplib::detail::gzip_decompressor decompressor;
  7617. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7618. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7619. size_t chunk_size = 130;
  7620. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7621. chunk_begin += chunk_size) {
  7622. size_t current_chunk_size =
  7623. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7624. bool result = decompressor.decompress(
  7625. compressed_data.data() + chunk_begin, current_chunk_size,
  7626. [&](const char *decompressed_data_chunk,
  7627. size_t decompressed_data_chunk_size) {
  7628. decompressed_data.insert(decompressed_data.size(),
  7629. decompressed_data_chunk,
  7630. decompressed_data_chunk_size);
  7631. return true;
  7632. });
  7633. ASSERT_TRUE(result);
  7634. }
  7635. }
  7636. ASSERT_EQ(data, decompressed_data);
  7637. }
  7638. TEST(GzipDecompressor, DeflateDecompression) {
  7639. std::string original_text = "Raw deflate without gzip";
  7640. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7641. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7642. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7643. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7644. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7645. std::string decompressed_data;
  7646. {
  7647. httplib::detail::gzip_decompressor decompressor;
  7648. bool result = decompressor.decompress(
  7649. compressed_data.data(), compressed_data.size(),
  7650. [&](const char *decompressed_data_chunk,
  7651. size_t decompressed_data_chunk_size) {
  7652. decompressed_data.insert(decompressed_data.size(),
  7653. decompressed_data_chunk,
  7654. decompressed_data_chunk_size);
  7655. return true;
  7656. });
  7657. ASSERT_TRUE(result);
  7658. }
  7659. ASSERT_EQ(original_text, decompressed_data);
  7660. }
  7661. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7662. std::string original_text = "Raw deflate without gzip";
  7663. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7664. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7665. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7666. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7667. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7668. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7669. std::string decompressed_data;
  7670. {
  7671. httplib::detail::gzip_decompressor decompressor;
  7672. bool result = decompressor.decompress(
  7673. compressed_data.data(), compressed_data.size(),
  7674. [&](const char *decompressed_data_chunk,
  7675. size_t decompressed_data_chunk_size) {
  7676. decompressed_data.insert(decompressed_data.size(),
  7677. decompressed_data_chunk,
  7678. decompressed_data_chunk_size);
  7679. return true;
  7680. });
  7681. ASSERT_TRUE(result);
  7682. }
  7683. ASSERT_EQ(original_text, decompressed_data);
  7684. }
  7685. #endif
  7686. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7687. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7688. Headers headers;
  7689. headers.emplace("Accept-Encoding", "br");
  7690. auto res = cli_.Get("/streamed-chunked", headers);
  7691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7692. EXPECT_EQ(StatusCode::OK_200, res->status);
  7693. EXPECT_EQ(std::string("123456789"), res->body);
  7694. }
  7695. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7696. Headers headers;
  7697. headers.emplace("Accept-Encoding", "br");
  7698. auto res = cli_.Get("/streamed-chunked2", headers);
  7699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7700. EXPECT_EQ(StatusCode::OK_200, res->status);
  7701. EXPECT_EQ(std::string("123456789"), res->body);
  7702. }
  7703. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7704. cli_.set_compress(true);
  7705. auto res = cli_.Put(
  7706. "/put", 3,
  7707. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7708. sink.os << "PUT";
  7709. return true;
  7710. },
  7711. "text/plain");
  7712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7713. EXPECT_EQ(StatusCode::OK_200, res->status);
  7714. EXPECT_EQ("PUT", res->body);
  7715. }
  7716. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7717. cli_.set_compress(true);
  7718. auto res = cli_.Put(
  7719. "/put",
  7720. [](size_t /*offset*/, DataSink &sink) {
  7721. sink.os << "PUT";
  7722. sink.done();
  7723. return true;
  7724. },
  7725. "text/plain");
  7726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7727. EXPECT_EQ(StatusCode::OK_200, res->status);
  7728. EXPECT_EQ("PUT", res->body);
  7729. }
  7730. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7731. cli_.set_compress(true);
  7732. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7734. EXPECT_EQ(StatusCode::OK_200, res->status);
  7735. EXPECT_EQ(LARGE_DATA, res->body);
  7736. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7737. }
  7738. #endif
  7739. TEST_F(ServerTest, Patch) {
  7740. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7742. EXPECT_EQ(StatusCode::OK_200, res->status);
  7743. EXPECT_EQ("PATCH", res->body);
  7744. }
  7745. TEST_F(ServerTest, Delete) {
  7746. auto res = cli_.Delete("/delete");
  7747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7748. EXPECT_EQ(StatusCode::OK_200, res->status);
  7749. EXPECT_EQ("DELETE", res->body);
  7750. }
  7751. TEST_F(ServerTest, DeleteContentReceiver) {
  7752. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7754. EXPECT_EQ(StatusCode::OK_200, res->status);
  7755. EXPECT_EQ("content", res->body);
  7756. }
  7757. TEST_F(ServerTest, Options) {
  7758. auto res = cli_.Options("*");
  7759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7760. EXPECT_EQ(StatusCode::OK_200, res->status);
  7761. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7762. EXPECT_TRUE(res->body.empty());
  7763. }
  7764. TEST_F(ServerTest, URL) {
  7765. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7767. EXPECT_EQ(StatusCode::OK_200, res->status);
  7768. }
  7769. TEST_F(ServerTest, ArrayParam) {
  7770. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7772. EXPECT_EQ(StatusCode::OK_200, res->status);
  7773. }
  7774. TEST_F(ServerTest, ArrayParamValues) {
  7775. auto res =
  7776. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7778. EXPECT_EQ(StatusCode::OK_200, res->status);
  7779. }
  7780. TEST_F(ServerTest, NoMultipleHeaders) {
  7781. Headers headers = {{"Content-Length", "5"}};
  7782. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7783. "text/plain");
  7784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7785. EXPECT_EQ(StatusCode::OK_200, res->status);
  7786. }
  7787. TEST_F(ServerTest, PostContentReceiver) {
  7788. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7790. ASSERT_EQ(StatusCode::OK_200, res->status);
  7791. ASSERT_EQ("content", res->body);
  7792. }
  7793. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7794. UploadFormDataItems items = {
  7795. {"text1", "text default", "", ""},
  7796. {"text2", "aωb", "", ""},
  7797. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7798. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7799. {"file3", "", "", "application/octet-stream"},
  7800. };
  7801. auto res = cli_.Post("/content_receiver", items);
  7802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7803. EXPECT_EQ(StatusCode::OK_200, res->status);
  7804. }
  7805. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7806. UploadFormDataItems items = {
  7807. {"text1", "text default", "", ""},
  7808. {"text2", "aωb", "", ""},
  7809. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7810. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7811. {"file3", "", "", "application/octet-stream"},
  7812. };
  7813. auto boundary = std::string("+++++");
  7814. std::string body;
  7815. for (const auto &item : items) {
  7816. body += "--" + boundary + "\r\n";
  7817. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7818. if (!item.filename.empty()) {
  7819. body += "; filename=\"" + item.filename + "\"";
  7820. }
  7821. body += "\r\n";
  7822. if (!item.content_type.empty()) {
  7823. body += "Content-Type: " + item.content_type + "\r\n";
  7824. }
  7825. body += "\r\n";
  7826. body += item.content + "\r\n";
  7827. }
  7828. body += "--" + boundary + "--\r\n";
  7829. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7830. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7832. EXPECT_EQ(StatusCode::OK_200, res->status);
  7833. }
  7834. TEST(MultipartFormDataTest, FieldEscaping) {
  7835. Server svr;
  7836. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7837. const ContentReader &content_reader) {
  7838. ASSERT_TRUE(req.is_multipart_form_data());
  7839. std::vector<FormData> received;
  7840. content_reader(
  7841. [&](const FormData &file) {
  7842. received.push_back(file);
  7843. return true;
  7844. },
  7845. [&](const char *data, size_t data_length) {
  7846. received.back().content.append(data, data_length);
  7847. return true;
  7848. });
  7849. // '"', CR and LF in names and filenames are escaped following the
  7850. // WHATWG HTML standard, so each part still parses as a single part
  7851. // with no injected headers. Content types get CR/LF escaped too,
  7852. // while '"' (legal there, e.g. quoted charset) is preserved.
  7853. ASSERT_EQ(4U, received.size());
  7854. EXPECT_EQ("na%22me", received[0].name);
  7855. EXPECT_EQ("quoted name", received[0].content);
  7856. EXPECT_EQ("file", received[1].name);
  7857. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7858. received[1].filename);
  7859. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7860. EXPECT_EQ("injected", received[1].content);
  7861. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7862. EXPECT_EQ("my%22file.txt", received[2].filename);
  7863. EXPECT_EQ("cr lf name", received[2].content);
  7864. EXPECT_EQ("typed", received[3].name);
  7865. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7866. received[3].content_type);
  7867. EXPECT_EQ("typed content", received[3].content);
  7868. });
  7869. auto port = svr.bind_to_any_port("localhost");
  7870. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7871. auto se = detail::scope_exit([&] {
  7872. svr.stop();
  7873. t.join();
  7874. ASSERT_FALSE(svr.is_running());
  7875. });
  7876. svr.wait_until_ready();
  7877. Client cli("localhost", port);
  7878. UploadFormDataItems items = {
  7879. {"na\"me", "quoted name", "", ""},
  7880. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7881. "application/octet-stream"},
  7882. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7883. {"typed", "typed content", "",
  7884. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7885. };
  7886. auto res = cli.Post("/post", items);
  7887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7888. EXPECT_EQ(StatusCode::OK_200, res->status);
  7889. }
  7890. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7891. const UploadFormDataItems items = {
  7892. {"name1", "Content 1", "", ""},
  7893. {"name2", "Content 2", "file2.txt", "text/plain"},
  7894. };
  7895. Server svr;
  7896. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7897. const ContentReader &content_reader) {
  7898. ASSERT_TRUE(req.is_multipart_form_data());
  7899. std::vector<FormData> received;
  7900. content_reader(
  7901. [&](const FormData &file) {
  7902. received.push_back(file);
  7903. return true;
  7904. },
  7905. [&](const char *data, size_t data_length) {
  7906. received.back().content.append(data, data_length);
  7907. return true;
  7908. });
  7909. ASSERT_EQ(2U, received.size());
  7910. EXPECT_EQ("name1", received[0].name);
  7911. EXPECT_EQ("Content 1", received[0].content);
  7912. EXPECT_EQ("name2", received[1].name);
  7913. EXPECT_EQ("Content 2", received[1].content);
  7914. EXPECT_EQ("file2.txt", received[1].filename);
  7915. EXPECT_EQ("text/plain", received[1].content_type);
  7916. });
  7917. auto port = svr.bind_to_any_port("localhost");
  7918. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7919. auto se = detail::scope_exit([&] {
  7920. svr.stop();
  7921. t.join();
  7922. ASSERT_FALSE(svr.is_running());
  7923. });
  7924. svr.wait_until_ready();
  7925. Client cli("localhost", port);
  7926. // Whole-body serialization with a generated boundary
  7927. {
  7928. MultipartFormDataWriter writer;
  7929. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7930. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7931. writer.content_type());
  7932. auto body = writer.serialize(items);
  7933. EXPECT_EQ(body.size(), writer.content_length(items));
  7934. auto res = cli.Post("/post", body, writer.content_type());
  7935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7936. EXPECT_EQ(StatusCode::OK_200, res->status);
  7937. }
  7938. // Per-part framing with a custom boundary via a content provider
  7939. {
  7940. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7941. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7942. MultipartFormDataWriter writer("custom-boundary_123");
  7943. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7944. std::string body;
  7945. for (const auto &item : items) {
  7946. body += writer.item_begin(item);
  7947. body += item.content;
  7948. body += MultipartFormDataWriter::item_end();
  7949. }
  7950. body += writer.finish();
  7951. EXPECT_EQ(body.size(), writer.content_length(items));
  7952. auto res = cli.Post(
  7953. "/post", body.size(),
  7954. [&](size_t offset, size_t length, DataSink &sink) {
  7955. sink.write(body.data() + offset, length);
  7956. return true;
  7957. },
  7958. writer.content_type());
  7959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7960. EXPECT_EQ(StatusCode::OK_200, res->status);
  7961. }
  7962. }
  7963. TEST_F(ServerTest, PostContentReceiverGzip) {
  7964. cli_.set_compress(true);
  7965. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7967. ASSERT_EQ(StatusCode::OK_200, res->status);
  7968. ASSERT_EQ("content", res->body);
  7969. }
  7970. TEST_F(ServerTest, PutContentReceiver) {
  7971. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7973. ASSERT_EQ(StatusCode::OK_200, res->status);
  7974. ASSERT_EQ("content", res->body);
  7975. }
  7976. TEST_F(ServerTest, PatchContentReceiver) {
  7977. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7979. ASSERT_EQ(StatusCode::OK_200, res->status);
  7980. ASSERT_EQ("content", res->body);
  7981. }
  7982. template <typename ClientType>
  7983. void TestWithHeadersAndContentReceiver(
  7984. ClientType &cli,
  7985. std::function<Result(ClientType &, const std::string &, const Headers &,
  7986. const std::string &, const std::string &,
  7987. ContentReceiver, DownloadProgress)>
  7988. request_func) {
  7989. Headers headers;
  7990. headers.emplace("X-Custom-Header", "test-value");
  7991. std::string received_body;
  7992. auto res = request_func(
  7993. cli, "/content_receiver", headers, "content", "application/json",
  7994. [&](const char *data, size_t data_length) {
  7995. received_body.append(data, data_length);
  7996. return true;
  7997. },
  7998. nullptr);
  7999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8000. EXPECT_EQ(StatusCode::OK_200, res->status);
  8001. EXPECT_EQ("content", received_body);
  8002. }
  8003. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8004. #ifdef CPPHTTPLIB_SSL_ENABLED
  8005. using ClientT = SSLClient;
  8006. #else
  8007. using ClientT = Client;
  8008. #endif
  8009. TestWithHeadersAndContentReceiver<ClientT>(
  8010. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8011. const std::string &body, const std::string &content_type,
  8012. ContentReceiver receiver, DownloadProgress progress) {
  8013. return cli.Post(path, headers, body, content_type, receiver, progress);
  8014. });
  8015. }
  8016. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8017. #ifdef CPPHTTPLIB_SSL_ENABLED
  8018. using ClientT = SSLClient;
  8019. #else
  8020. using ClientT = Client;
  8021. #endif
  8022. TestWithHeadersAndContentReceiver<ClientT>(
  8023. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8024. const std::string &body, const std::string &content_type,
  8025. ContentReceiver receiver, DownloadProgress progress) {
  8026. return cli.Put(path, headers, body, content_type, receiver, progress);
  8027. });
  8028. }
  8029. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8030. #ifdef CPPHTTPLIB_SSL_ENABLED
  8031. using ClientT = SSLClient;
  8032. #else
  8033. using ClientT = Client;
  8034. #endif
  8035. TestWithHeadersAndContentReceiver<ClientT>(
  8036. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8037. const std::string &body, const std::string &content_type,
  8038. ContentReceiver receiver, DownloadProgress progress) {
  8039. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8040. });
  8041. }
  8042. template <typename ClientType>
  8043. void TestWithHeadersAndContentReceiverWithProgress(
  8044. ClientType &cli,
  8045. std::function<Result(ClientType &, const std::string &, const Headers &,
  8046. const std::string &, const std::string &,
  8047. ContentReceiver, DownloadProgress)>
  8048. request_func) {
  8049. Headers headers;
  8050. headers.emplace("X-Test-Header", "progress-test");
  8051. std::string received_body;
  8052. auto progress_called = false;
  8053. auto res = request_func(
  8054. cli, "/content_receiver", headers, "content", "text/plain",
  8055. [&](const char *data, size_t data_length) {
  8056. received_body.append(data, data_length);
  8057. return true;
  8058. },
  8059. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8060. progress_called = true;
  8061. return true;
  8062. });
  8063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8064. EXPECT_EQ(StatusCode::OK_200, res->status);
  8065. EXPECT_EQ("content", received_body);
  8066. EXPECT_TRUE(progress_called);
  8067. }
  8068. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8069. #ifdef CPPHTTPLIB_SSL_ENABLED
  8070. using ClientT = SSLClient;
  8071. #else
  8072. using ClientT = Client;
  8073. #endif
  8074. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8075. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8076. const std::string &body, const std::string &content_type,
  8077. ContentReceiver receiver, DownloadProgress progress) {
  8078. return cli.Post(path, headers, body, content_type, receiver, progress);
  8079. });
  8080. }
  8081. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8082. #ifdef CPPHTTPLIB_SSL_ENABLED
  8083. using ClientT = SSLClient;
  8084. #else
  8085. using ClientT = Client;
  8086. #endif
  8087. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8088. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8089. const std::string &body, const std::string &content_type,
  8090. ContentReceiver receiver, DownloadProgress progress) {
  8091. return cli.Put(path, headers, body, content_type, receiver, progress);
  8092. });
  8093. }
  8094. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8095. #ifdef CPPHTTPLIB_SSL_ENABLED
  8096. using ClientT = SSLClient;
  8097. #else
  8098. using ClientT = Client;
  8099. #endif
  8100. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8101. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8102. const std::string &body, const std::string &content_type,
  8103. ContentReceiver receiver, DownloadProgress progress) {
  8104. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8105. });
  8106. }
  8107. template <typename ClientType>
  8108. void TestWithHeadersAndContentReceiverError(
  8109. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8110. const Headers &, const std::string &,
  8111. const std::string &, ContentReceiver)>
  8112. request_func) {
  8113. Headers headers;
  8114. headers.emplace("X-Error-Test", "true");
  8115. std::string received_body;
  8116. auto receiver_failed = false;
  8117. auto res =
  8118. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8119. [&](const char *data, size_t data_length) {
  8120. received_body.append(data, data_length);
  8121. receiver_failed = true;
  8122. return false;
  8123. });
  8124. ASSERT_FALSE(res);
  8125. EXPECT_TRUE(receiver_failed);
  8126. }
  8127. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8128. #ifdef CPPHTTPLIB_SSL_ENABLED
  8129. using ClientT = SSLClient;
  8130. #else
  8131. using ClientT = Client;
  8132. #endif
  8133. TestWithHeadersAndContentReceiverError<ClientT>(
  8134. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8135. const std::string &body, const std::string &content_type,
  8136. ContentReceiver receiver) {
  8137. return cli.Post(path, headers, body, content_type, receiver);
  8138. });
  8139. }
  8140. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8141. #ifdef CPPHTTPLIB_SSL_ENABLED
  8142. using ClientT = SSLClient;
  8143. #else
  8144. using ClientT = Client;
  8145. #endif
  8146. TestWithHeadersAndContentReceiverError<ClientT>(
  8147. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8148. const std::string &body, const std::string &content_type,
  8149. ContentReceiver receiver) {
  8150. return cli.Put(path, headers, body, content_type, receiver);
  8151. });
  8152. }
  8153. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8154. #ifdef CPPHTTPLIB_SSL_ENABLED
  8155. using ClientT = SSLClient;
  8156. #else
  8157. using ClientT = Client;
  8158. #endif
  8159. TestWithHeadersAndContentReceiverError<ClientT>(
  8160. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8161. const std::string &body, const std::string &content_type,
  8162. ContentReceiver receiver) {
  8163. return cli.Patch(path, headers, body, content_type, receiver);
  8164. });
  8165. }
  8166. TEST_F(ServerTest, PostQueryStringAndBody) {
  8167. auto res =
  8168. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8170. ASSERT_EQ(StatusCode::OK_200, res->status);
  8171. }
  8172. TEST_F(ServerTest, HTTP2Magic) {
  8173. Request req;
  8174. req.method = "PRI";
  8175. req.path = "*";
  8176. req.body = "SM";
  8177. auto res = std::make_shared<Response>();
  8178. auto error = Error::Success;
  8179. auto ret = cli_.send(req, *res, error);
  8180. ASSERT_TRUE(ret);
  8181. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8182. }
  8183. TEST_F(ServerTest, KeepAlive) {
  8184. auto res = cli_.Get("/hi");
  8185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8186. EXPECT_EQ(StatusCode::OK_200, res->status);
  8187. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8188. EXPECT_EQ("Hello World!", res->body);
  8189. res = cli_.Get("/hi");
  8190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8191. EXPECT_EQ(StatusCode::OK_200, res->status);
  8192. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8193. EXPECT_EQ("Hello World!", res->body);
  8194. res = cli_.Get("/hi");
  8195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8196. EXPECT_EQ(StatusCode::OK_200, res->status);
  8197. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8198. EXPECT_EQ("Hello World!", res->body);
  8199. res = cli_.Get("/not-exist");
  8200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8201. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8202. res = cli_.Post("/empty", "", "text/plain");
  8203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8204. EXPECT_EQ(StatusCode::OK_200, res->status);
  8205. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8206. EXPECT_EQ("empty", res->body);
  8207. EXPECT_EQ("close", res->get_header_value("Connection"));
  8208. res = cli_.Post(
  8209. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8210. "text/plain");
  8211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8212. EXPECT_EQ(StatusCode::OK_200, res->status);
  8213. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8214. EXPECT_EQ("empty", res->body);
  8215. cli_.set_keep_alive(false);
  8216. res = cli_.Get("/last-request");
  8217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8218. EXPECT_EQ(StatusCode::OK_200, res->status);
  8219. EXPECT_EQ("close", res->get_header_value("Connection"));
  8220. }
  8221. TEST_F(ServerTest, TooManyRedirect) {
  8222. cli_.set_follow_location(true);
  8223. auto res = cli_.Get("/redirect/0");
  8224. ASSERT_TRUE(!res);
  8225. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8226. }
  8227. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8228. Request req;
  8229. req.method = "FOOBAR";
  8230. req.path = "/hi";
  8231. cli_.set_keep_alive(true);
  8232. auto res = cli_.send(req);
  8233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8234. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8235. EXPECT_EQ("close", res->get_header_value("Connection"));
  8236. EXPECT_FALSE(cli_.is_socket_open());
  8237. }
  8238. TEST_F(ServerTest, CustomRouteReadsBody) {
  8239. const std::string xml =
  8240. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8241. Request req;
  8242. req.method = "PROPFIND";
  8243. req.path = "/dav/dir";
  8244. req.set_header("Depth", "1");
  8245. req.body = xml;
  8246. auto res = cli_.send(req);
  8247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8248. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8249. EXPECT_EQ(xml, res->body);
  8250. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8251. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8252. }
  8253. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8254. Request req;
  8255. req.method = "PROPFIND";
  8256. req.path = "/dav/42";
  8257. auto res = cli_.send(req);
  8258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8259. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8260. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8261. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8262. }
  8263. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8264. Request req;
  8265. req.method = "PROPFIND";
  8266. req.path = "/dav-re/123";
  8267. auto res = cli_.send(req);
  8268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8269. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8270. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8271. }
  8272. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8273. Request req;
  8274. req.method = "MKCOL";
  8275. req.path = "/dav-mkcol";
  8276. auto res = cli_.send(req);
  8277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8278. EXPECT_EQ(StatusCode::Created_201, res->status);
  8279. }
  8280. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8281. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8282. Request req;
  8283. req.method = "REPORT";
  8284. req.path = "/dav-report";
  8285. req.body = xml;
  8286. auto res = cli_.send(req);
  8287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8288. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8289. EXPECT_EQ(xml, res->body);
  8290. }
  8291. // A content reader route must fire even when the request carries no body,
  8292. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8293. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8294. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8295. Request req;
  8296. req.method = "REPORT";
  8297. req.path = "/dav-report";
  8298. auto res = cli_.send(req);
  8299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8300. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8301. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8302. }
  8303. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8304. Request req;
  8305. req.method = "PROPFIND";
  8306. req.path = "/not-dav";
  8307. auto res = cli_.send(req);
  8308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8309. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8310. }
  8311. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8312. Request req;
  8313. req.method = "UNLOCK";
  8314. req.path = "/dav/dir";
  8315. cli_.set_keep_alive(true);
  8316. auto res = cli_.send(req);
  8317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8318. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8319. EXPECT_EQ("close", res->get_header_value("Connection"));
  8320. EXPECT_FALSE(cli_.is_socket_open());
  8321. }
  8322. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8323. // The mount point serves this path, but only for GET and HEAD.
  8324. auto get_res = cli_.Get("/dir/index.html");
  8325. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8326. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8327. Request req;
  8328. req.method = "PROPFIND";
  8329. req.path = "/dir/index.html";
  8330. auto res = cli_.send(req);
  8331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8332. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8333. }
  8334. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8335. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8336. cli_.set_keep_alive(true);
  8337. for (auto i = 0; i < 2; i++) {
  8338. Request req;
  8339. req.method = "PROPFIND";
  8340. req.path = "/dav/dir";
  8341. req.body = xml;
  8342. auto res = cli_.send(req);
  8343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8344. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8345. EXPECT_EQ(xml, res->body);
  8346. EXPECT_TRUE(cli_.is_socket_open());
  8347. }
  8348. // A built-in method must still be served on the same connection.
  8349. cli_.set_keep_alive(false);
  8350. auto res = cli_.Get("/hi");
  8351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8352. EXPECT_EQ(StatusCode::OK_200, res->status);
  8353. EXPECT_EQ("close", res->get_header_value("Connection"));
  8354. }
  8355. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8356. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8357. Request req;
  8358. req.method = "PROPFIND";
  8359. req.path = "/dav/dir";
  8360. req.set_header("Expect", "100-continue");
  8361. req.body = xml;
  8362. auto res = cli_.send(req);
  8363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8364. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8365. EXPECT_EQ(xml, res->body);
  8366. }
  8367. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8368. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8369. TEST_F(ServerTest, Gzip) {
  8370. Headers headers;
  8371. headers.emplace("Accept-Encoding", "gzip, deflate");
  8372. auto res = cli_.Get("/compress", headers);
  8373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8374. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8375. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8376. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8377. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8378. "7890123456789012345678901234567890",
  8379. res->body);
  8380. EXPECT_EQ(StatusCode::OK_200, res->status);
  8381. }
  8382. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8383. Headers headers;
  8384. headers.emplace("Accept-Encoding", "gzip, deflate");
  8385. auto res = cli_.Get("/compress-with-charset", headers);
  8386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8387. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8388. EXPECT_EQ("application/json; charset=utf-8",
  8389. res->get_header_value("Content-Type"));
  8390. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8391. "7890123456789012345678901234567890",
  8392. res->body);
  8393. EXPECT_EQ(StatusCode::OK_200, res->status);
  8394. }
  8395. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8396. Headers headers;
  8397. headers.emplace("Accept-Encoding", "");
  8398. auto res = cli_.Get("/compress", headers);
  8399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8400. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8401. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8402. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8403. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8404. "7890123456789012345678901234567890",
  8405. res->body);
  8406. EXPECT_EQ(StatusCode::OK_200, res->status);
  8407. }
  8408. TEST_F(ServerTest, GzipWithContentReceiver) {
  8409. Headers headers;
  8410. headers.emplace("Accept-Encoding", "gzip, deflate");
  8411. std::string body;
  8412. auto res = cli_.Get("/compress", headers,
  8413. [&](const char *data, uint64_t data_length) {
  8414. EXPECT_EQ(100U, data_length);
  8415. body.append(data, data_length);
  8416. return true;
  8417. });
  8418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8419. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8420. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8421. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8422. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8423. "7890123456789012345678901234567890",
  8424. body);
  8425. EXPECT_EQ(StatusCode::OK_200, res->status);
  8426. }
  8427. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8428. Headers headers;
  8429. headers.emplace("Accept-Encoding", "gzip, deflate");
  8430. cli_.set_decompress(false);
  8431. auto res = cli_.Get("/compress", headers);
  8432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8433. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8434. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8435. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8436. EXPECT_EQ(33U, res->body.size());
  8437. EXPECT_EQ(StatusCode::OK_200, res->status);
  8438. }
  8439. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8440. Headers headers;
  8441. headers.emplace("Accept-Encoding", "");
  8442. std::string body;
  8443. auto res = cli_.Get("/compress", headers,
  8444. [&](const char *data, uint64_t data_length) {
  8445. EXPECT_EQ(100U, data_length);
  8446. body.append(data, data_length);
  8447. return true;
  8448. });
  8449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8450. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8451. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8452. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8453. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8454. "7890123456789012345678901234567890",
  8455. body);
  8456. EXPECT_EQ(StatusCode::OK_200, res->status);
  8457. }
  8458. TEST_F(ServerTest, NoGzip) {
  8459. Headers headers;
  8460. headers.emplace("Accept-Encoding", "gzip, deflate");
  8461. auto res = cli_.Get("/nocompress", headers);
  8462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8463. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8464. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8465. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8466. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8467. "7890123456789012345678901234567890",
  8468. res->body);
  8469. EXPECT_EQ(StatusCode::OK_200, res->status);
  8470. }
  8471. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8472. Headers headers;
  8473. headers.emplace("Accept-Encoding", "gzip, deflate");
  8474. std::string body;
  8475. auto res = cli_.Get("/nocompress", headers,
  8476. [&](const char *data, uint64_t data_length) {
  8477. EXPECT_EQ(100U, data_length);
  8478. body.append(data, data_length);
  8479. return true;
  8480. });
  8481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8482. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8483. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8484. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8485. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8486. "7890123456789012345678901234567890",
  8487. body);
  8488. EXPECT_EQ(StatusCode::OK_200, res->status);
  8489. }
  8490. TEST_F(ServerTest, MultipartFormDataGzip) {
  8491. UploadFormDataItems items = {
  8492. {"key1", "test", "", ""},
  8493. {"key2", "--abcdefg123", "", ""},
  8494. };
  8495. cli_.set_compress(true);
  8496. auto res = cli_.Post("/compress-multipart", items);
  8497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8498. EXPECT_EQ(StatusCode::OK_200, res->status);
  8499. }
  8500. #endif
  8501. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8502. // Static file compression is opt-in, so these run their own server rather than
  8503. // flipping it on for the shared ServerTest fixture, which would silently
  8504. // rewrite what every other static file test is asserting.
  8505. class StaticFileCompressionTest : public ::testing::Test {
  8506. protected:
  8507. void TearDown() override {
  8508. if (t_.joinable()) {
  8509. svr_.stop();
  8510. t_.join();
  8511. }
  8512. }
  8513. int start(const std::function<void(Server &)> &configure = nullptr) {
  8514. // Serves the same tree as a directory of build-time compressed assets
  8515. // would be served: the mount point names the coding the files are already
  8516. // stored in. Registered before "/" so it is the one that matches.
  8517. svr_.set_mount_point("/pre-encoded", "./www",
  8518. {{"Content-Encoding", "gzip"}});
  8519. svr_.set_mount_point("/", "./www");
  8520. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8521. res.set_file_content("./www/dir/index.html", "text/html");
  8522. });
  8523. svr_.Get("/pre-encoded-file-content",
  8524. [](const Request & /*req*/, Response &res) {
  8525. res.set_header("Content-Encoding", "gzip");
  8526. res.set_file_content("./www/dir/index.html", "text/html");
  8527. });
  8528. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8529. res.set_content_provider(
  8530. 6, "text/plain",
  8531. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8532. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8533. return true;
  8534. });
  8535. });
  8536. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8537. res.set_content_provider(
  8538. 1000, "text/plain",
  8539. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8540. if (offset < 100) {
  8541. std::string data(100, 'A');
  8542. sink.write(data.data(), data.size());
  8543. return true;
  8544. }
  8545. std::this_thread::sleep_for(std::chrono::seconds(2));
  8546. std::string data(900, 'B');
  8547. sink.write(data.data(), data.size());
  8548. return true;
  8549. });
  8550. });
  8551. if (configure) { configure(svr_); }
  8552. auto port = svr_.bind_to_any_port(HOST);
  8553. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8554. svr_.wait_until_ready();
  8555. return port;
  8556. }
  8557. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8558. // Every file under ./www except 1MB.txt is smaller than the default
  8559. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8560. // it out of the way.
  8561. static void enable_without_floor(Server &svr) {
  8562. svr.set_static_file_compression(true);
  8563. svr.set_static_file_compression_min_length(0);
  8564. }
  8565. Server svr_;
  8566. std::thread t_;
  8567. };
  8568. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8569. auto port = start();
  8570. Client cli(HOST, port);
  8571. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8573. EXPECT_EQ(StatusCode::OK_200, res->status);
  8574. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8575. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8576. EXPECT_EQ(1048576U, res->body.size());
  8577. }
  8578. TEST_F(StaticFileCompressionTest, MountPoint) {
  8579. auto port = start(enable);
  8580. Client cli(HOST, port);
  8581. cli.set_decompress(false);
  8582. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8584. EXPECT_EQ(StatusCode::OK_200, res->status);
  8585. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8586. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8587. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8588. // The response stays self-delimiting: a length, not a chunked body.
  8589. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8590. EXPECT_EQ(std::to_string(res->body.size()),
  8591. res->get_header_value("Content-Length"));
  8592. EXPECT_LT(res->body.size(), 1048576U);
  8593. EXPECT_FALSE(res->body.empty());
  8594. }
  8595. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8596. auto port = start(enable);
  8597. Client cli(HOST, port);
  8598. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8600. EXPECT_EQ(StatusCode::OK_200, res->status);
  8601. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8602. EXPECT_EQ(1048576U, res->body.size());
  8603. }
  8604. TEST_F(StaticFileCompressionTest, FileContent) {
  8605. auto port = start(enable_without_floor);
  8606. Client cli(HOST, port);
  8607. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8609. EXPECT_EQ(StatusCode::OK_200, res->status);
  8610. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8611. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8612. EXPECT_EQ(104U, res->body.size());
  8613. }
  8614. // A handler that serves an already-encoded file names the coding itself. The
  8615. // file-backed path decided its coding from Accept-Encoding and the content
  8616. // type alone, so it compressed the stored bytes a second time and appended a
  8617. // second Content-Encoding field line.
  8618. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8619. auto port = start(enable_without_floor);
  8620. Client cli(HOST, port);
  8621. cli.set_decompress(false);
  8622. auto res = cli.Get("/pre-encoded-file-content",
  8623. Headers{{"Accept-Encoding", "gzip"}});
  8624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8625. EXPECT_EQ(StatusCode::OK_200, res->status);
  8626. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8627. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8628. // Vary belongs to a coding the server chose, and it chose none here.
  8629. EXPECT_FALSE(res->has_header("Vary"));
  8630. // The file travels exactly as it is stored on disk.
  8631. EXPECT_EQ(104U, res->body.size());
  8632. }
  8633. // The 1MB file clears the default floor, so this one runs the configuration a
  8634. // deployment would actually have.
  8635. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8636. auto port = start(enable);
  8637. Client cli(HOST, port);
  8638. cli.set_decompress(false);
  8639. auto res =
  8640. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8642. EXPECT_EQ(StatusCode::OK_200, res->status);
  8643. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8644. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8645. EXPECT_FALSE(res->has_header("Vary"));
  8646. EXPECT_EQ(1048576U, res->body.size());
  8647. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8648. }
  8649. TEST_F(StaticFileCompressionTest, Head) {
  8650. auto port = start(enable);
  8651. Client cli(HOST, port);
  8652. cli.set_decompress(false);
  8653. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8654. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8655. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8657. EXPECT_EQ(StatusCode::OK_200, res->status);
  8658. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8659. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8660. // HEAD still reports the size a GET would return.
  8661. EXPECT_EQ(get->get_header_value("Content-Length"),
  8662. res->get_header_value("Content-Length"));
  8663. EXPECT_TRUE(res->body.empty());
  8664. }
  8665. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8666. auto port = start(enable);
  8667. Client cli(HOST, port);
  8668. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8669. {"Accept-Encoding", "gzip"}});
  8670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8671. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8672. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8673. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8674. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8675. EXPECT_EQ("cd", res->body);
  8676. }
  8677. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8678. auto port = start(enable);
  8679. Client cli(HOST, port);
  8680. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8682. EXPECT_EQ(StatusCode::OK_200, res->status);
  8683. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8684. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8685. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8686. }
  8687. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8688. auto port = start(enable);
  8689. Client cli(HOST, port);
  8690. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8692. EXPECT_EQ(StatusCode::OK_200, res->status);
  8693. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8694. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8695. EXPECT_TRUE(res->body.empty());
  8696. }
  8697. TEST_F(StaticFileCompressionTest, MinLength) {
  8698. auto port = start(enable);
  8699. Client cli(HOST, port);
  8700. // 104 bytes, well under the default floor. Compressing it would add the
  8701. // gzip header and trailer to a body that already fits in one packet.
  8702. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8704. EXPECT_EQ(StatusCode::OK_200, res->status);
  8705. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8706. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8707. }
  8708. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8709. auto port = start([](Server &svr) {
  8710. svr.set_static_file_compression(true);
  8711. svr.set_static_file_compression_min_length(1);
  8712. });
  8713. Client cli(HOST, port);
  8714. cli.set_decompress(false);
  8715. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8717. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8718. // A 9-byte file comes back larger than it went in, because gzip's header and
  8719. // trailer outweigh anything deflate can save. That is the end of the range
  8720. // the floor exists to keep out.
  8721. EXPECT_GT(res->body.size(), 9U);
  8722. }
  8723. TEST_F(StaticFileCompressionTest, MaxLength) {
  8724. auto port = start([](Server &svr) {
  8725. svr.set_static_file_compression(true);
  8726. svr.set_static_file_compression_min_length(0);
  8727. svr.set_static_file_compression_max_length(1024);
  8728. });
  8729. Client cli(HOST, port);
  8730. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8731. // defines `small` as a macro on Windows.
  8732. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8733. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8734. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8735. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8736. // Under it: compressed.
  8737. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8738. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8739. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8740. }
  8741. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8742. auto port = start(enable_without_floor);
  8743. Client cli(HOST, port);
  8744. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8745. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8746. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8747. auto identity_etag = identity->get_header_value("ETag");
  8748. ASSERT_FALSE(identity_etag.empty());
  8749. auto gzipped =
  8750. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8751. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8752. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8753. auto gzip_etag = gzipped->get_header_value("ETag");
  8754. ASSERT_FALSE(gzip_etag.empty());
  8755. // Two representations, two validators.
  8756. EXPECT_NE(identity_etag, gzip_etag);
  8757. // Each one revalidates against the request that would produce it...
  8758. auto fresh =
  8759. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8760. {"If-None-Match", gzip_etag}});
  8761. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8762. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8763. auto fresh_identity =
  8764. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8765. {"If-None-Match", identity_etag}});
  8766. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8767. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8768. // ...and not against the other representation.
  8769. auto crossed =
  8770. cli.Get("/dir/index.html",
  8771. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8772. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8773. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8774. }
  8775. // The opt-in covers responses the server reads off disk itself. A caller's own
  8776. // known-length provider keeps its Content-Length and, more importantly, keeps
  8777. // delivering incrementally: routing it through a compressor would hold every
  8778. // write back until zlib's window filled.
  8779. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8780. auto port = start(enable);
  8781. Client cli(HOST, port);
  8782. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8784. EXPECT_EQ(StatusCode::OK_200, res->status);
  8785. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8786. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8787. EXPECT_EQ("aaabbb", res->body);
  8788. }
  8789. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8790. auto port = start(enable);
  8791. Client cli(HOST, port);
  8792. cli.set_read_timeout(1, 0);
  8793. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8794. Headers{{"Accept-Encoding", "gzip"}});
  8795. ASSERT_TRUE(handle.is_valid());
  8796. // The provider writes 100 bytes and then stalls for longer than the read
  8797. // timeout. Those first bytes have to arrive anyway: run the response through
  8798. // a compressor and zlib holds them until its window fills, so the read would
  8799. // come back empty instead.
  8800. char buf[256];
  8801. auto n = handle.read(buf, sizeof(buf));
  8802. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8803. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8804. }
  8805. #endif
  8806. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8807. TEST_F(ServerTest, Brotli) {
  8808. Headers headers;
  8809. headers.emplace("Accept-Encoding", "br");
  8810. auto res = cli_.Get("/compress", headers);
  8811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8812. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8813. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8814. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8815. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8816. "7890123456789012345678901234567890",
  8817. res->body);
  8818. EXPECT_EQ(StatusCode::OK_200, res->status);
  8819. }
  8820. #endif
  8821. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8822. TEST_F(ServerTest, Zstd) {
  8823. Headers headers;
  8824. headers.emplace("Accept-Encoding", "zstd");
  8825. auto res = cli_.Get("/compress", headers);
  8826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8827. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8828. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8829. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8830. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8831. "7890123456789012345678901234567890",
  8832. res->body);
  8833. EXPECT_EQ(StatusCode::OK_200, res->status);
  8834. }
  8835. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8836. Headers headers;
  8837. headers.emplace("Accept-Encoding", "");
  8838. auto res = cli_.Get("/compress", headers);
  8839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8840. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8841. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8842. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8843. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8844. "7890123456789012345678901234567890",
  8845. res->body);
  8846. EXPECT_EQ(StatusCode::OK_200, res->status);
  8847. }
  8848. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8849. Headers headers;
  8850. headers.emplace("Accept-Encoding", "zstd");
  8851. std::string body;
  8852. auto res = cli_.Get("/compress", headers,
  8853. [&](const char *data, uint64_t data_length) {
  8854. EXPECT_EQ(100U, data_length);
  8855. body.append(data, data_length);
  8856. return true;
  8857. });
  8858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8859. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8860. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8861. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8862. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8863. "7890123456789012345678901234567890",
  8864. body);
  8865. EXPECT_EQ(StatusCode::OK_200, res->status);
  8866. }
  8867. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8868. Headers headers;
  8869. headers.emplace("Accept-Encoding", "zstd");
  8870. cli_.set_decompress(false);
  8871. auto res = cli_.Get("/compress", headers);
  8872. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8873. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8874. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8875. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8877. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8878. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8879. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8880. EXPECT_EQ(StatusCode::OK_200, res->status);
  8881. ASSERT_EQ(26U, res->body.size());
  8882. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8883. 0);
  8884. }
  8885. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8886. Headers headers;
  8887. headers.emplace("Accept-Encoding", "");
  8888. std::string body;
  8889. auto res = cli_.Get("/compress", headers,
  8890. [&](const char *data, uint64_t data_length) {
  8891. EXPECT_EQ(100U, data_length);
  8892. body.append(data, data_length);
  8893. return true;
  8894. });
  8895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8896. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8897. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8898. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8899. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8900. "7890123456789012345678901234567890",
  8901. body);
  8902. EXPECT_EQ(StatusCode::OK_200, res->status);
  8903. }
  8904. TEST_F(ServerTest, NoZstd) {
  8905. Headers headers;
  8906. headers.emplace("Accept-Encoding", "zstd");
  8907. auto res = cli_.Get("/nocompress", headers);
  8908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8909. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8910. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8911. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8912. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8913. "7890123456789012345678901234567890",
  8914. res->body);
  8915. EXPECT_EQ(StatusCode::OK_200, res->status);
  8916. }
  8917. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8918. Headers headers;
  8919. headers.emplace("Accept-Encoding", "zstd");
  8920. std::string body;
  8921. auto res = cli_.Get("/nocompress", headers,
  8922. [&](const char *data, uint64_t data_length) {
  8923. EXPECT_EQ(100U, data_length);
  8924. body.append(data, data_length);
  8925. return true;
  8926. });
  8927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8928. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8929. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8930. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8931. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8932. "7890123456789012345678901234567890",
  8933. body);
  8934. EXPECT_EQ(StatusCode::OK_200, res->status);
  8935. }
  8936. // TODO: How to enable zstd ??
  8937. TEST_F(ServerTest, MultipartFormDataZstd) {
  8938. UploadFormDataItems items = {
  8939. {"key1", "test", "", ""},
  8940. {"key2", "--abcdefg123", "", ""},
  8941. };
  8942. Headers headers;
  8943. headers.emplace("Accept-Encoding", "zstd");
  8944. cli_.set_compress(true);
  8945. auto res = cli_.Post("/compress-multipart", headers, items);
  8946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8947. EXPECT_EQ(StatusCode::OK_200, res->status);
  8948. }
  8949. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8950. Headers headers;
  8951. headers.emplace("Accept-Encoding", "zstd");
  8952. cli_.set_compress(true);
  8953. auto res = cli_.Put(
  8954. "/put", headers, 3,
  8955. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8956. sink.os << "PUT";
  8957. return true;
  8958. },
  8959. "text/plain");
  8960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8961. EXPECT_EQ(StatusCode::OK_200, res->status);
  8962. EXPECT_EQ("PUT", res->body);
  8963. }
  8964. // Pre-compression logging tests
  8965. TEST_F(ServerTest, PreCompressionLogging) {
  8966. // Test data for compression (matches the actual /compress endpoint content)
  8967. const std::string test_content =
  8968. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8969. "3456789012345678901234567890";
  8970. // Variables to capture logging data
  8971. std::string pre_compression_body;
  8972. std::string pre_compression_content_type;
  8973. std::string pre_compression_content_encoding;
  8974. std::string post_compression_body;
  8975. std::string post_compression_content_type;
  8976. std::string post_compression_content_encoding;
  8977. // Set up pre-compression logger
  8978. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8979. const Response &res) {
  8980. pre_compression_body = res.body;
  8981. pre_compression_content_type = res.get_header_value("Content-Type");
  8982. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8983. });
  8984. // Set up post-compression logger
  8985. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8986. post_compression_body = res.body;
  8987. post_compression_content_type = res.get_header_value("Content-Type");
  8988. post_compression_content_encoding =
  8989. res.get_header_value("Content-Encoding");
  8990. });
  8991. // Test with gzip compression
  8992. Headers headers;
  8993. headers.emplace("Accept-Encoding", "gzip");
  8994. auto res = cli_.Get("/compress", headers);
  8995. // Verify response was compressed
  8996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8997. EXPECT_EQ(StatusCode::OK_200, res->status);
  8998. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8999. // Verify pre-compression logger captured uncompressed content
  9000. EXPECT_EQ(test_content, pre_compression_body);
  9001. EXPECT_EQ("text/plain", pre_compression_content_type);
  9002. EXPECT_TRUE(pre_compression_content_encoding
  9003. .empty()); // No encoding header before compression
  9004. // Verify post-compression logger captured compressed content
  9005. EXPECT_NE(test_content,
  9006. post_compression_body); // Should be different after compression
  9007. EXPECT_EQ("text/plain", post_compression_content_type);
  9008. EXPECT_EQ("gzip", post_compression_content_encoding);
  9009. // Verify compressed content is smaller
  9010. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9011. }
  9012. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9013. const std::string test_content =
  9014. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9015. "3456789012345678901234567890";
  9016. std::string pre_compression_body;
  9017. std::string post_compression_body;
  9018. svr_.set_pre_compression_logger(
  9019. [&](const Request & /*req*/, const Response &res) {
  9020. pre_compression_body = res.body;
  9021. });
  9022. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9023. post_compression_body = res.body;
  9024. });
  9025. Headers headers;
  9026. headers.emplace("Accept-Encoding", "br");
  9027. auto res = cli_.Get("/compress", headers);
  9028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9029. EXPECT_EQ(StatusCode::OK_200, res->status);
  9030. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9031. // Verify pre-compression content is uncompressed
  9032. EXPECT_EQ(test_content, pre_compression_body);
  9033. // Verify post-compression content is compressed
  9034. EXPECT_NE(test_content, post_compression_body);
  9035. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9036. }
  9037. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9038. const std::string test_content =
  9039. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9040. "3456789012345678901234567890";
  9041. std::string pre_compression_body;
  9042. std::string post_compression_body;
  9043. svr_.set_pre_compression_logger(
  9044. [&](const Request & /*req*/, const Response &res) {
  9045. pre_compression_body = res.body;
  9046. });
  9047. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9048. post_compression_body = res.body;
  9049. });
  9050. // Request without compression (use /nocompress endpoint)
  9051. Headers headers;
  9052. auto res = cli_.Get("/nocompress", headers);
  9053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9054. EXPECT_EQ(StatusCode::OK_200, res->status);
  9055. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9056. // Pre-compression logger should not be called when no compression is applied
  9057. EXPECT_TRUE(
  9058. pre_compression_body.empty()); // Pre-compression logger not called
  9059. EXPECT_EQ(
  9060. test_content,
  9061. post_compression_body); // Post-compression logger captures final content
  9062. }
  9063. TEST_F(ServerTest, LoggerSeesContentLength) {
  9064. size_t logged_content_length = 0;
  9065. std::string logged_content_length_header;
  9066. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9067. logged_content_length = res.content_length_;
  9068. logged_content_length_header = res.get_header_value("Content-Length");
  9069. });
  9070. auto res = cli_.Get("/nocompress");
  9071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9072. EXPECT_EQ(StatusCode::OK_200, res->status);
  9073. EXPECT_EQ(res->body.size(), logged_content_length);
  9074. EXPECT_EQ(std::to_string(logged_content_length),
  9075. logged_content_length_header);
  9076. }
  9077. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9078. const std::string test_content =
  9079. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9080. "3456789012345678901234567890";
  9081. std::string pre_compression_body;
  9082. bool pre_logger_called = false;
  9083. // Set only pre-compression logger
  9084. svr_.set_pre_compression_logger(
  9085. [&](const Request & /*req*/, const Response &res) {
  9086. pre_compression_body = res.body;
  9087. pre_logger_called = true;
  9088. });
  9089. Headers headers;
  9090. headers.emplace("Accept-Encoding", "gzip");
  9091. auto res = cli_.Get("/compress", headers);
  9092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9093. EXPECT_EQ(StatusCode::OK_200, res->status);
  9094. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9095. // Verify pre-compression logger was called
  9096. EXPECT_TRUE(pre_logger_called);
  9097. EXPECT_EQ(test_content, pre_compression_body);
  9098. }
  9099. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9100. {
  9101. // Test with Expect: 100-continue header - success case
  9102. // Server returns 100 Continue, client sends body, server returns 200 OK
  9103. Request req;
  9104. req.method = "POST";
  9105. req.path = "/post-large";
  9106. req.set_header("Expect", "100-continue");
  9107. req.body = LARGE_DATA;
  9108. Response res;
  9109. auto error = Error::Success;
  9110. cli_.set_keep_alive(true);
  9111. auto ret = cli_.send(req, res, error);
  9112. EXPECT_TRUE(ret);
  9113. EXPECT_EQ(StatusCode::OK_200, res.status);
  9114. EXPECT_EQ(LARGE_DATA, res.body);
  9115. }
  9116. {
  9117. // Test with Expect: 100-continue header - error case
  9118. // Client should not send the body when server returns an error
  9119. Request req;
  9120. req.method = "POST";
  9121. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9122. req.set_header("Expect", "100-continue");
  9123. req.body = LARGE_DATA;
  9124. Response res;
  9125. auto error = Error::Success;
  9126. auto start = std::chrono::high_resolution_clock::now();
  9127. cli_.set_keep_alive(true);
  9128. auto ret = cli_.send(req, res, error);
  9129. auto end = std::chrono::high_resolution_clock::now();
  9130. auto elapsed =
  9131. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9132. .count();
  9133. // With Expect: 100-continue, request completes successfully but with error
  9134. EXPECT_TRUE(ret);
  9135. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9136. EXPECT_EQ("close", res.get_header_value("Connection"));
  9137. EXPECT_FALSE(cli_.is_socket_open());
  9138. EXPECT_LE(elapsed, 2000);
  9139. }
  9140. {
  9141. // Send an extra GET request to ensure error recovery without hanging
  9142. Request req;
  9143. req.method = "GET";
  9144. req.path = "/hi";
  9145. auto start = std::chrono::high_resolution_clock::now();
  9146. auto res = cli_.send(req);
  9147. auto end = std::chrono::high_resolution_clock::now();
  9148. auto elapsed =
  9149. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9150. .count();
  9151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9152. EXPECT_EQ(StatusCode::OK_200, res->status);
  9153. EXPECT_EQ("Hello World!", res->body);
  9154. EXPECT_LE(elapsed, 500);
  9155. }
  9156. }
  9157. TEST(ZstdDecompressor, ChunkedDecompression) {
  9158. std::string data;
  9159. for (size_t i = 0; i < 32 * 1024; ++i) {
  9160. data.push_back(static_cast<char>('a' + i % 26));
  9161. }
  9162. std::string compressed_data;
  9163. {
  9164. httplib::detail::zstd_compressor compressor;
  9165. bool result = compressor.compress(
  9166. data.data(), data.size(),
  9167. /*last=*/true,
  9168. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9169. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9170. compressed_data_size);
  9171. return true;
  9172. });
  9173. ASSERT_TRUE(result);
  9174. }
  9175. std::string decompressed_data;
  9176. {
  9177. httplib::detail::zstd_decompressor decompressor;
  9178. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9179. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9180. size_t chunk_size = 130;
  9181. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9182. chunk_begin += chunk_size) {
  9183. size_t current_chunk_size =
  9184. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9185. bool result = decompressor.decompress(
  9186. compressed_data.data() + chunk_begin, current_chunk_size,
  9187. [&](const char *decompressed_data_chunk,
  9188. size_t decompressed_data_chunk_size) {
  9189. decompressed_data.insert(decompressed_data.size(),
  9190. decompressed_data_chunk,
  9191. decompressed_data_chunk_size);
  9192. return true;
  9193. });
  9194. ASSERT_TRUE(result);
  9195. }
  9196. }
  9197. ASSERT_EQ(data, decompressed_data);
  9198. }
  9199. TEST(ZstdDecompressor, Decompress) {
  9200. std::string original_text = "Compressed with ZSTD";
  9201. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9202. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9203. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9204. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9205. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9206. std::string decompressed_data;
  9207. {
  9208. httplib::detail::zstd_decompressor decompressor;
  9209. bool result = decompressor.decompress(
  9210. compressed_data.data(), compressed_data.size(),
  9211. [&](const char *decompressed_data_chunk,
  9212. size_t decompressed_data_chunk_size) {
  9213. decompressed_data.insert(decompressed_data.size(),
  9214. decompressed_data_chunk,
  9215. decompressed_data_chunk_size);
  9216. return true;
  9217. });
  9218. ASSERT_TRUE(result);
  9219. }
  9220. ASSERT_EQ(original_text, decompressed_data);
  9221. }
  9222. #endif
  9223. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9224. // separate chunks so that the server sees each part in its own read(). Used to
  9225. // place a read boundary at a specific offset of a request body.
  9226. static bool send_request_in_parts(time_t read_timeout_sec,
  9227. const std::vector<std::string> &parts,
  9228. std::string *resp = nullptr,
  9229. int port = PORT) {
  9230. auto error = Error::Success;
  9231. auto client_sock = detail::create_client_socket(
  9232. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9233. /*connection_timeout_sec=*/5, 0,
  9234. /*read_timeout_sec=*/5, 0,
  9235. /*write_timeout_sec=*/5, 0, std::string(), error);
  9236. if (client_sock == INVALID_SOCKET) { return false; }
  9237. auto ret = detail::process_client_socket(
  9238. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9239. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9240. for (size_t i = 0; i < parts.size(); i++) {
  9241. const auto &part = parts[i];
  9242. if (part.size() !=
  9243. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9244. return false;
  9245. }
  9246. if (i + 1 < parts.size()) {
  9247. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9248. }
  9249. }
  9250. char buf[512];
  9251. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9252. while (line_reader.getline()) {
  9253. if (resp) { *resp += line_reader.ptr(); }
  9254. }
  9255. return true;
  9256. });
  9257. detail::close_socket(client_sock);
  9258. return ret;
  9259. }
  9260. // Sends a raw request to a server listening at HOST:PORT.
  9261. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9262. std::string *resp = nullptr, int port = PORT) {
  9263. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9264. }
  9265. #ifdef CPPHTTPLIB_SSL_ENABLED
  9266. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9267. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9268. ASSERT_TRUE(svr.is_valid());
  9269. svr.set_read_timeout(1, 0);
  9270. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9271. auto se = detail::scope_exit([&] {
  9272. svr.stop();
  9273. t.join();
  9274. ASSERT_FALSE(svr.is_running());
  9275. });
  9276. svr.wait_until_ready();
  9277. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9278. // keeps each wait well within the read timeout. The server gives up a
  9279. // second in, so the bytes sent after that fail.
  9280. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9281. parts.resize(26, std::string(1, '\0'));
  9282. EXPECT_FALSE(send_request_in_parts(5, parts));
  9283. }
  9284. #endif
  9285. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9286. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9287. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9288. const std::vector<std::string> &parts,
  9289. std::string *resp = nullptr,
  9290. int port = PORT) {
  9291. auto error = Error::Success;
  9292. auto sock = detail::create_client_socket(
  9293. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9294. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9295. /*write_timeout_sec=*/5, 0, std::string(), error);
  9296. if (sock == INVALID_SOCKET) { return false; }
  9297. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9298. auto ctx = SSL_CTX_new(TLS_client_method());
  9299. auto ssl = SSL_new(ctx);
  9300. auto ssl_se = detail::scope_exit([&] {
  9301. SSL_free(ssl);
  9302. SSL_CTX_free(ctx);
  9303. });
  9304. SSL_set_fd(ssl, static_cast<int>(sock));
  9305. if (SSL_connect(ssl) != 1) { return false; }
  9306. for (size_t i = 0; i < parts.size(); i++) {
  9307. const auto &part = parts[i];
  9308. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9309. static_cast<int>(part.size())) {
  9310. return false;
  9311. }
  9312. if (i + 1 < parts.size()) {
  9313. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9314. }
  9315. }
  9316. char buf[512];
  9317. int n;
  9318. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9319. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9320. }
  9321. return true;
  9322. }
  9323. #endif
  9324. // The request line, then a header value a byte at a time.
  9325. static std::vector<std::string> slow_request_head_parts() {
  9326. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9327. parts.resize(26, "a");
  9328. parts.emplace_back("\r\n\r\n");
  9329. return parts;
  9330. }
  9331. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9332. // within the one-second read timeout. The server gives up a second in, before
  9333. // the head is complete.
  9334. static void
  9335. expect_slow_request_head_dropped(Server &svr,
  9336. const std::function<std::string()> &send) {
  9337. std::atomic<bool> handled(false);
  9338. svr.Get("/", [&](const Request &, Response &res) {
  9339. handled = true;
  9340. res.set_content("ok", "text/plain");
  9341. });
  9342. svr.set_read_timeout(1, 0);
  9343. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9344. auto se = detail::scope_exit([&] {
  9345. svr.stop();
  9346. t.join();
  9347. ASSERT_FALSE(svr.is_running());
  9348. });
  9349. svr.wait_until_ready();
  9350. auto resp = send();
  9351. EXPECT_FALSE(handled);
  9352. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9353. }
  9354. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9355. Server svr;
  9356. expect_slow_request_head_dropped(svr, [] {
  9357. std::string resp;
  9358. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9359. return resp;
  9360. });
  9361. }
  9362. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9363. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9364. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9365. ASSERT_TRUE(svr.is_valid());
  9366. expect_slow_request_head_dropped(svr, [] {
  9367. std::string resp;
  9368. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9369. return resp;
  9370. });
  9371. }
  9372. #endif
  9373. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9374. Server svr;
  9375. std::string header_value;
  9376. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9377. header_value = req.get_header_value("foo");
  9378. res.set_content("ok", "text/plain");
  9379. });
  9380. thread t = thread([&] { svr.listen(HOST, PORT); });
  9381. auto se = detail::scope_exit([&] {
  9382. svr.stop();
  9383. t.join();
  9384. ASSERT_FALSE(svr.is_running());
  9385. });
  9386. svr.wait_until_ready();
  9387. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9388. // like characters are not treated the same - use vertical tab and escape.
  9389. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9390. "foo: \t \v bar \x1B\t \r\n"
  9391. "Connection: close\r\n"
  9392. "\r\n";
  9393. std::string res;
  9394. ASSERT_TRUE(send_request(5, req, &res));
  9395. EXPECT_EQ(header_value, "");
  9396. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9397. }
  9398. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9399. Server svr;
  9400. std::string received;
  9401. svr.Get("/order", [&](const Request &req, Response &res) {
  9402. received = entries_to_string(req.headers);
  9403. res.set_content("ok", "text/plain");
  9404. });
  9405. auto port = svr.bind_to_any_port(HOST);
  9406. thread t = thread([&] { svr.listen_after_bind(); });
  9407. auto se = detail::scope_exit([&] {
  9408. svr.stop();
  9409. t.join();
  9410. ASSERT_FALSE(svr.is_running());
  9411. });
  9412. svr.wait_until_ready();
  9413. const std::string req = "GET /order HTTP/1.1\r\n"
  9414. "Host: localhost\r\n"
  9415. "X-First: 1\r\n"
  9416. "X-Dup: a\r\n"
  9417. "X-Second: 2\r\n"
  9418. "X-Dup: b\r\n"
  9419. "Connection: close\r\n"
  9420. "\r\n";
  9421. std::string res;
  9422. ASSERT_TRUE(send_request(5, req, &res, port));
  9423. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9424. EXPECT_EQ(
  9425. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9426. received);
  9427. }
  9428. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9429. Server svr;
  9430. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9431. res.set_header("Set-Cookie", "first=1");
  9432. res.set_header("X-Between", "y");
  9433. res.set_header("Set-Cookie", "second=2");
  9434. res.set_content("ok", "text/plain");
  9435. });
  9436. auto port = svr.bind_to_any_port(HOST);
  9437. thread t = thread([&] { svr.listen_after_bind(); });
  9438. auto se = detail::scope_exit([&] {
  9439. svr.stop();
  9440. t.join();
  9441. ASSERT_FALSE(svr.is_running());
  9442. });
  9443. svr.wait_until_ready();
  9444. Client cli(HOST, port);
  9445. auto res = cli.Get("/cookies");
  9446. ASSERT_TRUE(res);
  9447. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9448. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9449. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9450. }
  9451. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9452. Server svr;
  9453. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9454. auto i = new int(0);
  9455. res.set_header("Trailer", "X-Safe, X-Reflected");
  9456. res.set_chunked_content_provider(
  9457. "text/plain",
  9458. [i](size_t /*offset*/, DataSink &sink) {
  9459. if (*i == 0) {
  9460. sink.os << "body";
  9461. } else {
  9462. Headers trailer;
  9463. // A valid trailer that must survive.
  9464. trailer.emplace("X-Safe", "safe");
  9465. // Attacker-controlled value carrying CR/LF (response splitting).
  9466. trailer.emplace("X-Reflected",
  9467. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9468. // Attacker-controlled name carrying CR/LF.
  9469. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9470. sink.done_with_trailer(trailer);
  9471. }
  9472. (*i)++;
  9473. return true;
  9474. },
  9475. [i](bool /*success*/) { delete i; });
  9476. });
  9477. thread t = thread([&] { svr.listen(HOST, PORT); });
  9478. auto se = detail::scope_exit([&] {
  9479. svr.stop();
  9480. t.join();
  9481. ASSERT_FALSE(svr.is_running());
  9482. });
  9483. svr.wait_until_ready();
  9484. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9485. "Host: " + HOST +
  9486. "\r\n"
  9487. "Connection: close\r\n"
  9488. "\r\n";
  9489. std::string res;
  9490. ASSERT_TRUE(send_request(5, req, &res));
  9491. // The injected fields must not appear anywhere in the raw response.
  9492. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9493. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9494. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9495. // Invalid trailers are dropped entirely, matching set_header().
  9496. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9497. // The valid trailer still passes through.
  9498. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9499. }
  9500. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9501. Server svr;
  9502. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9503. // res.headers is a public field an application can populate directly,
  9504. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9505. // A valid header that must survive.
  9506. res.headers.emplace("X-Safe", "safe");
  9507. // Attacker-controlled value carrying CR/LF (response splitting).
  9508. res.headers.emplace("X-Reflected",
  9509. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9510. // Attacker-controlled name carrying CR/LF.
  9511. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9512. res.set_content("body", "text/plain");
  9513. });
  9514. thread t = thread([&] { svr.listen(HOST, PORT); });
  9515. auto se = detail::scope_exit([&] {
  9516. svr.stop();
  9517. t.join();
  9518. ASSERT_FALSE(svr.is_running());
  9519. });
  9520. svr.wait_until_ready();
  9521. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9522. "Host: " + HOST +
  9523. "\r\n"
  9524. "Connection: close\r\n"
  9525. "\r\n";
  9526. std::string res;
  9527. ASSERT_TRUE(send_request(5, req, &res));
  9528. // The injected fields must not appear anywhere in the raw response.
  9529. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9530. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9531. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9532. // Invalid headers are dropped entirely, matching set_header().
  9533. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9534. // The valid header still passes through.
  9535. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9536. }
  9537. // Forward declaration: in split builds split.py strips `inline` and moves the
  9538. // definition into httplib.cc, so detail::write_request_line is not visible from
  9539. // the public httplib.h. Re-declaring it here lets the tests link against the
  9540. // symbol in both header-only and split builds.
  9541. namespace httplib {
  9542. namespace detail {
  9543. ssize_t write_request_line(Stream &strm, const std::string &method,
  9544. const std::string &path);
  9545. } // namespace detail
  9546. } // namespace httplib
  9547. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9548. // A well-formed target is written verbatim.
  9549. {
  9550. detail::BufferStream strm;
  9551. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9552. EXPECT_GT(n, 0);
  9553. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9554. }
  9555. // A target carrying CR/LF, SP or other control octets must be rejected
  9556. // before anything reaches the wire, otherwise it splits the request line and
  9557. // injects a header or a whole request.
  9558. const std::string evil_targets[] = {
  9559. "/a\r\nInjected: pwned",
  9560. "/a\rInjected",
  9561. "/a\nInjected",
  9562. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9563. "/a b",
  9564. "/a\tb",
  9565. "/a\x7f",
  9566. };
  9567. for (const auto &evil : evil_targets) {
  9568. detail::BufferStream strm;
  9569. auto n = detail::write_request_line(strm, "GET", evil);
  9570. EXPECT_LT(n, 0);
  9571. EXPECT_TRUE(strm.get_buffer().empty());
  9572. }
  9573. }
  9574. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9575. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9576. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9577. // target reaches write_request. The client must fail cleanly with
  9578. // Error::Write instead of putting a request-line-less, header-injecting
  9579. // request on the wire.
  9580. Server svr;
  9581. svr.Get("/a", [](const Request &, Response &res) {
  9582. res.set_content("ok", "text/plain");
  9583. });
  9584. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9585. auto se = detail::scope_exit([&] {
  9586. svr.stop();
  9587. thread.join();
  9588. ASSERT_FALSE(svr.is_running());
  9589. });
  9590. svr.wait_until_ready();
  9591. {
  9592. Client cli(HOST, PORT);
  9593. cli.set_path_encode(false);
  9594. // The request is rejected before anything is written, so the connection
  9595. // stays silent and the subsequent response read would otherwise block for
  9596. // the full default read timeout. Shorten it -- the assertion is on the
  9597. // error, not the timeout.
  9598. cli.set_read_timeout(1, 0);
  9599. auto res = cli.Get("/a\r\nInjected: pwned");
  9600. EXPECT_FALSE(res);
  9601. EXPECT_EQ(Error::Write, res.error());
  9602. }
  9603. }
  9604. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9605. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9606. // including extension methods.
  9607. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9608. for (const auto &method : good_methods) {
  9609. detail::BufferStream strm;
  9610. auto n = detail::write_request_line(strm, method, "/");
  9611. EXPECT_GT(n, 0);
  9612. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9613. }
  9614. // A method carrying CR/LF would split the request line and smuggle a whole
  9615. // request ahead of the real one. A space or an empty method corrupts the
  9616. // request line. All must be rejected before anything reaches the wire.
  9617. const std::string evil_methods[] = {
  9618. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9619. "GET\r\nInjected: pwned",
  9620. "GET\r",
  9621. "GET\n",
  9622. "GE T",
  9623. "",
  9624. };
  9625. for (const auto &evil : evil_methods) {
  9626. detail::BufferStream strm;
  9627. auto n = detail::write_request_line(strm, evil, "/");
  9628. EXPECT_LT(n, 0);
  9629. EXPECT_TRUE(strm.get_buffer().empty());
  9630. }
  9631. }
  9632. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9633. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9634. // through Client::send must fail with Error::Write and no request, neither
  9635. // the smuggled one nor the real one, may reach the server.
  9636. Server svr;
  9637. std::atomic<int> request_count(0);
  9638. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9639. request_count++;
  9640. res.status = StatusCode::OK_200;
  9641. return Server::HandlerResponse::Handled;
  9642. });
  9643. auto port = svr.bind_to_any_port(HOST);
  9644. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9645. auto se = detail::scope_exit([&] {
  9646. svr.stop();
  9647. thread.join();
  9648. ASSERT_FALSE(svr.is_running());
  9649. });
  9650. svr.wait_until_ready();
  9651. {
  9652. Client cli(HOST, port);
  9653. const std::string evil_methods[] = {
  9654. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9655. "GE T",
  9656. "",
  9657. };
  9658. for (const auto &evil : evil_methods) {
  9659. Request req;
  9660. req.method = evil;
  9661. req.path = "/";
  9662. auto res = cli.send(req);
  9663. EXPECT_FALSE(res);
  9664. EXPECT_EQ(Error::Write, res.error());
  9665. }
  9666. auto handle =
  9667. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9668. EXPECT_FALSE(handle.is_valid());
  9669. EXPECT_EQ(Error::Write, handle.error);
  9670. // A valid request on the same client still goes through.
  9671. auto res = cli.Get("/");
  9672. ASSERT_TRUE(res);
  9673. EXPECT_EQ(StatusCode::OK_200, res->status);
  9674. }
  9675. EXPECT_EQ(1, request_count.load());
  9676. }
  9677. // Sends a raw request and verifies that there isn't a crash or exception.
  9678. static void test_raw_request(const std::string &req,
  9679. std::string *out = nullptr) {
  9680. Server svr;
  9681. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9682. res.set_content("ok", "text/plain");
  9683. });
  9684. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9685. res.set_content("ok", "text/plain");
  9686. });
  9687. svr.Get("/header_field_value_check",
  9688. [&](const Request & /*req*/, Response &res) {
  9689. res.set_content("ok", "text/plain");
  9690. });
  9691. svr.CustomRoute("PROPFIND", "/dav",
  9692. [&](const Request & /*req*/, Response &res) {
  9693. res.status = StatusCode::MultiStatus_207;
  9694. });
  9695. // Server read timeout must be longer than the client read timeout for the
  9696. // bug to reproduce, probably to force the server to process a request
  9697. // without a trailing blank line.
  9698. const time_t client_read_timeout_sec = 1;
  9699. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9700. bool listen_thread_ok = false;
  9701. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9702. auto se = detail::scope_exit([&] {
  9703. svr.stop();
  9704. t.join();
  9705. ASSERT_FALSE(svr.is_running());
  9706. EXPECT_TRUE(listen_thread_ok);
  9707. });
  9708. svr.wait_until_ready();
  9709. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9710. }
  9711. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9712. // A certain header line causes an exception if the header property is parsed
  9713. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9714. test_raw_request(
  9715. "GET /hi HTTP/1.1\r\n"
  9716. " : "
  9717. " "
  9718. " ");
  9719. }
  9720. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9721. // A certain header line causes an exception if the header property *name* is
  9722. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9723. // greedy matcher and requires backtracking when there are a lot of ":"
  9724. // characters.
  9725. // This occurs with libc++ but not libstdc++.
  9726. test_raw_request(
  9727. "GET /hi HTTP/1.1\r\n"
  9728. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9729. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9730. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9731. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9732. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9733. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9734. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9735. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9736. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9737. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9738. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9739. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9740. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9741. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9742. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9743. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9744. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9745. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9746. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9747. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9748. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9749. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9750. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9751. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9752. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9753. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9754. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9755. "&&&%%%");
  9756. }
  9757. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9758. // Make sure this doesn't crash the server.
  9759. // In a previous version of the header line regex, the "\r" rendered the line
  9760. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9761. // a new position where the leading white space ended and the field value
  9762. // began.
  9763. // The crash occurs with libc++ but not libstdc++.
  9764. test_raw_request("GET /hi HTTP/1.1\r\n"
  9765. "a:" +
  9766. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9767. "\r\n"
  9768. "\r\n");
  9769. }
  9770. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9771. const char *rejected[] = {
  9772. // RFC 9112 §3: one SP between the parts, and nothing else
  9773. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9774. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9775. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9776. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9777. // A request-target has no fragment
  9778. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9779. // An HTTP/1.1 request needs a Host
  9780. "GET /hi HTTP/1.1\r\n\r\n",
  9781. };
  9782. for (auto request : rejected) {
  9783. std::string out;
  9784. test_raw_request(request, &out);
  9785. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9786. }
  9787. std::string out;
  9788. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9789. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9790. }
  9791. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9792. // RFC 9112 §6.1
  9793. const char *requests[] = {
  9794. "PUT /put_hi HTTP/1.1\r\n"
  9795. "Host: localhost\r\n"
  9796. "Content-Length: 0\r\n"
  9797. "Transfer-Encoding: chunked\r\n"
  9798. "\r\n"
  9799. "0\r\n\r\n",
  9800. "PUT /put_hi HTTP/1.0\r\n"
  9801. "Connection: keep-alive\r\n"
  9802. "Transfer-Encoding: chunked\r\n"
  9803. "\r\n"
  9804. "0\r\n\r\n",
  9805. };
  9806. for (auto request : requests) {
  9807. std::string out;
  9808. test_raw_request(request, &out);
  9809. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9810. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9811. }
  9812. }
  9813. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9814. std::string out;
  9815. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9816. "Content-Type: text/plain\r\n"
  9817. "Transfer-Encoding: chunked\r\n"
  9818. "\r\n"
  9819. "nothex\r\n",
  9820. &out);
  9821. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9822. }
  9823. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9824. std::string out;
  9825. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9826. "Content-Type: text/plain\r\n"
  9827. "Transfer-Encoding: chunked\r\n"
  9828. "\r\n"
  9829. "3\r\n"
  9830. "xyz\r\n"
  9831. "NaN\r\n",
  9832. &out);
  9833. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9834. }
  9835. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9836. std::string out;
  9837. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9838. "Content-Type: text/plain\r\n"
  9839. "Transfer-Encoding: chunked\r\n"
  9840. "\r\n"
  9841. // Length is too large for 64 bits.
  9842. "1ffffffffffffffff\r\n"
  9843. "xyz\r\n",
  9844. &out);
  9845. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9846. }
  9847. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9848. test_raw_request("GET /hi HTTP/1.1\r\n"
  9849. "Content-Type: text/plain\r\n\r");
  9850. }
  9851. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9852. std::string out;
  9853. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9854. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9855. }
  9856. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9857. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9858. std::string out;
  9859. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9860. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9861. }
  9862. }
  9863. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9864. std::string out;
  9865. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9866. "Host: localhost\r\n"
  9867. "Connection: close\r\n\r\n",
  9868. &out);
  9869. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9870. }
  9871. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9872. Server svr;
  9873. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9874. EXPECT_TRUE(!req.remote_addr.empty());
  9875. });
  9876. thread t = thread([&] { svr.listen(HOST, PORT); });
  9877. auto se = detail::scope_exit([&] {
  9878. svr.stop();
  9879. t.join();
  9880. ASSERT_FALSE(svr.is_running());
  9881. });
  9882. svr.wait_until_ready();
  9883. // Send an invalid request line to trigger Bad Request
  9884. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9885. std::string out;
  9886. ASSERT_TRUE(send_request(5, bad_req, &out));
  9887. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9888. }
  9889. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9890. // answered right away rather than blocking on a read that waits for EOF.
  9891. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9892. std::string out;
  9893. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9894. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9895. }
  9896. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9897. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9898. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9899. for (const auto *method : methods) {
  9900. Server svr;
  9901. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9902. EXPECT_FALSE(svr.is_valid()) << method;
  9903. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9904. }
  9905. }
  9906. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9907. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9908. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9909. for (const auto *method : methods) {
  9910. Server svr;
  9911. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9912. EXPECT_FALSE(svr.is_valid()) << method;
  9913. }
  9914. }
  9915. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9916. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9917. "COPY", "MOVE", "LOCK",
  9918. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9919. Server svr;
  9920. for (const auto *method : methods) {
  9921. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9922. }
  9923. EXPECT_TRUE(svr.is_valid());
  9924. }
  9925. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9926. Server svr;
  9927. svr.CustomRoute("POST", "/x",
  9928. [](const Request &, Response &, const ContentReader &) {});
  9929. EXPECT_FALSE(svr.is_valid());
  9930. }
  9931. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9932. Server svr;
  9933. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9934. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9935. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9936. EXPECT_FALSE(svr.is_valid());
  9937. }
  9938. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9939. Server svr;
  9940. auto captured = Error::Success;
  9941. svr.set_error_logger(
  9942. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9943. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9944. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9945. }
  9946. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9947. std::string out;
  9948. std::string request(
  9949. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9950. test_raw_request(request, &out);
  9951. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9952. }
  9953. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9954. std::string out;
  9955. std::string request(
  9956. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9957. test_raw_request(request, &out);
  9958. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9959. }
  9960. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9961. std::string out;
  9962. std::string request(
  9963. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9964. test_raw_request(request, &out);
  9965. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9966. }
  9967. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9968. std::string out;
  9969. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9970. "Host: localhost\r\n"
  9971. "Test: \r\n\r\n",
  9972. &out);
  9973. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9974. }
  9975. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9976. Server svr;
  9977. std::string x_custom;
  9978. std::string cookie;
  9979. std::string xff;
  9980. std::string x_unicode;
  9981. std::string x_iis;
  9982. svr.Get("/check", [&](const Request &req, Response &res) {
  9983. x_custom = req.get_header_value("X-Custom");
  9984. cookie = req.get_header_value("Cookie");
  9985. xff = req.get_header_value("X-Forwarded-For");
  9986. x_unicode = req.get_header_value("X-Unicode");
  9987. x_iis = req.get_header_value("X-IIS");
  9988. res.set_content("ok", "text/plain");
  9989. });
  9990. thread t = thread([&] { svr.listen(HOST, PORT); });
  9991. auto se = detail::scope_exit([&] {
  9992. svr.stop();
  9993. t.join();
  9994. ASSERT_FALSE(svr.is_running());
  9995. });
  9996. svr.wait_until_ready();
  9997. const std::string req = "GET /check HTTP/1.1\r\n"
  9998. "Host: localhost\r\n"
  9999. "X-Custom: a%0D%0AInjected: b\r\n"
  10000. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10001. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10002. "X-Unicode: %E3%81%82\r\n"
  10003. "X-IIS: %u00E9\r\n"
  10004. "Connection: close\r\n"
  10005. "\r\n";
  10006. std::string res;
  10007. ASSERT_TRUE(send_request(5, req, &res));
  10008. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10009. // Every value must be returned verbatim (wire form), with no decoding.
  10010. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10011. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10012. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10013. EXPECT_EQ("%E3%81%82", x_unicode);
  10014. EXPECT_EQ("%u00E9", x_iis);
  10015. }
  10016. // Applications that previously relied on automatic percent-decoding can
  10017. // reproduce the old behavior by explicitly calling decode_path_component()
  10018. // or, for RFC 3986 conformance, decode_uri_component().
  10019. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10020. Server svr;
  10021. std::string decoded;
  10022. svr.Get("/check", [&](const Request &req, Response &res) {
  10023. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10024. res.set_content("ok", "text/plain");
  10025. });
  10026. thread t = thread([&] { svr.listen(HOST, PORT); });
  10027. auto se = detail::scope_exit([&] {
  10028. svr.stop();
  10029. t.join();
  10030. ASSERT_FALSE(svr.is_running());
  10031. });
  10032. svr.wait_until_ready();
  10033. const std::string req = "GET /check HTTP/1.1\r\n"
  10034. "Host: localhost\r\n"
  10035. "X-Custom: hello%20world\r\n"
  10036. "Connection: close\r\n"
  10037. "\r\n";
  10038. std::string res;
  10039. ASSERT_TRUE(send_request(5, req, &res));
  10040. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10041. EXPECT_EQ("hello world", decoded);
  10042. }
  10043. // Regression test for #2033. Browsers send Referer values that include
  10044. // percent-encoded characters such as %0A inside the URL. Decoding the
  10045. // header value would either trip the post-decode CR/LF/NUL guard (the
  10046. // original bug, returning 400) or, after that guard was relaxed, silently
  10047. // store a literal LF — both unacceptable. The wire form must round-trip.
  10048. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10049. Server svr;
  10050. std::string referer;
  10051. svr.Get("/check", [&](const Request &req, Response &res) {
  10052. referer = req.get_header_value("Referer");
  10053. res.set_content("ok", "text/plain");
  10054. });
  10055. thread t = thread([&] { svr.listen(HOST, PORT); });
  10056. auto se = detail::scope_exit([&] {
  10057. svr.stop();
  10058. t.join();
  10059. ASSERT_FALSE(svr.is_running());
  10060. });
  10061. svr.wait_until_ready();
  10062. const std::string req = "GET /check HTTP/1.1\r\n"
  10063. "Host: localhost\r\n"
  10064. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10065. "Connection: close\r\n"
  10066. "\r\n";
  10067. std::string res;
  10068. ASSERT_TRUE(send_request(5, req, &res));
  10069. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10070. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10071. }
  10072. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10073. Server svr;
  10074. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10075. res.set_header("Cache-Control", "no-cache");
  10076. res.set_chunked_content_provider(
  10077. "text/event-stream", [](size_t offset, DataSink &sink) {
  10078. std::string s = "data:";
  10079. s += std::to_string(offset);
  10080. s += "\n\n";
  10081. auto ret = sink.write(s.data(), s.size());
  10082. EXPECT_TRUE(ret);
  10083. std::this_thread::sleep_for(std::chrono::seconds(1));
  10084. return true;
  10085. });
  10086. });
  10087. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10088. svr.wait_until_ready();
  10089. Client client(HOST, PORT);
  10090. const Headers headers = {{"Accept", "text/event-stream"}};
  10091. auto get_thread = std::thread([&client, &headers]() {
  10092. auto res = client.Get(
  10093. "/events", headers,
  10094. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10095. });
  10096. auto se = detail::scope_exit([&] {
  10097. svr.stop();
  10098. get_thread.join();
  10099. listen_thread.join();
  10100. ASSERT_FALSE(svr.is_running());
  10101. });
  10102. // Give GET time to get a few messages.
  10103. std::this_thread::sleep_for(std::chrono::seconds(2));
  10104. }
  10105. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10106. httplib::Server svr;
  10107. svr.Post("/hi",
  10108. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10109. res.status = StatusCode::OK_200;
  10110. });
  10111. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10112. svr.wait_until_ready();
  10113. Client cli(HOST, PORT);
  10114. auto res = cli.Post("/hi", "data", "text/plain");
  10115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10116. EXPECT_EQ(StatusCode::OK_200, res->status);
  10117. svr.stop();
  10118. thread.join();
  10119. ASSERT_FALSE(svr.is_running());
  10120. res = cli.Post("/hi", "data", "text/plain");
  10121. ASSERT_FALSE(res);
  10122. }
  10123. TEST(ServerStopTest, ListenFailure) {
  10124. Server svr;
  10125. auto t = thread([&]() {
  10126. auto ret = svr.listen("????", PORT);
  10127. EXPECT_FALSE(ret);
  10128. });
  10129. svr.wait_until_ready();
  10130. svr.stop();
  10131. t.join();
  10132. }
  10133. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10134. TEST(ServerStopTest, Decommision) {
  10135. Server svr;
  10136. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10137. for (int i = 0; i < 4; i++) {
  10138. auto is_even = !(i % 2);
  10139. std::thread t{[&] {
  10140. try {
  10141. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10142. if (is_even) {
  10143. throw std::runtime_error("Some thing that happens to go wrong.");
  10144. }
  10145. svr.listen(HOST, PORT);
  10146. } catch (...) { svr.decommission(); }
  10147. }};
  10148. svr.wait_until_ready();
  10149. // Server is up
  10150. {
  10151. Client cli(HOST, PORT);
  10152. auto res = cli.Get("/hi");
  10153. if (is_even) {
  10154. EXPECT_FALSE(res);
  10155. } else {
  10156. EXPECT_TRUE(res);
  10157. EXPECT_EQ("hi...", res->body);
  10158. }
  10159. }
  10160. svr.stop();
  10161. t.join();
  10162. // Server is down...
  10163. {
  10164. Client cli(HOST, PORT);
  10165. auto res = cli.Get("/hi");
  10166. EXPECT_FALSE(res);
  10167. }
  10168. }
  10169. }
  10170. #endif
  10171. // Helper function for string body upload progress tests
  10172. template <typename SetupHandler, typename ClientCall>
  10173. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10174. ClientCall &&client_call,
  10175. const string &body) {
  10176. Server svr;
  10177. setup_handler(svr);
  10178. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10179. auto se = detail::scope_exit([&] {
  10180. svr.stop();
  10181. t.join();
  10182. });
  10183. svr.wait_until_ready();
  10184. Client cli(HOST, PORT);
  10185. vector<uint64_t> progress_values;
  10186. bool progress_called = false;
  10187. auto res =
  10188. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10189. progress_values.push_back(current);
  10190. progress_called = true;
  10191. return true;
  10192. });
  10193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10194. EXPECT_EQ(200, res->status);
  10195. EXPECT_TRUE(progress_called);
  10196. }
  10197. TEST(UploadProgressTest, PostStringBodyBasic) {
  10198. TestStringBodyUploadProgress(
  10199. [](Server &svr) {
  10200. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10201. res.set_content("received", "text/plain");
  10202. });
  10203. },
  10204. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10205. return cli.Post("/test", body, "text/plain", progress_callback);
  10206. },
  10207. "test data for upload progress");
  10208. }
  10209. TEST(UploadProgressTest, PutStringBodyBasic) {
  10210. TestStringBodyUploadProgress(
  10211. [](Server &svr) {
  10212. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10213. res.set_content("put received", "text/plain");
  10214. });
  10215. },
  10216. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10217. return cli.Put("/test", body, "text/plain", progress_callback);
  10218. },
  10219. "put test data for upload progress");
  10220. }
  10221. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10222. TestStringBodyUploadProgress(
  10223. [](Server &svr) {
  10224. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10225. res.set_content("patch received", "text/plain");
  10226. });
  10227. },
  10228. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10229. return cli.Patch("/test", body, "text/plain", progress_callback);
  10230. },
  10231. "patch test data for upload progress");
  10232. }
  10233. // Helper function for content provider upload progress tests
  10234. template <typename SetupHandler, typename ClientCall>
  10235. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10236. ClientCall &&client_call) {
  10237. Server svr;
  10238. setup_handler(svr);
  10239. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10240. auto se = detail::scope_exit([&] {
  10241. svr.stop();
  10242. t.join();
  10243. });
  10244. svr.wait_until_ready();
  10245. Client cli(HOST, PORT);
  10246. vector<uint64_t> progress_values;
  10247. auto res =
  10248. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10249. progress_values.push_back(current);
  10250. return true;
  10251. });
  10252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10253. EXPECT_EQ(200, res->status);
  10254. EXPECT_FALSE(progress_values.empty());
  10255. }
  10256. TEST(UploadProgressTest, PostContentProviderProgress) {
  10257. TestContentProviderUploadProgress(
  10258. [](Server &svr) {
  10259. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10260. res.set_content("provider received", "text/plain");
  10261. });
  10262. },
  10263. [](Client &cli, UploadProgress progress_callback) {
  10264. return cli.Post(
  10265. "/test", 9,
  10266. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10267. sink.os << "test data";
  10268. return true;
  10269. },
  10270. "text/plain", progress_callback);
  10271. });
  10272. }
  10273. // Helper function for multipart upload progress tests
  10274. template <typename SetupHandler, typename ClientCall>
  10275. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10276. ClientCall &&client_call,
  10277. const string &endpoint) {
  10278. Server svr;
  10279. setup_handler(svr);
  10280. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10281. auto se = detail::scope_exit([&] {
  10282. svr.stop();
  10283. t.join();
  10284. });
  10285. svr.wait_until_ready();
  10286. Client cli(HOST, PORT);
  10287. vector<uint64_t> progress_values;
  10288. UploadFormDataItems items = {
  10289. {"field1", "value1", "", ""},
  10290. {"field2", "longer value for progress tracking test", "", ""},
  10291. {"file1", "file content data for upload progress", "test.txt",
  10292. "text/plain"}};
  10293. auto res = client_call(cli, endpoint, items,
  10294. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10295. progress_values.push_back(current);
  10296. return true;
  10297. });
  10298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10299. EXPECT_EQ(200, res->status);
  10300. EXPECT_FALSE(progress_values.empty());
  10301. }
  10302. TEST(UploadProgressTest, PostMultipartProgress) {
  10303. TestMultipartUploadProgress(
  10304. [](Server &svr) {
  10305. svr.Post("/multipart", [](const Request &req, Response &res) {
  10306. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10307. res.set_content("multipart received", "text/plain");
  10308. });
  10309. },
  10310. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10311. UploadProgress progress_callback) {
  10312. return cli.Post(endpoint, items, progress_callback);
  10313. },
  10314. "/multipart");
  10315. }
  10316. // Helper function for basic download progress tests
  10317. template <typename SetupHandler, typename ClientCall>
  10318. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10319. ClientCall &&client_call, const string &endpoint,
  10320. size_t expected_content_size) {
  10321. Server svr;
  10322. setup_handler(svr);
  10323. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10324. auto se = detail::scope_exit([&] {
  10325. svr.stop();
  10326. t.join();
  10327. });
  10328. svr.wait_until_ready();
  10329. Client cli(HOST, PORT);
  10330. vector<uint64_t> progress_values;
  10331. auto res = client_call(cli, endpoint,
  10332. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10333. progress_values.push_back(current);
  10334. return true;
  10335. });
  10336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10337. EXPECT_EQ(200, res->status);
  10338. EXPECT_FALSE(progress_values.empty());
  10339. EXPECT_EQ(expected_content_size, res->body.size());
  10340. }
  10341. TEST(DownloadProgressTest, GetBasic) {
  10342. TestBasicDownloadProgress(
  10343. [](Server &svr) {
  10344. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10345. string content(1000, 'D');
  10346. res.set_content(content, "text/plain");
  10347. });
  10348. },
  10349. [](Client &cli, const string &endpoint,
  10350. DownloadProgress progress_callback) {
  10351. return cli.Get(endpoint, progress_callback);
  10352. },
  10353. "/download", 1000u);
  10354. }
  10355. // Helper function for content receiver download progress tests
  10356. template <typename SetupHandler, typename ClientCall>
  10357. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10358. ClientCall &&client_call,
  10359. const string &endpoint,
  10360. size_t expected_content_size) {
  10361. Server svr;
  10362. setup_handler(svr);
  10363. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10364. auto se = detail::scope_exit([&] {
  10365. svr.stop();
  10366. t.join();
  10367. });
  10368. svr.wait_until_ready();
  10369. Client cli(HOST, PORT);
  10370. vector<uint64_t> progress_values;
  10371. string received_body;
  10372. auto res = client_call(
  10373. cli, endpoint,
  10374. [&](const char *data, size_t data_length) -> bool {
  10375. received_body.append(data, data_length);
  10376. return true;
  10377. },
  10378. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10379. progress_values.push_back(current);
  10380. return true;
  10381. });
  10382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10383. EXPECT_EQ(200, res->status);
  10384. EXPECT_FALSE(progress_values.empty());
  10385. EXPECT_EQ(expected_content_size, received_body.size());
  10386. EXPECT_TRUE(res->body.empty());
  10387. }
  10388. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10389. TestContentReceiverDownloadProgress(
  10390. [](Server &svr) {
  10391. svr.Get("/download-receiver",
  10392. [](const Request & /*req*/, Response &res) {
  10393. string content(2000, 'R');
  10394. res.set_content(content, "text/plain");
  10395. });
  10396. },
  10397. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10398. DownloadProgress progress_callback) {
  10399. return cli.Get(endpoint, content_receiver, progress_callback);
  10400. },
  10401. "/download-receiver", 2000u);
  10402. }
  10403. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10404. // A provider reaching a pass with nothing to hand over - an empty buffer
  10405. // popped off a queue, say - must not be taken to mean the body is finished.
  10406. // It used to end the loop with the terminating chunk unwritten while the
  10407. // server still considered the response complete, so the peer waited for an
  10408. // end that never arrived.
  10409. Server svr;
  10410. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10411. auto step = std::make_shared<int>(0);
  10412. res.set_chunked_content_provider("text/plain",
  10413. [step](size_t /*offset*/, DataSink &sink) {
  10414. switch ((*step)++) {
  10415. case 0: sink.write("", 0); break;
  10416. case 1: sink.write("hello", 5); break;
  10417. default: sink.done(); break;
  10418. }
  10419. return true;
  10420. });
  10421. });
  10422. auto port = svr.bind_to_any_port(HOST);
  10423. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10424. auto listen_se = detail::scope_exit([&] {
  10425. svr.stop();
  10426. listen_thread.join();
  10427. ASSERT_FALSE(svr.is_running());
  10428. });
  10429. svr.wait_until_ready();
  10430. Client cli(HOST, port);
  10431. // Without the fix the body is never terminated, so bound the wait rather
  10432. // than letting the test hang on the default read timeout.
  10433. cli.set_read_timeout(5, 0);
  10434. auto res = cli.Get("/stream");
  10435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10436. EXPECT_EQ(StatusCode::OK_200, res->status);
  10437. EXPECT_EQ("hello", res->body);
  10438. }
  10439. TEST(StreamingTest, NoContentLengthStreaming) {
  10440. Server svr;
  10441. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10442. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10443. if (offset < 6) {
  10444. sink.os << (offset < 3 ? "a" : "b");
  10445. } else {
  10446. sink.done();
  10447. }
  10448. return true;
  10449. });
  10450. });
  10451. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10452. auto listen_se = detail::scope_exit([&] {
  10453. svr.stop();
  10454. listen_thread.join();
  10455. ASSERT_FALSE(svr.is_running());
  10456. });
  10457. svr.wait_until_ready();
  10458. Client client(HOST, PORT);
  10459. auto get_thread = std::thread([&client]() {
  10460. std::string s;
  10461. auto res =
  10462. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10463. s += std::string(data, len);
  10464. return true;
  10465. });
  10466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10467. EXPECT_EQ(StatusCode::OK_200, res->status);
  10468. EXPECT_EQ("aaabbb", s);
  10469. });
  10470. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10471. // Give GET time to get a few messages.
  10472. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10473. }
  10474. TEST(MountTest, Unmount) {
  10475. Server svr;
  10476. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10477. auto se = detail::scope_exit([&] {
  10478. svr.stop();
  10479. listen_thread.join();
  10480. ASSERT_FALSE(svr.is_running());
  10481. });
  10482. svr.wait_until_ready();
  10483. Client cli("localhost", PORT);
  10484. svr.set_mount_point("/mount2", "./www2");
  10485. auto res = cli.Get("/");
  10486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10487. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10488. res = cli.Get("/mount2/dir/test.html");
  10489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10490. EXPECT_EQ(StatusCode::OK_200, res->status);
  10491. svr.set_mount_point("/", "./www");
  10492. res = cli.Get("/dir/");
  10493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10494. EXPECT_EQ(StatusCode::OK_200, res->status);
  10495. svr.remove_mount_point("/");
  10496. res = cli.Get("/dir/");
  10497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10498. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10499. svr.remove_mount_point("/mount2");
  10500. res = cli.Get("/mount2/dir/test.html");
  10501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10502. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10503. }
  10504. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10505. Server svr;
  10506. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10507. svr.Get("/api/hello", [](const Request &, Response &res) {
  10508. res.set_content("api", "text/plain");
  10509. });
  10510. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10511. auto se = detail::scope_exit([&] {
  10512. svr.stop();
  10513. listen_thread.join();
  10514. ASSERT_FALSE(svr.is_running());
  10515. });
  10516. svr.wait_until_ready();
  10517. Client cli(HOST, PORT);
  10518. auto res = cli.Get("/dir/test.html");
  10519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10520. EXPECT_EQ(StatusCode::OK_200, res->status);
  10521. res = cli.Get("/api/hello");
  10522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10523. EXPECT_EQ(StatusCode::OK_200, res->status);
  10524. EXPECT_EQ("api", res->body);
  10525. }
  10526. TEST(MountTest, PathSegmentBoundary) {
  10527. Server svr;
  10528. svr.set_mount_point("/mount2", "./www2");
  10529. svr.set_mount_point("/", "./www");
  10530. auto port = svr.bind_to_any_port(HOST);
  10531. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10532. auto se = detail::scope_exit([&] {
  10533. svr.stop();
  10534. listen_thread.join();
  10535. ASSERT_FALSE(svr.is_running());
  10536. });
  10537. svr.wait_until_ready();
  10538. Client cli(HOST, port);
  10539. auto res = cli.Get("/mount2/dir/test.html");
  10540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10541. EXPECT_EQ(StatusCode::OK_200, res->status);
  10542. // "/mount2" must not match part-way through a path segment.
  10543. res = cli.Get("/mount2dir/test.html");
  10544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10545. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10546. // A mount point ending in '/' keeps matching every path below it.
  10547. res = cli.Get("/dir/test.html");
  10548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10549. EXPECT_EQ(StatusCode::OK_200, res->status);
  10550. }
  10551. TEST(MountTest, Redicect) {
  10552. Server svr;
  10553. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10554. auto se = detail::scope_exit([&] {
  10555. svr.stop();
  10556. listen_thread.join();
  10557. ASSERT_FALSE(svr.is_running());
  10558. });
  10559. svr.set_mount_point("/", "./www");
  10560. svr.wait_until_ready();
  10561. Client cli("localhost", PORT);
  10562. auto res = cli.Get("/dir/");
  10563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10564. EXPECT_EQ(StatusCode::OK_200, res->status);
  10565. res = cli.Get("/dir");
  10566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10567. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10568. res = cli.Get("/file");
  10569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10570. EXPECT_EQ(StatusCode::OK_200, res->status);
  10571. res = cli.Get("/file/");
  10572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10573. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10574. cli.set_follow_location(true);
  10575. res = cli.Get("/dir");
  10576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10577. EXPECT_EQ(StatusCode::OK_200, res->status);
  10578. }
  10579. TEST(MountTest, MultibytesPathName) {
  10580. Server svr;
  10581. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10582. auto se = detail::scope_exit([&] {
  10583. svr.stop();
  10584. listen_thread.join();
  10585. ASSERT_FALSE(svr.is_running());
  10586. });
  10587. svr.set_mount_point("/", "./www");
  10588. svr.wait_until_ready();
  10589. Client cli("localhost", PORT);
  10590. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10592. EXPECT_EQ(StatusCode::OK_200, res->status);
  10593. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10594. }
  10595. #ifdef _WIN32
  10596. // Issue #2435: mmap::open() must succeed even when another handle holds
  10597. // the file open for writing (e.g. an active log file).
  10598. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10599. const char *path = "mmap_concurrent_writer_test.txt";
  10600. const char *content = "hello";
  10601. {
  10602. std::ofstream f(path, std::ios::binary);
  10603. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10604. }
  10605. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10606. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10607. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10608. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10609. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10610. detail::mmap m(path);
  10611. ASSERT_TRUE(m.is_open());
  10612. EXPECT_EQ(strlen(content), m.size());
  10613. char buf[8];
  10614. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10615. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10616. }
  10617. #endif
  10618. #ifndef _WIN32
  10619. // A directory or a device has no size to serve.
  10620. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10621. const char *path = "./mmap_not_regular_test_dir";
  10622. ASSERT_EQ(0, ::mkdir(path, 0755));
  10623. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10624. for (auto p : {path, "/dev/null"}) {
  10625. detail::mmap m(p);
  10626. EXPECT_FALSE(m.is_open()) << p;
  10627. EXPECT_EQ(0U, m.size()) << p;
  10628. }
  10629. Server svr;
  10630. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10631. res.set_file_content("/dev/null");
  10632. });
  10633. auto port = svr.bind_to_any_port(HOST);
  10634. thread t = thread([&] { svr.listen_after_bind(); });
  10635. auto se = detail::scope_exit([&] {
  10636. svr.stop();
  10637. t.join();
  10638. });
  10639. svr.wait_until_ready();
  10640. auto res = Client(HOST, port).Get("/null");
  10641. ASSERT_TRUE(res);
  10642. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10643. }
  10644. #endif
  10645. #ifdef __linux__
  10646. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10647. TEST(MmapTest, FileIsNotMapped) {
  10648. const char *path = "mmap_not_mapped_test.txt";
  10649. {
  10650. std::ofstream f(path, std::ios::binary);
  10651. f << "hello";
  10652. }
  10653. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10654. detail::mmap m(path);
  10655. ASSERT_TRUE(m.is_open());
  10656. std::ifstream maps("/proc/self/maps");
  10657. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10658. std::istreambuf_iterator<char>());
  10659. EXPECT_EQ(std::string::npos, mappings.find(path));
  10660. }
  10661. #endif
  10662. TEST(KeepAliveTest, ReadTimeout) {
  10663. Server svr;
  10664. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10665. std::this_thread::sleep_for(std::chrono::seconds(2));
  10666. res.set_content("a", "text/plain");
  10667. });
  10668. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10669. res.set_content("b", "text/plain");
  10670. });
  10671. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10672. auto se = detail::scope_exit([&] {
  10673. svr.stop();
  10674. listen_thread.join();
  10675. ASSERT_FALSE(svr.is_running());
  10676. });
  10677. svr.wait_until_ready();
  10678. Client cli("localhost", PORT);
  10679. cli.set_keep_alive(true);
  10680. cli.set_read_timeout(std::chrono::seconds(1));
  10681. auto resa = cli.Get("/a");
  10682. ASSERT_FALSE(resa);
  10683. EXPECT_EQ(Error::Read, resa.error());
  10684. auto resb = cli.Get("/b");
  10685. ASSERT_TRUE(resb);
  10686. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10687. EXPECT_EQ("b", resb->body);
  10688. }
  10689. TEST(KeepAliveTest, MaxCount) {
  10690. size_t keep_alive_max_count = 3;
  10691. Server svr;
  10692. svr.set_keep_alive_max_count(keep_alive_max_count);
  10693. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10694. res.set_content("Hello World!", "text/plain");
  10695. });
  10696. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10697. auto se = detail::scope_exit([&] {
  10698. svr.stop();
  10699. listen_thread.join();
  10700. ASSERT_FALSE(svr.is_running());
  10701. });
  10702. svr.wait_until_ready();
  10703. Client cli(HOST, PORT);
  10704. cli.set_keep_alive(true);
  10705. for (size_t i = 0; i < 5; i++) {
  10706. auto result = cli.Get("/hi");
  10707. ASSERT_TRUE(result);
  10708. EXPECT_EQ(StatusCode::OK_200, result->status);
  10709. if (i == keep_alive_max_count - 1) {
  10710. EXPECT_EQ("close", result->get_header_value("Connection"));
  10711. } else {
  10712. EXPECT_FALSE(result->has_header("Connection"));
  10713. }
  10714. }
  10715. }
  10716. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10717. // can pull the next one into the server's buffer. The server must serve it
  10718. // without waiting for the socket to become readable again. The keep-alive
  10719. // timeout outlasts the client's read timeout, so a request left waiting for it
  10720. // shows up as a missing response.
  10721. static void serve_pipelining_routes(Server &svr,
  10722. const std::function<void(int)> &client) {
  10723. svr.set_keep_alive_timeout(5);
  10724. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10725. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10726. });
  10727. svr.Post("/echo", [](const Request &req, Response &res) {
  10728. res.set_content("echo " + req.body, "text/plain");
  10729. });
  10730. auto port = svr.bind_to_any_port(HOST);
  10731. thread t = thread([&] { svr.listen_after_bind(); });
  10732. auto se = detail::scope_exit([&] {
  10733. svr.stop();
  10734. t.join();
  10735. });
  10736. svr.wait_until_ready();
  10737. client(port);
  10738. }
  10739. static std::string
  10740. send_pipelined_requests(const std::vector<std::string> &parts) {
  10741. Server svr;
  10742. std::string res;
  10743. serve_pipelining_routes(svr, [&](int port) {
  10744. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10745. });
  10746. return res;
  10747. }
  10748. static void expect_in_order(const std::string &res,
  10749. const std::vector<std::string> &bodies) {
  10750. size_t pos = 0;
  10751. for (const auto &body : bodies) {
  10752. pos = res.find(body, pos);
  10753. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10754. pos += body.size();
  10755. }
  10756. }
  10757. TEST(KeepAliveTest, PipelinedRequests) {
  10758. auto res = send_pipelined_requests(
  10759. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10760. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10761. "Content-Length: 4\r\n\r\nbody"
  10762. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10763. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10764. }
  10765. // The second request starts in the server's buffer and ends on the socket.
  10766. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10767. auto res =
  10768. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10769. "GET /hi/2 HTTP/1.1\r\nHo",
  10770. "st: localhost\r\nConnection: close\r\n\r\n"});
  10771. expect_in_order(res, {"hi 1", "hi 2"});
  10772. }
  10773. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10774. // CRLF after a body does not turn into a 400 for the next request.
  10775. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10776. auto res = send_pipelined_requests(
  10777. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10778. "Content-Length: 4\r\n\r\nbody\r\n"
  10779. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10780. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10781. expect_in_order(res, {"echo body", "hi 2"});
  10782. }
  10783. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10784. // must not be served as the next request.
  10785. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10786. auto res = send_pipelined_requests(
  10787. {"INVALID REQUEST LINE\r\n\r\n"
  10788. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10789. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10790. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10791. }
  10792. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10793. // Over TLS, the next request is held by the TLS library as already decrypted
  10794. // data rather than on the socket.
  10795. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10796. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10797. std::string res;
  10798. serve_pipelining_routes(svr, [&](int port) {
  10799. // One part, so all three requests arrive in one TLS record
  10800. EXPECT_TRUE(send_ssl_request_in_parts(
  10801. 2,
  10802. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10803. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10804. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  10805. &res, port));
  10806. });
  10807. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10808. }
  10809. #endif
  10810. TEST(KeepAliveTest, Issue1041) {
  10811. Server svr;
  10812. svr.set_keep_alive_timeout(3);
  10813. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10814. res.set_content("Hello World!", "text/plain");
  10815. });
  10816. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10817. auto se = detail::scope_exit([&] {
  10818. svr.stop();
  10819. listen_thread.join();
  10820. ASSERT_FALSE(svr.is_running());
  10821. });
  10822. svr.wait_until_ready();
  10823. Client cli(HOST, PORT);
  10824. cli.set_keep_alive(true);
  10825. auto result = cli.Get("/hi");
  10826. ASSERT_TRUE(result);
  10827. EXPECT_EQ(StatusCode::OK_200, result->status);
  10828. std::this_thread::sleep_for(std::chrono::seconds(5));
  10829. result = cli.Get("/hi");
  10830. ASSERT_TRUE(result);
  10831. EXPECT_EQ(StatusCode::OK_200, result->status);
  10832. }
  10833. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  10834. Server svr;
  10835. svr.set_keep_alive_max_count(0);
  10836. std::set<int> remote_ports;
  10837. svr.Get("/hi", [&](const Request &req, Response &res) {
  10838. remote_ports.insert(req.remote_port);
  10839. res.set_content("hi", "text/plain");
  10840. });
  10841. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10842. auto se = detail::scope_exit([&] {
  10843. svr.stop();
  10844. listen_thread.join();
  10845. ASSERT_FALSE(svr.is_running());
  10846. });
  10847. svr.wait_until_ready();
  10848. Client cli(HOST, PORT);
  10849. cli.set_keep_alive(true);
  10850. for (int i = 0; i < 3; i++) {
  10851. auto res = cli.Get("/hi");
  10852. ASSERT_TRUE(res);
  10853. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  10854. }
  10855. // All three over one connection
  10856. EXPECT_EQ(1u, remote_ports.size());
  10857. }
  10858. TEST(KeepAliveTest, Issue1959) {
  10859. Server svr;
  10860. svr.set_keep_alive_timeout(5);
  10861. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10862. res.set_content("a", "text/plain");
  10863. });
  10864. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10865. auto se = detail::scope_exit([&] {
  10866. if (!svr.is_running()) return;
  10867. svr.stop();
  10868. listen_thread.join();
  10869. ASSERT_FALSE(svr.is_running());
  10870. });
  10871. svr.wait_until_ready();
  10872. Client cli("localhost", PORT);
  10873. cli.set_keep_alive(true);
  10874. using namespace std::chrono;
  10875. auto start = steady_clock::now();
  10876. cli.Get("/a");
  10877. svr.stop();
  10878. listen_thread.join();
  10879. auto end = steady_clock::now();
  10880. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10881. EXPECT_LT(elapsed, 5000);
  10882. }
  10883. #ifdef CPPHTTPLIB_SSL_ENABLED
  10884. TEST(KeepAliveTest, SSLClientReconnection) {
  10885. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10886. ASSERT_TRUE(svr.is_valid());
  10887. svr.set_keep_alive_timeout(1);
  10888. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10889. res.set_content("Hello World!", "text/plain");
  10890. });
  10891. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10892. auto se = detail::scope_exit([&] {
  10893. svr.stop();
  10894. listen_thread.join();
  10895. ASSERT_FALSE(svr.is_running());
  10896. });
  10897. svr.wait_until_ready();
  10898. SSLClient cli(HOST, PORT);
  10899. cli.enable_server_certificate_verification(false);
  10900. cli.set_keep_alive(true);
  10901. auto result = cli.Get("/hi");
  10902. ASSERT_TRUE(result);
  10903. EXPECT_EQ(StatusCode::OK_200, result->status);
  10904. result = cli.Get("/hi");
  10905. ASSERT_TRUE(result);
  10906. EXPECT_EQ(StatusCode::OK_200, result->status);
  10907. std::this_thread::sleep_for(std::chrono::seconds(2));
  10908. // Recoonect
  10909. result = cli.Get("/hi");
  10910. ASSERT_TRUE(result);
  10911. EXPECT_EQ(StatusCode::OK_200, result->status);
  10912. result = cli.Get("/hi");
  10913. ASSERT_TRUE(result);
  10914. EXPECT_EQ(StatusCode::OK_200, result->status);
  10915. }
  10916. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10917. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10918. ASSERT_TRUE(svr.is_valid());
  10919. svr.set_keep_alive_timeout(1);
  10920. std::string content = "reconnect";
  10921. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10922. res.set_content("Hello World!", "text/plain");
  10923. });
  10924. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10925. auto se = detail::scope_exit([&] {
  10926. svr.stop();
  10927. listen_thread.join();
  10928. ASSERT_FALSE(svr.is_running());
  10929. });
  10930. svr.wait_until_ready();
  10931. SSLClient cli(HOST, PORT);
  10932. cli.enable_server_certificate_verification(false);
  10933. cli.set_keep_alive(true);
  10934. auto result = cli.Post(
  10935. "/hi", content.size(),
  10936. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10937. sink.write(content.c_str(), content.size());
  10938. return true;
  10939. },
  10940. "text/plain");
  10941. ASSERT_TRUE(result);
  10942. EXPECT_EQ(200, result->status);
  10943. std::this_thread::sleep_for(std::chrono::seconds(2));
  10944. // Recoonect
  10945. result = cli.Post(
  10946. "/hi", content.size(),
  10947. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10948. sink.write(content.c_str(), content.size());
  10949. return true;
  10950. },
  10951. "text/plain");
  10952. ASSERT_TRUE(result);
  10953. EXPECT_EQ(200, result->status);
  10954. result = cli.Post(
  10955. "/hi", content.size(),
  10956. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10957. sink.write(content.c_str(), content.size());
  10958. return true;
  10959. },
  10960. "text/plain");
  10961. ASSERT_TRUE(result);
  10962. EXPECT_EQ(200, result->status);
  10963. }
  10964. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10965. using namespace httplib::tls;
  10966. {
  10967. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10968. ASSERT_TRUE(svr.is_valid());
  10969. svr.Get("/sni", [&](const Request &req, Response &res) {
  10970. std::string expected = req.sni();
  10971. EXPECT_EQ(expected, req.get_param_value("expected"));
  10972. res.set_content("ok", "text/plain");
  10973. });
  10974. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10975. auto se = detail::scope_exit([&] {
  10976. svr.stop();
  10977. listen_thread.join();
  10978. ASSERT_FALSE(svr.is_running());
  10979. });
  10980. svr.wait_until_ready();
  10981. {
  10982. SSLClient cli("localhost", PORT);
  10983. cli.enable_server_certificate_verification(false);
  10984. auto res = cli.Get("/sni?expected=localhost");
  10985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10986. }
  10987. {
  10988. SSLClient cli("::1", PORT);
  10989. cli.enable_server_certificate_verification(false);
  10990. auto res = cli.Get("/sni?expected=");
  10991. // NOTE: This may fail if the server is listening on IPv4 only
  10992. // (e.g., when localhost resolves to 127.0.0.1 only)
  10993. if (res) {
  10994. EXPECT_EQ(StatusCode::OK_200, res->status);
  10995. } else {
  10996. EXPECT_EQ(Error::Connection, res.error());
  10997. }
  10998. }
  10999. }
  11000. }
  11001. #endif
  11002. TEST(ClientProblemDetectionTest, ContentProvider) {
  11003. Server svr;
  11004. size_t content_length = 1024 * 1024;
  11005. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11006. res.set_content_provider(
  11007. content_length, "text/plain",
  11008. [&](size_t offset, size_t length, DataSink &sink) {
  11009. auto out_len = std::min(length, static_cast<size_t>(1024));
  11010. std::string out(out_len, '@');
  11011. sink.write(out.data(), out_len);
  11012. return offset < 4096;
  11013. },
  11014. [](bool success) { ASSERT_FALSE(success); });
  11015. });
  11016. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11017. res.set_content_provider(
  11018. 0, "text/plain",
  11019. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11020. EXPECT_TRUE(false);
  11021. return true;
  11022. },
  11023. [](bool success) { ASSERT_FALSE(success); });
  11024. });
  11025. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11026. auto se = detail::scope_exit([&] {
  11027. svr.stop();
  11028. listen_thread.join();
  11029. ASSERT_FALSE(svr.is_running());
  11030. });
  11031. svr.wait_until_ready();
  11032. Client cli("localhost", PORT);
  11033. {
  11034. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11035. size_t /*data_length*/) { return false; });
  11036. ASSERT_FALSE(res);
  11037. }
  11038. {
  11039. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11040. size_t /*data_length*/) { return false; });
  11041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11042. }
  11043. }
  11044. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11045. // A provider that reports success without writing anything and without
  11046. // calling done() used to be handed the same offset and length again on every
  11047. // pass, so it spun for as long as the peer stayed connected.
  11048. Server svr;
  11049. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11050. res.set_content("ok", "text/plain");
  11051. });
  11052. auto port = svr.bind_to_any_port(HOST);
  11053. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11054. auto se = detail::scope_exit([&] {
  11055. svr.stop();
  11056. listen_thread.join();
  11057. ASSERT_FALSE(svr.is_running());
  11058. });
  11059. svr.wait_until_ready();
  11060. std::atomic<int> call_count{0};
  11061. Client cli(HOST, port);
  11062. auto res = cli.Post(
  11063. "/", 1024,
  11064. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11065. // Give up after enough passes to show the spin, so that losing the
  11066. // check below fails this test instead of hanging it.
  11067. return ++call_count < 100;
  11068. },
  11069. "text/plain");
  11070. ASSERT_FALSE(res);
  11071. EXPECT_EQ(Error::Write, res.error());
  11072. EXPECT_EQ(1, call_count.load());
  11073. }
  11074. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11075. // A writer only has to assign `write`. The other three used to be left as
  11076. // empty std::functions, so a provider calling one threw
  11077. // std::bad_function_call out of the thread running it and took the whole
  11078. // process down.
  11079. DataSink sink;
  11080. std::string written;
  11081. sink.write = [&](const char *data, size_t data_len) {
  11082. written.append(data, data_len);
  11083. return true;
  11084. };
  11085. EXPECT_TRUE(sink.is_writable());
  11086. sink.done();
  11087. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11088. EXPECT_TRUE(written.empty());
  11089. }
  11090. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11091. // A sink that cannot carry trailers still has to finish.
  11092. DataSink sink;
  11093. auto done_count = 0;
  11094. sink.done = [&]() { done_count++; };
  11095. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11096. EXPECT_EQ(1, done_count);
  11097. }
  11098. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11099. Server svr;
  11100. const std::string body(4096, 'x');
  11101. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11102. res.set_content_provider(body.size(), "text/plain",
  11103. [&](size_t offset, size_t length, DataSink &sink) {
  11104. sink.write(body.data() + offset, length);
  11105. sink.done();
  11106. return true;
  11107. });
  11108. });
  11109. auto port = svr.bind_to_any_port(HOST);
  11110. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11111. auto se = detail::scope_exit([&] {
  11112. svr.stop();
  11113. listen_thread.join();
  11114. ASSERT_FALSE(svr.is_running());
  11115. });
  11116. svr.wait_until_ready();
  11117. Client cli(HOST, port);
  11118. auto res = cli.Get("/");
  11119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11120. EXPECT_EQ(StatusCode::OK_200, res->status);
  11121. EXPECT_EQ(body, res->body);
  11122. }
  11123. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11124. Server svr;
  11125. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11126. res.set_content_provider(
  11127. 1024, "text/plain",
  11128. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11129. sink.write("hello", 5);
  11130. sink.done(); // short of the 1024 bytes the response promised
  11131. return true;
  11132. });
  11133. });
  11134. auto port = svr.bind_to_any_port(HOST);
  11135. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11136. auto se = detail::scope_exit([&] {
  11137. svr.stop();
  11138. listen_thread.join();
  11139. ASSERT_FALSE(svr.is_running());
  11140. });
  11141. svr.wait_until_ready();
  11142. Client cli(HOST, port);
  11143. cli.set_read_timeout(5, 0);
  11144. // The response is short of its Content-Length, so the client cannot read a
  11145. // complete body. What matters is that this returns at all: a no-op done()
  11146. // would leave the writer looping over a provider that never makes progress.
  11147. auto res = cli.Get("/");
  11148. EXPECT_FALSE(res);
  11149. }
  11150. // Read as the next response by a peer that sees it after a framed body.
  11151. static const std::string smuggled_response =
  11152. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11153. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11154. Server svr;
  11155. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11156. res.set_content_provider(
  11157. 5, "text/plain",
  11158. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11159. auto data = "AAAAA" + smuggled_response;
  11160. sink.write(data.data(), data.size());
  11161. return true;
  11162. });
  11163. });
  11164. thread t = thread([&] { svr.listen(HOST, PORT); });
  11165. auto se = detail::scope_exit([&] {
  11166. svr.stop();
  11167. t.join();
  11168. ASSERT_FALSE(svr.is_running());
  11169. });
  11170. svr.wait_until_ready();
  11171. std::string resp;
  11172. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11173. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11174. resp.clear();
  11175. ASSERT_TRUE(send_request(
  11176. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11177. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11178. }
  11179. TEST(NoContentTest, BodyIsNotSent) {
  11180. Server svr;
  11181. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11182. res.status = StatusCode::NoContent_204;
  11183. res.set_content(smuggled_response, "text/plain");
  11184. });
  11185. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11186. res.status = StatusCode::NotModified_304;
  11187. res.set_chunked_content_provider(
  11188. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11189. sink.write(smuggled_response.data(), smuggled_response.size());
  11190. sink.done();
  11191. return true;
  11192. });
  11193. });
  11194. thread t = thread([&] { svr.listen(HOST, PORT); });
  11195. auto se = detail::scope_exit([&] {
  11196. svr.stop();
  11197. t.join();
  11198. ASSERT_FALSE(svr.is_running());
  11199. });
  11200. svr.wait_until_ready();
  11201. for (auto path : {"/204", "/304"}) {
  11202. std::string resp;
  11203. ASSERT_TRUE(send_request(
  11204. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11205. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11206. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11207. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11208. }
  11209. }
  11210. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11211. Server svr;
  11212. std::atomic<bool> smuggled(false);
  11213. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11214. res.set_content("ok", "text/plain");
  11215. });
  11216. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11217. smuggled = true;
  11218. });
  11219. auto port = svr.bind_to_any_port(HOST);
  11220. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11221. auto se = detail::scope_exit([&] {
  11222. svr.stop();
  11223. listen_thread.join();
  11224. ASSERT_FALSE(svr.is_running());
  11225. });
  11226. svr.wait_until_ready();
  11227. // What follows the body would be read as the next request.
  11228. Client cli(HOST, port);
  11229. auto res = cli.Post(
  11230. "/", 5,
  11231. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11232. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11233. sink.write(data.data(), data.size());
  11234. return true;
  11235. },
  11236. "text/plain");
  11237. ASSERT_FALSE(res);
  11238. EXPECT_EQ(Error::Write, res.error());
  11239. EXPECT_FALSE(smuggled);
  11240. }
  11241. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11242. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11243. // The compressed path builds the whole body before connecting, so this
  11244. // fails client-side and never reaches a server.
  11245. Client cli(HOST, PORT);
  11246. cli.set_compress(true);
  11247. auto res = cli.Post(
  11248. "/", 1024,
  11249. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11250. sink.write("hello", 5);
  11251. sink.done(); // short of the 1024 bytes the request announced
  11252. return true;
  11253. },
  11254. "text/plain");
  11255. ASSERT_FALSE(res);
  11256. EXPECT_EQ(Error::Write, res.error());
  11257. }
  11258. #endif
  11259. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11260. Server svr;
  11261. svr.set_error_handler([](Request const &, Response &res) -> void {
  11262. res.set_chunked_content_provider(
  11263. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11264. sink.os << "hello";
  11265. sink.os << "world";
  11266. sink.done();
  11267. return true;
  11268. });
  11269. });
  11270. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11271. auto se = detail::scope_exit([&] {
  11272. svr.stop();
  11273. listen_thread.join();
  11274. ASSERT_FALSE(svr.is_running());
  11275. });
  11276. svr.wait_until_ready();
  11277. Client cli("localhost", PORT);
  11278. auto res = cli.Get("/");
  11279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11280. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11281. EXPECT_EQ("helloworld", res->body);
  11282. }
  11283. // A body set after a content provider must replace it, not be sent through it.
  11284. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11285. Server svr;
  11286. svr.set_mount_point("/", "./www");
  11287. svr.set_file_request_handler([](const Request &req, Response &res) {
  11288. if (req.path == "/dir/test.html") {
  11289. res.status = StatusCode::Forbidden_403;
  11290. res.set_content(std::string(5000, 'D'), "text/plain");
  11291. } else if (req.path == "/file") {
  11292. res.status = StatusCode::Forbidden_403;
  11293. res.body = "Denied";
  11294. }
  11295. });
  11296. auto port = svr.bind_to_any_port(HOST);
  11297. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11298. auto se = detail::scope_exit([&] {
  11299. svr.stop();
  11300. t.join();
  11301. ASSERT_FALSE(svr.is_running());
  11302. });
  11303. svr.wait_until_ready();
  11304. Client cli(HOST, port);
  11305. {
  11306. auto res = cli.Get("/dir/test.html");
  11307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11308. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11309. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11310. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11311. }
  11312. {
  11313. auto res = cli.Get("/file");
  11314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11315. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11316. EXPECT_EQ("Denied", res->body);
  11317. }
  11318. {
  11319. auto res = cli.Get("/dir/index.html");
  11320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11321. EXPECT_EQ(StatusCode::OK_200, res->status);
  11322. EXPECT_EQ(0U, res->body.find("<html>"));
  11323. }
  11324. }
  11325. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11326. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11327. Server svr;
  11328. std::vector<bool> released;
  11329. std::mutex released_mutex;
  11330. auto releaser = [&](bool success) {
  11331. std::lock_guard<std::mutex> guard(released_mutex);
  11332. released.push_back(success);
  11333. };
  11334. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11335. return sink.write(&"hello"[offset], length);
  11336. };
  11337. svr.Get("/sized", [&](const Request &, Response &res) {
  11338. res.status = StatusCode::NotFound_404;
  11339. res.set_content_provider(5, "text/plain", provider, releaser);
  11340. });
  11341. svr.Get("/chunked", [&](const Request &, Response &res) {
  11342. res.status = StatusCode::ServiceUnavailable_503;
  11343. res.set_chunked_content_provider(
  11344. "text/plain",
  11345. [](size_t, DataSink &sink) {
  11346. sink.os << "chunk";
  11347. sink.done();
  11348. return true;
  11349. },
  11350. releaser);
  11351. });
  11352. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11353. res.set_content_provider(5, "text/plain", provider, releaser);
  11354. throw std::runtime_error("after the provider");
  11355. });
  11356. svr.set_error_handler([](const Request &req, Response &res) {
  11357. // Leave the exception handler's content to it.
  11358. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11359. res.set_content(std::string(1000, 'E'), "text/html");
  11360. return Server::HandlerResponse::Handled;
  11361. });
  11362. svr.set_exception_handler(
  11363. [](const Request &, Response &res, std::exception_ptr) {
  11364. res.status = StatusCode::InternalServerError_500;
  11365. res.set_content(std::string(1000, 'X'), "text/html");
  11366. });
  11367. auto port = svr.bind_to_any_port(HOST);
  11368. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11369. auto se = detail::scope_exit([&] {
  11370. svr.stop();
  11371. t.join();
  11372. ASSERT_FALSE(svr.is_running());
  11373. });
  11374. svr.wait_until_ready();
  11375. Client cli(HOST, port);
  11376. {
  11377. auto res = cli.Get("/sized");
  11378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11379. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11380. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11381. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11382. }
  11383. {
  11384. auto res = cli.Get("/chunked");
  11385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11386. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11387. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11388. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11389. }
  11390. {
  11391. auto res = cli.Get("/throw");
  11392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11393. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11394. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11395. }
  11396. std::lock_guard<std::mutex> guard(released_mutex);
  11397. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11398. }
  11399. #endif
  11400. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11401. Server svr;
  11402. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11403. return sink.write(&"abc"[offset], length);
  11404. };
  11405. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11406. res.set_file_content("./www/dir/test.html");
  11407. res.set_content("body", "text/plain");
  11408. });
  11409. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11410. res.set_content(std::string(100, 'B'), "text/plain");
  11411. res.set_file_content("./www/dir/test.html");
  11412. });
  11413. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11414. res.set_content(std::string(100, 'B'), "text/plain");
  11415. res.set_content_provider(3, "text/x-provider", abc);
  11416. });
  11417. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11418. res.set_content_provider(3, "text/x-provider", abc);
  11419. res.set_content(std::string(100, 'B'), "text/plain");
  11420. });
  11421. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  11422. res.set_content_provider(3, "text/x-provider", abc);
  11423. res.set_file_content("./www/dir/test.html", "text/x-file");
  11424. });
  11425. svr.Get("/file-then-header", [](const Request &, Response &res) {
  11426. res.set_file_content("./www/dir/test.html");
  11427. res.set_header("Content-Type", "text/x-handler");
  11428. });
  11429. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11430. res.set_content_provider(3, "text/plain", abc);
  11431. res.body = "direct";
  11432. });
  11433. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11434. res.set_file_content("./www/dir/test.html");
  11435. res.body = "direct";
  11436. });
  11437. auto port = svr.bind_to_any_port(HOST);
  11438. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11439. auto se = detail::scope_exit([&] {
  11440. svr.stop();
  11441. t.join();
  11442. ASSERT_FALSE(svr.is_running());
  11443. });
  11444. svr.wait_until_ready();
  11445. Client cli(HOST, port);
  11446. auto expect_body = [&](const char *path, const std::string &body,
  11447. const std::string &type) {
  11448. // Uncompressed, so Content-Length can be compared with the body.
  11449. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11450. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11451. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11452. EXPECT_EQ(body, res->body) << path;
  11453. EXPECT_EQ(std::to_string(body.size()),
  11454. res->get_header_value("Content-Length"))
  11455. << path;
  11456. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  11457. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  11458. };
  11459. expect_body("/file-then-body", "body", "text/plain");
  11460. expect_body("/body-then-file", "test.html", "text/html");
  11461. expect_body("/body-then-provider", "abc", "text/x-provider");
  11462. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  11463. expect_body("/provider-then-file", "test.html", "text/x-file");
  11464. expect_body("/file-then-header", "test.html", "text/x-handler");
  11465. expect_body("/provider-then-direct-body", "direct", "text/plain");
  11466. expect_body("/file-then-direct-body", "direct", "text/plain");
  11467. // Ranges are checked against the body, not the dropped provider.
  11468. {
  11469. auto res = cli.Get("/provider-then-direct-body",
  11470. Headers{{make_range_header({{1, 2}})}});
  11471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11472. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11473. EXPECT_EQ("ir", res->body);
  11474. }
  11475. {
  11476. auto res = cli.Get("/file-then-direct-body",
  11477. Headers{{make_range_header({{7, 8}})}});
  11478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11479. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11480. }
  11481. }
  11482. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11483. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11484. const char *path = "./truncated_while_served.txt";
  11485. const size_t size = 32 * 1024 * 1024;
  11486. {
  11487. std::ofstream f(path, std::ios::binary);
  11488. f << std::string(size, 'x');
  11489. }
  11490. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11491. // Over TLS, where the bytes are encrypted in this process rather than
  11492. // copied by send().
  11493. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11494. svr.Get("/file", [&](const Request &, Response &res) {
  11495. res.set_file_content(path, "text/plain");
  11496. });
  11497. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11498. auto se = detail::scope_exit([&] {
  11499. svr.stop();
  11500. thread.join();
  11501. ASSERT_FALSE(svr.is_running());
  11502. });
  11503. svr.wait_until_ready();
  11504. // The file shrinks once the first bytes are in, as a rewrite in place
  11505. // would, and reading the mapping past its new end used to raise SIGBUS.
  11506. SSLClient cli(HOST, PORT);
  11507. cli.enable_server_certificate_verification(false);
  11508. size_t received = 0;
  11509. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11510. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11511. received += len;
  11512. return true;
  11513. });
  11514. EXPECT_FALSE(res);
  11515. EXPECT_LT(received, size);
  11516. }
  11517. #endif
  11518. // Forward declaration (see the base64_encode note).
  11519. namespace httplib {
  11520. namespace detail {
  11521. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11522. const std::string &content_type,
  11523. EncodingType encoding);
  11524. } // namespace detail
  11525. } // namespace httplib
  11526. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11527. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11528. ASSERT_TRUE(mm->is_open());
  11529. Response res;
  11530. detail::set_file_content_provider(res, mm, "text/html",
  11531. detail::EncodingType::None);
  11532. std::string out;
  11533. DataSink sink;
  11534. sink.write = [&](const char *d, size_t l) {
  11535. out.append(d, l);
  11536. return true;
  11537. };
  11538. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11539. EXPECT_EQ("test.html", out);
  11540. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11541. EXPECT_EQ("test.html", out);
  11542. }
  11543. TEST(LongPollingTest, ClientCloseDetection) {
  11544. Server svr;
  11545. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11546. res.set_chunked_content_provider(
  11547. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11548. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11549. sink.os << "hello";
  11550. auto count = 10;
  11551. while (count > 0 && sink.is_writable()) {
  11552. this_thread::sleep_for(chrono::milliseconds(10));
  11553. count--;
  11554. }
  11555. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11556. return true;
  11557. });
  11558. });
  11559. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11560. auto se = detail::scope_exit([&] {
  11561. svr.stop();
  11562. listen_thread.join();
  11563. ASSERT_FALSE(svr.is_running());
  11564. });
  11565. svr.wait_until_ready();
  11566. Client cli("localhost", PORT);
  11567. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11568. EXPECT_EQ("hello", string(data, data_length));
  11569. return false; // close the socket immediately.
  11570. });
  11571. ASSERT_FALSE(res);
  11572. }
  11573. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11574. Server svr;
  11575. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11576. res.set_chunked_content_provider(
  11577. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11578. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11579. sink.os << "hello";
  11580. EXPECT_TRUE(sink.os.good());
  11581. // Wait for the client to close the connection
  11582. auto count = 10;
  11583. while (count > 0 && sink.is_writable()) {
  11584. this_thread::sleep_for(chrono::milliseconds(10));
  11585. count--;
  11586. }
  11587. // After client disconnect, write repeatedly until the socket
  11588. // write actually fails (small writes may be absorbed by the
  11589. // kernel buffer)
  11590. std::string chunk(1024, 'x');
  11591. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11592. sink.os << chunk;
  11593. }
  11594. EXPECT_TRUE(sink.os.fail());
  11595. return true;
  11596. });
  11597. });
  11598. auto port = svr.bind_to_any_port("localhost");
  11599. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11600. auto se = detail::scope_exit([&] {
  11601. svr.stop();
  11602. listen_thread.join();
  11603. ASSERT_FALSE(svr.is_running());
  11604. });
  11605. svr.wait_until_ready();
  11606. Client cli("localhost", port);
  11607. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11608. EXPECT_EQ("hello", string(data, data_length));
  11609. return false; // close the socket immediately.
  11610. });
  11611. ASSERT_FALSE(res);
  11612. }
  11613. TEST(GetWithParametersTest, GetWithParameters) {
  11614. Server svr;
  11615. svr.Get("/", [&](const Request &req, Response &) {
  11616. EXPECT_EQ("world", req.get_param_value("hello"));
  11617. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11618. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11619. });
  11620. svr.Get("/params", [&](const Request &req, Response &) {
  11621. EXPECT_EQ("world", req.get_param_value("hello"));
  11622. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11623. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11624. });
  11625. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11626. EXPECT_EQ("resource-id", req.matches[1]);
  11627. EXPECT_EQ("foo", req.get_param_value("param1"));
  11628. EXPECT_EQ("bar", req.get_param_value("param2"));
  11629. });
  11630. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11631. EXPECT_EQ("user-id", req.path_params.at("id"));
  11632. EXPECT_EQ("foo", req.get_param_value("param1"));
  11633. EXPECT_EQ("bar", req.get_param_value("param2"));
  11634. });
  11635. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11636. auto se = detail::scope_exit([&] {
  11637. svr.stop();
  11638. listen_thread.join();
  11639. ASSERT_FALSE(svr.is_running());
  11640. });
  11641. svr.wait_until_ready();
  11642. {
  11643. Client cli(HOST, PORT);
  11644. Params params;
  11645. params.emplace("hello", "world");
  11646. params.emplace("hello2", "world2");
  11647. params.emplace("hello3", "world3");
  11648. auto res = cli.Get("/", params, Headers{});
  11649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11650. EXPECT_EQ(StatusCode::OK_200, res->status);
  11651. }
  11652. {
  11653. Client cli(HOST, PORT);
  11654. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11656. EXPECT_EQ(StatusCode::OK_200, res->status);
  11657. }
  11658. {
  11659. Client cli(HOST, PORT);
  11660. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11662. EXPECT_EQ(StatusCode::OK_200, res->status);
  11663. }
  11664. {
  11665. Client cli(HOST, PORT);
  11666. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11668. EXPECT_EQ(StatusCode::OK_200, res->status);
  11669. }
  11670. }
  11671. TEST(GetWithParametersTest, GetWithParameters2) {
  11672. Server svr;
  11673. svr.Get("/", [&](const Request &req, Response &res) {
  11674. auto text = req.get_param_value("hello");
  11675. res.set_content(text, "text/plain");
  11676. });
  11677. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11678. auto se = detail::scope_exit([&] {
  11679. svr.stop();
  11680. listen_thread.join();
  11681. ASSERT_FALSE(svr.is_running());
  11682. });
  11683. svr.wait_until_ready();
  11684. Client cli("localhost", PORT);
  11685. Params params;
  11686. params.emplace("hello", "world");
  11687. std::string body;
  11688. auto res = cli.Get("/", params, Headers{},
  11689. [&](const char *data, size_t data_length) {
  11690. body.append(data, data_length);
  11691. return true;
  11692. });
  11693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11694. EXPECT_EQ(StatusCode::OK_200, res->status);
  11695. EXPECT_EQ("world", body);
  11696. }
  11697. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11698. Server svr;
  11699. svr.Get("/search", [&](const Request &req, Response &res) {
  11700. auto q = req.get_param_value("q");
  11701. res.set_content(q, "text/plain");
  11702. });
  11703. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11704. auto se = detail::scope_exit([&] {
  11705. svr.stop();
  11706. listen_thread.join();
  11707. ASSERT_FALSE(svr.is_running());
  11708. });
  11709. svr.wait_until_ready();
  11710. Client cli("localhost", PORT);
  11711. // Verify that Get(path, params) works without requiring Headers argument
  11712. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11714. EXPECT_EQ(StatusCode::OK_200, res->status);
  11715. EXPECT_EQ("cpp-httplib", res->body);
  11716. }
  11717. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11718. auto host = "httpbingo.org";
  11719. auto path = std::string{"/range/32"};
  11720. #ifdef CPPHTTPLIB_SSL_ENABLED
  11721. SSLClient cli(host);
  11722. #else
  11723. Client cli(host);
  11724. #endif
  11725. cli.set_default_headers({make_range_header({{1, 10}})});
  11726. cli.set_connection_timeout(5);
  11727. {
  11728. auto res = cli.Get(path);
  11729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11730. EXPECT_EQ("bcdefghijk", res->body);
  11731. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11732. }
  11733. {
  11734. auto res = cli.Get(path);
  11735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11736. EXPECT_EQ("bcdefghijk", res->body);
  11737. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11738. }
  11739. }
  11740. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11741. Server svr;
  11742. svr.set_default_headers({{"Hello", "World"}});
  11743. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11744. res.set_content("ok", "text/plain");
  11745. });
  11746. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11747. auto se = detail::scope_exit([&] {
  11748. svr.stop();
  11749. listen_thread.join();
  11750. ASSERT_FALSE(svr.is_running());
  11751. });
  11752. svr.wait_until_ready();
  11753. Client cli("localhost", PORT);
  11754. auto res = cli.Get("/");
  11755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11756. EXPECT_EQ(StatusCode::OK_200, res->status);
  11757. EXPECT_EQ("ok", res->body);
  11758. EXPECT_EQ("World", res->get_header_value("Hello"));
  11759. }
  11760. #ifdef CPPHTTPLIB_SSL_ENABLED
  11761. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11762. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11763. ASSERT_TRUE(svr.is_valid());
  11764. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11765. std::this_thread::sleep_for(std::chrono::seconds(2));
  11766. res.set_content("a", "text/plain");
  11767. });
  11768. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11769. res.set_content("b", "text/plain");
  11770. });
  11771. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11772. auto se = detail::scope_exit([&] {
  11773. svr.stop();
  11774. listen_thread.join();
  11775. ASSERT_FALSE(svr.is_running());
  11776. });
  11777. svr.wait_until_ready();
  11778. SSLClient cli("localhost", PORT);
  11779. cli.enable_server_certificate_verification(false);
  11780. cli.set_keep_alive(true);
  11781. cli.set_read_timeout(std::chrono::seconds(1));
  11782. auto resa = cli.Get("/a");
  11783. ASSERT_TRUE(!resa);
  11784. EXPECT_EQ(Error::Read, resa.error());
  11785. auto resb = cli.Get("/b");
  11786. ASSERT_TRUE(resb);
  11787. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11788. EXPECT_EQ("b", resb->body);
  11789. }
  11790. // Closing an idle keep-alive connection sends close_notify and returns. The
  11791. // server must not wait for the client's close_notify: an idle client never
  11792. // sends one, so the worker would be held until the read timeout expires, and
  11793. // stop() would wait for it.
  11794. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11795. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11796. ASSERT_TRUE(svr.is_valid());
  11797. svr.set_keep_alive_timeout(1);
  11798. svr.set_read_timeout(10, 0);
  11799. svr.Get("/", [](const Request &, Response &res) {
  11800. res.set_content("ok", "text/plain");
  11801. });
  11802. auto port = svr.bind_to_any_port(HOST);
  11803. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11804. auto se = detail::scope_exit([&] {
  11805. if (listen_thread.joinable()) {
  11806. svr.stop();
  11807. listen_thread.join();
  11808. }
  11809. });
  11810. svr.wait_until_ready();
  11811. SSLClient cli(HOST, port);
  11812. cli.enable_server_certificate_verification(false);
  11813. cli.set_keep_alive(true);
  11814. auto res = cli.Get("/");
  11815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11816. EXPECT_EQ(StatusCode::OK_200, res->status);
  11817. // Stay idle past the keep-alive timeout so the server closes the connection.
  11818. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11819. auto start = std::chrono::steady_clock::now();
  11820. svr.stop();
  11821. listen_thread.join();
  11822. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11823. std::chrono::steady_clock::now() - start)
  11824. .count();
  11825. EXPECT_LT(elapsed, 3000);
  11826. }
  11827. #endif
  11828. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11829. protected:
  11830. ServerTestWithAI_PASSIVE()
  11831. : cli_(HOST, PORT)
  11832. #ifdef CPPHTTPLIB_SSL_ENABLED
  11833. ,
  11834. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11835. #endif
  11836. {
  11837. #ifdef CPPHTTPLIB_SSL_ENABLED
  11838. cli_.enable_server_certificate_verification(false);
  11839. #endif
  11840. }
  11841. virtual void SetUp() {
  11842. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11843. res.set_content("Hello World!", "text/plain");
  11844. });
  11845. t_ = thread(
  11846. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11847. svr_.wait_until_ready();
  11848. }
  11849. virtual void TearDown() {
  11850. svr_.stop();
  11851. t_.join();
  11852. }
  11853. #ifdef CPPHTTPLIB_SSL_ENABLED
  11854. SSLClient cli_;
  11855. SSLServer svr_;
  11856. #else
  11857. Client cli_;
  11858. Server svr_;
  11859. #endif
  11860. thread t_;
  11861. };
  11862. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11863. auto res = cli_.Get("/hi");
  11864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11865. EXPECT_EQ(StatusCode::OK_200, res->status);
  11866. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11867. EXPECT_EQ("Hello World!", res->body);
  11868. }
  11869. class ServerUpDownTest : public ::testing::Test {
  11870. protected:
  11871. ServerUpDownTest() : cli_(HOST, PORT) {}
  11872. virtual void SetUp() {
  11873. t_ = thread([&]() {
  11874. svr_.bind_to_any_port(HOST);
  11875. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11876. ASSERT_TRUE(svr_.listen_after_bind());
  11877. });
  11878. svr_.wait_until_ready();
  11879. }
  11880. virtual void TearDown() {
  11881. svr_.stop();
  11882. t_.join();
  11883. }
  11884. Client cli_;
  11885. Server svr_;
  11886. thread t_;
  11887. };
  11888. TEST_F(ServerUpDownTest, QuickStartStop) {
  11889. // Should not crash, especially when run with
  11890. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11891. }
  11892. class PayloadMaxLengthTest : public ::testing::Test {
  11893. protected:
  11894. PayloadMaxLengthTest()
  11895. : cli_(HOST, PORT)
  11896. #ifdef CPPHTTPLIB_SSL_ENABLED
  11897. ,
  11898. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11899. #endif
  11900. {
  11901. #ifdef CPPHTTPLIB_SSL_ENABLED
  11902. cli_.enable_server_certificate_verification(false);
  11903. #endif
  11904. }
  11905. virtual void SetUp() {
  11906. svr_.set_payload_max_length(8);
  11907. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11908. res.set_content("test", "text/plain");
  11909. });
  11910. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11911. svr_.wait_until_ready();
  11912. }
  11913. virtual void TearDown() {
  11914. svr_.stop();
  11915. t_.join();
  11916. }
  11917. #ifdef CPPHTTPLIB_SSL_ENABLED
  11918. SSLClient cli_;
  11919. SSLServer svr_;
  11920. #else
  11921. Client cli_;
  11922. Server svr_;
  11923. #endif
  11924. thread t_;
  11925. };
  11926. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11927. auto res = cli_.Post("/test", "123456789", "text/plain");
  11928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11929. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11930. res = cli_.Post("/test", "12345678", "text/plain");
  11931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11932. EXPECT_EQ(StatusCode::OK_200, res->status);
  11933. }
  11934. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11935. // Test chunked encoding with payload exceeding the 8-byte limit
  11936. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11937. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11939. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11940. }
  11941. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11942. // Test chunked encoding with payload within the 8-byte limit
  11943. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11944. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11946. EXPECT_EQ(StatusCode::OK_200, res->status);
  11947. }
  11948. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11949. // Test using send_request to send chunked data exceeding payload limit
  11950. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11951. "Host: " +
  11952. std::string(HOST) + ":" + std::to_string(PORT) +
  11953. "\r\n"
  11954. "Transfer-Encoding: chunked\r\n"
  11955. "Connection: close\r\n"
  11956. "\r\n"
  11957. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  11958. "0123456789\r\n"
  11959. "0\r\n" // End chunk
  11960. "\r\n";
  11961. std::string response;
  11962. bool result = send_request(1, chunked_request, &response);
  11963. if (!result) {
  11964. // If send_request fails, it might be because the server closed the
  11965. // connection due to payload limit enforcement, which is acceptable
  11966. SUCCEED()
  11967. << "Server rejected oversized chunked request (connection closed)";
  11968. } else {
  11969. // If we got a response, check if it's an error response or connection was
  11970. // closed early Short response length indicates connection was closed due to
  11971. // payload limit
  11972. if (response.length() <= 10) {
  11973. SUCCEED() << "Server closed connection for oversized chunked request";
  11974. } else {
  11975. // Check for error status codes
  11976. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11977. response.find("Payload Too Large") != std::string::npos ||
  11978. response.find("400") != std::string::npos);
  11979. }
  11980. }
  11981. }
  11982. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  11983. // Test request without Content-Length header exceeding payload limit
  11984. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11985. "Host: " +
  11986. std::string(HOST) + ":" +
  11987. std::to_string(PORT) +
  11988. "\r\n"
  11989. "Connection: close\r\n"
  11990. "\r\n";
  11991. // Add payload exceeding the 8-byte limit
  11992. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  11993. request_without_content_length += large_payload;
  11994. std::string response;
  11995. bool result = send_request(1, request_without_content_length, &response);
  11996. if (!result) {
  11997. // If send_request fails, server likely closed connection due to payload
  11998. // limit
  11999. SUCCEED() << "Server rejected oversized request without Content-Length "
  12000. "(connection closed)";
  12001. } else {
  12002. // Check if server responded with error or closed connection early
  12003. if (response.length() <= 10) {
  12004. SUCCEED() << "Server closed connection for oversized request without "
  12005. "Content-Length";
  12006. } else {
  12007. // Check for error status codes
  12008. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12009. response.find("Payload Too Large") != std::string::npos ||
  12010. response.find("400") != std::string::npos);
  12011. }
  12012. }
  12013. }
  12014. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  12015. // Test request without Content-Length header within payload limit
  12016. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12017. "Host: " +
  12018. std::string(HOST) + ":" +
  12019. std::to_string(PORT) +
  12020. "\r\n"
  12021. "Connection: close\r\n"
  12022. "\r\n";
  12023. // Add payload within the 8-byte limit
  12024. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  12025. request_without_content_length += small_payload;
  12026. std::string response;
  12027. bool result = send_request(1, request_without_content_length, &response);
  12028. // For requests without Content-Length, the server may have different behavior
  12029. // The key is that it should not reject due to payload limit for small
  12030. // payloads
  12031. if (result) {
  12032. // Check for any HTTP response (success or error, but not connection closed)
  12033. if (response.length() > 10) {
  12034. SUCCEED()
  12035. << "Server processed request without Content-Length within limit";
  12036. } else {
  12037. // Short response might indicate connection closed, which is acceptable
  12038. SUCCEED() << "Server closed connection for request without "
  12039. "Content-Length (acceptable behavior)";
  12040. }
  12041. } else {
  12042. // Connection failure might be due to protocol requirements
  12043. SUCCEED() << "Connection issue with request without Content-Length "
  12044. "(environment-specific)";
  12045. }
  12046. }
  12047. class LargePayloadMaxLengthTest : public ::testing::Test {
  12048. protected:
  12049. LargePayloadMaxLengthTest()
  12050. : cli_(HOST, PORT)
  12051. #ifdef CPPHTTPLIB_SSL_ENABLED
  12052. ,
  12053. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12054. #endif
  12055. {
  12056. #ifdef CPPHTTPLIB_SSL_ENABLED
  12057. cli_.enable_server_certificate_verification(false);
  12058. #endif
  12059. }
  12060. virtual void SetUp() {
  12061. // Set 10MB payload limit
  12062. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12063. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12064. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12065. res.set_content("Large payload test", "text/plain");
  12066. });
  12067. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12068. svr_.wait_until_ready();
  12069. }
  12070. virtual void TearDown() {
  12071. svr_.stop();
  12072. t_.join();
  12073. }
  12074. #ifdef CPPHTTPLIB_SSL_ENABLED
  12075. SSLClient cli_;
  12076. SSLServer svr_;
  12077. #else
  12078. Client cli_;
  12079. Server svr_;
  12080. #endif
  12081. thread t_;
  12082. };
  12083. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12084. // Test chunked encoding with payload within 10MB limit
  12085. std::string medium_payload(5 * 1024 * 1024,
  12086. 'A'); // 5MB payload, within 10MB limit
  12087. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12089. EXPECT_EQ(StatusCode::OK_200, res->status);
  12090. }
  12091. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12092. // Test chunked encoding with payload exceeding 10MB limit
  12093. std::string large_payload(12 * 1024 * 1024,
  12094. 'B'); // 12MB payload, exceeds 10MB limit
  12095. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12096. // Server may either return 413 or close the connection
  12097. if (res) {
  12098. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12099. } else {
  12100. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12101. }
  12102. }
  12103. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  12104. // Test request without Content-Length header within 10MB limit
  12105. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12106. "Host: " +
  12107. std::string(HOST) + ":" +
  12108. std::to_string(PORT) +
  12109. "\r\n"
  12110. "Connection: close\r\n"
  12111. "\r\n";
  12112. // Add 1MB payload (within 10MB limit)
  12113. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  12114. request_without_content_length += medium_payload;
  12115. std::string response;
  12116. bool result = send_request(5, request_without_content_length, &response);
  12117. if (result) {
  12118. // Should get a proper HTTP response for payloads within limit
  12119. if (response.length() > 10) {
  12120. SUCCEED() << "Server processed 1MB request without Content-Length within "
  12121. "10MB limit";
  12122. } else {
  12123. SUCCEED() << "Server closed connection (acceptable behavior for no "
  12124. "Content-Length)";
  12125. }
  12126. } else {
  12127. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  12128. }
  12129. }
  12130. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  12131. // Test request without Content-Length header exceeding 10MB limit
  12132. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  12133. "Host: " +
  12134. std::string(HOST) + ":" +
  12135. std::to_string(PORT) +
  12136. "\r\n"
  12137. "Connection: close\r\n"
  12138. "\r\n";
  12139. // Add 12MB payload (exceeds 10MB limit)
  12140. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  12141. request_without_content_length += large_payload;
  12142. std::string response;
  12143. bool result = send_request(10, request_without_content_length, &response);
  12144. if (!result) {
  12145. // Server should close connection due to payload limit
  12146. SUCCEED() << "Server rejected 12MB request without Content-Length "
  12147. "(connection closed)";
  12148. } else {
  12149. // Check for error response
  12150. if (response.length() <= 10) {
  12151. SUCCEED()
  12152. << "Server closed connection for 12MB request exceeding 10MB limit";
  12153. } else {
  12154. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12155. response.find("Payload Too Large") != std::string::npos ||
  12156. response.find("400") != std::string::npos);
  12157. }
  12158. }
  12159. }
  12160. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12161. Server svr;
  12162. svr.Get("/", [](const Request &, Response &res) {
  12163. // Claims far more than it sends, then drops the connection.
  12164. res.set_content_provider(size_t(1) << 41, "text/plain",
  12165. [](size_t, size_t, DataSink &sink) {
  12166. sink.write("abc", 3);
  12167. return false;
  12168. });
  12169. });
  12170. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12171. auto se = detail::scope_exit([&] {
  12172. svr.stop();
  12173. thread.join();
  12174. ASSERT_FALSE(svr.is_running());
  12175. });
  12176. svr.wait_until_ready();
  12177. Client cli(HOST, PORT);
  12178. cli.set_payload_max_length(0);
  12179. EXPECT_FALSE(cli.Get("/"));
  12180. }
  12181. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12182. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12183. // path.
  12184. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12185. Server svr;
  12186. const size_t LIMIT = 64 * 1024; // 64KB
  12187. svr.set_payload_max_length(LIMIT);
  12188. size_t total = 0;
  12189. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12190. const ContentReader &content_reader) {
  12191. content_reader([&](const char * /*data*/, size_t len) {
  12192. total += len;
  12193. return true;
  12194. });
  12195. res.status = 200;
  12196. res.set_content("stream_ok", "text/plain");
  12197. });
  12198. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12199. auto se = detail::scope_exit([&] {
  12200. svr.stop();
  12201. thread.join();
  12202. ASSERT_FALSE(svr.is_running());
  12203. });
  12204. svr.wait_until_ready();
  12205. // Prepare 256KB raw data and gzip-compress it
  12206. std::string raw(256 * 1024, 'A');
  12207. std::string gz;
  12208. {
  12209. z_stream zs{};
  12210. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12211. Z_DEFAULT_STRATEGY);
  12212. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12213. zs.avail_in = static_cast<uInt>(raw.size());
  12214. char outbuf[4096];
  12215. int ret;
  12216. do {
  12217. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12218. zs.avail_out = sizeof(outbuf);
  12219. ret = deflate(&zs, Z_FINISH);
  12220. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12221. } while (ret != Z_STREAM_END);
  12222. deflateEnd(&zs);
  12223. }
  12224. Client cli(HOST, PORT);
  12225. cli.set_connection_timeout(std::chrono::seconds(5));
  12226. Headers headers = {{"Content-Encoding", "gzip"}};
  12227. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12228. "application/octet-stream");
  12229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12230. // Server must reject oversized decompressed payloads with 413.
  12231. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12232. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12233. EXPECT_LE(total, LIMIT);
  12234. }
  12235. #ifndef CPPHTTPLIB_SSL_ENABLED
  12236. // For a request with neither Content-Length nor Transfer-Encoding, the
  12237. // non-SSL raw-socket fallback in read_content_core() used to hand the
  12238. // compressed wire bytes straight to the ContentReader without ever routing
  12239. // them through the decompressor, so payload_max_length_ only bounded the
  12240. // compressed size on the wire, not the decompressed size.
  12241. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  12242. Server svr;
  12243. const size_t LIMIT = 64 * 1024; // 64KB
  12244. svr.set_payload_max_length(LIMIT);
  12245. size_t total = 0;
  12246. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12247. const ContentReader &content_reader) {
  12248. content_reader([&](const char * /*data*/, size_t len) {
  12249. total += len;
  12250. return true;
  12251. });
  12252. res.status = 200;
  12253. res.set_content("stream_ok", "text/plain");
  12254. });
  12255. auto port = svr.bind_to_any_port(HOST);
  12256. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12257. auto se = detail::scope_exit([&] {
  12258. svr.stop();
  12259. thread.join();
  12260. ASSERT_FALSE(svr.is_running());
  12261. });
  12262. svr.wait_until_ready();
  12263. // Prepare 256KB raw data and gzip-compress it, same payload as the
  12264. // StreamingGzipDecompression test above.
  12265. std::string raw(256 * 1024, 'A');
  12266. std::string gz;
  12267. {
  12268. httplib::detail::gzip_compressor compressor;
  12269. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  12270. [&](const char *chunk, size_t len) {
  12271. gz.append(chunk, len);
  12272. return true;
  12273. });
  12274. ASSERT_TRUE(result);
  12275. }
  12276. // Send the gzip body over raw TCP with neither Content-Length nor
  12277. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  12278. // kicks in.
  12279. std::string req = "POST /stream HTTP/1.1\r\n"
  12280. "Host: " +
  12281. std::string(HOST) + ":" + std::to_string(port) +
  12282. "\r\n"
  12283. "Content-Encoding: gzip\r\n"
  12284. "Connection: close\r\n"
  12285. "\r\n" +
  12286. gz;
  12287. std::string response;
  12288. ASSERT_TRUE(send_request(5, req, &response, port));
  12289. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12290. EXPECT_LE(total, LIMIT);
  12291. }
  12292. #endif
  12293. #endif
  12294. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12295. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12296. // the payload must be passed through untouched instead of being rejected.
  12297. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12298. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12299. Server svr;
  12300. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12301. res.set_content(body, "image/jpeg");
  12302. res.set_header("Content-Encoding", "UTF-8");
  12303. });
  12304. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12305. res.set_content(body, "image/jpeg");
  12306. res.set_header("Content-Encoding", "identity");
  12307. });
  12308. svr.Post("/echo", [](const Request &req, Response &res) {
  12309. res.set_content(req.body, "image/jpeg");
  12310. });
  12311. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12312. auto se = detail::scope_exit([&] {
  12313. svr.stop();
  12314. t.join();
  12315. ASSERT_FALSE(svr.is_running());
  12316. });
  12317. svr.wait_until_ready();
  12318. Client cli(HOST, PORT);
  12319. {
  12320. auto res = cli.Get("/image");
  12321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12322. EXPECT_EQ(StatusCode::OK_200, res->status);
  12323. EXPECT_EQ(body, res->body);
  12324. }
  12325. {
  12326. auto res = cli.Get("/identity");
  12327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12328. EXPECT_EQ(StatusCode::OK_200, res->status);
  12329. EXPECT_EQ(body, res->body);
  12330. }
  12331. {
  12332. // The same applies to a request body reaching the server.
  12333. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12334. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12336. EXPECT_EQ(StatusCode::OK_200, res->status);
  12337. EXPECT_EQ(body, res->body);
  12338. }
  12339. }
  12340. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12341. // gzip-encoded response even when the build has no zlib support.
  12342. static const char GZIPPED_HELLO_WORLD[] = {
  12343. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12344. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12345. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12346. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12347. // A content coding is a whole token, not something the field value merely
  12348. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12349. // as "fibre" look like Brotli, and turned a multi-coding value like
  12350. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12351. // it was never meant to see.
  12352. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12353. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12354. Server svr;
  12355. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12356. res.set_content(body, "image/jpeg");
  12357. res.set_header("Content-Encoding", "fibre");
  12358. });
  12359. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12360. res.set_content(body, "image/jpeg");
  12361. res.set_header("Content-Encoding", "gzip, br");
  12362. });
  12363. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12364. res.set_content(body, "image/jpeg");
  12365. res.set_header("Content-Encoding", "x-zstd-ish");
  12366. });
  12367. auto port = svr.bind_to_any_port(HOST);
  12368. thread t = thread([&]() { svr.listen_after_bind(); });
  12369. auto se = detail::scope_exit([&] {
  12370. svr.stop();
  12371. t.join();
  12372. ASSERT_FALSE(svr.is_running());
  12373. });
  12374. svr.wait_until_ready();
  12375. Client cli(HOST, port);
  12376. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12377. auto res = cli.Get(path);
  12378. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12379. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12380. // Not a coding we recognize, so the payload comes back untouched
  12381. EXPECT_EQ(body, res->body) << path;
  12382. }
  12383. }
  12384. // A content coding cpp-httplib recognizes but was not built with must be
  12385. // reported as such. Handing the still-compressed payload back to the caller
  12386. // would silently corrupt it.
  12387. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12388. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12389. Server svr;
  12390. // "image/jpeg" keeps the server from applying a content coding of its own,
  12391. // so the hand-crafted Content-Encoding below survives.
  12392. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12393. res.set_content(gzipped, "image/jpeg");
  12394. res.set_header("Content-Encoding", "gzip");
  12395. });
  12396. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12397. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12398. res.set_content(gzipped, "image/jpeg");
  12399. res.set_header("Content-Encoding", "GZIP");
  12400. });
  12401. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12402. auto se = detail::scope_exit([&] {
  12403. svr.stop();
  12404. t.join();
  12405. ASSERT_FALSE(svr.is_running());
  12406. });
  12407. svr.wait_until_ready();
  12408. Client cli(HOST, PORT);
  12409. {
  12410. auto res = cli.Get("/gzipped");
  12411. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12413. EXPECT_EQ("Hello World!", res->body);
  12414. #else
  12415. ASSERT_FALSE(res);
  12416. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12417. #endif
  12418. }
  12419. {
  12420. // open_stream() must behave the same way.
  12421. auto handle = cli.open_stream("GET", "/gzipped");
  12422. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12423. ASSERT_TRUE(handle.is_valid());
  12424. std::string received;
  12425. char buf[256];
  12426. ssize_t n;
  12427. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12428. received.append(buf, static_cast<size_t>(n));
  12429. }
  12430. EXPECT_EQ("Hello World!", received);
  12431. #else
  12432. EXPECT_FALSE(handle.is_valid());
  12433. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12434. #endif
  12435. }
  12436. {
  12437. // A differently-cased coding must not be mistaken for an unknown one, or
  12438. // the body would be handed back still compressed.
  12439. auto res = cli.Get("/gzipped-uppercase");
  12440. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12442. EXPECT_EQ("Hello World!", res->body);
  12443. #else
  12444. ASSERT_FALSE(res);
  12445. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12446. #endif
  12447. }
  12448. }
  12449. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12450. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12451. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12452. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12453. // body a second time and appending a second Content-Encoding field line, so
  12454. // clients that decode one coding per listed value handed back raw gzip bytes.
  12455. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12456. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12457. Server svr;
  12458. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12459. // keeps the server from applying a coding of its own.
  12460. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12461. res.set_content(gzipped, "text/plain");
  12462. res.set_header("Content-Encoding", "gzip");
  12463. });
  12464. auto port = svr.bind_to_any_port(HOST);
  12465. thread t = thread([&]() { svr.listen_after_bind(); });
  12466. auto se = detail::scope_exit([&] {
  12467. svr.stop();
  12468. t.join();
  12469. ASSERT_FALSE(svr.is_running());
  12470. });
  12471. svr.wait_until_ready();
  12472. Client cli(HOST, port);
  12473. Headers headers = {{"Accept-Encoding", "gzip"}};
  12474. auto res = cli.Get("/pre-gzipped", headers);
  12475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12476. EXPECT_EQ(StatusCode::OK_200, res->status);
  12477. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12478. EXPECT_EQ("Hello World!", res->body);
  12479. }
  12480. // A chunked provider settles its coding where the headers are written and
  12481. // reuses it at write time. Both ends of that have to hold: a handler's own
  12482. // Content-Encoding suppresses the coding, and a response without one is still
  12483. // compressed as it always was.
  12484. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12485. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12486. const std::string plain = "Hello World! Hello World! Hello World!";
  12487. Server svr;
  12488. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12489. res.set_header("Content-Encoding", "gzip");
  12490. res.set_chunked_content_provider(
  12491. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12492. sink.write(gzipped.data(), gzipped.size());
  12493. sink.done();
  12494. return true;
  12495. });
  12496. });
  12497. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12498. res.set_chunked_content_provider(
  12499. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12500. sink.write(plain.data(), plain.size());
  12501. sink.done();
  12502. return true;
  12503. });
  12504. });
  12505. auto port = svr.bind_to_any_port(HOST);
  12506. thread t = thread([&]() { svr.listen_after_bind(); });
  12507. auto se = detail::scope_exit([&] {
  12508. svr.stop();
  12509. t.join();
  12510. ASSERT_FALSE(svr.is_running());
  12511. });
  12512. svr.wait_until_ready();
  12513. Client cli(HOST, port);
  12514. Headers headers = {{"Accept-Encoding", "gzip"}};
  12515. {
  12516. auto res = cli.Get("/pre-gzipped", headers);
  12517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12518. EXPECT_EQ(StatusCode::OK_200, res->status);
  12519. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12520. EXPECT_EQ("Hello World!", res->body);
  12521. }
  12522. {
  12523. auto res = cli.Get("/negotiated", headers);
  12524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12525. EXPECT_EQ(StatusCode::OK_200, res->status);
  12526. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12527. EXPECT_EQ(plain, res->body);
  12528. }
  12529. }
  12530. #endif
  12531. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12532. // the same message as the comma-joined one, so both have to be read the same
  12533. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12534. // single gzip coding, and a body the sender says was encoded twice was handed
  12535. // back after one pass, still compressed but presented as decoded.
  12536. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12537. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12538. Server svr;
  12539. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12540. res.set_content(body, "image/jpeg");
  12541. res.headers.emplace("Content-Encoding", "gzip");
  12542. res.headers.emplace("Content-Encoding", "gzip");
  12543. });
  12544. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12545. res.set_content(body, "image/jpeg");
  12546. res.set_header("Content-Encoding", "gzip, gzip");
  12547. });
  12548. auto port = svr.bind_to_any_port(HOST);
  12549. thread t = thread([&]() { svr.listen_after_bind(); });
  12550. auto se = detail::scope_exit([&] {
  12551. svr.stop();
  12552. t.join();
  12553. ASSERT_FALSE(svr.is_running());
  12554. });
  12555. svr.wait_until_ready();
  12556. Client cli(HOST, port);
  12557. // Two codings is not something cpp-httplib decodes, so both representations
  12558. // take the pass-through path rather than one of them being gunzipped once.
  12559. for (const char *path : {"/split", "/joined"}) {
  12560. auto res = cli.Get(path);
  12561. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12562. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12563. EXPECT_EQ(body, res->body) << path;
  12564. }
  12565. }
  12566. // Regression test for DoS vulnerability: a malicious server sending a response
  12567. // without Content-Length header must not cause unbounded memory consumption on
  12568. // the client side. The client should stop reading after a reasonable limit,
  12569. // similar to the server-side set_payload_max_length protection.
  12570. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12571. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12572. #ifndef _WIN32
  12573. signal(SIGPIPE, SIG_IGN);
  12574. #endif
  12575. auto server_thread = std::thread([] {
  12576. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12577. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12578. default_socket_options(srv);
  12579. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12580. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12581. sockaddr_in addr{};
  12582. addr.sin_family = AF_INET;
  12583. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12584. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12585. int opt = 1;
  12586. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12587. #ifdef _WIN32
  12588. reinterpret_cast<const char *>(&opt),
  12589. #else
  12590. &opt,
  12591. #endif
  12592. sizeof(opt));
  12593. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12594. ::listen(srv, 1);
  12595. sockaddr_in cli_addr{};
  12596. socklen_t cli_len = sizeof(cli_addr);
  12597. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12598. if (cli != INVALID_SOCKET) {
  12599. char buf[4096];
  12600. ::recv(cli, buf, sizeof(buf), 0);
  12601. // Malicious response: no Content-Length, no chunked encoding
  12602. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12603. "Connection: close\r\n"
  12604. "\r\n";
  12605. ::send(cli,
  12606. #ifdef _WIN32
  12607. static_cast<const char *>(response_header.c_str()),
  12608. static_cast<int>(response_header.size()),
  12609. #else
  12610. response_header.c_str(), response_header.size(),
  12611. #endif
  12612. 0);
  12613. // Send 10MB of data
  12614. std::string chunk(64 * 1024, 'A');
  12615. size_t total_sent = 0;
  12616. while (total_sent < MALICIOUS_DATA_SIZE) {
  12617. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12618. auto sent = ::send(cli,
  12619. #ifdef _WIN32
  12620. static_cast<const char *>(chunk.c_str()),
  12621. static_cast<int>(to_send),
  12622. #else
  12623. chunk.c_str(), to_send,
  12624. #endif
  12625. 0);
  12626. if (sent <= 0) break;
  12627. total_sent += static_cast<size_t>(sent);
  12628. }
  12629. detail::close_socket(cli);
  12630. }
  12631. detail::close_socket(srv);
  12632. });
  12633. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12634. size_t total_read = 0;
  12635. {
  12636. Client cli("127.0.0.1", PORT + 2);
  12637. cli.set_read_timeout(5, 0);
  12638. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12639. auto stream = cli.open_stream("GET", "/malicious");
  12640. ASSERT_TRUE(stream.is_valid());
  12641. char buffer[64 * 1024];
  12642. ssize_t n;
  12643. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12644. total_read += static_cast<size_t>(n);
  12645. }
  12646. } // StreamHandle and Client destroyed here, closing the socket
  12647. server_thread.join();
  12648. // With set_payload_max_length, the client must stop reading before consuming
  12649. // all 10MB. The read loop should be cut off at or near the configured limit.
  12650. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12651. << "Client read " << total_read << " bytes, exceeding the configured "
  12652. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12653. }
  12654. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12655. // the entire response body without truncation.
  12656. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12657. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12658. #ifndef _WIN32
  12659. signal(SIGPIPE, SIG_IGN);
  12660. #endif
  12661. auto server_thread = std::thread([] {
  12662. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12663. default_socket_options(srv);
  12664. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12665. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12666. sockaddr_in addr{};
  12667. addr.sin_family = AF_INET;
  12668. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12669. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12670. int opt = 1;
  12671. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12672. #ifdef _WIN32
  12673. reinterpret_cast<const char *>(&opt),
  12674. #else
  12675. &opt,
  12676. #endif
  12677. sizeof(opt));
  12678. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12679. ::listen(srv, 1);
  12680. sockaddr_in cli_addr{};
  12681. socklen_t cli_len = sizeof(cli_addr);
  12682. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12683. if (cli != INVALID_SOCKET) {
  12684. char buf[4096];
  12685. ::recv(cli, buf, sizeof(buf), 0);
  12686. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12687. "Connection: close\r\n"
  12688. "\r\n";
  12689. ::send(cli,
  12690. #ifdef _WIN32
  12691. static_cast<const char *>(response_header.c_str()),
  12692. static_cast<int>(response_header.size()),
  12693. #else
  12694. response_header.c_str(), response_header.size(),
  12695. #endif
  12696. 0);
  12697. std::string chunk(64 * 1024, 'A');
  12698. size_t total_sent = 0;
  12699. while (total_sent < DATA_SIZE) {
  12700. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12701. auto sent = ::send(cli,
  12702. #ifdef _WIN32
  12703. static_cast<const char *>(chunk.c_str()),
  12704. static_cast<int>(to_send),
  12705. #else
  12706. chunk.c_str(), to_send,
  12707. #endif
  12708. 0);
  12709. if (sent <= 0) break;
  12710. total_sent += static_cast<size_t>(sent);
  12711. }
  12712. #ifdef _WIN32
  12713. ::shutdown(cli, SD_SEND);
  12714. #else
  12715. ::shutdown(cli, SHUT_WR);
  12716. #endif
  12717. // Drain until the client closes its end, ensuring all data is delivered
  12718. char drain[1024];
  12719. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12720. detail::close_socket(cli);
  12721. }
  12722. detail::close_socket(srv);
  12723. });
  12724. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12725. size_t total_read = 0;
  12726. {
  12727. Client cli("127.0.0.1", PORT + 2);
  12728. cli.set_read_timeout(5, 0);
  12729. cli.set_payload_max_length(0); // 0 means no limit
  12730. auto stream = cli.open_stream("GET", "/data");
  12731. ASSERT_TRUE(stream.is_valid());
  12732. char buffer[64 * 1024];
  12733. ssize_t n;
  12734. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12735. total_read += static_cast<size_t>(n);
  12736. }
  12737. }
  12738. server_thread.join();
  12739. EXPECT_EQ(total_read, DATA_SIZE)
  12740. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12741. << " bytes without truncation, but only read " << total_read << " bytes.";
  12742. }
  12743. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12744. // enormous Content-Length must not cause the client to pre-allocate a huge
  12745. // response body buffer. The reservation is capped at payload_max_length_, and
  12746. // the read itself fails when the body exceeds the limit.
  12747. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12748. #ifndef _WIN32
  12749. signal(SIGPIPE, SIG_IGN);
  12750. #endif
  12751. auto server_thread = std::thread([] {
  12752. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12753. default_socket_options(srv);
  12754. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12755. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12756. sockaddr_in addr{};
  12757. addr.sin_family = AF_INET;
  12758. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12759. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12760. int opt = 1;
  12761. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12762. #ifdef _WIN32
  12763. reinterpret_cast<const char *>(&opt),
  12764. #else
  12765. &opt,
  12766. #endif
  12767. sizeof(opt));
  12768. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12769. ::listen(srv, 1);
  12770. sockaddr_in cli_addr{};
  12771. socklen_t cli_len = sizeof(cli_addr);
  12772. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12773. if (cli != INVALID_SOCKET) {
  12774. char buf[4096];
  12775. ::recv(cli, buf, sizeof(buf), 0);
  12776. // Malicious response: claim a 20GB body but send only a tiny payload.
  12777. std::string response = "HTTP/1.1 200 OK\r\n"
  12778. "Content-Length: 20000000000\r\n"
  12779. "\r\n"
  12780. "abc";
  12781. ::send(cli,
  12782. #ifdef _WIN32
  12783. static_cast<const char *>(response.c_str()),
  12784. static_cast<int>(response.size()),
  12785. #else
  12786. response.c_str(), response.size(),
  12787. #endif
  12788. 0);
  12789. detail::close_socket(cli);
  12790. }
  12791. detail::close_socket(srv);
  12792. });
  12793. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12794. {
  12795. Client cli("127.0.0.1", PORT + 2);
  12796. cli.set_read_timeout(5, 0);
  12797. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12798. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12799. // (server claims more bytes than payload_max_length permits), but it must
  12800. // not exhaust memory before getting there.
  12801. auto res = cli.Get("/malicious");
  12802. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12803. }
  12804. server_thread.join();
  12805. }
  12806. // Verify that content_receiver bypasses the default payload_max_length,
  12807. // allowing streaming downloads larger than 100MB without requiring an explicit
  12808. // set_payload_max_length call.
  12809. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12810. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12811. #ifndef _WIN32
  12812. signal(SIGPIPE, SIG_IGN);
  12813. #endif
  12814. auto server_thread = std::thread([] {
  12815. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12816. default_socket_options(srv);
  12817. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12818. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12819. sockaddr_in addr{};
  12820. addr.sin_family = AF_INET;
  12821. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12822. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12823. int opt = 1;
  12824. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12825. #ifdef _WIN32
  12826. reinterpret_cast<const char *>(&opt),
  12827. #else
  12828. &opt,
  12829. #endif
  12830. sizeof(opt));
  12831. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12832. ::listen(srv, 1);
  12833. sockaddr_in cli_addr{};
  12834. socklen_t cli_len = sizeof(cli_addr);
  12835. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12836. if (cli != INVALID_SOCKET) {
  12837. char buf[4096];
  12838. ::recv(cli, buf, sizeof(buf), 0);
  12839. // Response with Content-Length larger than default 100MB limit
  12840. auto content_length = std::to_string(DATA_SIZE);
  12841. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12842. "Content-Length: " +
  12843. content_length +
  12844. "\r\n"
  12845. "Connection: close\r\n"
  12846. "\r\n";
  12847. ::send(cli,
  12848. #ifdef _WIN32
  12849. static_cast<const char *>(response_header.c_str()),
  12850. static_cast<int>(response_header.size()),
  12851. #else
  12852. response_header.c_str(), response_header.size(),
  12853. #endif
  12854. 0);
  12855. std::string chunk(64 * 1024, 'A');
  12856. size_t total_sent = 0;
  12857. while (total_sent < DATA_SIZE) {
  12858. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12859. auto sent = ::send(cli,
  12860. #ifdef _WIN32
  12861. static_cast<const char *>(chunk.c_str()),
  12862. static_cast<int>(to_send),
  12863. #else
  12864. chunk.c_str(), to_send,
  12865. #endif
  12866. 0);
  12867. if (sent <= 0) break;
  12868. total_sent += static_cast<size_t>(sent);
  12869. }
  12870. detail::close_socket(cli);
  12871. }
  12872. detail::close_socket(srv);
  12873. });
  12874. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12875. size_t total_received = 0;
  12876. {
  12877. Client cli("127.0.0.1", PORT + 2);
  12878. cli.set_read_timeout(10, 0);
  12879. // Do NOT call set_payload_max_length — use the default 100MB limit
  12880. auto res =
  12881. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12882. total_received += data_length;
  12883. return true;
  12884. });
  12885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12886. EXPECT_EQ(StatusCode::OK_200, res->status);
  12887. }
  12888. server_thread.join();
  12889. EXPECT_EQ(total_received, DATA_SIZE)
  12890. << "With content_receiver, the client should read all " << DATA_SIZE
  12891. << " bytes despite the default 100MB payload_max_length, but only read "
  12892. << total_received << " bytes.";
  12893. }
  12894. // Verify that an explicit set_payload_max_length smaller than the response is
  12895. // enforced even when a content_receiver is used.
  12896. TEST(ClientVulnerabilityTest,
  12897. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12898. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12899. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12900. #ifndef _WIN32
  12901. signal(SIGPIPE, SIG_IGN);
  12902. #endif
  12903. auto server_thread = std::thread([] {
  12904. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12905. default_socket_options(srv);
  12906. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12907. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12908. sockaddr_in addr{};
  12909. addr.sin_family = AF_INET;
  12910. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12911. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12912. int opt = 1;
  12913. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12914. #ifdef _WIN32
  12915. reinterpret_cast<const char *>(&opt),
  12916. #else
  12917. &opt,
  12918. #endif
  12919. sizeof(opt));
  12920. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12921. ::listen(srv, 1);
  12922. sockaddr_in cli_addr{};
  12923. socklen_t cli_len = sizeof(cli_addr);
  12924. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12925. if (cli != INVALID_SOCKET) {
  12926. char buf[4096];
  12927. ::recv(cli, buf, sizeof(buf), 0);
  12928. auto content_length = std::to_string(DATA_SIZE);
  12929. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12930. "Content-Length: " +
  12931. content_length +
  12932. "\r\n"
  12933. "Connection: close\r\n"
  12934. "\r\n";
  12935. ::send(cli,
  12936. #ifdef _WIN32
  12937. static_cast<const char *>(response_header.c_str()),
  12938. static_cast<int>(response_header.size()),
  12939. #else
  12940. response_header.c_str(), response_header.size(),
  12941. #endif
  12942. 0);
  12943. std::string chunk(64 * 1024, 'A');
  12944. size_t total_sent = 0;
  12945. while (total_sent < DATA_SIZE) {
  12946. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12947. auto sent = ::send(cli,
  12948. #ifdef _WIN32
  12949. static_cast<const char *>(chunk.c_str()),
  12950. static_cast<int>(to_send),
  12951. #else
  12952. chunk.c_str(), to_send,
  12953. #endif
  12954. 0);
  12955. if (sent <= 0) break;
  12956. total_sent += static_cast<size_t>(sent);
  12957. }
  12958. detail::close_socket(cli);
  12959. }
  12960. detail::close_socket(srv);
  12961. });
  12962. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12963. size_t total_received = 0;
  12964. {
  12965. Client cli("127.0.0.1", PORT + 2);
  12966. cli.set_read_timeout(10, 0);
  12967. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  12968. auto res =
  12969. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12970. total_received += data_length;
  12971. return true;
  12972. });
  12973. // Should fail because 200MB exceeds the explicit 150MB limit
  12974. EXPECT_FALSE(res);
  12975. }
  12976. server_thread.join();
  12977. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12978. << "Client with content_receiver should respect the explicit "
  12979. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12980. << total_received << " bytes.";
  12981. }
  12982. // Verify that an explicit set_payload_max_length larger than the response
  12983. // allows the content_receiver to read all data successfully.
  12984. TEST(ClientVulnerabilityTest,
  12985. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  12986. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12987. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  12988. #ifndef _WIN32
  12989. signal(SIGPIPE, SIG_IGN);
  12990. #endif
  12991. auto server_thread = std::thread([] {
  12992. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12993. default_socket_options(srv);
  12994. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12995. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12996. sockaddr_in addr{};
  12997. addr.sin_family = AF_INET;
  12998. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12999. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13000. int opt = 1;
  13001. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13002. #ifdef _WIN32
  13003. reinterpret_cast<const char *>(&opt),
  13004. #else
  13005. &opt,
  13006. #endif
  13007. sizeof(opt));
  13008. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13009. ::listen(srv, 1);
  13010. sockaddr_in cli_addr{};
  13011. socklen_t cli_len = sizeof(cli_addr);
  13012. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13013. if (cli != INVALID_SOCKET) {
  13014. char buf[4096];
  13015. ::recv(cli, buf, sizeof(buf), 0);
  13016. auto content_length = std::to_string(DATA_SIZE);
  13017. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13018. "Content-Length: " +
  13019. content_length +
  13020. "\r\n"
  13021. "Connection: close\r\n"
  13022. "\r\n";
  13023. ::send(cli,
  13024. #ifdef _WIN32
  13025. static_cast<const char *>(response_header.c_str()),
  13026. static_cast<int>(response_header.size()),
  13027. #else
  13028. response_header.c_str(), response_header.size(),
  13029. #endif
  13030. 0);
  13031. std::string chunk(64 * 1024, 'A');
  13032. size_t total_sent = 0;
  13033. while (total_sent < DATA_SIZE) {
  13034. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13035. auto sent = ::send(cli,
  13036. #ifdef _WIN32
  13037. static_cast<const char *>(chunk.c_str()),
  13038. static_cast<int>(to_send),
  13039. #else
  13040. chunk.c_str(), to_send,
  13041. #endif
  13042. 0);
  13043. if (sent <= 0) break;
  13044. total_sent += static_cast<size_t>(sent);
  13045. }
  13046. #ifdef _WIN32
  13047. ::shutdown(cli, SD_SEND);
  13048. #else
  13049. ::shutdown(cli, SHUT_WR);
  13050. #endif
  13051. char drain[1024];
  13052. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13053. detail::close_socket(cli);
  13054. }
  13055. detail::close_socket(srv);
  13056. });
  13057. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13058. size_t total_received = 0;
  13059. {
  13060. Client cli("127.0.0.1", PORT + 2);
  13061. cli.set_read_timeout(10, 0);
  13062. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13063. auto res =
  13064. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13065. total_received += data_length;
  13066. return true;
  13067. });
  13068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13069. EXPECT_EQ(StatusCode::OK_200, res->status);
  13070. }
  13071. server_thread.join();
  13072. EXPECT_EQ(total_received, DATA_SIZE)
  13073. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13074. << " bytes (larger than " << DATA_SIZE
  13075. << " bytes response), content_receiver should read all data, but only "
  13076. "read "
  13077. << total_received << " bytes.";
  13078. }
  13079. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13080. // Regression test for "zip bomb" attack on the client side: a malicious server
  13081. // sends a small gzip-compressed response that decompresses to a huge payload.
  13082. // The client must enforce payload_max_length on the decompressed size.
  13083. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13084. constexpr size_t DECOMPRESSED_SIZE =
  13085. 10 * 1024 * 1024; // 10MB after decompression
  13086. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13087. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13088. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13089. std::string compressed;
  13090. {
  13091. httplib::detail::gzip_compressor compressor;
  13092. bool ok =
  13093. compressor.compress(uncompressed.data(), uncompressed.size(),
  13094. /*last=*/true, [&](const char *buf, size_t len) {
  13095. compressed.append(buf, len);
  13096. return true;
  13097. });
  13098. ASSERT_TRUE(ok);
  13099. }
  13100. // Sanity: compressed data should be much smaller than the decompressed size
  13101. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13102. #ifndef _WIN32
  13103. signal(SIGPIPE, SIG_IGN);
  13104. #endif
  13105. // Set up the listening socket in the main thread so the server is guaranteed
  13106. // to be ready before the client connects (eliminates race condition).
  13107. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13108. default_socket_options(srv);
  13109. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13110. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13111. sockaddr_in addr{};
  13112. addr.sin_family = AF_INET;
  13113. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13114. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13115. int opt = 1;
  13116. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13117. #ifdef _WIN32
  13118. reinterpret_cast<const char *>(&opt),
  13119. #else
  13120. &opt,
  13121. #endif
  13122. sizeof(opt));
  13123. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13124. ASSERT_EQ(0, ::listen(srv, 1));
  13125. auto server_thread = std::thread([&compressed, srv] {
  13126. sockaddr_in cli_addr{};
  13127. socklen_t cli_len = sizeof(cli_addr);
  13128. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13129. if (cli != INVALID_SOCKET) {
  13130. // Read the full HTTP request (until \r\n\r\n)
  13131. char buf[4096];
  13132. size_t total = 0;
  13133. while (total < sizeof(buf)) {
  13134. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13135. if (n <= 0) break;
  13136. total += static_cast<size_t>(n);
  13137. // Check for end of headers
  13138. if (total >= 4) {
  13139. std::string req(buf, total);
  13140. if (req.find("\r\n\r\n") != std::string::npos) break;
  13141. }
  13142. }
  13143. // Malicious response: gzip-compressed body, no Content-Length
  13144. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13145. "Content-Encoding: gzip\r\n"
  13146. "Connection: close\r\n"
  13147. "\r\n";
  13148. ::send(cli,
  13149. #ifdef _WIN32
  13150. static_cast<const char *>(response_header.c_str()),
  13151. static_cast<int>(response_header.size()),
  13152. #else
  13153. response_header.c_str(), response_header.size(),
  13154. #endif
  13155. 0);
  13156. // Send the compressed payload (small on the wire, huge when decompressed)
  13157. size_t total_sent = 0;
  13158. while (total_sent < compressed.size()) {
  13159. auto to_send = std::min(compressed.size() - total_sent,
  13160. static_cast<size_t>(64 * 1024));
  13161. auto sent =
  13162. ::send(cli,
  13163. #ifdef _WIN32
  13164. static_cast<const char *>(compressed.c_str() + total_sent),
  13165. static_cast<int>(to_send),
  13166. #else
  13167. compressed.c_str() + total_sent, to_send,
  13168. #endif
  13169. 0);
  13170. if (sent <= 0) break;
  13171. total_sent += static_cast<size_t>(sent);
  13172. }
  13173. detail::close_socket(cli);
  13174. }
  13175. });
  13176. auto se = detail::scope_exit([&] {
  13177. detail::close_socket(srv);
  13178. server_thread.join();
  13179. });
  13180. size_t total_decompressed = 0;
  13181. {
  13182. Client cli("127.0.0.1", PORT + 3);
  13183. cli.set_read_timeout(5, 0);
  13184. cli.set_decompress(true);
  13185. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13186. auto stream = cli.open_stream("GET", "/zipbomb");
  13187. ASSERT_TRUE(stream.is_valid());
  13188. char buffer[64 * 1024];
  13189. ssize_t n;
  13190. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13191. total_decompressed += static_cast<size_t>(n);
  13192. }
  13193. }
  13194. // The decompressed size must be capped by payload_max_length. Without
  13195. // protection, the client would decompress the full 10MB from a tiny
  13196. // compressed payload, enabling a zip bomb DoS attack.
  13197. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13198. << "Client decompressed " << total_decompressed
  13199. << " bytes from a gzip response. The decompressed size should be "
  13200. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13201. }
  13202. #endif
  13203. TEST(HostAndPortPropertiesTest, NoSSL) {
  13204. httplib::Client cli("www.google.com", 1234);
  13205. ASSERT_EQ("www.google.com", cli.host());
  13206. ASSERT_EQ(1234, cli.port());
  13207. }
  13208. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13209. httplib::Client cli("www.google.com:1234");
  13210. ASSERT_EQ("www.google.com", cli.host());
  13211. ASSERT_EQ(1234, cli.port());
  13212. }
  13213. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13214. // Port number that overflows int — should not crash, client becomes invalid
  13215. httplib::Client cli("http://www.google.com:99999999999999999999");
  13216. ASSERT_FALSE(cli.is_valid());
  13217. }
  13218. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13219. // Port 99999 exceeds valid range (1-65535) — should not crash
  13220. httplib::Client cli("http://www.google.com:99999");
  13221. ASSERT_FALSE(cli.is_valid());
  13222. auto res = cli.Get("/");
  13223. EXPECT_FALSE(res);
  13224. EXPECT_EQ(Error::Connection, res.error());
  13225. }
  13226. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13227. httplib::Client cli("http://user:pass@localhost:1234");
  13228. ASSERT_FALSE(cli.is_valid());
  13229. EXPECT_FALSE(cli.Get("/"));
  13230. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13231. }
  13232. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13233. httplib::Client cli("http://www.google.com:80abc");
  13234. ASSERT_FALSE(cli.is_valid());
  13235. }
  13236. #ifdef CPPHTTPLIB_SSL_ENABLED
  13237. TEST(HostAndPortPropertiesTest, SSL) {
  13238. httplib::SSLClient cli("www.google.com");
  13239. ASSERT_EQ("www.google.com", cli.host());
  13240. ASSERT_EQ(443, cli.port());
  13241. }
  13242. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13243. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13244. std::string cert;
  13245. read_file(CA_CERT_FILE, cert);
  13246. httplib::SSLClient httplib_client("www.google.com");
  13247. // Load CA store first time
  13248. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13249. // Load CA store second time (update)
  13250. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13251. // Verify client is still valid and can make connections
  13252. httplib_client.enable_server_certificate_verification(true);
  13253. auto res = httplib_client.Get("/");
  13254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13255. // Google may return 200 or 301 depending on various factors
  13256. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13257. res->status == StatusCode::MovedPermanently_301);
  13258. }
  13259. TEST(SSLClientTest, ServerNameIndication_Online) {
  13260. auto host = "httpbingo.org";
  13261. auto path = std::string{"/get"};
  13262. SSLClient cli(host, 443);
  13263. auto res = cli.Get(path);
  13264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13265. ASSERT_EQ(StatusCode::OK_200, res->status);
  13266. }
  13267. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13268. // Use a site that will cause SSL verification failure due to self-signed cert
  13269. SSLClient cli("self-signed.badssl.com", 443);
  13270. cli.enable_server_certificate_verification(true);
  13271. auto res = cli.Get("/");
  13272. ASSERT_TRUE(!res);
  13273. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13274. // Verify backend error is captured for SSLServerVerification
  13275. // This occurs when certificate verification fails
  13276. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13277. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13278. EXPECT_NE(0UL, res.ssl_backend_error());
  13279. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13280. // For OpenSSL, ssl_error is 0 for verification errors
  13281. EXPECT_EQ(0, res.ssl_error());
  13282. #if !defined(_WIN32) || \
  13283. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13284. // On non-Windows or when Windows Schannel is disabled, the error comes
  13285. // from OpenSSL's verification
  13286. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13287. res.ssl_backend_error());
  13288. #endif
  13289. #endif
  13290. }
  13291. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13292. // Use a site where hostname doesn't match the certificate
  13293. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13294. SSLClient cli("wrong.host.badssl.com", 443);
  13295. cli.enable_server_certificate_verification(true);
  13296. cli.enable_server_hostname_verification(true);
  13297. auto res = cli.Get("/");
  13298. ASSERT_TRUE(!res);
  13299. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13300. // Verify backend error is captured for hostname verification failure
  13301. EXPECT_NE(0UL, res.ssl_backend_error());
  13302. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13303. // For OpenSSL, ssl_error is 0 for verification errors
  13304. EXPECT_EQ(0, res.ssl_error());
  13305. #if !defined(_WIN32) || \
  13306. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13307. // On non-Windows or when Windows Schannel is disabled, the error comes
  13308. // from OpenSSL's hostname verification
  13309. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13310. res.ssl_backend_error());
  13311. #endif
  13312. #endif
  13313. }
  13314. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13315. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13316. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13317. SSLClient cli("www.google.com", 443);
  13318. cli.enable_server_certificate_verification(true);
  13319. auto res = cli.Get("/");
  13320. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13321. }
  13322. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13323. SSLClient cli("www.google.com", 443);
  13324. cli.enable_server_certificate_verification(true);
  13325. cli.enable_windows_certificate_verification(false);
  13326. auto res = cli.Get("/");
  13327. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13328. }
  13329. // The server sends an intermediate cross-signed by a root Windows trusts,
  13330. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13331. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13332. SSLClient cli("accounts.spotify.com", 443);
  13333. auto res = cli.Get("/");
  13334. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13335. << " ssl_backend_error=" << res.ssl_backend_error();
  13336. }
  13337. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13338. // policy status, which no backend reports for a self-signed certificate.
  13339. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13340. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13341. ASSERT_TRUE(svr.is_valid());
  13342. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13343. auto se = detail::scope_exit([&] {
  13344. svr.stop();
  13345. t.join();
  13346. ASSERT_FALSE(svr.is_running());
  13347. });
  13348. svr.wait_until_ready();
  13349. SSLClient cli("127.0.0.1", PORT);
  13350. cli.set_connection_timeout(30);
  13351. auto res = cli.Get("/");
  13352. ASSERT_FALSE(res);
  13353. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13354. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13355. }
  13356. #endif
  13357. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13358. Client cli("https://google.com");
  13359. auto res = cli.Get("/");
  13360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13361. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13362. }
  13363. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13364. SSLClient cli("google.com");
  13365. cli.set_ca_cert_path(CA_CERT_FILE);
  13366. auto res = cli.Get("/");
  13367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13368. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13369. }
  13370. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13371. SSLClient cli("google.com");
  13372. cli.enable_server_certificate_verification(true);
  13373. cli.set_ca_cert_path("hello");
  13374. auto res = cli.Get("/");
  13375. ASSERT_TRUE(!res);
  13376. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13377. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13378. // should be set
  13379. EXPECT_EQ(0, res.ssl_error());
  13380. // Verify backend error is captured for SSLLoadingCerts
  13381. // This error occurs when loading CA certificates fails
  13382. EXPECT_NE(0UL, res.ssl_backend_error());
  13383. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13384. // OpenSSL specific error codes:
  13385. // > openssl errstr 0x80000002
  13386. // error:80000002:system library::No such file or directory
  13387. // > openssl errstr 0xA000126
  13388. // error:0A000126:SSL routines::unexpected eof while reading
  13389. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13390. res.ssl_backend_error() == 0xA000126);
  13391. #endif
  13392. }
  13393. TEST(SSLClientTest, ServerCertificateVerification4) {
  13394. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13395. ASSERT_TRUE(svr.is_valid());
  13396. svr.Get("/test", [&](const Request &, Response &res) {
  13397. res.set_content("test", "text/plain");
  13398. svr.stop();
  13399. ASSERT_TRUE(true);
  13400. });
  13401. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13402. auto se = detail::scope_exit([&] {
  13403. t.join();
  13404. ASSERT_FALSE(svr.is_running());
  13405. });
  13406. svr.wait_until_ready();
  13407. SSLClient cli("127.0.0.1", PORT);
  13408. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13409. cli.enable_server_certificate_verification(true);
  13410. cli.set_connection_timeout(30);
  13411. auto res = cli.Get("/test");
  13412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13413. ASSERT_EQ(StatusCode::OK_200, res->status);
  13414. }
  13415. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13416. std::string cert;
  13417. read_file(CA_CERT_FILE, cert);
  13418. SSLClient cli("google.com");
  13419. cli.load_ca_cert_store(cert.data(), cert.size());
  13420. const auto res = cli.Get("/");
  13421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13422. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13423. }
  13424. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13425. // clang-format off
  13426. static constexpr char cert[] =
  13427. "GlobalSign Root CA\n"
  13428. "==================\n"
  13429. "-----BEGIN CERTIFICATE-----\n"
  13430. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13431. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13432. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13433. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13434. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13435. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13436. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13437. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13438. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13439. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13440. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13441. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13442. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13443. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13444. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13445. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13446. "-----END CERTIFICATE-----\n";
  13447. // clang-format on
  13448. SSLClient cli("google.com");
  13449. cli.load_ca_cert_store(cert, sizeof(cert));
  13450. const auto res = cli.Get("/");
  13451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13452. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13453. }
  13454. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13455. SSLClient cli("www.youtube.com");
  13456. cli.set_ca_cert_path(CA_CERT_FILE);
  13457. cli.enable_server_certificate_verification(true);
  13458. cli.set_follow_location(true);
  13459. auto res = cli.Get("/");
  13460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13461. ASSERT_EQ(StatusCode::OK_200, res->status);
  13462. }
  13463. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13464. SSLClient cli("wWw.YouTube.Com");
  13465. cli.set_ca_cert_path(CA_CERT_FILE);
  13466. cli.enable_server_certificate_verification(true);
  13467. cli.enable_server_hostname_verification(true);
  13468. cli.set_follow_location(true);
  13469. auto res = cli.Get("/");
  13470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13471. ASSERT_EQ(StatusCode::OK_200, res->status);
  13472. }
  13473. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13474. SSLClient cli("gOoGlE.COm");
  13475. cli.enable_server_certificate_verification(true);
  13476. cli.enable_server_hostname_verification(true);
  13477. cli.set_follow_location(true);
  13478. auto res = cli.Get("/");
  13479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13480. ASSERT_EQ(StatusCode::OK_200, res->status);
  13481. }
  13482. TEST(SSLClientTest, Issue2004_Online) {
  13483. Client client("https://google.com");
  13484. client.set_follow_location(true);
  13485. auto res = client.Get("/");
  13486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13487. ASSERT_EQ(StatusCode::OK_200, res->status);
  13488. auto body = res->body;
  13489. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13490. }
  13491. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13492. // Create SSLClient with invalid cert/key to make is_valid() return false
  13493. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13494. "nonexistent_key.pem");
  13495. // is_valid() should be false due to cert loading failure
  13496. ASSERT_FALSE(cli.is_valid());
  13497. auto res = cli.Get("/");
  13498. ASSERT_FALSE(res);
  13499. EXPECT_EQ(Error::SSLConnection, res.error());
  13500. }
  13501. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13502. // Test for Issue #2251: SSL error not properly reported when client cert
  13503. // and key paths are swapped or mismatched
  13504. // This simulates the scenario where user accidentally swaps the cert and key
  13505. // files
  13506. // Using client cert file as private key and vice versa (completely wrong)
  13507. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13508. // Should fail validation due to cert/key mismatch
  13509. ASSERT_FALSE(cli.is_valid());
  13510. // Attempt to make a request should fail with proper error
  13511. auto res = cli.Get("/");
  13512. ASSERT_FALSE(res);
  13513. EXPECT_EQ(Error::SSLConnection, res.error());
  13514. // SSL error should be recorded in the Result object (this is the key fix for
  13515. // Issue #2251)
  13516. auto backend_error = res.ssl_backend_error();
  13517. EXPECT_NE(0u, backend_error);
  13518. }
  13519. // Tests cert/key mismatch detection at the TLS context level
  13520. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13521. // Test that using mismatched cert/key causes connection failure.
  13522. // We verify this at the SSLClient level rather than through internal
  13523. // TLS API functions.
  13524. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13525. cli.enable_server_certificate_verification(false);
  13526. cli.set_connection_timeout(2);
  13527. // The mismatch should cause a connection or handshake error
  13528. auto res = cli.Get("/test");
  13529. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13530. // Either way, the request should fail
  13531. EXPECT_FALSE(res);
  13532. }
  13533. #endif
  13534. #if 0
  13535. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13536. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13537. ASSERT_TRUE(cli != nullptr);
  13538. cli->set_address_family(AF_INET6);
  13539. cli->set_interface("en0");
  13540. auto res = cli->Get("/get");
  13541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13542. ASSERT_EQ(StatusCode::OK_200, res->status);
  13543. }
  13544. #endif
  13545. // Client certificate tests - work with all TLS backends
  13546. #ifdef CPPHTTPLIB_SSL_ENABLED
  13547. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  13548. void ClientCertPresent(
  13549. const std::string &client_cert_file,
  13550. const std::string &client_private_key_file,
  13551. const std::string &client_encrypted_private_key_pass = std::string(),
  13552. const ClientCertServerSetup &setup = nullptr) {
  13553. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13554. CLIENT_CA_CERT_DIR);
  13555. ASSERT_TRUE(svr.is_valid());
  13556. if (setup) { setup(svr); }
  13557. svr.Get("/test", [&](const Request &req, Response &res) {
  13558. res.set_content("test", "text/plain");
  13559. auto cert = req.peer_cert();
  13560. ASSERT_TRUE(static_cast<bool>(cert));
  13561. std::string common_name = cert.subject_cn();
  13562. EXPECT_EQ("Common Name", common_name);
  13563. });
  13564. auto port = svr.bind_to_any_port(HOST);
  13565. ASSERT_LT(0, port);
  13566. thread t = thread([&]() { svr.listen_after_bind(); });
  13567. auto se = detail::scope_exit([&] {
  13568. svr.stop();
  13569. t.join();
  13570. ASSERT_FALSE(svr.is_running());
  13571. });
  13572. svr.wait_until_ready();
  13573. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  13574. client_encrypted_private_key_pass);
  13575. cli.enable_server_certificate_verification(false);
  13576. cli.set_connection_timeout(30);
  13577. auto res = cli.Get("/test");
  13578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13579. ASSERT_EQ(StatusCode::OK_200, res->status);
  13580. }
  13581. TEST(SSLClientServerTest, ClientCertPresent) {
  13582. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13583. }
  13584. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13585. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13586. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13587. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13588. }
  13589. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  13590. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13591. CLIENT_CA_CERT_DIR);
  13592. ASSERT_TRUE(svr.is_valid());
  13593. if (setup) { setup(svr); }
  13594. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  13595. auto port = svr.bind_to_any_port(HOST);
  13596. ASSERT_LT(0, port);
  13597. thread t = thread([&]() { svr.listen_after_bind(); });
  13598. auto se = detail::scope_exit([&] {
  13599. svr.stop();
  13600. t.join();
  13601. ASSERT_FALSE(svr.is_running());
  13602. });
  13603. svr.wait_until_ready();
  13604. SSLClient cli(HOST, port);
  13605. cli.set_connection_timeout(30);
  13606. // Skip the server certificate check, so that the request fails because the
  13607. // client certificate is missing rather than because cert.pem is not trusted
  13608. cli.enable_server_certificate_verification(false);
  13609. auto res = cli.Get("/test");
  13610. ASSERT_FALSE(res);
  13611. // The server rejects the client during the handshake, or on TLS 1.3 right
  13612. // after it, which the client notices on its first write or read
  13613. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  13614. res.error() == Error::Write || res.error() == Error::Read)
  13615. << to_string(res.error());
  13616. if (res.error() == Error::SSLConnection) {
  13617. EXPECT_NE(0UL, res.ssl_backend_error());
  13618. }
  13619. // A rejection noticed on the write keeps the TLS error the write hit
  13620. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  13621. }
  13622. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  13623. // A server that requires client certificates must keep requiring them after a
  13624. // verify callback is set on its context, or set and then cleared again.
  13625. void ClientCertStillRequired(bool clear_callback) {
  13626. auto setup = [clear_callback](SSLServer &svr) {
  13627. ASSERT_TRUE(tls::set_verify_callback(
  13628. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13629. if (clear_callback) {
  13630. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  13631. }
  13632. };
  13633. ClientCertMissing(setup);
  13634. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  13635. setup);
  13636. }
  13637. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  13638. ClientCertStillRequired(false);
  13639. }
  13640. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  13641. ClientCertStillRequired(true);
  13642. }
  13643. // A TLS error from one request must not show up in a later request's Result
  13644. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  13645. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13646. ASSERT_TRUE(svr.is_valid());
  13647. svr.Get("/test", [](const Request &, Response &res) {
  13648. res.set_content("test", "text/plain");
  13649. });
  13650. auto port = svr.bind_to_any_port(HOST);
  13651. ASSERT_LT(0, port);
  13652. thread t = thread([&]() { svr.listen_after_bind(); });
  13653. auto se = detail::scope_exit([&] {
  13654. svr.stop();
  13655. t.join();
  13656. ASSERT_FALSE(svr.is_running());
  13657. });
  13658. svr.wait_until_ready();
  13659. SSLClient cli(HOST, port);
  13660. cli.set_connection_timeout(30);
  13661. cli.enable_server_hostname_verification(false);
  13662. // cert.pem is not trusted, so the handshake fails
  13663. ASSERT_FALSE(cli.Get("/test"));
  13664. cli.enable_server_certificate_verification(false);
  13665. auto res = cli.Get("/test");
  13666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13667. EXPECT_EQ(0, res.ssl_error());
  13668. EXPECT_EQ(0UL, res.ssl_backend_error());
  13669. }
  13670. // PEM memory-based constructor tests (works with all TLS backends)
  13671. void PemMemoryClientCertPresent(
  13672. const std::string &client_cert_file,
  13673. const std::string &client_private_key_file,
  13674. const std::string &client_encrypted_private_key_pass = std::string()) {
  13675. // Read PEM files into memory
  13676. std::string server_cert_pem, server_key_pem;
  13677. std::string client_ca_pem;
  13678. std::string client_cert_pem, client_key_pem;
  13679. read_file(SERVER_CERT_FILE, server_cert_pem);
  13680. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13681. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13682. read_file(client_cert_file, client_cert_pem);
  13683. read_file(client_private_key_file, client_key_pem);
  13684. // Create server with PEM memory
  13685. SSLServer::PemMemory server_pem = {
  13686. server_cert_pem.c_str(),
  13687. server_cert_pem.size(),
  13688. server_key_pem.c_str(),
  13689. server_key_pem.size(),
  13690. client_ca_pem.c_str(),
  13691. client_ca_pem.size(),
  13692. nullptr // no password for server key
  13693. };
  13694. SSLServer svr(server_pem);
  13695. ASSERT_TRUE(svr.is_valid());
  13696. svr.Get("/test", [&](const Request &, Response &res) {
  13697. res.set_content("test", "text/plain");
  13698. });
  13699. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13700. auto se = detail::scope_exit([&] {
  13701. svr.stop();
  13702. t.join();
  13703. ASSERT_FALSE(svr.is_running());
  13704. });
  13705. svr.wait_until_ready();
  13706. // Create client with PEM memory
  13707. const char *password = client_encrypted_private_key_pass.empty()
  13708. ? nullptr
  13709. : client_encrypted_private_key_pass.c_str();
  13710. SSLClient::PemMemory client_pem = {
  13711. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  13712. client_key_pem.size(), password};
  13713. SSLClient cli(HOST, PORT, client_pem);
  13714. cli.enable_server_certificate_verification(false);
  13715. cli.set_connection_timeout(30);
  13716. auto res = cli.Get("/test");
  13717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13718. ASSERT_EQ(StatusCode::OK_200, res->status);
  13719. }
  13720. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13721. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13722. }
  13723. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13724. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13725. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13726. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13727. }
  13728. TEST(SSLClientServerTest, TrustDirOptional) {
  13729. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13730. ASSERT_TRUE(svr.is_valid());
  13731. svr.Get("/test", [&](const Request &, Response &res) {
  13732. res.set_content("test", "text/plain");
  13733. });
  13734. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13735. auto se = detail::scope_exit([&] {
  13736. svr.stop();
  13737. t.join();
  13738. ASSERT_FALSE(svr.is_running());
  13739. });
  13740. svr.wait_until_ready();
  13741. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13742. cli.enable_server_certificate_verification(false);
  13743. cli.set_connection_timeout(30);
  13744. auto res = cli.Get("/test");
  13745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13746. ASSERT_EQ(StatusCode::OK_200, res->status);
  13747. }
  13748. TEST(SSLClientServerTest, SSLConnectTimeout) {
  13749. class NoListenSSLServer : public SSLServer {
  13750. public:
  13751. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  13752. const char *client_ca_cert_file_path,
  13753. const char *client_ca_cert_dir_path = nullptr)
  13754. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  13755. client_ca_cert_dir_path),
  13756. stop_(false) {}
  13757. std::atomic_bool stop_;
  13758. private:
  13759. bool process_and_close_socket(socket_t /*sock*/) override {
  13760. // Don't create SSL context
  13761. while (!stop_.load()) {
  13762. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  13763. }
  13764. return true;
  13765. }
  13766. };
  13767. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13768. CLIENT_CA_CERT_FILE);
  13769. ASSERT_TRUE(svr.is_valid());
  13770. svr.Get("/test", [&](const Request &, Response &res) {
  13771. res.set_content("test", "text/plain");
  13772. });
  13773. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13774. auto se = detail::scope_exit([&] {
  13775. svr.stop_ = true;
  13776. svr.stop();
  13777. t.join();
  13778. ASSERT_FALSE(svr.is_running());
  13779. });
  13780. svr.wait_until_ready();
  13781. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13782. cli.enable_server_certificate_verification(false);
  13783. cli.set_connection_timeout(1);
  13784. auto res = cli.Get("/test");
  13785. ASSERT_TRUE(!res);
  13786. EXPECT_EQ(Error::SSLConnection, res.error());
  13787. // Timeout results in WantRead error code (maps to backend-specific value)
  13788. EXPECT_NE(0, res.ssl_error());
  13789. }
  13790. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  13791. // Test SSLServer with client certificate verification using the standard
  13792. // constructor (ContextSetupCallback is tested by backend-specific tests)
  13793. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13794. CLIENT_CA_CERT_DIR);
  13795. ASSERT_TRUE(svr.is_valid());
  13796. svr.Get("/test", [&](const Request &req, Response &res) {
  13797. res.set_content("test", "text/plain");
  13798. auto cert = req.peer_cert();
  13799. ASSERT_TRUE(static_cast<bool>(cert));
  13800. auto common_name = cert.subject_cn();
  13801. EXPECT_EQ("Common Name", common_name);
  13802. });
  13803. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13804. auto se = detail::scope_exit([&] {
  13805. svr.stop();
  13806. t.join();
  13807. ASSERT_FALSE(svr.is_running());
  13808. });
  13809. svr.wait_until_ready();
  13810. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13811. cli.enable_server_certificate_verification(false);
  13812. cli.set_connection_timeout(30);
  13813. auto res = cli.Get("/test");
  13814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13815. ASSERT_EQ(StatusCode::OK_200, res->status);
  13816. }
  13817. // Test verify_hostname for both OpenSSL and MbedTLS backends
  13818. // Verifies that wildcard matching and exact matching work consistently
  13819. TEST(SSLClientServerTest, TlsVerifyHostname) {
  13820. using namespace httplib::tls;
  13821. // We need a running server to test against
  13822. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13823. ASSERT_TRUE(svr.is_valid());
  13824. svr.Get("/test", [](const Request &, Response &res) {
  13825. res.set_content("ok", "text/plain");
  13826. });
  13827. thread t([&]() { svr.listen(HOST, PORT); });
  13828. auto se = detail::scope_exit([&] {
  13829. svr.stop();
  13830. t.join();
  13831. });
  13832. svr.wait_until_ready();
  13833. bool verify_callback_called = false;
  13834. bool verify_result_wrong = false;
  13835. SSLClient cli(HOST, PORT);
  13836. cli.enable_server_certificate_verification(true);
  13837. cli.set_ca_cert_path(CA_CERT_FILE);
  13838. cli.set_connection_timeout(5);
  13839. // Note: Test certificate has CN="Common Name", not "localhost"
  13840. bool verify_result_cn = false;
  13841. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13842. verify_callback_called = true;
  13843. if (!ctx.cert) return false;
  13844. // Test 1: "Common Name" should match (our test server cert CN)
  13845. verify_result_cn = ctx.check_hostname("Common Name");
  13846. // Test 2: wrong hostname should not match
  13847. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  13848. return true; // Accept for the purpose of this test
  13849. });
  13850. auto res = cli.Get("/test");
  13851. // The request may succeed or fail depending on cert configuration
  13852. // but the callback should have been called
  13853. ASSERT_TRUE(verify_callback_called)
  13854. << "Verify callback should have been called";
  13855. // CN="Common Name" should match our test certificate
  13856. //
  13857. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  13858. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  13859. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  13860. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  13861. // <openssl/base.h>, which is included transitively when
  13862. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  13863. #if defined(OPENSSL_IS_BORINGSSL)
  13864. EXPECT_FALSE(verify_result_cn)
  13865. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  13866. #else
  13867. EXPECT_TRUE(verify_result_cn)
  13868. << "verify_hostname should match 'Common Name' (certificate CN)";
  13869. #endif
  13870. // Wrong hostname should not match
  13871. EXPECT_FALSE(verify_result_wrong)
  13872. << "verify_hostname should not match 'wronghost.example.com'";
  13873. }
  13874. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  13875. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  13876. // X509_check_ip behavior and must hold for every backend.
  13877. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  13878. using namespace httplib::tls;
  13879. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  13880. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  13881. ASSERT_TRUE(svr.is_valid());
  13882. svr.Get("/test", [](const Request &, Response &res) {
  13883. res.set_content("ok", "text/plain");
  13884. });
  13885. thread t([&]() { svr.listen(HOST, PORT); });
  13886. auto se = detail::scope_exit([&] {
  13887. svr.stop();
  13888. t.join();
  13889. });
  13890. svr.wait_until_ready();
  13891. bool verify_callback_called = false;
  13892. bool ip_matched_via_cn = true;
  13893. SSLClient cli(HOST, PORT);
  13894. cli.enable_server_certificate_verification(true);
  13895. cli.set_ca_cert_path(CA_CERT_FILE);
  13896. cli.set_connection_timeout(5);
  13897. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13898. verify_callback_called = true;
  13899. if (!ctx.cert) return false;
  13900. // The IP appears only in the CN, so it must NOT be accepted.
  13901. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  13902. return true; // Accept for the purpose of this test
  13903. });
  13904. cli.Get("/test");
  13905. ASSERT_TRUE(verify_callback_called)
  13906. << "Verify callback should have been called";
  13907. EXPECT_FALSE(ip_matched_via_cn)
  13908. << "An IP host must not be authenticated via the certificate CN";
  13909. }
  13910. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  13911. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  13912. using namespace httplib::tls;
  13913. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  13914. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  13915. ASSERT_TRUE(svr.is_valid());
  13916. svr.Get("/test", [](const Request &, Response &res) {
  13917. res.set_content("ok", "text/plain");
  13918. });
  13919. thread t([&]() { svr.listen(HOST, PORT); });
  13920. auto se = detail::scope_exit([&] {
  13921. svr.stop();
  13922. t.join();
  13923. });
  13924. svr.wait_until_ready();
  13925. bool verify_callback_called = false;
  13926. bool san_matched = false;
  13927. bool wrong_ipv6_matched = true;
  13928. bool cn_ipv6_matched = true;
  13929. SSLClient cli(HOST, PORT);
  13930. cli.enable_server_certificate_verification(true);
  13931. cli.set_ca_cert_path(CA_CERT_FILE);
  13932. cli.set_connection_timeout(5);
  13933. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13934. verify_callback_called = true;
  13935. if (!ctx.cert) return false;
  13936. // Matches the IPv6 iPAddress SAN.
  13937. san_matched = ctx.check_hostname("2001:db8::1");
  13938. // A different IPv6 address must not match.
  13939. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  13940. // "::1" lives only in the CN, so it must not be accepted.
  13941. cn_ipv6_matched = ctx.check_hostname("::1");
  13942. return true; // Accept for the purpose of this test
  13943. });
  13944. cli.Get("/test");
  13945. ASSERT_TRUE(verify_callback_called)
  13946. << "Verify callback should have been called";
  13947. EXPECT_TRUE(san_matched)
  13948. << "verify_hostname should match an IPv6 iPAddress SAN";
  13949. EXPECT_FALSE(wrong_ipv6_matched)
  13950. << "verify_hostname should not match a non-matching IPv6 address";
  13951. EXPECT_FALSE(cn_ipv6_matched)
  13952. << "An IPv6 host must not be authenticated via the certificate CN";
  13953. }
  13954. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  13955. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  13956. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  13957. using namespace httplib::tls;
  13958. // SANs: DNS:a.zz, IP:42.46.122.122
  13959. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13960. ASSERT_TRUE(svr.is_valid());
  13961. svr.Get("/test", [](const Request &, Response &res) {
  13962. res.set_content("ok", "text/plain");
  13963. });
  13964. auto port = svr.bind_to_any_port(HOST);
  13965. thread t([&]() { svr.listen_after_bind(); });
  13966. auto se = detail::scope_exit([&] {
  13967. svr.stop();
  13968. t.join();
  13969. });
  13970. svr.wait_until_ready();
  13971. bool verify_callback_called = false;
  13972. bool dns_san_matched = false;
  13973. bool ip_san_matched = false;
  13974. bool ip_matched_via_dns_san = true;
  13975. bool dns_matched_via_ip_san = true;
  13976. bool cn_matched_next_to_dns_san = true;
  13977. SSLClient cli(HOST, port);
  13978. cli.enable_server_certificate_verification(true);
  13979. cli.set_ca_cert_path(CA_CERT_FILE);
  13980. cli.set_connection_timeout(5);
  13981. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13982. verify_callback_called = true;
  13983. if (!ctx.cert) return false;
  13984. dns_san_matched = ctx.check_hostname("a.zz");
  13985. ip_san_matched = ctx.check_hostname("42.46.122.122");
  13986. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  13987. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  13988. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  13989. return true; // Accept for the purpose of this test
  13990. });
  13991. cli.Get("/test");
  13992. ASSERT_TRUE(verify_callback_called)
  13993. << "Verify callback should have been called";
  13994. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  13995. EXPECT_TRUE(ip_san_matched)
  13996. << "verify_hostname should match an iPAddress SAN";
  13997. EXPECT_FALSE(ip_matched_via_dns_san)
  13998. << "An IP host must not be authenticated via a dNSName SAN";
  13999. EXPECT_FALSE(dns_matched_via_ip_san)
  14000. << "A DNS host must not be authenticated via an iPAddress SAN";
  14001. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14002. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14003. }
  14004. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14005. // "www.*.example.test" names one host and not every host under example.test.
  14006. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14007. using namespace httplib::tls;
  14008. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14009. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14010. ASSERT_TRUE(svr.is_valid());
  14011. svr.Get("/test", [](const Request &, Response &res) {
  14012. res.set_content("ok", "text/plain");
  14013. });
  14014. auto port = svr.bind_to_any_port(HOST);
  14015. thread t([&]() { svr.listen_after_bind(); });
  14016. auto se = detail::scope_exit([&] {
  14017. svr.stop();
  14018. t.join();
  14019. });
  14020. svr.wait_until_ready();
  14021. bool verify_callback_called = false;
  14022. bool leftmost_wildcard_matched = false;
  14023. bool wildcard_spanned_labels = true;
  14024. bool inner_wildcard_matched = true;
  14025. SSLClient cli(HOST, port);
  14026. cli.enable_server_certificate_verification(true);
  14027. cli.set_ca_cert_path(CA_CERT_FILE);
  14028. cli.set_connection_timeout(5);
  14029. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14030. verify_callback_called = true;
  14031. if (!ctx.cert) return false;
  14032. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14033. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14034. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14035. return true; // Accept for the purpose of this test
  14036. });
  14037. cli.Get("/test");
  14038. ASSERT_TRUE(verify_callback_called)
  14039. << "Verify callback should have been called";
  14040. EXPECT_TRUE(leftmost_wildcard_matched)
  14041. << "A leftmost wildcard should match a single label";
  14042. EXPECT_FALSE(wildcard_spanned_labels)
  14043. << "A wildcard label must not match more than one label";
  14044. EXPECT_FALSE(inner_wildcard_matched)
  14045. << "A wildcard outside the leftmost label must not be honoured";
  14046. }
  14047. // sans() must report each SAN entry under its own type.
  14048. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14049. using namespace httplib::tls;
  14050. // SANs: DNS:a.zz, IP:42.46.122.122
  14051. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14052. ASSERT_TRUE(svr.is_valid());
  14053. svr.Get("/test", [](const Request &, Response &res) {
  14054. res.set_content("ok", "text/plain");
  14055. });
  14056. auto port = svr.bind_to_any_port(HOST);
  14057. thread t([&]() { svr.listen_after_bind(); });
  14058. auto se = detail::scope_exit([&] {
  14059. svr.stop();
  14060. t.join();
  14061. });
  14062. svr.wait_until_ready();
  14063. bool verify_callback_called = false;
  14064. std::vector<SanEntry> sans;
  14065. SSLClient cli(HOST, port);
  14066. cli.enable_server_certificate_verification(true);
  14067. cli.set_ca_cert_path(CA_CERT_FILE);
  14068. cli.set_connection_timeout(5);
  14069. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14070. verify_callback_called = true;
  14071. if (!ctx.cert) return false;
  14072. sans = ctx.sans();
  14073. return true; // Accept for the purpose of this test
  14074. });
  14075. cli.Get("/test");
  14076. ASSERT_TRUE(verify_callback_called)
  14077. << "Verify callback should have been called";
  14078. auto has_san = [&](SanType type, const std::string &value) {
  14079. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14080. return san.type == type && san.value == value;
  14081. });
  14082. };
  14083. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14084. << "sans() should report the dNSName SAN";
  14085. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14086. << "sans() should report the iPAddress SAN";
  14087. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14088. << "sans() must not report the dNSName SAN as an address";
  14089. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14090. << "sans() must not report the iPAddress SAN as a DNS name";
  14091. }
  14092. #endif
  14093. // mbedTLS-specific callback constructor test
  14094. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14095. #ifdef CPPHTTPLIB_SSL_ENABLED
  14096. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14097. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14098. ASSERT_TRUE(svr.is_valid());
  14099. // Set up a handler to verify client certificate is present
  14100. bool client_cert_verified = false;
  14101. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14102. // Verify that client certificate was provided
  14103. client_cert_verified = true;
  14104. res.set_content("success", "text/plain");
  14105. });
  14106. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14107. auto se = detail::scope_exit([&] {
  14108. svr.stop();
  14109. t.join();
  14110. ASSERT_FALSE(svr.is_running());
  14111. });
  14112. svr.wait_until_ready();
  14113. // Client with certificate
  14114. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14115. cli.enable_server_certificate_verification(false);
  14116. cli.set_connection_timeout(30);
  14117. auto res = cli.Get("/test");
  14118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14119. ASSERT_EQ(StatusCode::OK_200, res->status);
  14120. ASSERT_TRUE(client_cert_verified);
  14121. EXPECT_EQ("success", res->body);
  14122. }
  14123. #endif
  14124. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14125. // backends
  14126. #ifdef CPPHTTPLIB_SSL_ENABLED
  14127. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14128. using namespace httplib::tls;
  14129. // Test that when client CA cert file is provided,
  14130. // the server properly requests and validates client certificates
  14131. // Create a server with client authentication
  14132. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14133. ASSERT_TRUE(svr.is_valid());
  14134. bool handler_called = false;
  14135. svr.Get("/test", [&](const Request &req, Response &res) {
  14136. handler_called = true;
  14137. // Verify that a client certificate was provided
  14138. auto cert = req.peer_cert();
  14139. ASSERT_TRUE(static_cast<bool>(cert));
  14140. // Get the issuer name
  14141. std::string issuer_str = cert.issuer_name();
  14142. ASSERT_FALSE(issuer_str.empty());
  14143. // The client certificate should be issued by our test CA
  14144. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14145. res.set_content("authenticated", "text/plain");
  14146. });
  14147. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14148. auto se = detail::scope_exit([&] {
  14149. svr.stop();
  14150. t.join();
  14151. ASSERT_FALSE(svr.is_running());
  14152. });
  14153. svr.wait_until_ready();
  14154. // Connect with a client certificate issued by the CA
  14155. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14156. cli.enable_server_certificate_verification(false);
  14157. cli.set_connection_timeout(30);
  14158. auto res = cli.Get("/test");
  14159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14160. ASSERT_EQ(StatusCode::OK_200, res->status);
  14161. ASSERT_TRUE(handler_called);
  14162. EXPECT_EQ("authenticated", res->body);
  14163. }
  14164. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14165. using namespace httplib::tls;
  14166. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14167. ASSERT_TRUE(svr.is_valid());
  14168. svr.Get("/test", [](const Request &, Response &res) {
  14169. res.set_content("ok", "text/plain");
  14170. });
  14171. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14172. auto se = detail::scope_exit([&] {
  14173. svr.stop();
  14174. t.join();
  14175. });
  14176. svr.wait_until_ready();
  14177. SSLClient cli(HOST, PORT);
  14178. cli.enable_server_certificate_verification(false);
  14179. cli.set_connection_timeout(30);
  14180. bool cert_checked = false;
  14181. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14182. if (ctx.cert) {
  14183. auto sans = ctx.sans();
  14184. // Test certificate may or may not have SANs - just verify the API
  14185. // works If SANs exist, verify the types are valid
  14186. for (const auto &san : sans) {
  14187. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14188. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14189. san.type == SanType::OTHER);
  14190. EXPECT_FALSE(san.value.empty());
  14191. }
  14192. cert_checked = true;
  14193. }
  14194. return true;
  14195. });
  14196. auto res = cli.Get("/test");
  14197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14198. EXPECT_TRUE(cert_checked);
  14199. }
  14200. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14201. using namespace httplib::tls;
  14202. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14203. ASSERT_TRUE(svr.is_valid());
  14204. svr.Get("/test", [](const Request &, Response &res) {
  14205. res.set_content("ok", "text/plain");
  14206. });
  14207. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14208. auto se = detail::scope_exit([&] {
  14209. svr.stop();
  14210. t.join();
  14211. });
  14212. svr.wait_until_ready();
  14213. SSLClient cli(HOST, PORT);
  14214. cli.enable_server_certificate_verification(false);
  14215. cli.set_connection_timeout(30);
  14216. bool validity_checked = false;
  14217. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14218. if (ctx.cert) {
  14219. time_t not_before = 0, not_after = 0;
  14220. bool result = ctx.validity(not_before, not_after);
  14221. EXPECT_TRUE(result);
  14222. // Verify that not_before < now < not_after for a valid cert
  14223. time_t now = time(nullptr);
  14224. EXPECT_LT(not_before, now);
  14225. EXPECT_GT(not_after, now);
  14226. validity_checked = true;
  14227. }
  14228. return true;
  14229. });
  14230. auto res = cli.Get("/test");
  14231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14232. EXPECT_TRUE(validity_checked);
  14233. }
  14234. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14235. using namespace httplib::tls;
  14236. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14237. ASSERT_TRUE(svr.is_valid());
  14238. svr.Get("/test", [](const Request &, Response &res) {
  14239. res.set_content("ok", "text/plain");
  14240. });
  14241. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14242. auto se = detail::scope_exit([&] {
  14243. svr.stop();
  14244. t.join();
  14245. });
  14246. svr.wait_until_ready();
  14247. SSLClient cli(HOST, PORT);
  14248. cli.enable_server_certificate_verification(false);
  14249. cli.set_connection_timeout(30);
  14250. bool serial_checked = false;
  14251. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14252. if (ctx.cert) {
  14253. std::string serial = ctx.serial();
  14254. EXPECT_FALSE(serial.empty());
  14255. // Serial should be a hex string
  14256. for (char c : serial) {
  14257. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14258. (c >= 'a' && c <= 'f'));
  14259. }
  14260. serial_checked = true;
  14261. }
  14262. return true;
  14263. });
  14264. auto res = cli.Get("/test");
  14265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14266. EXPECT_TRUE(serial_checked);
  14267. }
  14268. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14269. // Test 1: Valid CA file - no error should be recorded
  14270. {
  14271. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14272. CLIENT_CA_CERT_FILE);
  14273. ASSERT_TRUE(svr.is_valid());
  14274. // With valid setup, last_ssl_error should be 0
  14275. EXPECT_EQ(0, svr.ssl_last_error());
  14276. }
  14277. // Test 2: Invalid CA file content
  14278. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14279. {
  14280. // Create a temporary file with completely invalid content
  14281. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14282. {
  14283. std::ofstream ofs(temp_invalid_ca);
  14284. ofs << "This is not a certificate file at all\n";
  14285. ofs << "Just plain text content\n";
  14286. }
  14287. // Create server with invalid CA file
  14288. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14289. // Clean up temporary file
  14290. std::remove(temp_invalid_ca);
  14291. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14292. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14293. // Note: SSL_CTX_load_verify_locations typically fails first,
  14294. // but our error handling code path is still exercised
  14295. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14296. }
  14297. }
  14298. TEST(VerifyCallbackTest, VerifyContextFields) {
  14299. using namespace httplib::tls;
  14300. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14301. ASSERT_TRUE(svr.is_valid());
  14302. svr.Get("/test", [](const Request &, Response &res) {
  14303. res.set_content("ok", "text/plain");
  14304. });
  14305. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14306. auto se = detail::scope_exit([&] {
  14307. svr.stop();
  14308. t.join();
  14309. });
  14310. svr.wait_until_ready();
  14311. SSLClient cli(HOST, PORT);
  14312. cli.enable_server_certificate_verification(false);
  14313. cli.set_connection_timeout(30);
  14314. int callback_count = 0;
  14315. bool saw_leaf_cert = false;
  14316. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14317. if (ctx.cert) {
  14318. callback_count++;
  14319. // We should see at least one certificate (the leaf)
  14320. std::string cn = ctx.subject_cn();
  14321. if (!cn.empty()) { saw_leaf_cert = true; }
  14322. // Verify context fields are populated
  14323. EXPECT_NE(ctx.session, nullptr);
  14324. EXPECT_GE(ctx.depth, 0);
  14325. }
  14326. return true;
  14327. });
  14328. auto res = cli.Get("/test");
  14329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14330. EXPECT_GT(callback_count, 0);
  14331. EXPECT_TRUE(saw_leaf_cert);
  14332. }
  14333. // A verifier belongs to the client that set it, not to the thread that set it.
  14334. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14335. using namespace httplib::tls;
  14336. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14337. ASSERT_TRUE(svr.is_valid());
  14338. svr.Get("/test", [](const Request &, Response &res) {
  14339. res.set_content("ok", "text/plain");
  14340. });
  14341. auto port = svr.bind_to_any_port(HOST);
  14342. thread t([&]() { svr.listen_after_bind(); });
  14343. auto se = detail::scope_exit([&] {
  14344. svr.stop();
  14345. t.join();
  14346. });
  14347. svr.wait_until_ready();
  14348. auto rejecting_calls = 0;
  14349. SSLClient rejecting(HOST, port);
  14350. rejecting.enable_server_certificate_verification(false);
  14351. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14352. rejecting_calls++;
  14353. return false;
  14354. });
  14355. auto accepting_calls = 0;
  14356. SSLClient accepting(HOST, port);
  14357. accepting.enable_server_certificate_verification(false);
  14358. // Set on another thread than the requests below.
  14359. thread([&]() {
  14360. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14361. accepting_calls++;
  14362. return true;
  14363. });
  14364. }).join();
  14365. // Requested on another thread than the verifier was set on.
  14366. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14367. EXPECT_GT(rejecting_calls, 0);
  14368. auto res = accepting.Get("/test");
  14369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14370. EXPECT_GT(accepting_calls, 0);
  14371. }
  14372. // A verifier replaced while a handshake runs it lives until it returns.
  14373. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14374. using namespace httplib::tls;
  14375. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14376. ASSERT_TRUE(svr.is_valid());
  14377. svr.Get("/test", [](const Request &, Response &res) {
  14378. res.set_content("ok", "text/plain");
  14379. });
  14380. auto port = svr.bind_to_any_port(HOST);
  14381. thread t([&]() { svr.listen_after_bind(); });
  14382. auto se = detail::scope_exit([&] {
  14383. svr.stop();
  14384. t.join();
  14385. });
  14386. svr.wait_until_ready();
  14387. SSLClient cli(HOST, port);
  14388. cli.enable_server_certificate_verification(false);
  14389. std::promise<void> entered;
  14390. std::promise<void> replaced;
  14391. auto replaced_future = replaced.get_future();
  14392. auto first_call = true;
  14393. // Long enough to live on the heap
  14394. std::string expected(64, 'v');
  14395. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14396. if (first_call) {
  14397. first_call = false;
  14398. entered.set_value();
  14399. replaced_future.wait();
  14400. }
  14401. return expected == std::string(64, 'v');
  14402. });
  14403. thread request([&]() {
  14404. auto res = cli.Get("/test");
  14405. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14406. });
  14407. entered.get_future().wait();
  14408. cli.set_server_certificate_verifier(
  14409. [](const VerifyContext &) { return true; });
  14410. replaced.set_value();
  14411. request.join();
  14412. }
  14413. // VerifyContext::session is the same handle the other tls:: functions take.
  14414. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14415. using namespace httplib::tls;
  14416. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14417. ASSERT_TRUE(svr.is_valid());
  14418. svr.Get("/test", [](const Request &, Response &res) {
  14419. res.set_content("ok", "text/plain");
  14420. });
  14421. auto port = svr.bind_to_any_port(HOST);
  14422. thread t([&]() { svr.listen_after_bind(); });
  14423. auto se = detail::scope_exit([&] {
  14424. svr.stop();
  14425. t.join();
  14426. });
  14427. svr.wait_until_ready();
  14428. SSLClient cli(HOST, port);
  14429. cli.enable_server_certificate_verification(false);
  14430. session_t verifier_session = nullptr;
  14431. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14432. verifier_session = ctx.session;
  14433. return true;
  14434. });
  14435. session_t session_verifier_session = nullptr;
  14436. cli.set_session_verifier([&](session_t session) {
  14437. session_verifier_session = session;
  14438. return SSLVerifierResponse::NoDecisionMade;
  14439. });
  14440. auto res = cli.Get("/test");
  14441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14442. EXPECT_NE(nullptr, verifier_session);
  14443. EXPECT_EQ(session_verifier_session, verifier_session);
  14444. }
  14445. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14446. using httplib::tls::TlsError;
  14447. // Test that verify_error_to_string returns empty for success
  14448. std::string success_str = TlsError::verify_error_to_string(0);
  14449. EXPECT_TRUE(success_str.empty());
  14450. // Test that verify_error_to_string returns non-empty for error codes
  14451. // Using a common error code (certificate expired)
  14452. std::string error_str =
  14453. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14454. EXPECT_FALSE(error_str.empty());
  14455. }
  14456. TEST(SessionVerifierTest, CertificateAccepted) {
  14457. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14458. ASSERT_TRUE(svr.is_valid());
  14459. svr.Get("/test", [](const Request &, Response &res) {
  14460. res.set_content("ok", "text/plain");
  14461. });
  14462. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14463. auto se = detail::scope_exit([&] {
  14464. svr.stop();
  14465. t.join();
  14466. });
  14467. svr.wait_until_ready();
  14468. SSLClient cli(HOST, PORT);
  14469. cli.enable_server_certificate_verification(false);
  14470. cli.set_connection_timeout(30);
  14471. bool callback_called = false;
  14472. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14473. EXPECT_NE(session, nullptr);
  14474. callback_called = true;
  14475. return SSLVerifierResponse::CertificateAccepted;
  14476. });
  14477. auto res = cli.Get("/test");
  14478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14479. EXPECT_EQ(200, res->status);
  14480. EXPECT_TRUE(callback_called);
  14481. }
  14482. TEST(SessionVerifierTest, CertificateRejected) {
  14483. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14484. ASSERT_TRUE(svr.is_valid());
  14485. svr.Get("/test", [](const Request &, Response &res) {
  14486. res.set_content("ok", "text/plain");
  14487. });
  14488. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14489. auto se = detail::scope_exit([&] {
  14490. svr.stop();
  14491. t.join();
  14492. });
  14493. svr.wait_until_ready();
  14494. SSLClient cli(HOST, PORT);
  14495. cli.enable_server_certificate_verification(false);
  14496. cli.set_connection_timeout(30);
  14497. bool callback_called = false;
  14498. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14499. EXPECT_NE(session, nullptr);
  14500. callback_called = true;
  14501. return SSLVerifierResponse::CertificateRejected;
  14502. });
  14503. auto res = cli.Get("/test");
  14504. EXPECT_FALSE(res);
  14505. EXPECT_TRUE(callback_called);
  14506. }
  14507. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14508. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14509. ASSERT_TRUE(svr.is_valid());
  14510. svr.Get("/test", [](const Request &, Response &res) {
  14511. res.set_content("ok", "text/plain");
  14512. });
  14513. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14514. auto se = detail::scope_exit([&] {
  14515. svr.stop();
  14516. t.join();
  14517. });
  14518. svr.wait_until_ready();
  14519. // NoDecisionMade with verification disabled should succeed (no default check)
  14520. SSLClient cli(HOST, PORT);
  14521. cli.enable_server_certificate_verification(false);
  14522. cli.set_connection_timeout(30);
  14523. bool callback_called = false;
  14524. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14525. EXPECT_NE(session, nullptr);
  14526. callback_called = true;
  14527. return SSLVerifierResponse::NoDecisionMade;
  14528. });
  14529. auto res = cli.Get("/test");
  14530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14531. EXPECT_EQ(200, res->status);
  14532. EXPECT_TRUE(callback_called);
  14533. }
  14534. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14535. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14536. ASSERT_TRUE(svr.is_valid());
  14537. svr.Get("/test", [](const Request &, Response &res) {
  14538. res.set_content("ok", "text/plain");
  14539. });
  14540. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14541. auto se = detail::scope_exit([&] {
  14542. svr.stop();
  14543. t.join();
  14544. });
  14545. svr.wait_until_ready();
  14546. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14547. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14548. // so we only check that the request fails, not whether the callback was
  14549. // called.
  14550. SSLClient cli(HOST, PORT);
  14551. cli.enable_server_certificate_verification(true);
  14552. cli.set_connection_timeout(30);
  14553. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14554. EXPECT_NE(session, nullptr);
  14555. return SSLVerifierResponse::NoDecisionMade;
  14556. });
  14557. auto res = cli.Get("/test");
  14558. EXPECT_FALSE(res);
  14559. }
  14560. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14561. // Test SSL server using PemMemory constructor with client CA certificates
  14562. // Read PEM files
  14563. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14564. read_file(SERVER_CERT_FILE, server_cert_pem);
  14565. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14566. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14567. // Create SSLServer with PemMemory constructor including client CA
  14568. SSLServer::PemMemory server_pem = {
  14569. server_cert_pem.c_str(),
  14570. server_cert_pem.size(),
  14571. server_key_pem.c_str(),
  14572. server_key_pem.size(),
  14573. client_ca_pem.c_str(),
  14574. client_ca_pem.size(),
  14575. nullptr // no password for server key
  14576. };
  14577. SSLServer svr(server_pem);
  14578. ASSERT_TRUE(svr.is_valid());
  14579. // No SSL error should be recorded for valid setup
  14580. EXPECT_EQ(0, svr.ssl_last_error());
  14581. // Set up server endpoints
  14582. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14583. res.set_content("ok", "text/plain");
  14584. });
  14585. // Start server in a thread
  14586. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14587. svr.wait_until_ready();
  14588. // Connect with client certificate (using constructor with paths)
  14589. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14590. cli.enable_server_certificate_verification(false);
  14591. auto res = cli.Get("/test-pem-ca");
  14592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14593. EXPECT_EQ(200, res->status);
  14594. EXPECT_EQ("ok", res->body);
  14595. svr.stop();
  14596. server_thread.join();
  14597. }
  14598. #endif
  14599. #ifdef _WIN32
  14600. TEST(CleanupTest, WSACleanup) {
  14601. int ret = WSACleanup();
  14602. ASSERT_EQ(0, ret);
  14603. }
  14604. #endif
  14605. #ifndef CPPHTTPLIB_SSL_ENABLED
  14606. TEST(NoSSLSupport, SimpleInterface) {
  14607. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14608. }
  14609. #endif
  14610. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14611. TEST(InvalidScheme, SimpleInterface) {
  14612. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14613. }
  14614. #endif
  14615. TEST(NoScheme, SimpleInterface) {
  14616. Client cli("yahoo.com:80");
  14617. ASSERT_TRUE(cli.is_valid());
  14618. }
  14619. TEST(SendAPI, SimpleInterface_Online) {
  14620. Client cli("http://yahoo.com");
  14621. Request req;
  14622. req.method = "GET";
  14623. req.path = "/";
  14624. auto res = cli.send(req);
  14625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14626. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14627. }
  14628. TEST(SendAPI, WithParamsInRequest) {
  14629. Server svr;
  14630. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14631. EXPECT_TRUE(req.has_param("test"));
  14632. EXPECT_EQ("test_value", req.get_param_value("test"));
  14633. });
  14634. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14635. auto se = detail::scope_exit([&] {
  14636. svr.stop();
  14637. t.join();
  14638. ASSERT_FALSE(svr.is_running());
  14639. });
  14640. svr.wait_until_ready();
  14641. Client cli(HOST, PORT);
  14642. {
  14643. Request req;
  14644. req.method = "GET";
  14645. req.path = "/";
  14646. req.params.emplace("test", "test_value");
  14647. auto res = cli.send(req);
  14648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14649. }
  14650. {
  14651. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14653. }
  14654. }
  14655. TEST(ClientImplMethods, GetSocketTest) {
  14656. httplib::Server svr;
  14657. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14658. res.status = StatusCode::OK_200;
  14659. });
  14660. auto port = svr.bind_to_any_port("127.0.0.1");
  14661. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14662. auto se = detail::scope_exit([&] {
  14663. svr.stop();
  14664. thread.join();
  14665. ASSERT_FALSE(svr.is_running());
  14666. });
  14667. svr.wait_until_ready();
  14668. {
  14669. httplib::Client cli("127.0.0.1", port);
  14670. cli.set_keep_alive(true);
  14671. // Use the behavior of cpp-httplib of opening the connection
  14672. // only when the first request happens. If that changes,
  14673. // this test would be obsolete.
  14674. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14675. // This also implicitly tests the server. But other tests would fail much
  14676. // earlier than this one to be considered.
  14677. auto res = cli.Get("/");
  14678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14679. EXPECT_EQ(StatusCode::OK_200, res->status);
  14680. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14681. }
  14682. }
  14683. #ifdef CPPHTTPLIB_SSL_ENABLED
  14684. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  14685. Client cli("http://yahoo.com");
  14686. auto res = cli.Get("/");
  14687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14688. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14689. cli.set_follow_location(true);
  14690. res = cli.Get("/");
  14691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14692. EXPECT_EQ(StatusCode::OK_200, res->status);
  14693. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14694. }
  14695. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  14696. Client cli("https://yahoo.com");
  14697. auto res = cli.Get("/");
  14698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14699. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14700. cli.set_follow_location(true);
  14701. res = cli.Get("/");
  14702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14703. EXPECT_EQ(StatusCode::OK_200, res->status);
  14704. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14705. }
  14706. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  14707. Client cli("https://yahoo.com");
  14708. auto res = cli.Get("/");
  14709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14710. ASSERT_FALSE(!res);
  14711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14712. ASSERT_FALSE(res == nullptr);
  14713. ASSERT_TRUE(res != nullptr);
  14714. EXPECT_EQ(Error::Success, res.error());
  14715. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  14716. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  14717. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14718. cli.set_follow_location(true);
  14719. res = cli.Get("/");
  14720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14721. EXPECT_EQ(Error::Success, res.error());
  14722. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  14723. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  14724. EXPECT_EQ(StatusCode::OK_200, res->status);
  14725. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14726. }
  14727. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14728. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  14729. Client cli("https://cdnjs.cloudflare.com");
  14730. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  14731. Headers{{"Accept-Encoding", "br"}});
  14732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14733. EXPECT_EQ(StatusCode::OK_200, res->status);
  14734. EXPECT_EQ(287630U, res->body.size());
  14735. EXPECT_EQ("application/javascript; charset=utf-8",
  14736. res->get_header_value("Content-Type"));
  14737. }
  14738. #endif
  14739. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  14740. #undef REDIR_HOST // Silence compiler warning
  14741. #define REDIR_HOST "https://httpbingo.org"
  14742. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  14743. Client cli(REDIR_HOST);
  14744. cli.set_follow_location(true);
  14745. auto res =
  14746. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  14747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14748. EXPECT_EQ(StatusCode::OK_200, res->status);
  14749. }
  14750. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  14751. Client cli(REDIR_HOST);
  14752. cli.set_follow_location(true);
  14753. Params params;
  14754. params.emplace("url", "http://example.com");
  14755. params.emplace("status_code", "302");
  14756. auto res = cli.Get(REDIR_PATH, params, Headers{});
  14757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14758. EXPECT_EQ(StatusCode::OK_200, res->status);
  14759. }
  14760. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  14761. Client cli(REDIR_HOST);
  14762. cli.set_follow_location(true);
  14763. Params params;
  14764. params.emplace("url", "http://example.com");
  14765. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  14766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14767. EXPECT_EQ(StatusCode::OK_200, res->status);
  14768. }
  14769. TEST(HttpToHttpsRedirectTest, CertFile) {
  14770. auto ssl_port = PORT + 1;
  14771. Server svr;
  14772. ASSERT_TRUE(svr.is_valid());
  14773. svr.Get("/index", [&](const Request &, Response &res) {
  14774. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14775. "/index");
  14776. svr.stop();
  14777. });
  14778. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14779. ASSERT_TRUE(ssl_svr.is_valid());
  14780. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  14781. res.set_content("test", "text/plain");
  14782. ssl_svr.stop();
  14783. });
  14784. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14785. thread t2 =
  14786. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  14787. auto se = detail::scope_exit([&] {
  14788. t2.join();
  14789. t.join();
  14790. ASSERT_FALSE(svr.is_running());
  14791. });
  14792. svr.wait_until_ready();
  14793. ssl_svr.wait_until_ready();
  14794. Client cli("127.0.0.1", PORT);
  14795. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14796. cli.enable_server_certificate_verification(true);
  14797. cli.set_follow_location(true);
  14798. cli.set_connection_timeout(30);
  14799. auto res = cli.Get("/index");
  14800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14801. ASSERT_EQ(StatusCode::OK_200, res->status);
  14802. }
  14803. TEST(SSLClientRedirectTest, CertFile) {
  14804. auto ssl_port = PORT + 1;
  14805. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14806. ASSERT_TRUE(ssl_svr1.is_valid());
  14807. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14808. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14809. "/index");
  14810. ssl_svr1.stop();
  14811. });
  14812. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14813. ASSERT_TRUE(ssl_svr2.is_valid());
  14814. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14815. res.set_content("test", "text/plain");
  14816. ssl_svr2.stop();
  14817. });
  14818. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14819. thread t2 =
  14820. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14821. auto se = detail::scope_exit([&] {
  14822. t2.join();
  14823. t.join();
  14824. ASSERT_FALSE(ssl_svr1.is_running());
  14825. });
  14826. ssl_svr1.wait_until_ready();
  14827. ssl_svr2.wait_until_ready();
  14828. SSLClient cli("127.0.0.1", PORT);
  14829. std::string cert;
  14830. read_file(SERVER_CERT2_FILE, cert);
  14831. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14832. cli.enable_server_certificate_verification(true);
  14833. cli.set_follow_location(true);
  14834. cli.set_connection_timeout(30);
  14835. auto res = cli.Get("/index");
  14836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14837. ASSERT_EQ(StatusCode::OK_200, res->status);
  14838. }
  14839. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  14840. // another port, so the client follows it with a new client.
  14841. static Result GetThroughTlsRedirectToDifferentPort(
  14842. const std::function<void(SSLClient &)> &setup,
  14843. const char *target_cert = SERVER_CERT2_FILE,
  14844. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  14845. auto ssl_port = PORT + 1;
  14846. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14847. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14848. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14849. "/index");
  14850. });
  14851. SSLServer ssl_svr2(target_cert, target_key);
  14852. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14853. res.set_content("test", "text/plain");
  14854. });
  14855. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  14856. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  14857. auto se = detail::scope_exit([&] {
  14858. ssl_svr2.stop();
  14859. ssl_svr1.stop();
  14860. t2.join();
  14861. t.join();
  14862. });
  14863. ssl_svr1.wait_until_ready();
  14864. ssl_svr2.wait_until_ready();
  14865. SSLClient cli("127.0.0.1", PORT);
  14866. cli.set_follow_location(true);
  14867. cli.set_connection_timeout(30);
  14868. setup(cli);
  14869. return cli.Get("/index");
  14870. }
  14871. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  14872. auto calls = 0;
  14873. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  14874. cli.enable_server_certificate_verification(false);
  14875. // Accept the first server only.
  14876. cli.set_session_verifier([&](tls::session_t) {
  14877. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  14878. : SSLVerifierResponse::CertificateRejected;
  14879. });
  14880. });
  14881. ASSERT_FALSE(res);
  14882. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14883. EXPECT_EQ(2, calls);
  14884. }
  14885. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  14886. std::string pinned;
  14887. auto res = GetThroughTlsRedirectToDifferentPort(
  14888. [&](SSLClient &cli) {
  14889. cli.enable_server_certificate_verification(false);
  14890. // Pin the first certificate seen.
  14891. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  14892. if (pinned.empty()) { pinned = ctx.serial(); }
  14893. return ctx.serial() == pinned;
  14894. });
  14895. },
  14896. // A certificate other than the first server's.
  14897. SERVER_CERT_FILE);
  14898. EXPECT_FALSE(res);
  14899. EXPECT_FALSE(pinned.empty());
  14900. }
  14901. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  14902. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  14903. std::string cert;
  14904. read_file(SERVER_CERT2_FILE, cert);
  14905. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14906. });
  14907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14908. EXPECT_EQ(StatusCode::OK_200, res->status);
  14909. }
  14910. // The target's certificate is signed by the root CA, which the first server's
  14911. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  14912. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  14913. auto res = GetThroughTlsRedirectToDifferentPort(
  14914. [](SSLClient &cli) {
  14915. std::string root_ca, cert;
  14916. read_file(CLIENT_CA_CERT_FILE, root_ca);
  14917. read_file(SERVER_CERT2_FILE, cert);
  14918. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  14919. cli.load_ca_cert_store(cert.data(), cert.size());
  14920. cli.enable_server_hostname_verification(false);
  14921. },
  14922. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14924. EXPECT_EQ(StatusCode::OK_200, res->status);
  14925. }
  14926. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  14927. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  14928. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  14929. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  14930. auto res = GetThroughTlsRedirectToDifferentPort(
  14931. [](SSLClient &cli) {
  14932. std::string root_ca, cert;
  14933. read_file(CLIENT_CA_CERT_FILE, root_ca);
  14934. read_file(SERVER_CERT2_FILE, cert);
  14935. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  14936. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14937. cli.enable_server_hostname_verification(false);
  14938. },
  14939. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14940. ASSERT_FALSE(res);
  14941. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14942. }
  14943. #endif
  14944. #endif
  14945. #ifdef CPPHTTPLIB_SSL_ENABLED
  14946. // Test that set_ca_cert_store() skips system certs (consistent with
  14947. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  14948. // should be trusted - system certs should NOT be loaded.
  14949. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  14950. // Load a specific cert that is NOT a system CA cert
  14951. std::string cert;
  14952. read_file(SERVER_CERT2_FILE, cert);
  14953. SSLClient cli("google.com");
  14954. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14955. cli.enable_server_certificate_verification(true);
  14956. // This should FAIL because:
  14957. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  14958. // 2. System certs should NOT be loaded when custom store is set
  14959. // If system certs WERE loaded, this would succeed
  14960. auto res = cli.Get("/");
  14961. ASSERT_FALSE(res);
  14962. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14963. }
  14964. // Same as above, but through the native store handle path. Regression test:
  14965. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  14966. // merged system certs into the user-provided store.
  14967. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  14968. std::string cert;
  14969. read_file(SERVER_CERT2_FILE, cert);
  14970. SSLClient cli("google.com");
  14971. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14972. cli.enable_server_certificate_verification(true);
  14973. auto res = cli.Get("/");
  14974. ASSERT_FALSE(res);
  14975. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14976. }
  14977. // A custom store set via the native handle must still verify a server whose
  14978. // cert it does contain.
  14979. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  14980. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14981. ASSERT_TRUE(svr.is_valid());
  14982. svr.Get("/test", [&](const Request &, Response &res) {
  14983. res.set_content("test", "text/plain");
  14984. });
  14985. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14986. auto se = detail::scope_exit([&] {
  14987. svr.stop();
  14988. t.join();
  14989. ASSERT_FALSE(svr.is_running());
  14990. });
  14991. svr.wait_until_ready();
  14992. SSLClient cli("127.0.0.1", PORT);
  14993. std::string cert;
  14994. read_file(SERVER_CERT2_FILE, cert);
  14995. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14996. cli.enable_server_certificate_verification(true);
  14997. cli.set_connection_timeout(30);
  14998. auto res = cli.Get("/test");
  14999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15000. ASSERT_EQ(StatusCode::OK_200, res->status);
  15001. }
  15002. // CA certs loaded through the universal Client must be transferred to the
  15003. // client created internally for following an HTTPS redirect. Regression test:
  15004. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15005. // the CA data for redirect transfer.
  15006. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15007. auto ssl_port = PORT + 1;
  15008. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15009. ASSERT_TRUE(ssl_svr1.is_valid());
  15010. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15011. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15012. "/index");
  15013. });
  15014. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15015. ASSERT_TRUE(ssl_svr2.is_valid());
  15016. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15017. res.set_content("test", "text/plain");
  15018. });
  15019. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15020. thread t2 =
  15021. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15022. auto se = detail::scope_exit([&] {
  15023. ssl_svr2.stop();
  15024. ssl_svr1.stop();
  15025. t2.join();
  15026. t.join();
  15027. ASSERT_FALSE(ssl_svr1.is_running());
  15028. });
  15029. ssl_svr1.wait_until_ready();
  15030. ssl_svr2.wait_until_ready();
  15031. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15032. std::string cert;
  15033. read_file(SERVER_CERT2_FILE, cert);
  15034. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15035. cli.enable_server_certificate_verification(true);
  15036. cli.set_follow_location(true);
  15037. cli.set_connection_timeout(30);
  15038. auto res = cli.Get("/index");
  15039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15040. ASSERT_EQ(StatusCode::OK_200, res->status);
  15041. }
  15042. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  15043. // so a host signed by a system CA verifies even though a custom CA is set
  15044. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  15045. std::string cert;
  15046. read_file(SERVER_CERT2_FILE, cert);
  15047. SSLClient cli("google.com");
  15048. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15049. cli.enable_system_ca(true);
  15050. cli.enable_server_certificate_verification(true);
  15051. auto res = cli.Get("/");
  15052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15053. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15054. }
  15055. // The custom CA remains effective when combined with the system CA
  15056. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  15057. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15058. ASSERT_TRUE(svr.is_valid());
  15059. svr.Get("/test", [&](const Request &, Response &res) {
  15060. res.set_content("test", "text/plain");
  15061. });
  15062. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15063. auto se = detail::scope_exit([&] {
  15064. svr.stop();
  15065. t.join();
  15066. ASSERT_FALSE(svr.is_running());
  15067. });
  15068. svr.wait_until_ready();
  15069. SSLClient cli("127.0.0.1", PORT);
  15070. std::string cert;
  15071. read_file(SERVER_CERT2_FILE, cert);
  15072. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15073. cli.enable_system_ca(true);
  15074. cli.enable_server_certificate_verification(true);
  15075. cli.set_connection_timeout(30);
  15076. auto res = cli.Get("/test");
  15077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15078. ASSERT_EQ(StatusCode::OK_200, res->status);
  15079. }
  15080. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15081. // skip chain verification entirely (only the certificate identity was
  15082. // checked), so a server presenting an untrusted certificate with a matching
  15083. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15084. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15085. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15086. ASSERT_TRUE(svr.is_valid());
  15087. svr.Get("/test", [&](const Request &, Response &res) {
  15088. res.set_content("test", "text/plain");
  15089. });
  15090. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15091. auto se = detail::scope_exit([&] {
  15092. svr.stop();
  15093. t.join();
  15094. ASSERT_FALSE(svr.is_running());
  15095. });
  15096. svr.wait_until_ready();
  15097. SSLClient cli("127.0.0.1", PORT);
  15098. std::string cert;
  15099. // A trusted CA that did not sign the server certificate. The server cert
  15100. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15101. // this connection.
  15102. read_file(CLIENT_CA_CERT_FILE, cert);
  15103. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15104. cli.enable_server_certificate_verification(true);
  15105. cli.set_connection_timeout(30);
  15106. auto res = cli.Get("/test");
  15107. ASSERT_FALSE(res);
  15108. }
  15109. // enable_system_ca(false) prevents system CA loading entirely
  15110. TEST(SSLClientTest, DisableSystemCa_Online) {
  15111. SSLClient cli("google.com");
  15112. cli.enable_system_ca(false);
  15113. cli.enable_server_certificate_verification(true);
  15114. auto res = cli.Get("/");
  15115. ASSERT_FALSE(res);
  15116. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15117. // itself when the CA chain is empty
  15118. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15119. res.error() == Error::SSLConnection);
  15120. }
  15121. // The universal Client forwards enable_system_ca()
  15122. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15123. std::string cert;
  15124. read_file(SERVER_CERT2_FILE, cert);
  15125. Client cli("https://google.com");
  15126. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15127. cli.enable_system_ca(true);
  15128. cli.enable_server_certificate_verification(true);
  15129. auto res = cli.Get("/");
  15130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15131. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15132. }
  15133. // The system CA policy must carry over to the client created internally for
  15134. // following a cross-host HTTPS redirect
  15135. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15136. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15137. ASSERT_TRUE(svr.is_valid());
  15138. svr.Get("/index", [&](const Request &, Response &res) {
  15139. res.set_redirect("https://www.google.com/");
  15140. });
  15141. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15142. auto se = detail::scope_exit([&] {
  15143. svr.stop();
  15144. t.join();
  15145. ASSERT_FALSE(svr.is_running());
  15146. });
  15147. svr.wait_until_ready();
  15148. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15149. std::string cert;
  15150. read_file(SERVER_CERT2_FILE, cert);
  15151. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15152. cli.enable_system_ca(true);
  15153. cli.enable_server_certificate_verification(true);
  15154. cli.set_follow_location(true);
  15155. cli.set_connection_timeout(30);
  15156. // Receiving any response proves the redirect client completed the TLS
  15157. // handshake with a system-CA-signed host
  15158. auto res = cli.Get("/index");
  15159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15160. }
  15161. TEST(MultipartFormDataTest, LargeData) {
  15162. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15163. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15164. const ContentReader &content_reader) {
  15165. if (req.is_multipart_form_data()) {
  15166. std::vector<FormData> items;
  15167. content_reader(
  15168. [&](const FormData &file) {
  15169. items.push_back(file);
  15170. return true;
  15171. },
  15172. [&](const char *data, size_t data_length) {
  15173. items.back().content.append(data, data_length);
  15174. return true;
  15175. });
  15176. EXPECT_TRUE(std::string(items[0].name) == "document");
  15177. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15178. EXPECT_TRUE(items[0].filename == "2MB_data");
  15179. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15180. EXPECT_TRUE(items[1].name == "hello");
  15181. EXPECT_TRUE(items[1].content == "world");
  15182. EXPECT_TRUE(items[1].filename == "");
  15183. EXPECT_TRUE(items[1].content_type == "");
  15184. } else {
  15185. std::string body;
  15186. content_reader([&](const char *data, size_t data_length) {
  15187. body.append(data, data_length);
  15188. return true;
  15189. });
  15190. }
  15191. });
  15192. auto port = svr.bind_to_any_port(HOST);
  15193. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15194. auto se = detail::scope_exit([&] {
  15195. svr.stop();
  15196. t.join();
  15197. ASSERT_FALSE(svr.is_running());
  15198. });
  15199. svr.wait_until_ready();
  15200. {
  15201. std::string data(1024 * 1024 * 2, '.');
  15202. std::stringstream buffer;
  15203. buffer << data;
  15204. SSLClient cli(HOST, port);
  15205. cli.enable_server_certificate_verification(false);
  15206. UploadFormDataItems items{
  15207. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15208. {"hello", "world", "", ""},
  15209. };
  15210. auto res = cli.Post("/post", items);
  15211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15212. ASSERT_EQ(StatusCode::OK_200, res->status);
  15213. }
  15214. }
  15215. TEST(MultipartFormDataTest, DataProviderItems) {
  15216. std::random_device seed_gen;
  15217. std::mt19937 random(seed_gen());
  15218. std::string rand1;
  15219. rand1.resize(1000);
  15220. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15221. std::string rand2;
  15222. rand2.resize(3000);
  15223. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15224. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15225. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15226. const ContentReader &content_reader) {
  15227. ASSERT_FALSE(req.is_multipart_form_data());
  15228. std::string body;
  15229. content_reader([&](const char *data, size_t data_length) {
  15230. body.append(data, data_length);
  15231. return true;
  15232. });
  15233. EXPECT_EQ(body, "");
  15234. });
  15235. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15236. const ContentReader &content_reader) {
  15237. ASSERT_TRUE(req.is_multipart_form_data());
  15238. std::vector<FormData> items;
  15239. content_reader(
  15240. [&](const FormData &file) {
  15241. items.push_back(file);
  15242. return true;
  15243. },
  15244. [&](const char *data, size_t data_length) {
  15245. items.back().content.append(data, data_length);
  15246. return true;
  15247. });
  15248. ASSERT_TRUE(items.size() == 2);
  15249. EXPECT_EQ(std::string(items[0].name), "name1");
  15250. EXPECT_EQ(items[0].content, "Testing123");
  15251. EXPECT_EQ(items[0].filename, "filename1");
  15252. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15253. EXPECT_EQ(items[1].name, "name2");
  15254. EXPECT_EQ(items[1].content, "Testing456");
  15255. EXPECT_EQ(items[1].filename, "");
  15256. EXPECT_EQ(items[1].content_type, "");
  15257. });
  15258. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15259. const ContentReader &content_reader) {
  15260. ASSERT_TRUE(req.is_multipart_form_data());
  15261. std::vector<FormData> items;
  15262. content_reader(
  15263. [&](const FormData &file) {
  15264. items.push_back(file);
  15265. return true;
  15266. },
  15267. [&](const char *data, size_t data_length) {
  15268. items.back().content.append(data, data_length);
  15269. return true;
  15270. });
  15271. ASSERT_TRUE(items.size() == 2);
  15272. EXPECT_EQ(items[0].name, "name3");
  15273. EXPECT_EQ(items[0].content, rand1);
  15274. EXPECT_EQ(items[0].filename, "filename3");
  15275. EXPECT_EQ(items[0].content_type, "");
  15276. EXPECT_EQ(items[1].name, "name4");
  15277. EXPECT_EQ(items[1].content, rand2);
  15278. EXPECT_EQ(items[1].filename, "filename4");
  15279. EXPECT_EQ(items[1].content_type, "");
  15280. });
  15281. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15282. const ContentReader &content_reader) {
  15283. ASSERT_TRUE(req.is_multipart_form_data());
  15284. std::vector<FormData> items;
  15285. content_reader(
  15286. [&](const FormData &file) {
  15287. items.push_back(file);
  15288. return true;
  15289. },
  15290. [&](const char *data, size_t data_length) {
  15291. items.back().content.append(data, data_length);
  15292. return true;
  15293. });
  15294. ASSERT_TRUE(items.size() == 4);
  15295. EXPECT_EQ(std::string(items[0].name), "name1");
  15296. EXPECT_EQ(items[0].content, "Testing123");
  15297. EXPECT_EQ(items[0].filename, "filename1");
  15298. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15299. EXPECT_EQ(items[1].name, "name2");
  15300. EXPECT_EQ(items[1].content, "Testing456");
  15301. EXPECT_EQ(items[1].filename, "");
  15302. EXPECT_EQ(items[1].content_type, "");
  15303. EXPECT_EQ(items[2].name, "name3");
  15304. EXPECT_EQ(items[2].content, rand1);
  15305. EXPECT_EQ(items[2].filename, "filename3");
  15306. EXPECT_EQ(items[2].content_type, "");
  15307. EXPECT_EQ(items[3].name, "name4");
  15308. EXPECT_EQ(items[3].content, rand2);
  15309. EXPECT_EQ(items[3].filename, "filename4");
  15310. EXPECT_EQ(items[3].content_type, "");
  15311. });
  15312. auto port = svr.bind_to_any_port("localhost");
  15313. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15314. auto se = detail::scope_exit([&] {
  15315. svr.stop();
  15316. t.join();
  15317. ASSERT_FALSE(svr.is_running());
  15318. });
  15319. svr.wait_until_ready();
  15320. {
  15321. SSLClient cli("localhost", port);
  15322. cli.enable_server_certificate_verification(false);
  15323. UploadFormDataItems items{
  15324. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15325. {"name2", "Testing456", "", ""}, // not a file
  15326. };
  15327. {
  15328. auto res = cli.Post("/post-none", {}, {}, {});
  15329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15330. ASSERT_EQ(StatusCode::OK_200, res->status);
  15331. }
  15332. FormDataProviderItems providers;
  15333. {
  15334. auto res =
  15335. cli.Post("/post-items", {}, items, providers); // empty providers
  15336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15337. ASSERT_EQ(StatusCode::OK_200, res->status);
  15338. }
  15339. providers.push_back({"name3",
  15340. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15341. // test the offset is given correctly at each step
  15342. if (!offset)
  15343. sink.os.write(rand1.data(), 30);
  15344. else if (offset == 30)
  15345. sink.os.write(rand1.data() + 30, 300);
  15346. else if (offset == 330)
  15347. sink.os.write(rand1.data() + 330, 670);
  15348. else if (offset == rand1.size())
  15349. sink.done();
  15350. return true;
  15351. },
  15352. "filename3",
  15353. {}});
  15354. providers.push_back({"name4",
  15355. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15356. // test the offset is given correctly at each step
  15357. if (!offset)
  15358. sink.os.write(rand2.data(), 2000);
  15359. else if (offset == 2000)
  15360. sink.os.write(rand2.data() + 2000, 1);
  15361. else if (offset == 2001)
  15362. sink.os.write(rand2.data() + 2001, 999);
  15363. else if (offset == rand2.size())
  15364. sink.done();
  15365. return true;
  15366. },
  15367. "filename4",
  15368. {}});
  15369. {
  15370. auto res = cli.Post("/post-providers", {}, {}, providers);
  15371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15372. ASSERT_EQ(StatusCode::OK_200, res->status);
  15373. }
  15374. {
  15375. auto res = cli.Post("/post-both", {}, items, providers);
  15376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15377. ASSERT_EQ(StatusCode::OK_200, res->status);
  15378. }
  15379. }
  15380. }
  15381. TEST(MultipartFormDataTest, BadHeader) {
  15382. Server svr;
  15383. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15384. res.set_content("ok", "text/plain");
  15385. });
  15386. thread t = thread([&] { svr.listen(HOST, PORT); });
  15387. auto se = detail::scope_exit([&] {
  15388. svr.stop();
  15389. t.join();
  15390. ASSERT_FALSE(svr.is_running());
  15391. });
  15392. svr.wait_until_ready();
  15393. const std::string body =
  15394. "This is the preamble. It is to be ignored, though it\r\n"
  15395. "is a handy place for composition agents to include an\r\n"
  15396. "explanatory note to non-MIME conformant readers.\r\n"
  15397. "\r\n"
  15398. "\r\n"
  15399. "--simple boundary\r\n"
  15400. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15401. ": BAD...\r\n"
  15402. "\r\n"
  15403. "value1\r\n"
  15404. "--simple boundary\r\n"
  15405. "Content-Disposition: form-data; name=\"field2\"; "
  15406. "filename=\"example.txt\"\r\n"
  15407. "\r\n"
  15408. "value2\r\n"
  15409. "--simple boundary--\r\n"
  15410. "This is the epilogue. It is also to be ignored.\r\n";
  15411. std::string content_type =
  15412. R"(multipart/form-data; boundary="simple boundary")";
  15413. Client cli(HOST, PORT);
  15414. auto res = cli.Post("/post", body, content_type.c_str());
  15415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15416. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15417. }
  15418. TEST(MultipartFormDataTest, WithPreamble) {
  15419. Server svr;
  15420. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15421. res.set_content("ok", "text/plain");
  15422. });
  15423. thread t = thread([&] { svr.listen(HOST, PORT); });
  15424. auto se = detail::scope_exit([&] {
  15425. svr.stop();
  15426. t.join();
  15427. ASSERT_FALSE(svr.is_running());
  15428. });
  15429. svr.wait_until_ready();
  15430. const std::string body =
  15431. "This is the preamble. It is to be ignored, though it\r\n"
  15432. "is a handy place for composition agents to include an\r\n"
  15433. "explanatory note to non-MIME conformant readers.\r\n"
  15434. "\r\n"
  15435. "\r\n"
  15436. "--simple boundary\r\n"
  15437. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15438. "\r\n"
  15439. "value1\r\n"
  15440. "--simple boundary\r\n"
  15441. "Content-Disposition: form-data; name=\"field2\"; "
  15442. "filename=\"example.txt\"\r\n"
  15443. "\r\n"
  15444. "value2\r\n"
  15445. "--simple boundary--\r\n"
  15446. "This is the epilogue. It is also to be ignored.\r\n";
  15447. std::string content_type =
  15448. R"(multipart/form-data; boundary="simple boundary")";
  15449. Client cli(HOST, PORT);
  15450. auto res = cli.Post("/post", body, content_type.c_str());
  15451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15452. EXPECT_EQ(StatusCode::OK_200, res->status);
  15453. }
  15454. TEST(MultipartFormDataTest, PostCustomBoundary) {
  15455. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15456. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  15457. const ContentReader &content_reader) {
  15458. if (req.is_multipart_form_data()) {
  15459. std::vector<FormData> items;
  15460. content_reader(
  15461. [&](const FormData &file) {
  15462. items.push_back(file);
  15463. return true;
  15464. },
  15465. [&](const char *data, size_t data_length) {
  15466. items.back().content.append(data, data_length);
  15467. return true;
  15468. });
  15469. EXPECT_TRUE(std::string(items[0].name) == "document");
  15470. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15471. EXPECT_TRUE(items[0].filename == "2MB_data");
  15472. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15473. EXPECT_TRUE(items[1].name == "hello");
  15474. EXPECT_TRUE(items[1].content == "world");
  15475. EXPECT_TRUE(items[1].filename == "");
  15476. EXPECT_TRUE(items[1].content_type == "");
  15477. } else {
  15478. std::string body;
  15479. content_reader([&](const char *data, size_t data_length) {
  15480. body.append(data, data_length);
  15481. return true;
  15482. });
  15483. }
  15484. });
  15485. auto port = svr.bind_to_any_port("localhost");
  15486. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15487. auto se = detail::scope_exit([&] {
  15488. svr.stop();
  15489. t.join();
  15490. ASSERT_FALSE(svr.is_running());
  15491. });
  15492. svr.wait_until_ready();
  15493. {
  15494. std::string data(1024 * 1024 * 2, '.');
  15495. std::stringstream buffer;
  15496. buffer << data;
  15497. SSLClient cli("localhost", port);
  15498. cli.enable_server_certificate_verification(false);
  15499. UploadFormDataItems items{
  15500. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15501. {"hello", "world", "", ""},
  15502. };
  15503. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  15504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15505. ASSERT_EQ(StatusCode::OK_200, res->status);
  15506. }
  15507. }
  15508. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  15509. std::string data(1024 * 1024 * 2, '&');
  15510. std::stringstream buffer;
  15511. buffer << data;
  15512. Client cli("https://localhost:8080");
  15513. UploadFormDataItems items{
  15514. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15515. {"hello", "world", "", ""},
  15516. };
  15517. for (const char &c : " \t\r\n") {
  15518. auto res =
  15519. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  15520. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15521. ASSERT_FALSE(res);
  15522. }
  15523. }
  15524. TEST(MultipartFormDataTest, PutFormData) {
  15525. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15526. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  15527. const ContentReader &content_reader) {
  15528. if (req.is_multipart_form_data()) {
  15529. std::vector<FormData> items;
  15530. content_reader(
  15531. [&](const FormData &file) {
  15532. items.push_back(file);
  15533. return true;
  15534. },
  15535. [&](const char *data, size_t data_length) {
  15536. items.back().content.append(data, data_length);
  15537. return true;
  15538. });
  15539. EXPECT_TRUE(std::string(items[0].name) == "document");
  15540. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15541. EXPECT_TRUE(items[0].filename == "2MB_data");
  15542. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15543. EXPECT_TRUE(items[1].name == "hello");
  15544. EXPECT_TRUE(items[1].content == "world");
  15545. EXPECT_TRUE(items[1].filename == "");
  15546. EXPECT_TRUE(items[1].content_type == "");
  15547. } else {
  15548. std::string body;
  15549. content_reader([&](const char *data, size_t data_length) {
  15550. body.append(data, data_length);
  15551. return true;
  15552. });
  15553. }
  15554. });
  15555. auto port = svr.bind_to_any_port("localhost");
  15556. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15557. auto se = detail::scope_exit([&] {
  15558. svr.stop();
  15559. t.join();
  15560. ASSERT_FALSE(svr.is_running());
  15561. });
  15562. svr.wait_until_ready();
  15563. {
  15564. std::string data(1024 * 1024 * 2, '&');
  15565. std::stringstream buffer;
  15566. buffer << data;
  15567. SSLClient cli("localhost", port);
  15568. cli.enable_server_certificate_verification(false);
  15569. UploadFormDataItems items{
  15570. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15571. {"hello", "world", "", ""},
  15572. };
  15573. auto res = cli.Put("/put", items);
  15574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15575. ASSERT_EQ(StatusCode::OK_200, res->status);
  15576. }
  15577. }
  15578. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  15579. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15580. svr.Put("/put_customboundary",
  15581. [&](const Request &req, const Response & /*res*/,
  15582. const ContentReader &content_reader) {
  15583. if (req.is_multipart_form_data()) {
  15584. std::vector<FormData> items;
  15585. content_reader(
  15586. [&](const FormData &file) {
  15587. items.push_back(file);
  15588. return true;
  15589. },
  15590. [&](const char *data, size_t data_length) {
  15591. items.back().content.append(data, data_length);
  15592. return true;
  15593. });
  15594. EXPECT_TRUE(std::string(items[0].name) == "document");
  15595. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15596. EXPECT_TRUE(items[0].filename == "2MB_data");
  15597. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15598. EXPECT_TRUE(items[1].name == "hello");
  15599. EXPECT_TRUE(items[1].content == "world");
  15600. EXPECT_TRUE(items[1].filename == "");
  15601. EXPECT_TRUE(items[1].content_type == "");
  15602. } else {
  15603. std::string body;
  15604. content_reader([&](const char *data, size_t data_length) {
  15605. body.append(data, data_length);
  15606. return true;
  15607. });
  15608. }
  15609. });
  15610. auto port = svr.bind_to_any_port("localhost");
  15611. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15612. auto se = detail::scope_exit([&] {
  15613. svr.stop();
  15614. t.join();
  15615. ASSERT_FALSE(svr.is_running());
  15616. });
  15617. svr.wait_until_ready();
  15618. {
  15619. std::string data(1024 * 1024 * 2, '&');
  15620. std::stringstream buffer;
  15621. buffer << data;
  15622. SSLClient cli("localhost", port);
  15623. cli.enable_server_certificate_verification(false);
  15624. UploadFormDataItems items{
  15625. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15626. {"hello", "world", "", ""},
  15627. };
  15628. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  15629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15630. ASSERT_EQ(StatusCode::OK_200, res->status);
  15631. }
  15632. }
  15633. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  15634. std::string data(1024 * 1024 * 2, '&');
  15635. std::stringstream buffer;
  15636. buffer << data;
  15637. Client cli("https://localhost:8080");
  15638. cli.enable_server_certificate_verification(false);
  15639. UploadFormDataItems items{
  15640. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15641. {"hello", "world", "", ""},
  15642. };
  15643. for (const char &c : " \t\r\n") {
  15644. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  15645. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15646. ASSERT_FALSE(res);
  15647. }
  15648. }
  15649. TEST(MultipartFormDataTest, AlternateFilename) {
  15650. auto handled = false;
  15651. Server svr;
  15652. svr.Post("/test", [&](const Request &req, Response &res) {
  15653. ASSERT_EQ(2u, req.form.files.size());
  15654. ASSERT_EQ(1u, req.form.fields.size());
  15655. // Test files
  15656. const auto &file1 = req.form.get_file("file1");
  15657. ASSERT_EQ("file1", file1.name);
  15658. ASSERT_EQ("A.txt", file1.filename);
  15659. ASSERT_EQ("text/plain", file1.content_type);
  15660. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  15661. const auto &file2 = req.form.get_file("file2");
  15662. ASSERT_EQ("file2", file2.name);
  15663. ASSERT_EQ("a.html", file2.filename);
  15664. ASSERT_EQ("text/html", file2.content_type);
  15665. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  15666. file2.content);
  15667. // Test text field
  15668. const auto &text = req.form.get_field("text");
  15669. ASSERT_EQ("text default", text);
  15670. res.set_content("ok", "text/plain");
  15671. handled = true;
  15672. });
  15673. thread t = thread([&] { svr.listen(HOST, PORT); });
  15674. auto se = detail::scope_exit([&] {
  15675. svr.stop();
  15676. t.join();
  15677. ASSERT_FALSE(svr.is_running());
  15678. ASSERT_TRUE(handled);
  15679. });
  15680. svr.wait_until_ready();
  15681. auto req = "POST /test HTTP/1.1\r\n"
  15682. "Host: localhost\r\n"
  15683. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15684. "Content-Length: 399\r\n"
  15685. "\r\n"
  15686. "----------\r\n"
  15687. "Content-Disposition: form-data; name=\"text\"\r\n"
  15688. "\r\n"
  15689. "text default\r\n"
  15690. "----------\r\n"
  15691. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  15692. "filename=\"a.txt\"; name=\"file1\"\r\n"
  15693. "Content-Type: text/plain\r\n"
  15694. "\r\n"
  15695. "Content of a.txt.\r\n"
  15696. "\r\n"
  15697. "----------\r\n"
  15698. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  15699. "\"a.html\"\r\n"
  15700. "Content-Type: text/html\r\n"
  15701. "\r\n"
  15702. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  15703. "\r\n"
  15704. "------------\r\n";
  15705. ASSERT_TRUE(send_request(1, req));
  15706. }
  15707. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  15708. auto handled = false;
  15709. Server svr;
  15710. svr.Post("/test", [&](const Request &req, Response &res) {
  15711. // Case-insensitive "utf-8''" prefix with a long value
  15712. const auto &file = req.form.get_file("file1");
  15713. ASSERT_EQ("file1", file.name);
  15714. // 8000 chars exercises both the Content-Disposition parser and the
  15715. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  15716. // Prior to the fix, std::regex_match on this header would cause O(N)
  15717. // stack recursion in libstdc++, leading to SIGSEGV.
  15718. std::string expected_filename(8000, 'A');
  15719. ASSERT_EQ(expected_filename, file.filename);
  15720. res.set_content("ok", "text/plain");
  15721. handled = true;
  15722. });
  15723. thread t = thread([&] { svr.listen(HOST, PORT); });
  15724. auto se = detail::scope_exit([&] {
  15725. svr.stop();
  15726. t.join();
  15727. ASSERT_FALSE(svr.is_running());
  15728. ASSERT_TRUE(handled);
  15729. });
  15730. svr.wait_until_ready();
  15731. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  15732. // Regression test for GHSA-qq6v-r583-3h69
  15733. std::string long_filename(8000, 'A');
  15734. std::string body = "----------\r\n"
  15735. "Content-Disposition: form-data; name=\"file1\"; "
  15736. "filename*=\"Utf-8''" +
  15737. long_filename +
  15738. "\"\r\n"
  15739. "\r\n"
  15740. "hello\r\n"
  15741. "------------\r\n";
  15742. auto req = "POST /test HTTP/1.1\r\n"
  15743. "Host: localhost\r\n"
  15744. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15745. "Content-Length: " +
  15746. std::to_string(body.size()) + "\r\n\r\n" + body;
  15747. ASSERT_TRUE(send_request(1, req));
  15748. }
  15749. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  15750. auto handled = false;
  15751. Server svr;
  15752. svr.Post("/test", [&](const Request &req, Response &) {
  15753. ASSERT_EQ(2u, req.form.fields.size());
  15754. const auto &text1 = req.form.get_field("text1");
  15755. ASSERT_EQ("text1", text1);
  15756. const auto &text2 = req.form.get_field("text2");
  15757. ASSERT_EQ("text2", text2);
  15758. handled = true;
  15759. });
  15760. thread t = thread([&] { svr.listen(HOST, PORT); });
  15761. auto se = detail::scope_exit([&] {
  15762. svr.stop();
  15763. t.join();
  15764. ASSERT_FALSE(svr.is_running());
  15765. ASSERT_TRUE(handled);
  15766. });
  15767. svr.wait_until_ready();
  15768. auto req = "POST /test HTTP/1.1\r\n"
  15769. "Host: localhost\r\n"
  15770. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15771. "Content-Length: 146\r\n"
  15772. "\r\n----------\r\n"
  15773. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15774. "\r\n"
  15775. "text1"
  15776. "\r\n----------\r\n"
  15777. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15778. "\r\n"
  15779. "text2"
  15780. "\r\n------------";
  15781. std::string response;
  15782. ASSERT_TRUE(send_request(1, req, &response));
  15783. ASSERT_EQ("200", response.substr(9, 3));
  15784. }
  15785. TEST(MultipartFormDataTest, ContentLength) {
  15786. auto handled = false;
  15787. Server svr;
  15788. svr.Post("/test", [&](const Request &req, Response &) {
  15789. ASSERT_EQ(2u, req.form.fields.size());
  15790. const auto &text1 = req.form.get_field("text1");
  15791. ASSERT_EQ("text1", text1);
  15792. const auto &text2 = req.form.get_field("text2");
  15793. ASSERT_EQ("text2", text2);
  15794. handled = true;
  15795. });
  15796. thread t = thread([&] { svr.listen(HOST, PORT); });
  15797. auto se = detail::scope_exit([&] {
  15798. svr.stop();
  15799. t.join();
  15800. ASSERT_FALSE(svr.is_running());
  15801. ASSERT_TRUE(handled);
  15802. });
  15803. svr.wait_until_ready();
  15804. auto req = "POST /test HTTP/1.1\r\n"
  15805. "Host: localhost\r\n"
  15806. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15807. "Content-Length: 167\r\n"
  15808. "\r\n----------\r\n"
  15809. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15810. "Content-Length: 5\r\n"
  15811. "\r\n"
  15812. "text1"
  15813. "\r\n----------\r\n"
  15814. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15815. "\r\n"
  15816. "text2"
  15817. "\r\n------------\r\n";
  15818. std::string response;
  15819. ASSERT_TRUE(send_request(1, req, &response));
  15820. ASSERT_EQ("200", response.substr(9, 3));
  15821. }
  15822. TEST(MultipartFormDataTest, AccessPartHeaders) {
  15823. auto handled = false;
  15824. Server svr;
  15825. svr.Post("/test", [&](const Request &req, Response &) {
  15826. ASSERT_EQ(2u, req.form.fields.size());
  15827. const auto &text1 = req.form.get_field("text1");
  15828. ASSERT_EQ("text1", text1);
  15829. // TODO: Add header access for text fields if needed
  15830. const auto &text2 = req.form.get_field("text2");
  15831. ASSERT_EQ("text2", text2);
  15832. // TODO: Header access for text fields needs to be implemented
  15833. // auto &headers = it->second.headers;
  15834. // ASSERT_EQ(3U, headers.size());
  15835. // auto custom_header = headers.find("x-whatever");
  15836. // ASSERT_TRUE(custom_header != headers.end());
  15837. // ASSERT_NE("customvalue", custom_header->second);
  15838. // ASSERT_EQ("CustomValue", custom_header->second);
  15839. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  15840. handled = true;
  15841. });
  15842. thread t = thread([&] { svr.listen(HOST, PORT); });
  15843. auto se = detail::scope_exit([&] {
  15844. svr.stop();
  15845. t.join();
  15846. ASSERT_FALSE(svr.is_running());
  15847. ASSERT_TRUE(handled);
  15848. });
  15849. svr.wait_until_ready();
  15850. auto req = "POST /test HTTP/1.1\r\n"
  15851. "Host: localhost\r\n"
  15852. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15853. "Content-Length: 232\r\n"
  15854. "\r\n----------\r\n"
  15855. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15856. "Content-Length: 5\r\n"
  15857. "X-Test: 1\r\n"
  15858. "\r\n"
  15859. "text1"
  15860. "\r\n----------\r\n"
  15861. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15862. "Content-Type: text/plain\r\n"
  15863. "X-Whatever: CustomValue\r\n"
  15864. "\r\n"
  15865. "text2"
  15866. "\r\n------------\r\n"
  15867. "That should be disregarded. Not even read";
  15868. std::string response;
  15869. ASSERT_TRUE(send_request(1, req, &response));
  15870. ASSERT_EQ("200", response.substr(9, 3));
  15871. }
  15872. TEST(MultipartFormDataTest, LargeHeader) {
  15873. auto handled = false;
  15874. Server svr;
  15875. svr.Post("/test", [&](const Request &req, Response &) {
  15876. ASSERT_EQ(1u, req.form.fields.size());
  15877. const auto &text = req.form.get_field("name1");
  15878. ASSERT_EQ("text1", text);
  15879. handled = true;
  15880. });
  15881. thread t = thread([&] { svr.listen(HOST, PORT); });
  15882. auto se = detail::scope_exit([&] {
  15883. svr.stop();
  15884. t.join();
  15885. ASSERT_FALSE(svr.is_running());
  15886. ASSERT_TRUE(handled);
  15887. });
  15888. svr.wait_until_ready();
  15889. auto boundary = std::string("cpp-httplib-multipart-data");
  15890. std::string content = "--" + boundary +
  15891. "\r\n"
  15892. "Content-Disposition: form-data; name=\"name1\"\r\n"
  15893. "\r\n"
  15894. "text1\r\n"
  15895. "--" +
  15896. boundary + "--\r\n";
  15897. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  15898. "Host: localhost\r\n"
  15899. "Content-Type: multipart/form-data;boundary=" +
  15900. boundary +
  15901. "\r\n"
  15902. "Content-Length: " +
  15903. std::to_string(content.size()) +
  15904. "\r\n"
  15905. "Dummy-Header: ";
  15906. std::string header_suffix = "\r\n"
  15907. "\r\n";
  15908. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  15909. size_t header_dummy_size =
  15910. read_buff_size -
  15911. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  15912. auto header_dummy = std::string(header_dummy_size, '@');
  15913. auto req = header_prefix + header_dummy + header_suffix + content;
  15914. std::string response;
  15915. ASSERT_TRUE(send_request(1, req, &response));
  15916. ASSERT_EQ("200", response.substr(9, 3));
  15917. }
  15918. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  15919. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  15920. // (not chunked Transfer-Encoding) after the streaming refactor.
  15921. auto handled = false;
  15922. Server svr;
  15923. svr.Post("/upload", [&](const Request &req, Response &res) {
  15924. auto cl_it = req.headers.find("Content-Length");
  15925. EXPECT_TRUE(cl_it != req.headers.end());
  15926. auto te_it = req.headers.find("Transfer-Encoding");
  15927. EXPECT_TRUE(te_it == req.headers.end());
  15928. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  15929. res.set_content("ok", "text/plain");
  15930. handled = true;
  15931. });
  15932. auto port = svr.bind_to_any_port(HOST);
  15933. auto t = thread([&] { svr.listen_after_bind(); });
  15934. auto se = detail::scope_exit([&] {
  15935. svr.stop();
  15936. t.join();
  15937. ASSERT_FALSE(svr.is_running());
  15938. ASSERT_TRUE(handled);
  15939. });
  15940. svr.wait_until_ready();
  15941. UploadFormDataItems items = {
  15942. {"field1", "hello", "", "text/plain"},
  15943. {"file1", "world", "test.txt", "application/octet-stream"},
  15944. };
  15945. Client cli(HOST, port);
  15946. auto res = cli.Post("/upload", {}, items);
  15947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15948. EXPECT_EQ(StatusCode::OK_200, res->status);
  15949. }
  15950. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  15951. // Verify that make_multipart_content_provider coalesces many small segments
  15952. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  15953. constexpr size_t kItemCount = 1000;
  15954. UploadFormDataItems items;
  15955. items.reserve(kItemCount);
  15956. for (size_t i = 0; i < kItemCount; i++) {
  15957. items.push_back(
  15958. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15959. }
  15960. const std::string boundary = "----test-boundary";
  15961. auto content_length = detail::get_multipart_content_length(items, boundary);
  15962. auto provider = detail::make_multipart_content_provider(items, boundary);
  15963. // Drive the provider the same way write_content_with_progress does
  15964. size_t write_count = 0;
  15965. size_t total_bytes = 0;
  15966. DataSink sink;
  15967. size_t offset = 0;
  15968. sink.write = [&](const char *d, size_t l) -> bool {
  15969. (void)d;
  15970. write_count++;
  15971. total_bytes += l;
  15972. offset += l;
  15973. return true;
  15974. };
  15975. sink.is_writable = []() -> bool { return true; };
  15976. while (offset < content_length) {
  15977. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  15978. }
  15979. EXPECT_EQ(content_length, total_bytes);
  15980. // The total number of segments is 3 * kItemCount + 1 = 3001.
  15981. // With buffering into 64KB blocks, write_count should be much smaller.
  15982. auto segment_count = 3 * kItemCount + 1;
  15983. EXPECT_LT(write_count, segment_count / 10);
  15984. }
  15985. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  15986. // Integration test: send many UploadFormDataItems and verify the server
  15987. // receives all of them correctly (#2410).
  15988. constexpr size_t kItemCount = 500;
  15989. auto handled = false;
  15990. Server svr;
  15991. svr.Post("/upload", [&](const Request &req, Response &res) {
  15992. EXPECT_EQ(kItemCount, req.form.fields.size());
  15993. for (size_t i = 0; i < kItemCount; i++) {
  15994. auto key = "field" + std::to_string(i);
  15995. auto val = "value" + std::to_string(i);
  15996. auto it = req.form.fields.find(key);
  15997. if (it != req.form.fields.end()) {
  15998. EXPECT_EQ(val, it->second.content);
  15999. } else {
  16000. ADD_FAILURE() << "Missing field: " << key;
  16001. }
  16002. }
  16003. res.set_content("ok", "text/plain");
  16004. handled = true;
  16005. });
  16006. auto port = svr.bind_to_any_port(HOST);
  16007. auto t = thread([&] { svr.listen_after_bind(); });
  16008. auto se = detail::scope_exit([&] {
  16009. svr.stop();
  16010. t.join();
  16011. ASSERT_FALSE(svr.is_running());
  16012. ASSERT_TRUE(handled);
  16013. });
  16014. svr.wait_until_ready();
  16015. UploadFormDataItems items;
  16016. items.reserve(kItemCount);
  16017. for (size_t i = 0; i < kItemCount; i++) {
  16018. items.push_back(
  16019. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16020. }
  16021. Client cli(HOST, port);
  16022. auto res = cli.Post("/upload", items);
  16023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16024. EXPECT_EQ(StatusCode::OK_200, res->status);
  16025. }
  16026. TEST(MultipartFormDataTest, MakeFileProvider) {
  16027. // Verify make_file_provider sends a file's contents correctly.
  16028. const std::string file_content(4096, 'Z');
  16029. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  16030. {
  16031. std::ofstream ofs(tmp_path, std::ios::binary);
  16032. ofs.write(file_content.data(),
  16033. static_cast<std::streamsize>(file_content.size()));
  16034. }
  16035. auto handled = false;
  16036. Server svr;
  16037. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  16038. const ContentReader &content_reader) {
  16039. ASSERT_TRUE(req.is_multipart_form_data());
  16040. std::vector<FormData> items;
  16041. content_reader(
  16042. [&](const FormData &file) {
  16043. items.push_back(file);
  16044. return true;
  16045. },
  16046. [&](const char *data, size_t data_length) {
  16047. items.back().content.append(data, data_length);
  16048. return true;
  16049. });
  16050. ASSERT_EQ(1u, items.size());
  16051. EXPECT_EQ("myfile", items[0].name);
  16052. EXPECT_EQ("data.bin", items[0].filename);
  16053. EXPECT_EQ("application/octet-stream", items[0].content_type);
  16054. EXPECT_EQ(file_content, items[0].content);
  16055. handled = true;
  16056. });
  16057. auto port = svr.bind_to_any_port(HOST);
  16058. auto t = thread([&] { svr.listen_after_bind(); });
  16059. auto se = detail::scope_exit([&] {
  16060. svr.stop();
  16061. t.join();
  16062. ASSERT_FALSE(svr.is_running());
  16063. ASSERT_TRUE(handled);
  16064. std::remove(tmp_path.c_str());
  16065. });
  16066. svr.wait_until_ready();
  16067. FormDataProviderItems providers;
  16068. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  16069. "application/octet-stream"));
  16070. Client cli(HOST, port);
  16071. auto res = cli.Post("/upload", {}, {}, providers);
  16072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16073. EXPECT_EQ(StatusCode::OK_200, res->status);
  16074. }
  16075. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  16076. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  16077. // (100) headers is rejected with a 400 Bad Request response.
  16078. Server svr;
  16079. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16080. res.set_content("ok", "text/plain");
  16081. });
  16082. thread t = thread([&] { svr.listen(HOST, PORT); });
  16083. auto se = detail::scope_exit([&] {
  16084. svr.stop();
  16085. t.join();
  16086. ASSERT_FALSE(svr.is_running());
  16087. });
  16088. svr.wait_until_ready();
  16089. // Build a multipart part with 101 custom headers (exceeding
  16090. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  16091. std::stringstream body;
  16092. body << "--simpleboundary\r\n"
  16093. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  16094. for (int i = 0; i < 101; i++) {
  16095. body << "X-Custom-Header-" << i << ": value\r\n";
  16096. }
  16097. body << "\r\n"
  16098. << "value1\r\n"
  16099. << "--simpleboundary--\r\n";
  16100. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16101. Client cli(HOST, PORT);
  16102. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16104. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16105. }
  16106. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16107. // A body that never contains the declared boundary must not be accumulated
  16108. // while the parser waits for it. Buffering it would also make every read
  16109. // rescan everything seen so far, which is quadratic in the body size.
  16110. Server svr;
  16111. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16112. res.set_content("ok", "text/plain");
  16113. });
  16114. auto port = svr.bind_to_any_port(HOST);
  16115. thread t = thread([&] { svr.listen_after_bind(); });
  16116. auto se = detail::scope_exit([&] {
  16117. svr.stop();
  16118. t.join();
  16119. ASSERT_FALSE(svr.is_running());
  16120. });
  16121. svr.wait_until_ready();
  16122. Client cli(HOST, port);
  16123. cli.set_read_timeout(60, 0);
  16124. cli.set_write_timeout(60, 0);
  16125. // '-' is the worst case: it matches the first character of the boundary, so
  16126. // every position has to be checked against it.
  16127. auto post_dashes = [&](size_t size) {
  16128. const std::string body(size, '-');
  16129. auto start = std::chrono::steady_clock::now();
  16130. auto res =
  16131. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16132. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16133. std::chrono::steady_clock::now() - start)
  16134. .count();
  16135. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16136. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16137. return ms;
  16138. };
  16139. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16140. // Windows.
  16141. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16142. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16143. // Comparing the two sizes rather than checking an absolute duration keeps
  16144. // this meaningful across build types and CI load, both of which move the
  16145. // absolute numbers by more than an order of magnitude. Four times the bytes
  16146. // costs about four times the time when parsing is linear, and about sixteen
  16147. // times when the body is buffered and rescanned.
  16148. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16149. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16150. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16151. << "ms, which suggests the body is being buffered and rescanned";
  16152. }
  16153. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16154. // A boundary can only be followed by CRLF or by "--", so anything else is
  16155. // malformed no matter what comes next. The parser must say so right away
  16156. // instead of buffering the rest of the declared body.
  16157. Server svr;
  16158. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16159. res.set_content("ok", "text/plain");
  16160. });
  16161. auto port = svr.bind_to_any_port(HOST);
  16162. thread t = thread([&] { svr.listen_after_bind(); });
  16163. auto se = detail::scope_exit([&] {
  16164. svr.stop();
  16165. t.join();
  16166. ASSERT_FALSE(svr.is_running());
  16167. });
  16168. svr.wait_until_ready();
  16169. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16170. // buffers instead of failing would still be waiting for the remaining bytes.
  16171. const std::string body = "--zzzz\r\n"
  16172. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16173. "\r\n"
  16174. "text1"
  16175. "\r\n--zzzzXX";
  16176. const std::string req = "POST /post HTTP/1.1\r\n"
  16177. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16178. "Content-Length: 1048576\r\n"
  16179. "\r\n" +
  16180. body;
  16181. std::string response;
  16182. ASSERT_TRUE(send_request(3, req, &response, port));
  16183. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16184. EXPECT_EQ("400", response.substr(9, 3));
  16185. }
  16186. // Posts a multipart body split into two writes, so that the server sees the
  16187. // split at whatever offset the caller chose, and expects the single "text1"
  16188. // field to come through.
  16189. static void expect_split_multipart_ok(const std::string &body1,
  16190. const std::string &body2) {
  16191. auto handled = false;
  16192. Server svr;
  16193. svr.Post("/post", [&](const Request &req, Response &) {
  16194. EXPECT_EQ(1u, req.form.fields.size());
  16195. EXPECT_EQ("text1", req.form.get_field("text1"));
  16196. handled = true;
  16197. });
  16198. auto port = svr.bind_to_any_port(HOST);
  16199. thread t = thread([&] { svr.listen_after_bind(); });
  16200. auto se = detail::scope_exit([&] {
  16201. svr.stop();
  16202. t.join();
  16203. ASSERT_FALSE(svr.is_running());
  16204. ASSERT_TRUE(handled);
  16205. });
  16206. svr.wait_until_ready();
  16207. // "Connection: close" makes the server close once it has answered, so the
  16208. // response drain ends immediately instead of idling until the read timeout.
  16209. const std::string head =
  16210. "POST /post HTTP/1.1\r\n"
  16211. "Host: localhost\r\n"
  16212. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16213. "Connection: close\r\n"
  16214. "Content-Length: " +
  16215. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16216. std::string response;
  16217. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16218. ASSERT_GE(response.size(), 12u) << "no response";
  16219. EXPECT_EQ("200", response.substr(9, 3));
  16220. }
  16221. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16222. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16223. // ignored, including when it does not arrive in the same read as the
  16224. // close-delimiter itself.
  16225. expect_split_multipart_ok("--zzzz\r\n"
  16226. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16227. "\r\n"
  16228. "text1"
  16229. "\r\n--zzzz--",
  16230. "\r\nthis epilogue must be ignored\r\n");
  16231. }
  16232. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16233. // The initial boundary may be preceded by a preamble of any length and may
  16234. // straddle a read boundary. Discarding data while waiting for it must not
  16235. // throw away a partial boundary sitting at the end of the buffer.
  16236. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16237. "zz\r\n"
  16238. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16239. "\r\n"
  16240. "text1"
  16241. "\r\n--zzzz--\r\n");
  16242. }
  16243. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16244. // The received boundary was only checked for being non-empty, so it could be
  16245. // as long as a header is allowed to be. The parser scans the body for
  16246. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16247. // costs a nearly full comparison at nearly every position, making the
  16248. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16249. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16250. Server svr;
  16251. svr.Post("/post", [](const Request &req, Response &res) {
  16252. EXPECT_EQ(1u, req.form.fields.size());
  16253. EXPECT_EQ("text1", req.form.get_field("text1"));
  16254. res.set_content("ok", "text/plain");
  16255. });
  16256. auto port = svr.bind_to_any_port(HOST);
  16257. thread t = thread([&] { svr.listen_after_bind(); });
  16258. auto se = detail::scope_exit([&] {
  16259. svr.stop();
  16260. t.join();
  16261. ASSERT_FALSE(svr.is_running());
  16262. });
  16263. svr.wait_until_ready();
  16264. Client cli(HOST, port);
  16265. auto post_with_boundary_of_length = [&](size_t len) {
  16266. const std::string boundary(len, 'a');
  16267. const std::string body =
  16268. "--" + boundary +
  16269. "\r\n"
  16270. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16271. "\r\n"
  16272. "text1"
  16273. "\r\n--" +
  16274. boundary + "--\r\n";
  16275. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16276. };
  16277. auto res = post_with_boundary_of_length(70);
  16278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16279. EXPECT_EQ(StatusCode::OK_200, res->status);
  16280. res = post_with_boundary_of_length(71);
  16281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16282. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16283. }
  16284. TEST(MakeFileBodyTest, Basic) {
  16285. const std::string file_content(4096, 'Z');
  16286. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16287. {
  16288. std::ofstream ofs(tmp_path, std::ios::binary);
  16289. ofs.write(file_content.data(),
  16290. static_cast<std::streamsize>(file_content.size()));
  16291. }
  16292. auto handled = false;
  16293. Server svr;
  16294. svr.Post("/upload", [&](const Request &req, Response &res) {
  16295. EXPECT_EQ(file_content, req.body);
  16296. handled = true;
  16297. res.status = StatusCode::OK_200;
  16298. });
  16299. auto port = svr.bind_to_any_port(HOST);
  16300. auto t = thread([&] { svr.listen_after_bind(); });
  16301. auto se = detail::scope_exit([&] {
  16302. svr.stop();
  16303. t.join();
  16304. ASSERT_FALSE(svr.is_running());
  16305. ASSERT_TRUE(handled);
  16306. std::remove(tmp_path.c_str());
  16307. });
  16308. svr.wait_until_ready();
  16309. auto fb = make_file_body(tmp_path);
  16310. ASSERT_GT(fb.first, 0u);
  16311. Client cli(HOST, port);
  16312. auto res =
  16313. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16315. EXPECT_EQ(StatusCode::OK_200, res->status);
  16316. }
  16317. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16318. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16319. {
  16320. std::ofstream ofs(path, std::ios::binary);
  16321. const std::string content(100, 'A');
  16322. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16323. }
  16324. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16325. auto body = make_file_body(path);
  16326. ASSERT_EQ(100u, body.first);
  16327. ASSERT_TRUE(static_cast<bool>(body.second));
  16328. // Rewritten shorter after its length was measured - and, on a server, after
  16329. // that length has already gone out as Content-Length.
  16330. {
  16331. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16332. const std::string content(10, 'A');
  16333. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16334. }
  16335. std::string written;
  16336. DataSink sink;
  16337. sink.write = [&](const char *d, size_t l) {
  16338. written.append(d, l);
  16339. return true;
  16340. };
  16341. // The provider has to report failure. write_content_with_progress() advances
  16342. // its offset only by what was written, so a provider that returns true
  16343. // without completing the length it promised is called again straight away,
  16344. // and again.
  16345. EXPECT_FALSE(body.second(0, body.first, sink));
  16346. EXPECT_EQ(std::string(10, 'A'), written);
  16347. }
  16348. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16349. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16350. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16351. {
  16352. std::ofstream ofs(path, std::ios::binary);
  16353. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16354. }
  16355. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16356. auto body = make_file_body(path);
  16357. ASSERT_EQ(content.size(), body.first);
  16358. ASSERT_TRUE(static_cast<bool>(body.second));
  16359. std::string written;
  16360. DataSink sink;
  16361. sink.write = [&](const char *d, size_t l) {
  16362. written.append(d, l);
  16363. return true;
  16364. };
  16365. EXPECT_TRUE(body.second(0, body.first, sink));
  16366. EXPECT_EQ(content, written);
  16367. }
  16368. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  16369. static constexpr unsigned int number_of_tasks{1000000};
  16370. std::atomic_uint count{0};
  16371. std::unique_ptr<TaskQueue> task_queue{
  16372. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  16373. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16374. auto queued = task_queue->enqueue(
  16375. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  16376. EXPECT_TRUE(queued);
  16377. }
  16378. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16379. task_queue->shutdown();
  16380. #else
  16381. EXPECT_NO_THROW(task_queue->shutdown());
  16382. #endif
  16383. EXPECT_EQ(number_of_tasks, count.load());
  16384. }
  16385. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  16386. static constexpr unsigned int number_of_tasks{1000000};
  16387. static constexpr unsigned int qlimit{2};
  16388. unsigned int queued_count{0};
  16389. std::atomic_uint count{0};
  16390. std::unique_ptr<TaskQueue> task_queue{
  16391. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  16392. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16393. if (task_queue->enqueue(
  16394. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  16395. queued_count++;
  16396. }
  16397. }
  16398. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16399. task_queue->shutdown();
  16400. #else
  16401. EXPECT_NO_THROW(task_queue->shutdown());
  16402. #endif
  16403. EXPECT_EQ(queued_count, count.load());
  16404. EXPECT_TRUE(queued_count <= number_of_tasks);
  16405. EXPECT_TRUE(queued_count >= qlimit);
  16406. }
  16407. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  16408. // Use a short idle timeout so a dynamic thread spawns, times out and
  16409. // exits during the test, and the pool keeps working afterwards.
  16410. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16411. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16412. /*idle_timeout_sec=*/1}};
  16413. std::atomic_uint count{0};
  16414. std::condition_variable cv;
  16415. std::mutex mtx;
  16416. bool release = false;
  16417. // Block the base thread so the second task spawns a dynamic thread.
  16418. EXPECT_TRUE(task_queue->enqueue([&] {
  16419. std::unique_lock<std::mutex> lock(mtx);
  16420. while (!release) {
  16421. cv.wait(lock);
  16422. }
  16423. count++;
  16424. }));
  16425. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16426. // Let the dynamic thread finish its task and exceed the idle timeout.
  16427. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16428. {
  16429. std::unique_lock<std::mutex> lock(mtx);
  16430. release = true;
  16431. }
  16432. cv.notify_all();
  16433. // The pool must still accept and run tasks after the dynamic thread exited.
  16434. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16435. task_queue->shutdown();
  16436. EXPECT_EQ(3u, count.load());
  16437. }
  16438. TEST(TaskQueueTest, MaxQueuedRequests) {
  16439. static constexpr unsigned int qlimit{3};
  16440. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  16441. std::condition_variable sem_cv;
  16442. std::mutex sem_mtx;
  16443. int credits = 0;
  16444. bool queued;
  16445. /* Fill up the queue with tasks that will block until we give them credits to
  16446. * complete. */
  16447. for (unsigned int n = 0; n <= qlimit;) {
  16448. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  16449. std::unique_lock<std::mutex> lock(sem_mtx);
  16450. while (credits <= 0) {
  16451. sem_cv.wait(lock);
  16452. }
  16453. /* Consume the credit and signal the test code if they are all gone. */
  16454. if (--credits == 0) { sem_cv.notify_one(); }
  16455. });
  16456. if (n < qlimit) {
  16457. /* The first qlimit enqueues must succeed. */
  16458. EXPECT_TRUE(queued);
  16459. } else {
  16460. /* The last one will succeed only when the worker thread
  16461. * starts and dequeues the first blocking task. Although
  16462. * not necessary for the correctness of this test, we sleep for
  16463. * a short while to avoid busy waiting. */
  16464. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16465. }
  16466. if (queued) { n++; }
  16467. }
  16468. /* Further enqueues must fail since the queue is full. */
  16469. for (auto i = 0; i < 4; i++) {
  16470. queued = task_queue->enqueue([] {});
  16471. EXPECT_FALSE(queued);
  16472. }
  16473. /* Give the credits to allow the previous tasks to complete. */
  16474. {
  16475. std::unique_lock<std::mutex> lock(sem_mtx);
  16476. credits += qlimit + 1;
  16477. }
  16478. sem_cv.notify_all();
  16479. /* Wait for all the credits to be consumed. */
  16480. {
  16481. std::unique_lock<std::mutex> lock(sem_mtx);
  16482. while (credits > 0) {
  16483. sem_cv.wait(lock);
  16484. }
  16485. }
  16486. /* Check that we are able again to enqueue at least qlimit tasks. */
  16487. for (unsigned int i = 0; i < qlimit; i++) {
  16488. queued = task_queue->enqueue([] {});
  16489. EXPECT_TRUE(queued);
  16490. }
  16491. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16492. task_queue->shutdown();
  16493. #else
  16494. EXPECT_NO_THROW(task_queue->shutdown());
  16495. #endif
  16496. }
  16497. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  16498. Server svr;
  16499. std::string method;
  16500. std::string body;
  16501. auto has_content_length = false;
  16502. auto has_transfer_encoding = false;
  16503. std::atomic<int> bad_requests{0};
  16504. // Leftover body bytes get parsed as a malformed request and answered with
  16505. // 400
  16506. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  16507. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  16508. });
  16509. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  16510. res.set_redirect("/down", StatusCode::SeeOther_303);
  16511. });
  16512. svr.Get("/down", [&](const Request &req, Response &res) {
  16513. method = req.method;
  16514. body = req.body;
  16515. has_content_length = req.has_header("Content-Length");
  16516. has_transfer_encoding = req.has_header("Transfer-Encoding");
  16517. res.set_content("ok", "text/plain");
  16518. });
  16519. auto port = svr.bind_to_any_port(HOST);
  16520. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16521. auto se = detail::scope_exit([&] {
  16522. svr.stop();
  16523. thread.join();
  16524. ASSERT_FALSE(svr.is_running());
  16525. });
  16526. svr.wait_until_ready();
  16527. const std::string payload = "SECRET-BODY";
  16528. auto check = [&](Client &cli, const Result &res) {
  16529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16530. EXPECT_EQ(StatusCode::OK_200, res->status);
  16531. EXPECT_EQ("ok", res->body);
  16532. EXPECT_EQ("GET", method);
  16533. EXPECT_TRUE(body.empty());
  16534. EXPECT_FALSE(has_content_length);
  16535. EXPECT_FALSE(has_transfer_encoding);
  16536. // Nothing of the original body may be left on the connection
  16537. auto res2 = cli.Get("/down");
  16538. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16539. EXPECT_EQ(StatusCode::OK_200, res2->status);
  16540. EXPECT_EQ("ok", res2->body);
  16541. EXPECT_EQ(0, bad_requests);
  16542. };
  16543. // With content length
  16544. {
  16545. Client cli(HOST, port);
  16546. cli.set_keep_alive(true);
  16547. cli.set_follow_location(true);
  16548. auto res = cli.Post(
  16549. "/up", payload.size(),
  16550. [&](size_t offset, size_t length, DataSink &sink) {
  16551. return sink.write(payload.data() + offset, length);
  16552. },
  16553. "text/plain");
  16554. check(cli, res);
  16555. }
  16556. // Without content length (chunked)
  16557. {
  16558. Client cli(HOST, port);
  16559. cli.set_keep_alive(true);
  16560. cli.set_follow_location(true);
  16561. auto res = cli.Post(
  16562. "/up",
  16563. [&](size_t /*offset*/, DataSink &sink) {
  16564. sink.write(payload.data(), payload.size());
  16565. sink.done();
  16566. return true;
  16567. },
  16568. "text/plain");
  16569. check(cli, res);
  16570. }
  16571. }
  16572. TEST(RedirectTest, LocationPathIsNotDecoded) {
  16573. Server svr;
  16574. std::string target;
  16575. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  16576. // Echo the still-encoded name back in the Location
  16577. const std::string prefix = "/start/";
  16578. res.status = StatusCode::Found_302;
  16579. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  16580. });
  16581. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  16582. target = req.target;
  16583. res.set_content("ok", "text/plain");
  16584. });
  16585. auto port = svr.bind_to_any_port(HOST);
  16586. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16587. auto se = detail::scope_exit([&] {
  16588. svr.stop();
  16589. thread.join();
  16590. ASSERT_FALSE(svr.is_running());
  16591. });
  16592. svr.wait_until_ready();
  16593. // Decoding the Location path would turn the first four into a path
  16594. // separator, a query delimiter, a fragment delimiter and a different
  16595. // percent-encoded octet. The rest must keep reaching the server as they are.
  16596. const std::vector<std::string> names = {
  16597. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  16598. };
  16599. for (auto path_encode : {true, false}) {
  16600. Client cli(HOST, port);
  16601. cli.set_follow_location(true);
  16602. cli.set_path_encode(path_encode);
  16603. for (const auto &name : names) {
  16604. target.clear();
  16605. auto res = cli.Get("/start/" + name);
  16606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16607. EXPECT_EQ(StatusCode::OK_200, res->status);
  16608. EXPECT_EQ("/dest/" + name, target);
  16609. }
  16610. }
  16611. }
  16612. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  16613. Server svr;
  16614. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16615. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  16616. });
  16617. svr.Get("/hello", [](const Request &req, Response &res) {
  16618. res.set_content(req.get_param_value("key"), "text/plain");
  16619. });
  16620. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16621. auto se = detail::scope_exit([&] {
  16622. svr.stop();
  16623. thread.join();
  16624. ASSERT_FALSE(svr.is_running());
  16625. });
  16626. svr.wait_until_ready();
  16627. {
  16628. Client cli(HOST, PORT);
  16629. cli.set_follow_location(true);
  16630. auto res = cli.Get("/");
  16631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16632. EXPECT_EQ(StatusCode::OK_200, res->status);
  16633. EXPECT_EQ("val&key2=val2", res->body);
  16634. }
  16635. }
  16636. #endif
  16637. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  16638. Server svr;
  16639. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16640. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  16641. });
  16642. svr.Get("/hello", [](const Request &req, Response &res) {
  16643. res.set_content(req.get_param_value("key"), "text/plain");
  16644. });
  16645. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16646. auto se = detail::scope_exit([&] {
  16647. svr.stop();
  16648. thread.join();
  16649. ASSERT_FALSE(svr.is_running());
  16650. });
  16651. svr.wait_until_ready();
  16652. {
  16653. Client cli(HOST, PORT);
  16654. cli.set_follow_location(true);
  16655. auto res = cli.Get("/");
  16656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16657. EXPECT_EQ(StatusCode::OK_200, res->status);
  16658. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  16659. }
  16660. }
  16661. TEST(RedirectTest, RedirectWithPlusInPath) {
  16662. Server svr;
  16663. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16664. res.set_redirect("/a+b");
  16665. });
  16666. // Route pattern uses regex; escape + as \\+
  16667. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  16668. res.set_content(req.path, "text/plain");
  16669. });
  16670. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16671. auto se = detail::scope_exit([&] {
  16672. svr.stop();
  16673. thread.join();
  16674. ASSERT_FALSE(svr.is_running());
  16675. });
  16676. svr.wait_until_ready();
  16677. {
  16678. Client cli(HOST, PORT);
  16679. cli.set_follow_location(true);
  16680. auto res = cli.Get("/");
  16681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16682. EXPECT_EQ(StatusCode::OK_200, res->status);
  16683. EXPECT_EQ("/a+b", res->body);
  16684. }
  16685. }
  16686. TEST(RedirectTest, ResolveRelativeLocation) {
  16687. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  16688. const std::vector<std::pair<std::string, std::string>> cases = {
  16689. {"g", "/b/c/g"},
  16690. {"./g", "/b/c/g"},
  16691. {"g/", "/b/c/g/"},
  16692. {"?y", "/b/c/d;p?y"},
  16693. {"g?y", "/b/c/g?y"},
  16694. {"#s", "/b/c/d;p?q#s"},
  16695. {"g#s", "/b/c/g#s"},
  16696. {"g?y#s", "/b/c/g?y#s"},
  16697. {";x", "/b/c/;x"},
  16698. {"g;x", "/b/c/g;x"},
  16699. {".", "/b/c/"},
  16700. {"./", "/b/c/"},
  16701. {"..", "/b/"},
  16702. {"../", "/b/"},
  16703. {"../g", "/b/g"},
  16704. {"../..", "/"},
  16705. {"../../", "/"},
  16706. {"../../g", "/g"},
  16707. {"../../../g", "/g"},
  16708. {"g.", "/b/c/g."},
  16709. {".g", "/b/c/.g"},
  16710. {"g..", "/b/c/g.."},
  16711. {"..g", "/b/c/..g"},
  16712. {"./../g", "/b/g"},
  16713. {"./g/.", "/b/c/g/"},
  16714. {"g/./h", "/b/c/g/h"},
  16715. {"g/../h", "/b/c/h"},
  16716. {"g;x=1/./y", "/b/c/g;x=1/y"},
  16717. {"g;x=1/../y", "/b/c/y"},
  16718. {"g?y/./x", "/b/c/g?y/./x"},
  16719. {"g#s/../x", "/b/c/g#s/../x"},
  16720. // Not relative-path references, so left for parse_url.
  16721. {"/g", "/g"},
  16722. {"//g", "//g"},
  16723. {"http://g/x", "http://g/x"},
  16724. {"g:h", "g:h"},
  16725. };
  16726. for (const auto &c : cases) {
  16727. EXPECT_EQ(c.second,
  16728. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  16729. << c.first;
  16730. }
  16731. }
  16732. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  16733. Server svr;
  16734. svr.Get("/dir/page", [](const Request &req, Response &res) {
  16735. res.set_redirect(req.get_param_value("to"));
  16736. });
  16737. svr.Get("/dir/next", [](const Request &req, Response &res) {
  16738. res.set_content(req.target, "text/plain");
  16739. });
  16740. svr.Get("/other", [](const Request &req, Response &res) {
  16741. res.set_content(req.target, "text/plain");
  16742. });
  16743. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16744. auto se = detail::scope_exit([&] {
  16745. svr.stop();
  16746. thread.join();
  16747. ASSERT_FALSE(svr.is_running());
  16748. });
  16749. svr.wait_until_ready();
  16750. const std::vector<std::pair<std::string, std::string>> cases = {
  16751. {"next", "/dir/next"},
  16752. {"./next?x=1", "/dir/next?x=1"},
  16753. {"../other", "/other"},
  16754. };
  16755. for (const auto &c : cases) {
  16756. Client cli(HOST, PORT);
  16757. cli.set_follow_location(true);
  16758. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  16759. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  16760. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  16761. EXPECT_EQ(c.second, res->body) << c.first;
  16762. }
  16763. }
  16764. #ifdef CPPHTTPLIB_SSL_ENABLED
  16765. TEST(RedirectTest, Issue2185_Online) {
  16766. SSLClient client("github.com");
  16767. client.set_follow_location(true);
  16768. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  16769. "Coollab-Windows.zip");
  16770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16771. EXPECT_EQ(StatusCode::OK_200, res->status);
  16772. EXPECT_EQ(9920427U, res->body.size());
  16773. }
  16774. #endif
  16775. TEST(VulnerabilityTest, CRLFInjection) {
  16776. Server svr;
  16777. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  16778. res.set_content("Hello 1", "text/plain");
  16779. });
  16780. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  16781. res.set_content("Hello 2", "text/plain");
  16782. });
  16783. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  16784. res.set_content("Hello 3", "text/plain");
  16785. });
  16786. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  16787. res.set_content("Hello 4", "text/plain");
  16788. });
  16789. svr.set_logger([](const Request &req, const Response & /*res*/) {
  16790. for (const auto &x : req.headers) {
  16791. auto key = x.first;
  16792. EXPECT_STRNE("evil", key.c_str());
  16793. }
  16794. });
  16795. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16796. auto se = detail::scope_exit([&] {
  16797. svr.stop();
  16798. thread.join();
  16799. ASSERT_FALSE(svr.is_running());
  16800. });
  16801. svr.wait_until_ready();
  16802. {
  16803. Client cli(HOST, PORT);
  16804. cli.Post("/test1", "A=B",
  16805. "application/x-www-form-urlencoded\r\nevil: hello1");
  16806. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  16807. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  16808. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  16809. }
  16810. }
  16811. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  16812. auto server_thread = std::thread([] {
  16813. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16814. default_socket_options(srv);
  16815. sockaddr_in addr{};
  16816. addr.sin_family = AF_INET;
  16817. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16818. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16819. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  16820. ::listen(srv, 1);
  16821. sockaddr_in cli_addr{};
  16822. socklen_t cli_len = sizeof(cli_addr);
  16823. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16824. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  16825. std::string buf_all;
  16826. char buf[2048];
  16827. ssize_t n;
  16828. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  16829. buf_all.append(buf, static_cast<size_t>(n));
  16830. size_t pos;
  16831. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  16832. auto request_block = buf_all.substr(0, pos + 4); // include separator
  16833. auto e = request_block.find("\r\n");
  16834. if (e != std::string::npos) {
  16835. auto request_line = request_block.substr(0, e);
  16836. std::string msg =
  16837. "CRLF injection detected in request line: '" + request_line + "'";
  16838. EXPECT_FALSE(true) << msg;
  16839. }
  16840. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  16841. ::send(cli,
  16842. #ifdef _WIN32
  16843. static_cast<const char *>(resp.c_str()),
  16844. static_cast<int>(resp.size()),
  16845. #else
  16846. resp.c_str(), resp.size(),
  16847. #endif
  16848. 0);
  16849. buf_all.erase(0, pos + 4);
  16850. }
  16851. }
  16852. detail::close_socket(cli);
  16853. detail::close_socket(srv);
  16854. });
  16855. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16856. auto cli = Client("127.0.0.1", PORT + 1);
  16857. auto headers = Headers{
  16858. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  16859. {"Connection", "keep-alive"}};
  16860. auto res = cli.Get("/hi", headers);
  16861. EXPECT_FALSE(res);
  16862. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16863. server_thread.join();
  16864. }
  16865. // A request rejected before any byte reaches the socket must fail right away
  16866. // instead of waiting for a response the server will never send.
  16867. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  16868. // The kernel completes the TCP handshake from the listen backlog, so the
  16869. // client connects, but nothing ever reads, responds or closes.
  16870. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16871. default_socket_options(srv);
  16872. sockaddr_in addr{};
  16873. addr.sin_family = AF_INET;
  16874. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16875. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16876. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16877. ASSERT_EQ(0, ::listen(srv, 8));
  16878. auto cli = Client("127.0.0.1", PORT + 1);
  16879. cli.set_read_timeout(10, 0);
  16880. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  16881. return std::chrono::duration_cast<std::chrono::milliseconds>(
  16882. std::chrono::steady_clock::now() - start)
  16883. .count();
  16884. };
  16885. {
  16886. Request req;
  16887. req.method = "GE T";
  16888. req.path = "/";
  16889. auto start = std::chrono::steady_clock::now();
  16890. auto res = cli.send(req);
  16891. EXPECT_FALSE(res);
  16892. EXPECT_EQ(Error::Write, res.error());
  16893. EXPECT_LT(elapsed_ms(start), 1000);
  16894. }
  16895. {
  16896. auto start = std::chrono::steady_clock::now();
  16897. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  16898. EXPECT_FALSE(res);
  16899. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16900. EXPECT_LT(elapsed_ms(start), 1000);
  16901. }
  16902. EXPECT_FALSE(cli.is_socket_open());
  16903. detail::close_socket(srv);
  16904. }
  16905. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  16906. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16907. default_socket_options(srv);
  16908. sockaddr_in addr{};
  16909. addr.sin_family = AF_INET;
  16910. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16911. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16912. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16913. ASSERT_EQ(0, ::listen(srv, 1));
  16914. std::string received;
  16915. auto server_thread = std::thread([&] {
  16916. auto sock = ::accept(srv, nullptr, nullptr);
  16917. if (sock == INVALID_SOCKET) { return; }
  16918. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  16919. char buf[2048];
  16920. ssize_t n;
  16921. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  16922. received.append(buf, static_cast<size_t>(n));
  16923. }
  16924. detail::close_socket(sock);
  16925. });
  16926. {
  16927. auto cli = Client("127.0.0.1", PORT + 1);
  16928. // "Z" sorts after the default headers, so writing straight to the socket
  16929. // would have sent the request line and those headers before the rejection.
  16930. auto handle =
  16931. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  16932. EXPECT_FALSE(handle.is_valid());
  16933. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  16934. }
  16935. server_thread.join();
  16936. detail::close_socket(srv);
  16937. EXPECT_TRUE(received.empty()) << received;
  16938. }
  16939. TEST(PathParamsTest, StaticMatch) {
  16940. const auto pattern = "/users/all";
  16941. detail::PathParamsMatcher matcher(pattern);
  16942. Request request;
  16943. request.path = "/users/all";
  16944. ASSERT_TRUE(matcher.match(request));
  16945. std::unordered_map<std::string, std::string> expected_params = {};
  16946. EXPECT_EQ(request.path_params, expected_params);
  16947. }
  16948. TEST(PathParamsTest, StaticMismatch) {
  16949. const auto pattern = "/users/all";
  16950. detail::PathParamsMatcher matcher(pattern);
  16951. Request request;
  16952. request.path = "/users/1";
  16953. ASSERT_FALSE(matcher.match(request));
  16954. }
  16955. TEST(PathParamsTest, SingleParamInTheMiddle) {
  16956. const auto pattern = "/users/:id/subscriptions";
  16957. detail::PathParamsMatcher matcher(pattern);
  16958. Request request;
  16959. request.path = "/users/42/subscriptions";
  16960. ASSERT_TRUE(matcher.match(request));
  16961. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16962. EXPECT_EQ(request.path_params, expected_params);
  16963. }
  16964. TEST(PathParamsTest, SingleParamInTheEnd) {
  16965. const auto pattern = "/users/:id";
  16966. detail::PathParamsMatcher matcher(pattern);
  16967. Request request;
  16968. request.path = "/users/24";
  16969. ASSERT_TRUE(matcher.match(request));
  16970. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  16971. EXPECT_EQ(request.path_params, expected_params);
  16972. }
  16973. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  16974. const auto pattern = "/users/:id/";
  16975. detail::PathParamsMatcher matcher(pattern);
  16976. Request request;
  16977. request.path = "/users/42/";
  16978. ASSERT_TRUE(matcher.match(request));
  16979. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16980. EXPECT_EQ(request.path_params, expected_params);
  16981. }
  16982. TEST(PathParamsTest, EmptyParam) {
  16983. const auto pattern = "/users/:id/";
  16984. detail::PathParamsMatcher matcher(pattern);
  16985. Request request;
  16986. request.path = "/users//";
  16987. ASSERT_TRUE(matcher.match(request));
  16988. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  16989. EXPECT_EQ(request.path_params, expected_params);
  16990. }
  16991. TEST(PathParamsTest, FragmentMismatch) {
  16992. const auto pattern = "/users/:id/";
  16993. detail::PathParamsMatcher matcher(pattern);
  16994. Request request;
  16995. request.path = "/admins/24/";
  16996. ASSERT_FALSE(matcher.match(request));
  16997. }
  16998. TEST(PathParamsTest, ExtraFragments) {
  16999. const auto pattern = "/users/:id";
  17000. detail::PathParamsMatcher matcher(pattern);
  17001. Request request;
  17002. request.path = "/users/42/subscriptions";
  17003. ASSERT_FALSE(matcher.match(request));
  17004. }
  17005. TEST(PathParamsTest, MissingTrailingParam) {
  17006. const auto pattern = "/users/:id";
  17007. detail::PathParamsMatcher matcher(pattern);
  17008. Request request;
  17009. request.path = "/users";
  17010. ASSERT_FALSE(matcher.match(request));
  17011. }
  17012. TEST(PathParamsTest, MissingParamInTheMiddle) {
  17013. const auto pattern = "/users/:id/subscriptions";
  17014. detail::PathParamsMatcher matcher(pattern);
  17015. Request request;
  17016. request.path = "/users/subscriptions";
  17017. ASSERT_FALSE(matcher.match(request));
  17018. }
  17019. TEST(PathParamsTest, MultipleParams) {
  17020. const auto pattern = "/users/:userid/subscriptions/:subid";
  17021. detail::PathParamsMatcher matcher(pattern);
  17022. Request request;
  17023. request.path = "/users/42/subscriptions/2";
  17024. ASSERT_TRUE(matcher.match(request));
  17025. std::unordered_map<std::string, std::string> expected_params = {
  17026. {"userid", "42"}, {"subid", "2"}};
  17027. EXPECT_EQ(request.path_params, expected_params);
  17028. }
  17029. TEST(PathParamsTest, SequenceOfParams) {
  17030. const auto pattern = "/values/:x/:y/:z";
  17031. detail::PathParamsMatcher matcher(pattern);
  17032. Request request;
  17033. request.path = "/values/1/2/3";
  17034. ASSERT_TRUE(matcher.match(request));
  17035. std::unordered_map<std::string, std::string> expected_params = {
  17036. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  17037. EXPECT_EQ(request.path_params, expected_params);
  17038. }
  17039. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  17040. const auto pattern = "/prefix:suffix";
  17041. detail::PathParamsMatcher matcher(pattern);
  17042. Request request;
  17043. request.path = "/prefix:suffix";
  17044. ASSERT_TRUE(matcher.match(request));
  17045. const std::unordered_map<std::string, std::string> expected_params = {};
  17046. EXPECT_EQ(request.path_params, expected_params);
  17047. }
  17048. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  17049. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  17050. // calling thread's stack on a long enough path for a quantified pattern;
  17051. // RegexMatcher must refuse to run regex matching on paths beyond
  17052. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  17053. detail::RegexMatcher matcher("/files/(.*)");
  17054. Request within_limit;
  17055. within_limit.path = "/files/" + std::string(10, 'A');
  17056. EXPECT_TRUE(matcher.match(within_limit));
  17057. Request over_limit;
  17058. over_limit.path =
  17059. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  17060. EXPECT_FALSE(matcher.match(over_limit));
  17061. }
  17062. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  17063. Server svr;
  17064. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  17065. res.set_content("ok", "text/plain");
  17066. });
  17067. auto port = svr.bind_to_any_port(HOST);
  17068. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17069. auto se = detail::scope_exit([&] {
  17070. svr.stop();
  17071. thread.join();
  17072. ASSERT_FALSE(svr.is_running());
  17073. });
  17074. svr.wait_until_ready();
  17075. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  17076. // request URI limit; this used to be able to crash the process.
  17077. std::string path =
  17078. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  17079. std::string req = "GET " + path +
  17080. " HTTP/1.1\r\n"
  17081. "Host: " +
  17082. std::string(HOST) + ":" + std::to_string(port) +
  17083. "\r\n"
  17084. "Connection: close\r\n"
  17085. "\r\n";
  17086. std::string response;
  17087. ASSERT_TRUE(send_request(5, req, &response, port));
  17088. EXPECT_NE(std::string::npos, response.find("404"));
  17089. }
  17090. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  17091. Server svr;
  17092. auto handler = [](const Request & /*req*/, Response &res) {
  17093. res.set_content("hit", "text/plain");
  17094. };
  17095. // No regex metacharacter, so this one is compared literally
  17096. svr.Get("/literal/route", handler);
  17097. // '.' is a regex metacharacter, so this one must keep regex semantics
  17098. svr.Get("/a.c", handler);
  17099. auto port = svr.bind_to_any_port(HOST);
  17100. std::thread t([&]() { svr.listen_after_bind(); });
  17101. auto se = detail::scope_exit([&] {
  17102. svr.stop();
  17103. t.join();
  17104. ASSERT_FALSE(svr.is_running());
  17105. });
  17106. svr.wait_until_ready();
  17107. Client cli(HOST, port);
  17108. struct {
  17109. const char *path;
  17110. int status;
  17111. } cases[] = {
  17112. {"/literal/route", StatusCode::OK_200},
  17113. {"/literal/routes", StatusCode::NotFound_404},
  17114. {"/literal/rout", StatusCode::NotFound_404},
  17115. {"/abc", StatusCode::OK_200},
  17116. {"/a.c", StatusCode::OK_200},
  17117. };
  17118. for (const auto &x : cases) {
  17119. auto res = cli.Get(x.path);
  17120. ASSERT_TRUE(res) << x.path;
  17121. EXPECT_EQ(x.status, res->status) << x.path;
  17122. }
  17123. }
  17124. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  17125. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  17126. // from exhausting the stack, so it must only constrain routes that actually
  17127. // run a regular expression. A literal route is matched by comparison and
  17128. // stays usable at any length.
  17129. Server svr;
  17130. const std::string pattern =
  17131. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  17132. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  17133. res.set_content("hit", "text/plain");
  17134. });
  17135. auto port = svr.bind_to_any_port(HOST);
  17136. std::thread t([&]() { svr.listen_after_bind(); });
  17137. auto se = detail::scope_exit([&] {
  17138. svr.stop();
  17139. t.join();
  17140. ASSERT_FALSE(svr.is_running());
  17141. });
  17142. svr.wait_until_ready();
  17143. Client cli(HOST, port);
  17144. auto res = cli.Get(pattern);
  17145. ASSERT_TRUE(res);
  17146. EXPECT_EQ(StatusCode::OK_200, res->status);
  17147. }
  17148. TEST(ParseUrlTest, VariousPatterns) {
  17149. {
  17150. detail::UrlComponents uc;
  17151. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  17152. EXPECT_EQ("http", uc.scheme);
  17153. EXPECT_EQ("example.com", uc.host);
  17154. EXPECT_EQ("8080", uc.port);
  17155. EXPECT_EQ("/path", uc.path);
  17156. EXPECT_EQ("?q=1", uc.query);
  17157. }
  17158. {
  17159. detail::UrlComponents uc;
  17160. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  17161. EXPECT_EQ("https", uc.scheme);
  17162. EXPECT_EQ("example.com", uc.host);
  17163. EXPECT_TRUE(uc.port.empty());
  17164. EXPECT_EQ("/path", uc.path);
  17165. }
  17166. {
  17167. detail::UrlComponents uc;
  17168. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  17169. EXPECT_EQ("::1", uc.host);
  17170. EXPECT_EQ("8080", uc.port);
  17171. EXPECT_EQ("/path", uc.path);
  17172. }
  17173. {
  17174. detail::UrlComponents uc;
  17175. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  17176. }
  17177. {
  17178. // Bytes after the IPv6 literal must be a delimiter, not folded into
  17179. // the path while the connection still targets the bracketed host.
  17180. detail::UrlComponents uc;
  17181. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  17182. }
  17183. {
  17184. detail::UrlComponents uc;
  17185. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  17186. }
  17187. {
  17188. detail::UrlComponents uc;
  17189. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  17190. EXPECT_EQ("::1", uc.host);
  17191. EXPECT_TRUE(uc.port.empty());
  17192. EXPECT_EQ("/path", uc.path);
  17193. }
  17194. {
  17195. detail::UrlComponents uc;
  17196. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  17197. EXPECT_TRUE(uc.scheme.empty());
  17198. EXPECT_EQ("example.com", uc.host);
  17199. EXPECT_EQ("/path", uc.path);
  17200. EXPECT_EQ("?q=1", uc.query);
  17201. }
  17202. {
  17203. detail::UrlComponents uc;
  17204. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  17205. EXPECT_TRUE(uc.host.empty());
  17206. EXPECT_EQ("/path", uc.path);
  17207. EXPECT_EQ("?q=1", uc.query);
  17208. }
  17209. {
  17210. detail::UrlComponents uc;
  17211. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  17212. EXPECT_EQ("example.com", uc.host);
  17213. EXPECT_EQ("8080", uc.port);
  17214. }
  17215. {
  17216. // Unix socket path — must not be parsed as host
  17217. detail::UrlComponents uc;
  17218. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  17219. EXPECT_TRUE(uc.host.empty());
  17220. }
  17221. {
  17222. detail::UrlComponents uc;
  17223. ASSERT_TRUE(detail::parse_url("", uc));
  17224. EXPECT_TRUE(uc.host.empty());
  17225. EXPECT_TRUE(uc.path.empty());
  17226. }
  17227. {
  17228. detail::UrlComponents uc;
  17229. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  17230. }
  17231. {
  17232. detail::UrlComponents uc;
  17233. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  17234. }
  17235. {
  17236. // Accepted by parse_url; callers restrict to http/https
  17237. detail::UrlComponents uc;
  17238. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  17239. EXPECT_EQ("ftp", uc.scheme);
  17240. }
  17241. {
  17242. detail::UrlComponents uc;
  17243. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  17244. }
  17245. {
  17246. detail::UrlComponents uc;
  17247. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  17248. }
  17249. }
  17250. TEST(ParseUrlTest, FragmentHandling) {
  17251. {
  17252. detail::UrlComponents uc;
  17253. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  17254. EXPECT_EQ("/path", uc.path);
  17255. EXPECT_TRUE(uc.query.empty());
  17256. }
  17257. {
  17258. detail::UrlComponents uc;
  17259. ASSERT_TRUE(detail::parse_url("#frag", uc));
  17260. EXPECT_TRUE(uc.path.empty());
  17261. EXPECT_TRUE(uc.query.empty());
  17262. }
  17263. }
  17264. TEST(ParseUrlTest, UserinfoHandling) {
  17265. // userinfo, and a backslash some parsers take for '/', are rejected: such
  17266. // parsers would see evil.com as the host.
  17267. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  17268. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  17269. for (auto url : urls) {
  17270. detail::UrlComponents uc;
  17271. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  17272. }
  17273. }
  17274. TEST(ParseUrlTest, IPv6EdgeCases) {
  17275. {
  17276. detail::UrlComponents uc;
  17277. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  17278. EXPECT_TRUE(uc.scheme.empty());
  17279. EXPECT_EQ("::1", uc.host);
  17280. EXPECT_EQ("8080", uc.port);
  17281. }
  17282. {
  17283. // Zone ID '%25' is not in [a-fA-F0-9:]
  17284. detail::UrlComponents uc;
  17285. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  17286. }
  17287. }
  17288. TEST(ParseUrlTest, SchemeEdgeCases) {
  17289. {
  17290. detail::UrlComponents uc;
  17291. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  17292. }
  17293. {
  17294. detail::UrlComponents uc;
  17295. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  17296. }
  17297. {
  17298. detail::UrlComponents uc;
  17299. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  17300. }
  17301. }
  17302. TEST(ParseUrlTest, PortEdgeCases) {
  17303. {
  17304. detail::UrlComponents uc;
  17305. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  17306. EXPECT_TRUE(uc.port.empty());
  17307. EXPECT_EQ("/path", uc.path);
  17308. }
  17309. {
  17310. // parse_url accepts any port string; validation is done by parse_port
  17311. detail::UrlComponents uc;
  17312. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  17313. EXPECT_EQ("abc", uc.port);
  17314. }
  17315. }
  17316. TEST(ParseUrlTest, WebSocketPatterns) {
  17317. {
  17318. detail::UrlComponents uc;
  17319. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  17320. EXPECT_EQ("ws", uc.scheme);
  17321. EXPECT_EQ("echo.example.com", uc.host);
  17322. EXPECT_EQ("8080", uc.port);
  17323. EXPECT_EQ("/ws", uc.path);
  17324. }
  17325. {
  17326. detail::UrlComponents uc;
  17327. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  17328. EXPECT_EQ("wss", uc.scheme);
  17329. EXPECT_EQ("echo.example.com", uc.host);
  17330. EXPECT_TRUE(uc.port.empty());
  17331. EXPECT_EQ("/ws", uc.path);
  17332. }
  17333. }
  17334. TEST(ParseUrlTest, QueryOnly) {
  17335. detail::UrlComponents uc;
  17336. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  17337. EXPECT_TRUE(uc.host.empty());
  17338. EXPECT_TRUE(uc.path.empty());
  17339. EXPECT_EQ("?q=1&r=2", uc.query);
  17340. }
  17341. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  17342. detail::UrlComponents uc;
  17343. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  17344. EXPECT_TRUE(uc.scheme.empty());
  17345. EXPECT_EQ("example.com", uc.host);
  17346. EXPECT_EQ("443", uc.port);
  17347. EXPECT_EQ("/path", uc.path);
  17348. }
  17349. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  17350. // If ipv6 regex working, regex match codepath is taken.
  17351. // else port will default to 80 in Client impl
  17352. int clientImplMagicPort = 80;
  17353. int port = 4321;
  17354. // above ports must be different to avoid false negative
  17355. EXPECT_NE(clientImplMagicPort, port);
  17356. std::string ipV6TestURL = "http://[ff06::c3]";
  17357. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  17358. CLIENT_PRIVATE_KEY_FILE);
  17359. EXPECT_EQ(cli.port(), port);
  17360. }
  17361. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  17362. auto file_path = "./www/dir/index.html";
  17363. auto dir_path = "./www/dir";
  17364. detail::FileStat stat_file(file_path);
  17365. EXPECT_TRUE(stat_file.is_file());
  17366. EXPECT_FALSE(stat_file.is_dir());
  17367. detail::FileStat stat_dir(dir_path);
  17368. EXPECT_FALSE(stat_dir.is_file());
  17369. EXPECT_TRUE(stat_dir.is_dir());
  17370. }
  17371. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  17372. // IPv4 with default HTTP port (80)
  17373. EXPECT_EQ("example.com",
  17374. detail::make_host_and_port_string("example.com", 80, false));
  17375. // IPv4 with default HTTPS port (443)
  17376. EXPECT_EQ("example.com",
  17377. detail::make_host_and_port_string("example.com", 443, true));
  17378. // IPv4 with non-default HTTP port
  17379. EXPECT_EQ("example.com:8080",
  17380. detail::make_host_and_port_string("example.com", 8080, false));
  17381. // IPv4 with non-default HTTPS port
  17382. EXPECT_EQ("example.com:8443",
  17383. detail::make_host_and_port_string("example.com", 8443, true));
  17384. // IPv6 with default HTTP port (80)
  17385. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  17386. // IPv6 with default HTTPS port (443)
  17387. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  17388. // IPv6 with non-default HTTP port
  17389. EXPECT_EQ("[::1]:8080",
  17390. detail::make_host_and_port_string("::1", 8080, false));
  17391. // IPv6 with non-default HTTPS port
  17392. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  17393. // IPv6 full address with default port
  17394. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  17395. detail::make_host_and_port_string(
  17396. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  17397. // IPv6 full address with non-default port
  17398. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  17399. detail::make_host_and_port_string(
  17400. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  17401. // IPv6 localhost with non-default port
  17402. EXPECT_EQ("[::1]:3000",
  17403. detail::make_host_and_port_string("::1", 3000, false));
  17404. // IPv6 with zone ID (link-local address) with default port
  17405. EXPECT_EQ("[fe80::1%eth0]",
  17406. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  17407. // IPv6 with zone ID (link-local address) with non-default port
  17408. EXPECT_EQ("[fe80::1%eth0]:8080",
  17409. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  17410. // Edge case: Port 443 with is_ssl=false (should add port)
  17411. EXPECT_EQ("example.com:443",
  17412. detail::make_host_and_port_string("example.com", 443, false));
  17413. // Edge case: Port 80 with is_ssl=true (should add port)
  17414. EXPECT_EQ("example.com:80",
  17415. detail::make_host_and_port_string("example.com", 80, true));
  17416. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  17417. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  17418. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  17419. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  17420. // Security fix: Already bracketed IPv6 should not get double brackets
  17421. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  17422. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  17423. EXPECT_EQ("[::1]:8080",
  17424. detail::make_host_and_port_string("[::1]", 8080, false));
  17425. EXPECT_EQ("[2001:db8::1]:8080",
  17426. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  17427. EXPECT_EQ("[fe80::1%eth0]",
  17428. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  17429. EXPECT_EQ("[fe80::1%eth0]:8080",
  17430. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  17431. // Edge case: Empty host (should return as-is)
  17432. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  17433. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  17434. // This is a known limitation but shouldn't crash
  17435. EXPECT_EQ("[host:name]",
  17436. detail::make_host_and_port_string("host:name", 80, false));
  17437. // Port number edge cases (no validation, but should not crash)
  17438. EXPECT_EQ("example.com:0",
  17439. detail::make_host_and_port_string("example.com", 0, false));
  17440. EXPECT_EQ("example.com:-1",
  17441. detail::make_host_and_port_string("example.com", -1, false));
  17442. EXPECT_EQ("example.com:65535",
  17443. detail::make_host_and_port_string("example.com", 65535, false));
  17444. EXPECT_EQ("example.com:65536",
  17445. detail::make_host_and_port_string("example.com", 65536, false));
  17446. }
  17447. #ifdef CPPHTTPLIB_SSL_ENABLED
  17448. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  17449. httplib::SSLClient cli("roblox.com", 443);
  17450. cli.set_follow_location(true);
  17451. auto res = cli.Get("/");
  17452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17453. EXPECT_EQ(StatusCode::OK_200, res->status);
  17454. }
  17455. #endif
  17456. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  17457. Server svr;
  17458. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17459. EXPECT_EQ(res.status, 400);
  17460. });
  17461. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17462. auto se = detail::scope_exit([&] {
  17463. svr.stop();
  17464. thread.join();
  17465. ASSERT_FALSE(svr.is_running());
  17466. });
  17467. svr.wait_until_ready();
  17468. Client cli(HOST, PORT);
  17469. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  17470. }
  17471. TEST(InvalidHeaderCharsTest, is_field_name) {
  17472. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  17473. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  17474. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  17475. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  17476. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  17477. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  17478. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  17479. EXPECT_FALSE(detail::fields::is_field_name(""));
  17480. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  17481. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  17482. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  17483. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  17484. }
  17485. TEST(InvalidHeaderCharsTest, is_field_value) {
  17486. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  17487. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  17488. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  17489. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  17490. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  17491. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  17492. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  17493. EXPECT_TRUE(detail::fields::is_field_value(""));
  17494. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  17495. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  17496. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  17497. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  17498. EXPECT_TRUE(detail::fields::is_field_value("0"));
  17499. }
  17500. TEST(InvalidHeaderCharsTest, OnServer) {
  17501. Server svr;
  17502. svr.Get("/test_name", [&](const Request &req, Response &res) {
  17503. std::string header = "Not Set";
  17504. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17505. res.set_header(header, "value");
  17506. res.set_content("Page Content Page Content", "text/plain");
  17507. });
  17508. svr.Get("/test_value", [&](const Request &req, Response &res) {
  17509. std::string header = "Not Set";
  17510. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17511. res.set_header("X-Test", header);
  17512. res.set_content("Page Content Page Content", "text/plain");
  17513. });
  17514. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17515. auto se = detail::scope_exit([&] {
  17516. svr.stop();
  17517. thread.join();
  17518. ASSERT_FALSE(svr.is_running());
  17519. });
  17520. svr.wait_until_ready();
  17521. Client cli(HOST, PORT);
  17522. {
  17523. auto res = cli.Get(
  17524. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17526. EXPECT_EQ("Page Content Page Content", res->body);
  17527. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17528. }
  17529. {
  17530. auto res = cli.Get(
  17531. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17533. EXPECT_EQ("Page Content Page Content", res->body);
  17534. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17535. }
  17536. }
  17537. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  17538. auto handled = false;
  17539. Server svr;
  17540. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17541. thread t = thread([&] { svr.listen(HOST, PORT); });
  17542. auto se = detail::scope_exit([&] {
  17543. svr.stop();
  17544. t.join();
  17545. ASSERT_FALSE(svr.is_running());
  17546. ASSERT_FALSE(handled);
  17547. });
  17548. svr.wait_until_ready();
  17549. auto req = "POST /test HTTP/1.1\r\n"
  17550. "Content-Length: x\r\n"
  17551. "\r\n";
  17552. std::string response;
  17553. ASSERT_TRUE(send_request(1, req, &response));
  17554. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17555. response.substr(0, response.find("\r\n")));
  17556. }
  17557. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  17558. // case-insensitive, and a server that receives a 100-continue expectation in
  17559. // an HTTP/1.0 request MUST ignore it.
  17560. static void probe_expect(int port, const std::string &req, bool *got_100) {
  17561. std::string response;
  17562. ASSERT_TRUE(send_request(1, req, &response, port));
  17563. *got_100 = response.find("100 Continue") != std::string::npos;
  17564. }
  17565. class ExpectTokenTest : public ::testing::Test {
  17566. protected:
  17567. void SetUp() override {
  17568. svr_.Post("/p", [](const Request &, Response &res) {
  17569. res.set_content("ok", "text/plain");
  17570. });
  17571. port_ = svr_.bind_to_any_port(HOST);
  17572. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17573. svr_.wait_until_ready();
  17574. }
  17575. void TearDown() override {
  17576. svr_.stop();
  17577. if (thread_.joinable()) { thread_.join(); }
  17578. }
  17579. std::string request(const char *version, const char *expect_value) const {
  17580. return std::string("POST /p ") + version +
  17581. "\r\n"
  17582. "Host: localhost\r\n"
  17583. "Content-Length: 2\r\n"
  17584. "Connection: close\r\n"
  17585. "Expect: " +
  17586. expect_value +
  17587. "\r\n"
  17588. "\r\n"
  17589. "hi";
  17590. }
  17591. Server svr_;
  17592. int port_ = 0;
  17593. thread thread_;
  17594. };
  17595. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  17596. bool got_100 = false;
  17597. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  17598. EXPECT_TRUE(got_100);
  17599. }
  17600. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  17601. bool got_100 = true;
  17602. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  17603. EXPECT_FALSE(got_100);
  17604. }
  17605. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  17606. bool got_100 = false;
  17607. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  17608. EXPECT_TRUE(got_100);
  17609. }
  17610. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  17611. bool got_100 = false;
  17612. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  17613. EXPECT_TRUE(got_100);
  17614. }
  17615. // `100 Continue` is sent only when the server starts reading the body, so a
  17616. // request rejected before that never invites the client to send it. The
  17617. // requests below carry the expectation but withhold the body, as a client
  17618. // waiting for `100 Continue` would.
  17619. // A POST that expects `100 Continue` and withholds its two-byte body.
  17620. static std::string expect_headers_only(const std::string &path) {
  17621. return "POST " + path +
  17622. " HTTP/1.1\r\n"
  17623. "Host: localhost\r\n"
  17624. "Content-Length: 2\r\n"
  17625. "Expect: 100-continue\r\n"
  17626. "\r\n";
  17627. }
  17628. class ExpectLazyContinueTest : public ::testing::Test {
  17629. protected:
  17630. void SetUp() override {
  17631. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  17632. if (req.path == "/pre-routing") {
  17633. res.status = StatusCode::Unauthorized_401;
  17634. return Server::HandlerResponse::Handled;
  17635. }
  17636. return Server::HandlerResponse::Unhandled;
  17637. });
  17638. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  17639. if (req.matched_route == "/pre-request") {
  17640. res.status = StatusCode::Forbidden_403;
  17641. return Server::HandlerResponse::Handled;
  17642. }
  17643. return Server::HandlerResponse::Unhandled;
  17644. });
  17645. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  17646. res.set_content("ok", "text/plain");
  17647. });
  17648. svr_.Post("/pre-request", [](const Request &, Response &res) {
  17649. res.set_content("ok", "text/plain");
  17650. });
  17651. svr_.Post("/reader-used", [](const Request &, Response &res,
  17652. const ContentReader &content_reader) {
  17653. std::string body;
  17654. content_reader([&](const char *data, size_t len) {
  17655. body.append(data, len);
  17656. return true;
  17657. });
  17658. res.set_content(body, "text/plain");
  17659. });
  17660. svr_.Post("/reader-unused",
  17661. [](const Request &, Response &res, const ContentReader &) {
  17662. res.set_content("ignored", "text/plain");
  17663. });
  17664. port_ = svr_.bind_to_any_port(HOST);
  17665. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17666. svr_.wait_until_ready();
  17667. }
  17668. void TearDown() override {
  17669. svr_.stop();
  17670. if (thread_.joinable()) { thread_.join(); }
  17671. }
  17672. // Sends `req` and reads until the server closes the connection. Returns
  17673. // false if the read had to wait for the client-side timeout instead.
  17674. bool send_until_closed(const std::string &req, std::string *resp) const {
  17675. auto start = std::chrono::steady_clock::now();
  17676. if (!send_request(3, req, resp, port_)) { return false; }
  17677. auto elapsed = std::chrono::steady_clock::now() - start;
  17678. return elapsed < std::chrono::seconds(2);
  17679. }
  17680. // The final response comes without `100 Continue`, and the server closes
  17681. // the connection since the body may or may not follow.
  17682. void expect_final_without_interim(const std::string &path,
  17683. const char *status_line) const {
  17684. std::string resp;
  17685. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  17686. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  17687. EXPECT_EQ(0u, resp.find(status_line));
  17688. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17689. }
  17690. Server svr_;
  17691. int port_ = 0;
  17692. thread thread_;
  17693. };
  17694. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  17695. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  17696. }
  17697. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  17698. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  17699. }
  17700. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  17701. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  17702. }
  17703. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  17704. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  17705. }
  17706. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  17707. // The body follows once `100 Continue` has had time to arrive.
  17708. auto req = expect_headers_only("/reader-used");
  17709. req.insert(req.size() - 2, "Connection: close\r\n");
  17710. std::string resp;
  17711. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  17712. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  17713. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  17714. EXPECT_NE(std::string::npos, resp.find("hi"));
  17715. }
  17716. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  17717. // Large enough for the client to add `Expect: 100-continue` itself.
  17718. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  17719. std::atomic<bool> body_sent{false};
  17720. Client cli(HOST, port_);
  17721. auto res = cli.Post(
  17722. "/pre-request", length,
  17723. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  17724. body_sent = true;
  17725. std::string chunk(len, 'x');
  17726. sink.write(chunk.data(), chunk.size());
  17727. return true;
  17728. },
  17729. "application/octet-stream");
  17730. ASSERT_TRUE(res);
  17731. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  17732. EXPECT_FALSE(body_sent);
  17733. }
  17734. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  17735. Server svr;
  17736. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  17737. return StatusCode::ExpectationFailed_417;
  17738. });
  17739. svr.Post("/p", [](const Request &, Response &res) {
  17740. res.set_content("ok", "text/plain");
  17741. });
  17742. auto port = svr.bind_to_any_port(HOST);
  17743. thread t = thread([&] { svr.listen_after_bind(); });
  17744. auto se = detail::scope_exit([&] {
  17745. svr.stop();
  17746. t.join();
  17747. });
  17748. svr.wait_until_ready();
  17749. std::string resp;
  17750. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  17751. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  17752. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  17753. // Exactly one response: the route handler must not run after the 417.
  17754. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  17755. }
  17756. #ifndef _WIN32
  17757. TEST(Expect100ContinueTest, ServerClosesConnection) {
  17758. static constexpr char reject[] = "Unauthorized";
  17759. static constexpr char accept[] = "Upload accepted";
  17760. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  17761. Server svr;
  17762. svr.set_expect_100_continue_handler(
  17763. [](const Request & /*req*/, Response &res) {
  17764. res.status = StatusCode::Unauthorized_401;
  17765. res.set_content(reject, "text/plain");
  17766. return res.status;
  17767. });
  17768. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  17769. res.set_content(accept, "text/plain");
  17770. });
  17771. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17772. auto se = detail::scope_exit([&] {
  17773. svr.stop();
  17774. thread.join();
  17775. ASSERT_FALSE(svr.is_running());
  17776. });
  17777. svr.wait_until_ready();
  17778. {
  17779. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  17780. curl_easy_init(), &curl_easy_cleanup};
  17781. ASSERT_NE(curl, nullptr);
  17782. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  17783. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  17784. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  17785. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  17786. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  17787. &curl_slist_free_all};
  17788. ASSERT_NE(list, nullptr);
  17789. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  17790. struct read_data {
  17791. size_t read_size;
  17792. size_t total_size;
  17793. } data = {0, total_size};
  17794. using read_callback_t =
  17795. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17796. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  17797. void *userdata) -> size_t {
  17798. read_data *d = (read_data *)userdata;
  17799. if (!userdata || d->read_size >= d->total_size) { return 0; }
  17800. std::fill_n(ptr, size * nmemb, 'A');
  17801. d->read_size += size * nmemb;
  17802. return size * nmemb;
  17803. };
  17804. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  17805. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  17806. std::vector<char> buffer;
  17807. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  17808. using write_callback_t =
  17809. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17810. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  17811. void *userdata) -> size_t {
  17812. std::vector<char> *buf = (std::vector<char> *)userdata;
  17813. buf->reserve(buf->size() + size * nmemb + 1);
  17814. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  17815. return size * nmemb;
  17816. };
  17817. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  17818. {
  17819. const auto res = curl_easy_perform(curl.get());
  17820. ASSERT_EQ(res, CURLE_OK);
  17821. }
  17822. {
  17823. auto response_code = long{};
  17824. const auto res =
  17825. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  17826. ASSERT_EQ(res, CURLE_OK);
  17827. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  17828. }
  17829. {
  17830. auto dl = curl_off_t{};
  17831. const auto res =
  17832. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  17833. ASSERT_EQ(res, CURLE_OK);
  17834. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  17835. }
  17836. {
  17837. buffer.push_back('\0');
  17838. ASSERT_STRCASEEQ(buffer.data(), reject);
  17839. }
  17840. }
  17841. }
  17842. #endif
  17843. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  17844. // Regression test for #2458.
  17845. //
  17846. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  17847. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  17848. // ticket can make the client socket spuriously readable during the
  17849. // 100-continue wait. If the readiness is mistaken for an incoming response,
  17850. // the client withholds the body and then blocks reading a response that never
  17851. // comes, failing with `Failed to read connection`.
  17852. //
  17853. // A correct client (like curl) sends the body once no `100 Continue` arrives
  17854. // within the timeout. This raw OpenSSL server deliberately never sends
  17855. // `100 Continue`; the client must still deliver the body and receive 200.
  17856. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  17857. signal(SIGPIPE, SIG_IGN);
  17858. const auto port = PORT + 4;
  17859. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17860. ASSERT_NE(srv, INVALID_SOCKET);
  17861. int opt = 1;
  17862. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  17863. sockaddr_in addr{};
  17864. addr.sin_family = AF_INET;
  17865. addr.sin_port = htons(static_cast<uint16_t>(port));
  17866. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17867. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17868. ASSERT_EQ(0, ::listen(srv, 1));
  17869. std::atomic<size_t> server_body_bytes{0};
  17870. auto server_thread = std::thread([&] {
  17871. sockaddr_in cli_addr{};
  17872. socklen_t cli_len = sizeof(cli_addr);
  17873. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17874. if (cli == INVALID_SOCKET) { return; }
  17875. // Bound the lifetime of the server side so a buggy client (which never
  17876. // sends the body) cannot make this thread block forever on join.
  17877. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  17878. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  17879. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  17880. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  17881. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  17882. SSL *ssl = SSL_new(ctx);
  17883. SSL_set_fd(ssl, static_cast<int>(cli));
  17884. if (SSL_accept(ssl) > 0) {
  17885. // Read the request headers. Reading here also flushes the TLS 1.3
  17886. // session tickets to the client. Deliberately do NOT send
  17887. // `100 Continue`.
  17888. std::string buf;
  17889. char tmp[1024];
  17890. while (buf.find("\r\n\r\n") == std::string::npos) {
  17891. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17892. if (n <= 0) { break; }
  17893. buf.append(tmp, static_cast<size_t>(n));
  17894. }
  17895. // A correct client sends the body now; count what arrives.
  17896. auto pos = buf.find("\r\n\r\n");
  17897. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  17898. while (body < 4096) {
  17899. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17900. if (n <= 0) { break; }
  17901. body += static_cast<size_t>(n);
  17902. }
  17903. server_body_bytes = body;
  17904. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  17905. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  17906. SSL_shutdown(ssl);
  17907. }
  17908. SSL_free(ssl);
  17909. detail::close_socket(cli);
  17910. SSL_CTX_free(ctx);
  17911. });
  17912. auto se = detail::scope_exit([&] {
  17913. server_thread.join();
  17914. detail::close_socket(srv);
  17915. });
  17916. SSLClient cli("127.0.0.1", port);
  17917. cli.enable_server_certificate_verification(false);
  17918. cli.set_connection_timeout(5, 0);
  17919. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  17920. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  17921. std::string body(4096, 'A');
  17922. auto res = cli.Put("/api/test", body, "application/json");
  17923. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  17924. EXPECT_EQ(StatusCode::OK_200, res->status);
  17925. EXPECT_EQ(body.size(), server_body_bytes.load());
  17926. }
  17927. #endif
  17928. template <typename S, typename C>
  17929. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  17930. svr.Get("/stream", [&](const Request &, Response &res) {
  17931. auto data = new std::string("01234567890123456789");
  17932. res.set_content_provider(
  17933. data->size(), "text/plain",
  17934. [&, data](size_t offset, size_t length, DataSink &sink) {
  17935. const size_t DATA_CHUNK_SIZE = 4;
  17936. const auto &d = *data;
  17937. std::this_thread::sleep_for(std::chrono::seconds(1));
  17938. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  17939. return true;
  17940. },
  17941. [data](bool success) {
  17942. EXPECT_FALSE(success);
  17943. delete data;
  17944. });
  17945. });
  17946. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  17947. auto i = new size_t(0);
  17948. res.set_content_provider(
  17949. "text/plain",
  17950. [i](size_t, DataSink &sink) {
  17951. if (*i < 5) {
  17952. std::this_thread::sleep_for(std::chrono::seconds(1));
  17953. sink.write("abcd", 4);
  17954. (*i)++;
  17955. } else {
  17956. sink.done();
  17957. }
  17958. return true;
  17959. },
  17960. [i](bool success) {
  17961. EXPECT_FALSE(success);
  17962. delete i;
  17963. });
  17964. });
  17965. svr.Get("/chunked", [&](const Request &, Response &res) {
  17966. auto i = new size_t(0);
  17967. res.set_chunked_content_provider(
  17968. "text/plain",
  17969. [i](size_t, DataSink &sink) {
  17970. if (*i < 5) {
  17971. std::this_thread::sleep_for(std::chrono::seconds(1));
  17972. sink.os << "abcd";
  17973. (*i)++;
  17974. } else {
  17975. sink.done();
  17976. }
  17977. return true;
  17978. },
  17979. [i](bool success) {
  17980. EXPECT_FALSE(success);
  17981. delete i;
  17982. });
  17983. });
  17984. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  17985. auto se = detail::scope_exit([&] {
  17986. svr.stop();
  17987. listen_thread.join();
  17988. ASSERT_FALSE(svr.is_running());
  17989. });
  17990. svr.wait_until_ready();
  17991. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  17992. {
  17993. auto start = std::chrono::steady_clock::now();
  17994. auto res = cli.Get("/stream");
  17995. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17996. std::chrono::steady_clock::now() - start)
  17997. .count();
  17998. ASSERT_FALSE(res);
  17999. EXPECT_EQ(Error::Read, res.error());
  18000. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18001. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18002. }
  18003. {
  18004. auto start = std::chrono::steady_clock::now();
  18005. auto res = cli.Get("/stream_without_length");
  18006. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18007. std::chrono::steady_clock::now() - start)
  18008. .count();
  18009. ASSERT_FALSE(res);
  18010. EXPECT_EQ(Error::Read, res.error());
  18011. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18012. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18013. }
  18014. {
  18015. auto start = std::chrono::steady_clock::now();
  18016. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  18017. EXPECT_EQ("abcd", string(data, data_length));
  18018. return true;
  18019. });
  18020. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18021. std::chrono::steady_clock::now() - start)
  18022. .count();
  18023. ASSERT_FALSE(res);
  18024. EXPECT_EQ(Error::Read, res.error());
  18025. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18026. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18027. }
  18028. }
  18029. TEST(MaxTimeoutTest, ContentStream) {
  18030. time_t timeout = 2000;
  18031. time_t threshold = 200;
  18032. Server svr;
  18033. Client cli("localhost", PORT);
  18034. max_timeout_test(svr, cli, timeout, threshold);
  18035. }
  18036. #ifdef CPPHTTPLIB_SSL_ENABLED
  18037. TEST(MaxTimeoutTest, ContentStreamSSL) {
  18038. time_t timeout = 2000;
  18039. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  18040. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18041. SSLClient cli("localhost", PORT);
  18042. cli.enable_server_certificate_verification(false);
  18043. max_timeout_test(svr, cli, timeout, threshold);
  18044. }
  18045. #endif
  18046. class EventDispatcher {
  18047. public:
  18048. EventDispatcher() {}
  18049. bool wait_event(DataSink *sink) {
  18050. unique_lock<mutex> lk(m_);
  18051. int id = id_;
  18052. // Wait with timeout to prevent hanging if client disconnects
  18053. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  18054. [&] { return cid_ == id; })) {
  18055. return false; // Timeout occurred
  18056. }
  18057. sink->write(message_.data(), message_.size());
  18058. return true;
  18059. }
  18060. void send_event(const string &message) {
  18061. lock_guard<mutex> lk(m_);
  18062. cid_ = id_++;
  18063. message_ = message;
  18064. cv_.notify_all();
  18065. }
  18066. private:
  18067. mutex m_;
  18068. condition_variable cv_;
  18069. atomic_int id_{0};
  18070. atomic_int cid_{-1};
  18071. string message_;
  18072. };
  18073. TEST(ClientInThreadTest, Issue2068) {
  18074. EventDispatcher ed;
  18075. Server svr;
  18076. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  18077. res.set_chunked_content_provider("text/event-stream",
  18078. [&](size_t /*offset*/, DataSink &sink) {
  18079. return ed.wait_event(&sink);
  18080. });
  18081. });
  18082. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  18083. svr.wait_until_ready();
  18084. thread event_thread([&] {
  18085. int id = 0;
  18086. while (svr.is_running()) {
  18087. this_thread::sleep_for(chrono::milliseconds(500));
  18088. std::stringstream ss;
  18089. ss << "data: " << id << "\n\n";
  18090. ed.send_event(ss.str());
  18091. id++;
  18092. }
  18093. });
  18094. auto se = detail::scope_exit([&] {
  18095. svr.stop();
  18096. listen_thread.join();
  18097. event_thread.join();
  18098. ASSERT_FALSE(svr.is_running());
  18099. });
  18100. {
  18101. auto client = detail::make_unique<Client>(HOST, PORT);
  18102. client->set_read_timeout(std::chrono::minutes(10));
  18103. std::atomic<bool> stop{false};
  18104. std::thread t([&] {
  18105. client->Get("/event1",
  18106. [&](const char *, size_t) -> bool { return !stop; });
  18107. });
  18108. std::this_thread::sleep_for(std::chrono::seconds(2));
  18109. stop = true;
  18110. client->stop();
  18111. t.join();
  18112. // Reset client after thread has finished
  18113. client.reset();
  18114. }
  18115. }
  18116. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  18117. auto handled = false;
  18118. Server svr;
  18119. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18120. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18121. auto se = detail::scope_exit([&] {
  18122. svr.stop();
  18123. t.join();
  18124. ASSERT_FALSE(svr.is_running());
  18125. ASSERT_FALSE(handled);
  18126. });
  18127. svr.wait_until_ready();
  18128. // Two Content-Length headers with different values — must be rejected
  18129. auto req = "POST /test HTTP/1.1\r\n"
  18130. "Content-Length: 5\r\n"
  18131. "Content-Length: 10\r\n"
  18132. "\r\n"
  18133. "hello";
  18134. std::string response;
  18135. ASSERT_TRUE(send_request(1, req, &response));
  18136. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18137. response.substr(0, response.find("\r\n")));
  18138. }
  18139. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  18140. auto handled = false;
  18141. Server svr;
  18142. svr.Post("/test", [&](const Request &, Response &res) {
  18143. handled = true;
  18144. res.set_content("ok", "text/plain");
  18145. });
  18146. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18147. auto se = detail::scope_exit([&] {
  18148. svr.stop();
  18149. t.join();
  18150. ASSERT_FALSE(svr.is_running());
  18151. ASSERT_TRUE(handled);
  18152. });
  18153. svr.wait_until_ready();
  18154. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  18155. auto req = "POST /test HTTP/1.1\r\n"
  18156. "Host: localhost\r\n"
  18157. "Content-Length: 5\r\n"
  18158. "Content-Length: 5\r\n"
  18159. "\r\n"
  18160. "hello";
  18161. std::string response;
  18162. ASSERT_TRUE(send_request(1, req, &response));
  18163. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18164. }
  18165. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  18166. Server svr;
  18167. svr.Get("/test", [](const Request &, Response &res) {
  18168. res.set_content("ok", "text/plain");
  18169. });
  18170. auto port = svr.bind_to_any_port(HOST);
  18171. thread t = thread([&] { svr.listen_after_bind(); });
  18172. auto se = detail::scope_exit([&] {
  18173. svr.stop();
  18174. t.join();
  18175. ASSERT_FALSE(svr.is_running());
  18176. });
  18177. svr.wait_until_ready();
  18178. auto status_line = [&](const std::string &host_lines) {
  18179. std::string res;
  18180. send_request(
  18181. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  18182. &res, port);
  18183. return res.substr(0, res.find("\r\n"));
  18184. };
  18185. const char *accepted[] = {
  18186. "Host: localhost\r\n",
  18187. "Host: a.example:8080\r\n",
  18188. "Host: my_service\r\n",
  18189. "Host: [::1]:8080\r\n",
  18190. "Host: [fe80::1%25eth0]\r\n",
  18191. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  18192. };
  18193. for (auto host_lines : accepted) {
  18194. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  18195. }
  18196. const char *rejected[] = {
  18197. "Host: a.example\r\nHost: b.example\r\n",
  18198. "Host: a.example\r\nHost: a.example\r\n",
  18199. "Host: a@b.example\r\n",
  18200. "Host: a.example/b\r\n",
  18201. "Host: a.example\\b\r\n",
  18202. "Host: a.example?b\r\n",
  18203. "Host: a.example#b\r\n",
  18204. "Host: a.example b.example\r\n",
  18205. };
  18206. for (auto host_lines : rejected) {
  18207. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  18208. << host_lines;
  18209. }
  18210. }
  18211. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  18212. Server svr;
  18213. svr.Get("/", [](const Request &req, Response &res) {
  18214. EXPECT_EQ(2U, req.trailers.size());
  18215. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  18216. // Denied
  18217. EXPECT_FALSE(req.has_trailer("Content-Length"));
  18218. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  18219. // Accepted
  18220. EXPECT_TRUE(req.has_trailer("X-Hello"));
  18221. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  18222. EXPECT_TRUE(req.has_trailer("X-World"));
  18223. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  18224. res.set_content("ok", "text/plain");
  18225. });
  18226. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18227. auto se = detail::scope_exit([&] {
  18228. svr.stop();
  18229. t.join();
  18230. ASSERT_FALSE(svr.is_running());
  18231. });
  18232. svr.wait_until_ready();
  18233. const std::string req = "GET / HTTP/1.1\r\n"
  18234. "Transfer-Encoding: chunked\r\n"
  18235. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  18236. "\r\n"
  18237. "0\r\n"
  18238. "Content-Length: 10\r\n"
  18239. "Host: internal.local\r\n"
  18240. "Content-Type: malicious/content\r\n"
  18241. "Cookie: any\r\n"
  18242. "Set-Cookie: any\r\n"
  18243. "X-Forwarded-For: attacker.com\r\n"
  18244. "X-Real-Ip: 1.1.1.1\r\n"
  18245. "X-Hello: hello\r\n"
  18246. "X-World: world\r\n"
  18247. "\r\n";
  18248. std::string res;
  18249. ASSERT_TRUE(send_request(1, req, &res));
  18250. }
  18251. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  18252. // several field lines, and the combined value is what has to be parsed. A
  18253. // Trailer field split across lines therefore declares every name it lists;
  18254. // reading only the first line silently drops the trailers the later lines
  18255. // declare. The prohibited-trailer filter still applies to every line.
  18256. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  18257. Server svr;
  18258. size_t observed_trailer_count = 0;
  18259. std::string observed_hello;
  18260. std::string observed_world;
  18261. bool observed_content_length = true;
  18262. svr.Get("/", [&](const Request &req, Response &res) {
  18263. observed_trailer_count = req.trailers.size();
  18264. observed_hello = req.get_trailer_value("X-Hello");
  18265. observed_world = req.get_trailer_value("X-World");
  18266. observed_content_length = req.has_trailer("Content-Length");
  18267. res.set_content("ok", "text/plain");
  18268. });
  18269. auto port = svr.bind_to_any_port(HOST);
  18270. thread t = thread([&]() { svr.listen_after_bind(); });
  18271. auto se = detail::scope_exit([&] {
  18272. svr.stop();
  18273. t.join();
  18274. ASSERT_FALSE(svr.is_running());
  18275. });
  18276. svr.wait_until_ready();
  18277. const std::string req = "GET / HTTP/1.1\r\n"
  18278. "Host: localhost\r\n"
  18279. "Transfer-Encoding: chunked\r\n"
  18280. "Trailer: X-Hello\r\n"
  18281. "Trailer: X-World, Content-Length\r\n"
  18282. "\r\n"
  18283. "0\r\n"
  18284. "X-Hello: hello\r\n"
  18285. "X-World: world\r\n"
  18286. "Content-Length: 10\r\n"
  18287. "\r\n";
  18288. std::string res;
  18289. ASSERT_TRUE(send_request(1, req, &res, port));
  18290. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  18291. // Accepted: both field lines contribute to the declared set
  18292. EXPECT_EQ(2U, observed_trailer_count);
  18293. EXPECT_EQ(observed_hello, "hello");
  18294. EXPECT_EQ(observed_world, "world");
  18295. // Denied: a prohibited name stays prohibited on a later field line
  18296. EXPECT_FALSE(observed_content_length);
  18297. }
  18298. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  18299. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  18300. // unbounded run of fields that are never declared, because the counter would
  18301. // only advance for declared fields.
  18302. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  18303. Server svr;
  18304. bool handler_called = false;
  18305. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  18306. handler_called = true;
  18307. res.set_content("ok", "text/plain");
  18308. });
  18309. auto port = svr.bind_to_any_port(HOST);
  18310. thread t = thread([&]() { svr.listen_after_bind(); });
  18311. auto se = detail::scope_exit([&] {
  18312. svr.stop();
  18313. t.join();
  18314. ASSERT_FALSE(svr.is_running());
  18315. });
  18316. svr.wait_until_ready();
  18317. // Declare nothing, then send far more undeclared trailer fields than the
  18318. // header-count limit. Parsing must stop and reject the request rather than
  18319. // read every line.
  18320. std::string req = "GET / HTTP/1.1\r\n"
  18321. "Transfer-Encoding: chunked\r\n"
  18322. "\r\n"
  18323. "0\r\n";
  18324. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  18325. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  18326. }
  18327. req += "\r\n";
  18328. std::string res;
  18329. ASSERT_TRUE(send_request(1, req, &res, port));
  18330. // The request is rejected before the handler runs.
  18331. EXPECT_FALSE(handler_called);
  18332. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  18333. }
  18334. // The set of declared trailer names is capped so a peer cannot grow it without
  18335. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  18336. // declared past the cap is not honored, even if the field is actually sent.
  18337. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  18338. Server svr;
  18339. // One name inside the cap and one past it, so the test tracks the cap rather
  18340. // than a fixed count.
  18341. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  18342. const std::string within_cap_name = "X-T-0";
  18343. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  18344. bool observed_within_cap = false;
  18345. bool observed_past_cap = false;
  18346. svr.Get("/", [&](const Request &req, Response &res) {
  18347. observed_within_cap = req.has_trailer(within_cap_name);
  18348. observed_past_cap = req.has_trailer(past_cap_name);
  18349. res.set_content("ok", "text/plain");
  18350. });
  18351. auto port = svr.bind_to_any_port(HOST);
  18352. thread t = thread([&]() { svr.listen_after_bind(); });
  18353. auto se = detail::scope_exit([&] {
  18354. svr.stop();
  18355. t.join();
  18356. ASSERT_FALSE(svr.is_running());
  18357. });
  18358. svr.wait_until_ready();
  18359. // Declare more trailer names than the cap in a single Trailer field, then
  18360. // actually send the first (within the cap) and the last (past it).
  18361. std::string trailer_decl = "Trailer: ";
  18362. for (int i = 0; i < declared_count; i++) {
  18363. if (i != 0) { trailer_decl += ", "; }
  18364. trailer_decl += "X-T-" + std::to_string(i);
  18365. }
  18366. trailer_decl += "\r\n";
  18367. const std::string req = "GET / HTTP/1.1\r\n"
  18368. "Host: localhost\r\n"
  18369. "Transfer-Encoding: chunked\r\n" +
  18370. trailer_decl +
  18371. "\r\n"
  18372. "0\r\n" +
  18373. within_cap_name + ": a\r\n" + past_cap_name +
  18374. ": b\r\n"
  18375. "\r\n";
  18376. std::string res;
  18377. ASSERT_TRUE(send_request(1, req, &res, port));
  18378. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  18379. // A name within the cap is honored; one declared past the cap is dropped.
  18380. EXPECT_TRUE(observed_within_cap);
  18381. EXPECT_FALSE(observed_past_cap);
  18382. }
  18383. // A direct client that is not listed in trusted_proxies must not be able to
  18384. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  18385. // the peer address on the actual TCP connection determines whether the
  18386. // header is honored.
  18387. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  18388. Server svr;
  18389. // Deliberately does NOT include the loopback address the test client
  18390. // actually connects from, so the direct connection is not a trusted proxy.
  18391. svr.set_trusted_proxies({"203.0.113.66"});
  18392. std::string observed_remote_addr;
  18393. svr.Get("/ip", [&](const Request &req, Response &res) {
  18394. observed_remote_addr = req.remote_addr;
  18395. res.set_content("ok", "text/plain");
  18396. });
  18397. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18398. auto se = detail::scope_exit([&] {
  18399. svr.stop();
  18400. t.join();
  18401. ASSERT_FALSE(svr.is_running());
  18402. });
  18403. svr.wait_until_ready();
  18404. Client cli(HOST, PORT);
  18405. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  18406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18407. EXPECT_EQ(StatusCode::OK_200, res->status);
  18408. // The connecting peer is not a trusted proxy, so the spoofed header must be
  18409. // ignored entirely and the real connection-level address retained.
  18410. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18411. observed_remote_addr == "127.0.0.1");
  18412. }
  18413. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  18414. Server svr;
  18415. std::string observed_remote_addr;
  18416. std::string observed_xff;
  18417. svr.Get("/ip", [&](const Request &req, Response &res) {
  18418. observed_remote_addr = req.remote_addr;
  18419. observed_xff = req.get_header_value("X-Forwarded-For");
  18420. res.set_content("ok", "text/plain");
  18421. });
  18422. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18423. auto se = detail::scope_exit([&] {
  18424. svr.stop();
  18425. t.join();
  18426. ASSERT_FALSE(svr.is_running());
  18427. });
  18428. svr.wait_until_ready();
  18429. Client cli(HOST, PORT);
  18430. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  18431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18432. EXPECT_EQ(StatusCode::OK_200, res->status);
  18433. EXPECT_EQ(observed_xff, "203.0.113.66");
  18434. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18435. observed_remote_addr == "127.0.0.1");
  18436. }
  18437. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  18438. Server svr;
  18439. svr.set_trusted_proxies({"203.0.113.66"});
  18440. std::string observed_remote_addr;
  18441. std::string observed_xff;
  18442. svr.Get("/ip", [&](const Request &req, Response &res) {
  18443. observed_remote_addr = req.remote_addr;
  18444. observed_xff = req.get_header_value("X-Forwarded-For");
  18445. res.set_content("ok", "text/plain");
  18446. });
  18447. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18448. auto se = detail::scope_exit([&] {
  18449. svr.stop();
  18450. t.join();
  18451. ASSERT_FALSE(svr.is_running());
  18452. });
  18453. svr.wait_until_ready();
  18454. Client cli(HOST, PORT);
  18455. auto res = cli.Get("/ip");
  18456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18457. EXPECT_EQ(StatusCode::OK_200, res->status);
  18458. EXPECT_EQ(observed_xff, "");
  18459. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18460. observed_remote_addr == "127.0.0.1");
  18461. }
  18462. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  18463. Server svr;
  18464. // Include the loopback address the test client actually connects from, so
  18465. // the direct connection itself is recognized as the trusted proxy hop.
  18466. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  18467. std::string observed_remote_addr;
  18468. std::string observed_xff;
  18469. svr.Get("/ip", [&](const Request &req, Response &res) {
  18470. observed_remote_addr = req.remote_addr;
  18471. observed_xff = req.get_header_value("X-Forwarded-For");
  18472. res.set_content("ok", "text/plain");
  18473. });
  18474. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18475. auto se = detail::scope_exit([&] {
  18476. svr.stop();
  18477. t.join();
  18478. ASSERT_FALSE(svr.is_running());
  18479. });
  18480. svr.wait_until_ready();
  18481. Client cli(HOST, PORT);
  18482. auto res = cli.Get(
  18483. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  18484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18485. EXPECT_EQ(StatusCode::OK_200, res->status);
  18486. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  18487. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18488. }
  18489. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  18490. Server svr;
  18491. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  18492. std::string observed_remote_addr;
  18493. std::string observed_xff;
  18494. svr.Get("/ip", [&](const Request &req, Response &res) {
  18495. observed_remote_addr = req.remote_addr;
  18496. observed_xff = req.get_header_value("X-Forwarded-For");
  18497. res.set_content("ok", "text/plain");
  18498. });
  18499. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18500. auto se = detail::scope_exit([&] {
  18501. svr.stop();
  18502. t.join();
  18503. ASSERT_FALSE(svr.is_running());
  18504. });
  18505. svr.wait_until_ready();
  18506. Client cli(HOST, PORT);
  18507. auto res = cli.Get(
  18508. "/ip",
  18509. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18511. EXPECT_EQ(StatusCode::OK_200, res->status);
  18512. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18513. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18514. }
  18515. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  18516. Server svr;
  18517. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18518. std::string observed_remote_addr;
  18519. std::string observed_xff;
  18520. svr.Get("/ip", [&](const Request &req, Response &res) {
  18521. observed_remote_addr = req.remote_addr;
  18522. observed_xff = req.get_header_value("X-Forwarded-For");
  18523. res.set_content("ok", "text/plain");
  18524. });
  18525. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18526. auto se = detail::scope_exit([&] {
  18527. svr.stop();
  18528. t.join();
  18529. ASSERT_FALSE(svr.is_running());
  18530. });
  18531. svr.wait_until_ready();
  18532. Client cli(HOST, PORT);
  18533. auto res = cli.Get(
  18534. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  18535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18536. EXPECT_EQ(StatusCode::OK_200, res->status);
  18537. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  18538. // by the closest hop) is used. The leftmost entry is fully client-controlled
  18539. // and must not be selected.
  18540. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  18541. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  18542. }
  18543. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  18544. Server svr;
  18545. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  18546. std::string observed_remote_addr;
  18547. svr.Get("/ip", [&](const Request &req, Response &res) {
  18548. observed_remote_addr = req.remote_addr;
  18549. res.set_content("ok", "text/plain");
  18550. });
  18551. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18552. auto se = detail::scope_exit([&] {
  18553. svr.stop();
  18554. t.join();
  18555. ASSERT_FALSE(svr.is_running());
  18556. });
  18557. svr.wait_until_ready();
  18558. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  18559. // a forged address and the trusted proxy's own address; the forged value must
  18560. // not win over the address the trusted proxy actually recorded.
  18561. Client cli(HOST, PORT);
  18562. auto res = cli.Get(
  18563. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  18564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18565. EXPECT_EQ(StatusCode::OK_200, res->status);
  18566. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  18567. }
  18568. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  18569. Server svr;
  18570. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18571. std::string observed_remote_addr;
  18572. std::string observed_xff;
  18573. svr.Get("/ip", [&](const Request &req, Response &res) {
  18574. observed_remote_addr = req.remote_addr;
  18575. observed_xff = req.get_header_value("X-Forwarded-For");
  18576. res.set_content("ok", "text/plain");
  18577. });
  18578. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18579. auto se = detail::scope_exit([&] {
  18580. svr.stop();
  18581. t.join();
  18582. ASSERT_FALSE(svr.is_running());
  18583. });
  18584. svr.wait_until_ready();
  18585. Client cli(HOST, PORT);
  18586. auto res = cli.Get(
  18587. "/ip",
  18588. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18590. EXPECT_EQ(StatusCode::OK_200, res->status);
  18591. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18592. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18593. }
  18594. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  18595. Server svr;
  18596. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18597. std::string observed_remote_addr;
  18598. std::string observed_xff;
  18599. svr.Get("/ip", [&](const Request &req, Response &res) {
  18600. observed_remote_addr = req.remote_addr;
  18601. observed_xff = req.get_header_value("X-Forwarded-For");
  18602. res.set_content("ok", "text/plain");
  18603. });
  18604. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18605. auto se = detail::scope_exit([&] {
  18606. svr.stop();
  18607. t.join();
  18608. ASSERT_FALSE(svr.is_running());
  18609. });
  18610. svr.wait_until_ready();
  18611. std::string raw_req =
  18612. "GET /ip HTTP/1.1\r\n"
  18613. "Host: localhost\r\n"
  18614. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  18615. "Connection: close\r\n"
  18616. "\r\n";
  18617. std::string out;
  18618. ASSERT_TRUE(send_request(5, raw_req, &out));
  18619. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18620. // Header parser trims surrounding whitespace of the header value
  18621. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  18622. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  18623. }
  18624. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  18625. // one comma-joined value, in the order received. Proxies such as HAProxy append
  18626. // their own X-Forwarded-For as a separate field line rather than extending the
  18627. // one the client sent, so every occurrence has to be taken into account.
  18628. // Reading only the first one hands back the address the client chose.
  18629. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  18630. Server svr;
  18631. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18632. std::string observed_remote_addr;
  18633. size_t observed_xff_count = 0;
  18634. svr.Get("/ip", [&](const Request &req, Response &res) {
  18635. observed_remote_addr = req.remote_addr;
  18636. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  18637. res.set_content("ok", "text/plain");
  18638. });
  18639. auto port = svr.bind_to_any_port(HOST);
  18640. thread t = thread([&]() { svr.listen_after_bind(); });
  18641. auto se = detail::scope_exit([&] {
  18642. svr.stop();
  18643. t.join();
  18644. ASSERT_FALSE(svr.is_running());
  18645. });
  18646. svr.wait_until_ready();
  18647. // The client supplies the first field line; the trusted proxy appends the
  18648. // address it observed as a second one.
  18649. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  18650. "Host: localhost\r\n"
  18651. "X-Forwarded-For: 1.2.3.4\r\n"
  18652. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  18653. "Connection: close\r\n"
  18654. "\r\n";
  18655. std::string out;
  18656. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18657. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18658. EXPECT_EQ(observed_xff_count, 2U);
  18659. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18660. // The same chain spread over one field line per hop derives the same client
  18661. // address, i.e. the split and the comma-joined representations agree.
  18662. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  18663. "Host: localhost\r\n"
  18664. "X-Forwarded-For: 1.2.3.4\r\n"
  18665. "X-Forwarded-For: 198.51.100.23\r\n"
  18666. "X-Forwarded-For: 192.0.2.45\r\n"
  18667. "Connection: close\r\n"
  18668. "\r\n";
  18669. out.clear();
  18670. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  18671. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18672. EXPECT_EQ(observed_xff_count, 3U);
  18673. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18674. }
  18675. // An X-Forwarded-For header whose value parses to zero IP segments must not
  18676. // crash the server (it used to call front() on an empty vector inside
  18677. // get_client_ip). The connection-level remote address must be retained instead.
  18678. static void run_malformed_xff_test(const std::string &xff_value) {
  18679. Server svr;
  18680. svr.set_trusted_proxies({"192.0.2.45"});
  18681. std::string observed_remote_addr;
  18682. svr.Get("/ip", [&](const Request &req, Response &res) {
  18683. observed_remote_addr = req.remote_addr;
  18684. res.set_content("ok", "text/plain");
  18685. });
  18686. int port = 0;
  18687. thread t = thread([&]() {
  18688. port = svr.bind_to_any_port(HOST);
  18689. svr.listen_after_bind();
  18690. });
  18691. auto se = detail::scope_exit([&] {
  18692. svr.stop();
  18693. t.join();
  18694. ASSERT_FALSE(svr.is_running());
  18695. });
  18696. svr.wait_until_ready();
  18697. Client cli(HOST, port);
  18698. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  18699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18700. EXPECT_EQ(StatusCode::OK_200, res->status);
  18701. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18702. observed_remote_addr == "127.0.0.1");
  18703. }
  18704. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  18705. run_malformed_xff_test("");
  18706. }
  18707. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  18708. run_malformed_xff_test(",");
  18709. }
  18710. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  18711. run_malformed_xff_test(", , ,");
  18712. }
  18713. // The same rule applies to Accept: a request whose acceptable types are spread
  18714. // over several field lines must be negotiated against all of them.
  18715. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  18716. // case-insensitive connection options. Comparing the whole field value against
  18717. // one option misses a client that sends several of them, and misses every
  18718. // casing but the one written in the comparison.
  18719. //
  18720. // Sends req, reads the response, then reuses the same socket for a second
  18721. // request to find out whether the server kept the connection.
  18722. static void probe_connection_reuse(int port, const std::string &req,
  18723. bool *announced_close, bool *reusable) {
  18724. auto error = Error::Success;
  18725. auto sock = detail::create_client_socket(
  18726. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  18727. /*connection_timeout_sec=*/5, 0,
  18728. /*read_timeout_sec=*/1, 0,
  18729. /*write_timeout_sec=*/5, 0, std::string(), error);
  18730. ASSERT_NE(sock, INVALID_SOCKET);
  18731. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  18732. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  18733. "Host: localhost\r\n"
  18734. "Connection: close\r\n"
  18735. "\r\n";
  18736. std::string first_response;
  18737. std::string second_response;
  18738. detail::process_client_socket(
  18739. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  18740. [&](Stream &strm) {
  18741. if (strm.write(req.data(), req.size()) !=
  18742. static_cast<ssize_t>(req.size())) {
  18743. return false;
  18744. }
  18745. char buf[512];
  18746. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  18747. // Headers plus the two-byte body of the handler below
  18748. while (reader.getline()) {
  18749. first_response += reader.ptr();
  18750. if (first_response.find("ok") != std::string::npos) { break; }
  18751. }
  18752. if (strm.write(second.data(), second.size()) !=
  18753. static_cast<ssize_t>(second.size())) {
  18754. return true;
  18755. }
  18756. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  18757. while (reader2.getline()) {
  18758. second_response += reader2.ptr();
  18759. if (second_response.find("ok") != std::string::npos) { break; }
  18760. }
  18761. return true;
  18762. });
  18763. *announced_close =
  18764. first_response.find("Connection: close") != std::string::npos;
  18765. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  18766. }
  18767. class ConnectionTokenTest : public ::testing::Test {
  18768. protected:
  18769. void SetUp() override {
  18770. svr_.Get("/keepalive", [](const Request &, Response &res) {
  18771. res.set_content("ok", "text/plain");
  18772. });
  18773. port_ = svr_.bind_to_any_port(HOST);
  18774. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18775. svr_.wait_until_ready();
  18776. }
  18777. void TearDown() override {
  18778. svr_.stop();
  18779. if (thread_.joinable()) { thread_.join(); }
  18780. }
  18781. Server svr_;
  18782. int port_ = 0;
  18783. thread thread_;
  18784. };
  18785. // "close" alongside another option still closes the connection, and the
  18786. // response says so rather than leaving the peer to discover it.
  18787. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  18788. bool announced_close = false;
  18789. bool reusable = true;
  18790. probe_connection_reuse(port_,
  18791. "GET /keepalive HTTP/1.1\r\n"
  18792. "Host: localhost\r\n"
  18793. "Connection: keep-alive, close\r\n"
  18794. "\r\n",
  18795. &announced_close, &reusable);
  18796. EXPECT_TRUE(announced_close);
  18797. EXPECT_FALSE(reusable);
  18798. }
  18799. // "close" split over two field lines is the same list, so it is honored too.
  18800. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  18801. bool announced_close = false;
  18802. bool reusable = true;
  18803. probe_connection_reuse(port_,
  18804. "GET /keepalive HTTP/1.1\r\n"
  18805. "Host: localhost\r\n"
  18806. "Connection: keep-alive\r\n"
  18807. "Connection: close\r\n"
  18808. "\r\n",
  18809. &announced_close, &reusable);
  18810. EXPECT_TRUE(announced_close);
  18811. EXPECT_FALSE(reusable);
  18812. }
  18813. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  18814. // keep-alive in the spelling everyone actually sends keeps its connection.
  18815. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  18816. bool announced_close = false;
  18817. bool reusable = false;
  18818. probe_connection_reuse(port_,
  18819. "GET /keepalive HTTP/1.0\r\n"
  18820. "Host: localhost\r\n"
  18821. "Connection: keep-alive\r\n"
  18822. "\r\n",
  18823. &announced_close, &reusable);
  18824. EXPECT_FALSE(announced_close);
  18825. EXPECT_TRUE(reusable);
  18826. }
  18827. // A token the value merely contains is not the token itself.
  18828. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  18829. bool announced_close = false;
  18830. bool reusable = false;
  18831. probe_connection_reuse(port_,
  18832. "GET /keepalive HTTP/1.1\r\n"
  18833. "Host: localhost\r\n"
  18834. "Connection: notclose\r\n"
  18835. "\r\n",
  18836. &announced_close, &reusable);
  18837. EXPECT_FALSE(announced_close);
  18838. EXPECT_TRUE(reusable);
  18839. }
  18840. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  18841. Server svr;
  18842. std::vector<std::string> observed_types;
  18843. svr.Get("/", [&](const Request &req, Response &res) {
  18844. observed_types = req.accept_content_types;
  18845. res.set_content("ok", "text/plain");
  18846. });
  18847. auto port = svr.bind_to_any_port(HOST);
  18848. thread t = thread([&]() { svr.listen_after_bind(); });
  18849. auto se = detail::scope_exit([&] {
  18850. svr.stop();
  18851. t.join();
  18852. ASSERT_FALSE(svr.is_running());
  18853. });
  18854. svr.wait_until_ready();
  18855. Client cli(HOST, port);
  18856. Headers headers;
  18857. headers.emplace("Accept", "text/plain;q=0.5");
  18858. headers.emplace("Accept", "application/json");
  18859. auto res = cli.Get("/", headers);
  18860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18861. EXPECT_EQ(StatusCode::OK_200, res->status);
  18862. // Sorted by q-value, so the second field line's type comes first
  18863. ASSERT_EQ(2U, observed_types.size());
  18864. EXPECT_EQ("application/json", observed_types[0]);
  18865. EXPECT_EQ("text/plain", observed_types[1]);
  18866. }
  18867. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  18868. // empty field line must not contribute a bare comma to the combined value.
  18869. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  18870. Server svr;
  18871. std::vector<std::string> observed_types;
  18872. svr.Get("/", [&](const Request &req, Response &res) {
  18873. observed_types = req.accept_content_types;
  18874. res.set_content("ok", "text/plain");
  18875. });
  18876. auto port = svr.bind_to_any_port(HOST);
  18877. thread t = thread([&]() { svr.listen_after_bind(); });
  18878. auto se = detail::scope_exit([&] {
  18879. svr.stop();
  18880. t.join();
  18881. ASSERT_FALSE(svr.is_running());
  18882. });
  18883. svr.wait_until_ready();
  18884. // Empty first field line, then a real one
  18885. std::string raw_req = "GET / HTTP/1.1\r\n"
  18886. "Host: localhost\r\n"
  18887. "Accept:\r\n"
  18888. "Accept: application/json\r\n"
  18889. "Connection: close\r\n"
  18890. "\r\n";
  18891. std::string out;
  18892. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18893. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18894. ASSERT_EQ(1U, observed_types.size());
  18895. EXPECT_EQ("application/json", observed_types[0]);
  18896. }
  18897. // The skip in get_combined_header_value() is what keeps an empty field line
  18898. // from contributing a bare comma. Only a trailing empty field line exercises
  18899. // it: a leading one is already covered by the "combined is still empty" check,
  18900. // and parse_accept_header() now ignores the empty element either way, so the
  18901. // request-level test above can no longer tell the two apart.
  18902. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  18903. Headers headers;
  18904. headers.emplace("Accept", "text/html");
  18905. headers.emplace("Accept", "");
  18906. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  18907. headers.clear();
  18908. headers.emplace("Accept", "");
  18909. headers.emplace("Accept", "application/json");
  18910. EXPECT_EQ("application/json",
  18911. detail::get_combined_header_value(headers, "Accept"));
  18912. }
  18913. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18914. // An encoding offered on a later Accept-Encoding field line is still offered.
  18915. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  18916. Server svr;
  18917. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18918. res.set_content(std::string(1024, 'x'), "text/plain");
  18919. });
  18920. auto port = svr.bind_to_any_port(HOST);
  18921. thread t = thread([&]() { svr.listen_after_bind(); });
  18922. auto se = detail::scope_exit([&] {
  18923. svr.stop();
  18924. t.join();
  18925. ASSERT_FALSE(svr.is_running());
  18926. });
  18927. svr.wait_until_ready();
  18928. Client cli(HOST, port);
  18929. cli.set_decompress(false);
  18930. Headers headers;
  18931. headers.emplace("Accept-Encoding", "identity");
  18932. headers.emplace("Accept-Encoding", "gzip");
  18933. auto res = cli.Get("/", headers);
  18934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18935. EXPECT_EQ(StatusCode::OK_200, res->status);
  18936. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  18937. }
  18938. #endif
  18939. #ifndef _WIN32
  18940. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  18941. Server svr;
  18942. svr.Post("/post", [&](const Request &req, Response &res) {
  18943. res.set_content(req.body, "text/plain");
  18944. });
  18945. svr.Put("/put", [&](const Request &req, Response &res) {
  18946. res.set_content(req.body, "text/plain");
  18947. });
  18948. svr.Patch("/patch", [&](const Request &req, Response &res) {
  18949. res.set_content(req.body, "text/plain");
  18950. });
  18951. svr.Delete("/delete", [&](const Request &req, Response &res) {
  18952. res.set_content(req.body, "text/plain");
  18953. });
  18954. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18955. auto se = detail::scope_exit([&] {
  18956. svr.stop();
  18957. t.join();
  18958. ASSERT_FALSE(svr.is_running());
  18959. });
  18960. svr.wait_until_ready();
  18961. std::string resp;
  18962. // POST without Content-Length
  18963. ASSERT_TRUE(send_request(5,
  18964. "POST /post HTTP/1.1\r\n"
  18965. "Host: localhost\r\n"
  18966. "Connection: close\r\n"
  18967. "\r\n",
  18968. &resp));
  18969. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18970. // PUT without Content-Length
  18971. resp.clear();
  18972. ASSERT_TRUE(send_request(5,
  18973. "PUT /put HTTP/1.1\r\n"
  18974. "Host: localhost\r\n"
  18975. "Connection: close\r\n"
  18976. "\r\n",
  18977. &resp));
  18978. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18979. // PATCH without Content-Length
  18980. resp.clear();
  18981. ASSERT_TRUE(send_request(5,
  18982. "PATCH /patch HTTP/1.1\r\n"
  18983. "Host: localhost\r\n"
  18984. "Connection: close\r\n"
  18985. "\r\n",
  18986. &resp));
  18987. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18988. // DELETE without Content-Length
  18989. resp.clear();
  18990. ASSERT_TRUE(send_request(5,
  18991. "DELETE /delete HTTP/1.1\r\n"
  18992. "Host: localhost\r\n"
  18993. "Connection: close\r\n"
  18994. "\r\n",
  18995. &resp));
  18996. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18997. }
  18998. #endif
  18999. //==============================================================================
  19000. // open_stream() Tests
  19001. //==============================================================================
  19002. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  19003. std::string result;
  19004. char buf[8192];
  19005. ssize_t n;
  19006. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19007. result.append(buf, static_cast<size_t>(n));
  19008. }
  19009. return result;
  19010. }
  19011. // Mock stream for unit tests
  19012. class MockStream : public Stream {
  19013. public:
  19014. std::string data;
  19015. size_t pos = 0;
  19016. ssize_t error_after = -1; // -1 = no error
  19017. explicit MockStream(const std::string &d, ssize_t err = -1)
  19018. : data(d), error_after(err) {}
  19019. bool is_readable() const override { return true; }
  19020. bool wait_readable() const override { return true; }
  19021. bool wait_writable() const override { return true; }
  19022. ssize_t read(char *ptr, size_t size) override {
  19023. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  19024. if (pos >= data.size()) return 0;
  19025. size_t limit =
  19026. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  19027. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  19028. std::memcpy(ptr, data.data() + pos, to_read);
  19029. pos += to_read;
  19030. return static_cast<ssize_t>(to_read);
  19031. }
  19032. ssize_t write(const char *, size_t) override { return -1; }
  19033. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  19034. ip = "127.0.0.1";
  19035. port = 0;
  19036. }
  19037. void get_local_ip_and_port(std::string &ip, int &port) const override {
  19038. ip = "127.0.0.1";
  19039. port = 0;
  19040. }
  19041. socket_t socket() const override { return INVALID_SOCKET; }
  19042. time_t duration() const override { return 0; }
  19043. };
  19044. TEST(StreamHandleTest, Basic) {
  19045. ClientImpl::StreamHandle handle;
  19046. EXPECT_FALSE(handle.is_valid());
  19047. handle.response = detail::make_unique<Response>();
  19048. handle.error = Error::Connection;
  19049. EXPECT_FALSE(handle.is_valid());
  19050. handle.error = Error::Success;
  19051. EXPECT_TRUE(handle.is_valid());
  19052. }
  19053. TEST(BodyReaderTest, Basic) {
  19054. MockStream stream("Hello, World!");
  19055. detail::BodyReader reader;
  19056. reader.stream = &stream;
  19057. reader.content_length = 13;
  19058. char buf[32];
  19059. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  19060. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  19061. EXPECT_TRUE(reader.eof);
  19062. }
  19063. TEST(BodyReaderTest, NoStream) {
  19064. detail::BodyReader reader;
  19065. char buf[32];
  19066. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19067. EXPECT_EQ(Error::Connection, reader.last_error);
  19068. }
  19069. TEST(BodyReaderTest, Error) {
  19070. MockStream stream("Hello, World!", 5);
  19071. detail::BodyReader reader;
  19072. reader.stream = &stream;
  19073. reader.content_length = 13;
  19074. char buf[32];
  19075. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  19076. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19077. EXPECT_EQ(Error::Read, reader.last_error);
  19078. }
  19079. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  19080. // Mock-based StreamHandle tests relying on private internals are removed.
  19081. class OpenStreamTest : public ::testing::Test {
  19082. protected:
  19083. void SetUp() override {
  19084. svr_.Get("/hello", [](const Request &, Response &res) {
  19085. res.set_content("Hello World!", "text/plain");
  19086. });
  19087. svr_.Get("/large", [](const Request &, Response &res) {
  19088. res.set_content(std::string(10000, 'X'), "text/plain");
  19089. });
  19090. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  19091. res.set_content("Hello World!", "image/jpeg");
  19092. res.set_header("Content-Encoding", "UTF-8");
  19093. });
  19094. svr_.Get("/chunked", [](const Request &, Response &res) {
  19095. res.set_chunked_content_provider("text/plain",
  19096. [](size_t offset, DataSink &sink) {
  19097. if (offset < 15) {
  19098. sink.write("chunk", 5);
  19099. return true;
  19100. }
  19101. sink.done();
  19102. return true;
  19103. });
  19104. });
  19105. svr_.Get("/compressible", [](const Request &, Response &res) {
  19106. res.set_chunked_content_provider("text/plain", [](size_t offset,
  19107. DataSink &sink) {
  19108. if (offset < 100 * 1024) {
  19109. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  19110. sink.write(chunk.data(), chunk.size());
  19111. return true;
  19112. }
  19113. sink.done();
  19114. return true;
  19115. });
  19116. });
  19117. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  19118. [](const Request & /*req*/, Response &res) {
  19119. auto i = new int(0);
  19120. res.set_header("Trailer", "Content-Length, X-Allowed");
  19121. res.set_chunked_content_provider(
  19122. "text/plain",
  19123. [i](size_t /*offset*/, DataSink &sink) {
  19124. switch (*i) {
  19125. case 0: sink.os << "123"; break;
  19126. case 1: sink.os << "456"; break;
  19127. case 2: sink.os << "789"; break;
  19128. case 3: {
  19129. sink.done_with_trailer(
  19130. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  19131. } break;
  19132. }
  19133. (*i)++;
  19134. return true;
  19135. },
  19136. [i](bool success) {
  19137. EXPECT_TRUE(success);
  19138. delete i;
  19139. });
  19140. });
  19141. // Echo headers endpoint for header-related tests
  19142. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  19143. std::string body;
  19144. for (const auto &h : req.headers) {
  19145. body.append(h.first);
  19146. body.push_back(':');
  19147. body.append(h.second);
  19148. body.push_back('\n');
  19149. }
  19150. res.set_content(body, "text/plain");
  19151. });
  19152. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  19153. std::string body;
  19154. for (const auto &h : req.headers) {
  19155. body.append(h.first);
  19156. body.push_back(':');
  19157. body.append(h.second);
  19158. body.push_back('\n');
  19159. }
  19160. res.set_content(body, "text/plain");
  19161. });
  19162. port_ = svr_.bind_to_any_port("127.0.0.1");
  19163. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19164. svr_.wait_until_ready();
  19165. }
  19166. void TearDown() override {
  19167. svr_.stop();
  19168. if (thread_.joinable()) thread_.join();
  19169. }
  19170. Server svr_;
  19171. std::thread thread_;
  19172. int port_ = 0;
  19173. };
  19174. TEST_F(OpenStreamTest, Basic) {
  19175. Client cli("127.0.0.1", port_);
  19176. auto handle = cli.open_stream("GET", "/hello");
  19177. EXPECT_TRUE(handle.is_valid());
  19178. EXPECT_EQ("Hello World!", read_all(handle));
  19179. }
  19180. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  19181. Client cli("127.0.0.1", port_);
  19182. auto handle = cli.open_stream("GET", "/unknown-encoding");
  19183. ASSERT_TRUE(handle.is_valid());
  19184. EXPECT_EQ("Hello World!", read_all(handle));
  19185. }
  19186. TEST_F(OpenStreamTest, SmallBuffer) {
  19187. Client cli("127.0.0.1", port_);
  19188. auto handle = cli.open_stream("GET", "/hello");
  19189. std::string result;
  19190. char buf[4];
  19191. ssize_t n;
  19192. while ((n = handle.read(buf, sizeof(buf))) > 0)
  19193. result.append(buf, static_cast<size_t>(n));
  19194. EXPECT_EQ("Hello World!", result);
  19195. }
  19196. TEST_F(OpenStreamTest, DefaultHeaders) {
  19197. Client cli("127.0.0.1", port_);
  19198. // open_stream GET should include Host, User-Agent and Accept-Encoding
  19199. {
  19200. auto handle = cli.open_stream("GET", "/echo-headers");
  19201. ASSERT_TRUE(handle.is_valid());
  19202. auto body = read_all(handle);
  19203. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  19204. std::string::npos);
  19205. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  19206. std::string::npos);
  19207. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  19208. }
  19209. // open_stream POST with body and no explicit content_type should NOT add
  19210. // text/plain Content-Type (behavior differs from non-streaming path), but
  19211. // should include Content-Length
  19212. {
  19213. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  19214. ASSERT_TRUE(handle.is_valid());
  19215. auto body = read_all(handle);
  19216. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  19217. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  19218. }
  19219. // open_stream POST with explicit Content-Type should preserve it
  19220. {
  19221. auto handle = cli.open_stream("POST", "/echo-headers", {},
  19222. {{"Content-Type", "application/custom"}},
  19223. "{}", "application/custom");
  19224. ASSERT_TRUE(handle.is_valid());
  19225. auto body = read_all(handle);
  19226. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  19227. }
  19228. // User-specified User-Agent must not be overwritten for stream API
  19229. {
  19230. auto handle = cli.open_stream("GET", "/echo-headers", {},
  19231. {{"User-Agent", "MyAgent/1.2"}});
  19232. ASSERT_TRUE(handle.is_valid());
  19233. auto body = read_all(handle);
  19234. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  19235. }
  19236. }
  19237. TEST_F(OpenStreamTest, Large) {
  19238. Client cli("127.0.0.1", port_);
  19239. auto handle = cli.open_stream("GET", "/large");
  19240. EXPECT_EQ(10000u, read_all(handle).size());
  19241. }
  19242. TEST_F(OpenStreamTest, ConnectionError) {
  19243. Client cli("127.0.0.1", 9999);
  19244. auto handle = cli.open_stream("GET", "/hello");
  19245. EXPECT_FALSE(handle.is_valid());
  19246. }
  19247. TEST_F(OpenStreamTest, Chunked) {
  19248. Client cli("127.0.0.1", port_);
  19249. auto handle = cli.open_stream("GET", "/chunked");
  19250. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19251. "Transfer-Encoding") == "chunked");
  19252. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  19253. }
  19254. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  19255. Client cli("127.0.0.1", port_);
  19256. auto handle =
  19257. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  19258. ASSERT_TRUE(handle.is_valid());
  19259. // Consume body to allow trailers to be received/parsed
  19260. auto body = read_all(handle);
  19261. // Explicitly parse trailers (ensure trailers are available for assertion)
  19262. handle.parse_trailers_if_needed();
  19263. EXPECT_EQ(std::string("123456789"), body);
  19264. // The response should include a Trailer header declaring both names
  19265. ASSERT_TRUE(handle.response);
  19266. EXPECT_TRUE(handle.response->has_header("Trailer"));
  19267. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  19268. handle.response->get_header_value("Trailer"));
  19269. // Prohibited trailer must not be present
  19270. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  19271. // Allowed trailer should be present
  19272. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  19273. EXPECT_EQ(std::string("yes"),
  19274. handle.response->get_trailer_value("X-Allowed"));
  19275. // Verify trailers are NOT present as regular headers
  19276. EXPECT_EQ(std::string(""),
  19277. handle.response->get_header_value("Content-Length"));
  19278. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  19279. }
  19280. // Accepts one connection on an OS-assigned port, which it hands over through
  19281. // port_promise, reads the request head and sends back response. after_send,
  19282. // if given, runs on the connection before it is closed.
  19283. static std::thread
  19284. serve_single_response(std::promise<int> &port_promise,
  19285. const std::string &response,
  19286. std::function<void(socket_t)> after_send = nullptr) {
  19287. return std::thread([&port_promise, response, after_send] {
  19288. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19289. default_socket_options(srv);
  19290. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19291. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19292. sockaddr_in addr{};
  19293. addr.sin_family = AF_INET;
  19294. addr.sin_port = htons(0); // Let OS assign a free port
  19295. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19296. int opt = 1;
  19297. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  19298. #ifdef _WIN32
  19299. reinterpret_cast<const char *>(&opt),
  19300. #else
  19301. &opt,
  19302. #endif
  19303. sizeof(opt));
  19304. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  19305. ::listen(srv, 1) != 0) {
  19306. port_promise.set_value(-1);
  19307. detail::close_socket(srv);
  19308. return;
  19309. }
  19310. socklen_t addr_len = sizeof(addr);
  19311. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  19312. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  19313. sockaddr_in cli_addr{};
  19314. socklen_t cli_len = sizeof(cli_addr);
  19315. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19316. if (cli != INVALID_SOCKET) {
  19317. // Read the complete HTTP request (until the blank line that terminates
  19318. // headers) before sending the response. If the server closes the socket
  19319. // while the client's request data is still unread in the kernel receive
  19320. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  19321. // connection on both sides: it discards the client's receive buffer
  19322. // (which already holds our response) and causes any in-progress write on
  19323. // the client to fail with ECONNRESET. Reading all request data first
  19324. // ensures close() emits a graceful FIN.
  19325. {
  19326. char rbuf[256];
  19327. std::string req;
  19328. while (req.find("\r\n\r\n") == std::string::npos) {
  19329. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  19330. if (n <= 0) { break; }
  19331. req.append(rbuf, static_cast<size_t>(n));
  19332. }
  19333. }
  19334. ::send(cli,
  19335. #ifdef _WIN32
  19336. static_cast<const char *>(response.c_str()),
  19337. static_cast<int>(response.size()),
  19338. #else
  19339. response.c_str(), response.size(),
  19340. #endif
  19341. 0);
  19342. if (after_send) { after_send(cli); }
  19343. detail::close_socket(cli);
  19344. }
  19345. detail::close_socket(srv);
  19346. });
  19347. }
  19348. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  19349. #ifndef _WIN32
  19350. signal(SIGPIPE, SIG_IGN);
  19351. #endif
  19352. std::promise<int> port_promise;
  19353. auto port_future = port_promise.get_future();
  19354. auto server_thread =
  19355. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  19356. "Content-Type: text/plain\r\n"
  19357. "Content-Length: not-a-number\r\n"
  19358. "Connection: close\r\n"
  19359. "\r\n"
  19360. "hello");
  19361. auto port = port_future.get();
  19362. ASSERT_GT(port, 0);
  19363. Client cli("127.0.0.1", port);
  19364. auto handle = cli.open_stream("GET", "/");
  19365. EXPECT_FALSE(handle.is_valid());
  19366. server_thread.join();
  19367. }
  19368. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  19369. #ifndef _WIN32
  19370. signal(SIGPIPE, SIG_IGN);
  19371. #endif
  19372. std::promise<int> port_promise;
  19373. auto port_future = port_promise.get_future();
  19374. auto server_thread = serve_single_response(
  19375. port_promise, "HTTP/1.1 200 OK\r\n"
  19376. "Content-Type: text/plain\r\n"
  19377. "Content-Length: 99999999999999999999999999\r\n"
  19378. "Connection: close\r\n"
  19379. "\r\n"
  19380. "hello");
  19381. auto port = port_future.get();
  19382. ASSERT_GT(port, 0);
  19383. // Historically std::stoull would throw std::out_of_range here and crash
  19384. // the process, then parsing silently clamped to a bogus framing length and
  19385. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  19386. // so the stream fails to open, matching the not-a-number case above. The
  19387. // process still must NOT terminate.
  19388. Client cli("127.0.0.1", port);
  19389. auto handle = cli.open_stream("GET", "/");
  19390. EXPECT_FALSE(handle.is_valid());
  19391. server_thread.join();
  19392. }
  19393. // Serves `response` to the single request `fn` makes with a fresh client.
  19394. template <typename Fn>
  19395. static void with_single_response(const std::string &response, Fn fn) {
  19396. #ifndef _WIN32
  19397. signal(SIGPIPE, SIG_IGN);
  19398. #endif
  19399. std::promise<int> port_promise;
  19400. auto port_future = port_promise.get_future();
  19401. auto server_thread = serve_single_response(port_promise, response);
  19402. auto se = detail::scope_exit([&] { server_thread.join(); });
  19403. auto port = port_future.get();
  19404. ASSERT_GT(port, 0);
  19405. Client cli("127.0.0.1", port);
  19406. fn(cli);
  19407. }
  19408. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  19409. const char *responses[] = {
  19410. "HTTP/1.1 103 Early Hints\r\n"
  19411. "Link: </style.css>; rel=preload\r\n"
  19412. "\r\n"
  19413. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19414. "HTTP/1.1 100 Continue\r\n"
  19415. "X-Note: interim\r\n"
  19416. "\r\n"
  19417. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19418. };
  19419. for (auto response : responses) {
  19420. with_single_response(response, [](Client &cli) {
  19421. auto res = cli.Get("/");
  19422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19423. EXPECT_EQ(StatusCode::OK_200, res->status);
  19424. EXPECT_EQ("ok", res->body);
  19425. });
  19426. }
  19427. }
  19428. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  19429. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  19430. const std::string final_response =
  19431. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  19432. std::string interims;
  19433. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  19434. interims += interim;
  19435. }
  19436. with_single_response(interims + final_response, [](Client &cli) {
  19437. auto res = cli.Get("/");
  19438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19439. EXPECT_EQ("ok", res->body);
  19440. });
  19441. with_single_response(interims + interim + final_response, [](Client &cli) {
  19442. auto res = cli.Get("/");
  19443. ASSERT_FALSE(res);
  19444. EXPECT_EQ(Error::Read, res.error());
  19445. });
  19446. }
  19447. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  19448. #ifndef _WIN32
  19449. signal(SIGPIPE, SIG_IGN);
  19450. #endif
  19451. // The server answers the head without asking for the body. Bytes it then
  19452. // reads on the connection would be taken for the body the request declared.
  19453. auto closed_by_client = false;
  19454. std::promise<int> port_promise;
  19455. auto server_thread = serve_single_response(
  19456. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  19457. [&](socket_t sock) {
  19458. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19459. char buf[256];
  19460. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  19461. });
  19462. Client cli("127.0.0.1", port_promise.get_future().get());
  19463. cli.set_keep_alive(true);
  19464. cli.set_read_timeout(1, 0);
  19465. // Long enough for the client to send Expect: 100-continue.
  19466. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19468. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19469. cli.Get("/second");
  19470. server_thread.join();
  19471. EXPECT_TRUE(closed_by_client);
  19472. }
  19473. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  19474. // Long enough for the client to send Expect: 100-continue
  19475. with_single_response(
  19476. "HTTP/1.1 103 Early Hints\r\n"
  19477. "Link: </style.css>; rel=preload\r\n"
  19478. "\r\n"
  19479. "HTTP/1.1 401 Unauthorized\r\n"
  19480. "Content-Length: 0\r\n\r\n",
  19481. [](Client &cli) {
  19482. cli.set_read_timeout(2, 0);
  19483. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19485. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19486. });
  19487. }
  19488. #ifdef CPPHTTPLIB_SSL_ENABLED
  19489. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  19490. #ifndef _WIN32
  19491. signal(SIGPIPE, SIG_IGN);
  19492. #endif
  19493. auto reused = false;
  19494. std::promise<int> port_promise;
  19495. auto server_thread = serve_single_response(
  19496. port_promise,
  19497. "HTTP/1.1 401 Unauthorized\r\n"
  19498. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  19499. "Content-Length: 0\r\n\r\n",
  19500. [&](socket_t sock) {
  19501. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19502. char buf[256];
  19503. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  19504. });
  19505. Client cli("127.0.0.1", port_promise.get_future().get());
  19506. cli.set_keep_alive(true);
  19507. cli.set_digest_auth("user", "pass");
  19508. cli.set_read_timeout(1, 0);
  19509. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19510. server_thread.join();
  19511. EXPECT_FALSE(reused);
  19512. }
  19513. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  19514. // Any other answer to CONNECT would read as the origin's response.
  19515. struct {
  19516. const char *response;
  19517. bool passed_on;
  19518. } cases[] = {
  19519. {"HTTP/1.1 201 Created\r\n"
  19520. "Set-Cookie: session=from-proxy\r\n"
  19521. "Content-Length: 0\r\n\r\n",
  19522. false},
  19523. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  19524. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  19525. "Content-Length: 0\r\n\r\n",
  19526. true},
  19527. };
  19528. for (const auto &c : cases) {
  19529. std::promise<int> port_promise;
  19530. auto server_thread = serve_single_response(port_promise, c.response);
  19531. SSLClient cli("example.com", 443);
  19532. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  19533. auto res = cli.Get("/");
  19534. server_thread.join();
  19535. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  19536. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  19537. if (res) {
  19538. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  19539. }
  19540. }
  19541. }
  19542. #endif
  19543. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  19544. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  19545. // the chunked coding and drop Content-Length, so a front-end that trusts
  19546. // Content-Length would disagree about where the body ends (response
  19547. // smuggling). The client must reject such a response.
  19548. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  19549. for (const char *te : {"chunked", "gzip, chunked"}) {
  19550. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  19551. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  19552. "\r\n" + "Connection: close\r\n" + "\r\n" +
  19553. "5\r\nhello\r\n0\r\n\r\n";
  19554. with_single_response(response, [&](Client &cli) {
  19555. auto res = cli.Get("/");
  19556. EXPECT_FALSE(static_cast<bool>(res)) << te;
  19557. EXPECT_EQ(Error::Read, res.error()) << te;
  19558. });
  19559. with_single_response(response, [&](Client &cli) {
  19560. auto handle = cli.open_stream("GET", "/");
  19561. EXPECT_FALSE(handle.is_valid()) << te;
  19562. EXPECT_EQ(Error::Read, handle.error) << te;
  19563. });
  19564. }
  19565. }
  19566. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  19567. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  19568. // closing the connection (unlike a request, which must be rejected).
  19569. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  19570. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19571. "Transfer-Encoding: chunked\r\n"
  19572. "Connection: close\r\n"
  19573. "\r\n"
  19574. "5\r\nhello\r\n0\r\n\r\n",
  19575. "HTTP/1.1 200 OK\r\n"
  19576. "Transfer-Encoding: gzip\r\n"
  19577. "Connection: close\r\n"
  19578. "\r\n"
  19579. "hello"}) {
  19580. with_single_response(response, [&](Client &cli) {
  19581. auto res = cli.Get("/");
  19582. ASSERT_TRUE(static_cast<bool>(res)) << response;
  19583. EXPECT_EQ("hello", res->body);
  19584. });
  19585. with_single_response(response, [&](Client &cli) {
  19586. auto handle = cli.open_stream("GET", "/");
  19587. ASSERT_TRUE(handle.is_valid()) << response;
  19588. EXPECT_EQ("hello", read_all(handle));
  19589. });
  19590. }
  19591. }
  19592. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  19593. // framing headers describe nothing to read and must not be rejected.
  19594. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  19595. const std::string framing = "Content-Length: 5\r\n"
  19596. "Transfer-Encoding: chunked\r\n"
  19597. "Connection: close\r\n"
  19598. "\r\n";
  19599. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19600. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  19601. });
  19602. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  19603. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  19604. });
  19605. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  19606. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  19607. with_single_response(response, [&](Client &cli) {
  19608. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  19609. });
  19610. with_single_response(response, [&](Client &cli) {
  19611. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  19612. });
  19613. }
  19614. }
  19615. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  19616. // response, is faulty framing, so the connection is not reused after it.
  19617. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  19618. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19619. "Content-Length: 0\r\n"
  19620. "Transfer-Encoding: chunked\r\n"
  19621. "\r\n"
  19622. "5\r\nhello\r\n0\r\n\r\n",
  19623. "HTTP/1.0 200 Connection established\r\n"
  19624. "Connection: keep-alive\r\n"
  19625. "Transfer-Encoding: chunked\r\n"
  19626. "\r\n"
  19627. "5\r\nhello\r\n0\r\n\r\n"}) {
  19628. with_single_response(response, [&](Client &cli) {
  19629. cli.set_keep_alive(true);
  19630. auto res = cli.Get("/");
  19631. ASSERT_TRUE(res) << response;
  19632. EXPECT_EQ("hello", res->body);
  19633. EXPECT_FALSE(cli.is_socket_open()) << response;
  19634. });
  19635. }
  19636. }
  19637. // A payload max length of 0 means no limit, however the body is framed.
  19638. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  19639. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  19640. "Transfer-Encoding: chunked\r\n"
  19641. "\r\n"
  19642. "5\r\nhello\r\n0\r\n\r\n",
  19643. "HTTP/1.1 200 OK\r\n"
  19644. "Connection: close\r\n"
  19645. "\r\n"
  19646. "hello"}) {
  19647. with_single_response(response, [&](Client &cli) {
  19648. cli.set_payload_max_length(0);
  19649. auto res = cli.Get("/");
  19650. ASSERT_TRUE(res) << response;
  19651. EXPECT_EQ("hello", res->body) << response;
  19652. });
  19653. }
  19654. }
  19655. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  19656. Server svr;
  19657. svr.set_payload_max_length(0);
  19658. svr.Post("/echo", [](const Request &req, Response &res) {
  19659. res.set_content(req.body, "text/plain");
  19660. });
  19661. auto port = svr.bind_to_any_port(HOST);
  19662. thread t = thread([&] { svr.listen_after_bind(); });
  19663. auto se = detail::scope_exit([&] {
  19664. svr.stop();
  19665. t.join();
  19666. ASSERT_FALSE(svr.is_running());
  19667. });
  19668. svr.wait_until_ready();
  19669. Client cli(HOST, port);
  19670. auto res = cli.Post(
  19671. "/echo",
  19672. [](size_t /*offset*/, DataSink &sink) {
  19673. sink.write("hello", 5);
  19674. sink.done();
  19675. return true;
  19676. },
  19677. "text/plain");
  19678. ASSERT_TRUE(res);
  19679. EXPECT_EQ(StatusCode::OK_200, res->status);
  19680. EXPECT_EQ("hello", res->body);
  19681. }
  19682. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19683. TEST_F(OpenStreamTest, Gzip) {
  19684. Client cli("127.0.0.1", port_);
  19685. auto handle = cli.open_stream("GET", "/compressible", {},
  19686. {{"Accept-Encoding", "gzip"}});
  19687. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  19688. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19689. }
  19690. #endif
  19691. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19692. TEST_F(OpenStreamTest, Brotli) {
  19693. Client cli("127.0.0.1", port_);
  19694. auto handle =
  19695. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  19696. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  19697. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19698. }
  19699. #endif
  19700. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19701. TEST_F(OpenStreamTest, Zstd) {
  19702. Client cli("127.0.0.1", port_);
  19703. auto handle = cli.open_stream("GET", "/compressible", {},
  19704. {{"Accept-Encoding", "zstd"}});
  19705. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  19706. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  19707. }
  19708. #endif
  19709. #ifdef CPPHTTPLIB_SSL_ENABLED
  19710. class SSLOpenStreamTest : public ::testing::Test {
  19711. protected:
  19712. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  19713. void SetUp() override {
  19714. svr_.Get("/hello", [](const Request &, Response &res) {
  19715. res.set_content("Hello SSL World!", "text/plain");
  19716. });
  19717. svr_.Get("/chunked", [](const Request &, Response &res) {
  19718. res.set_chunked_content_provider("text/plain",
  19719. [](size_t offset, DataSink &sink) {
  19720. if (offset < 15) {
  19721. sink.write("chunk", 5);
  19722. return true;
  19723. }
  19724. sink.done();
  19725. return true;
  19726. });
  19727. });
  19728. svr_.Post("/echo", [](const Request &req, Response &res) {
  19729. res.set_content(req.body, req.get_header_value("Content-Type"));
  19730. });
  19731. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  19732. std::string body = req.body;
  19733. res.set_chunked_content_provider(
  19734. "text/plain", [body](size_t offset, DataSink &sink) {
  19735. if (offset < body.size()) {
  19736. sink.write(body.data() + offset, body.size() - offset);
  19737. }
  19738. sink.done();
  19739. return true;
  19740. });
  19741. });
  19742. port_ = svr_.bind_to_any_port("127.0.0.1");
  19743. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19744. svr_.wait_until_ready();
  19745. }
  19746. void TearDown() override {
  19747. svr_.stop();
  19748. if (thread_.joinable()) thread_.join();
  19749. }
  19750. SSLServer svr_;
  19751. std::thread thread_;
  19752. int port_ = 0;
  19753. };
  19754. TEST_F(SSLOpenStreamTest, Basic) {
  19755. SSLClient cli("127.0.0.1", port_);
  19756. cli.enable_server_certificate_verification(false);
  19757. auto handle = cli.open_stream("GET", "/hello");
  19758. ASSERT_TRUE(handle.is_valid());
  19759. EXPECT_EQ("Hello SSL World!", read_all(handle));
  19760. }
  19761. TEST_F(SSLOpenStreamTest, Chunked) {
  19762. SSLClient cli("127.0.0.1", port_);
  19763. cli.enable_server_certificate_verification(false);
  19764. auto handle = cli.open_stream("GET", "/chunked");
  19765. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19766. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19767. "Transfer-Encoding") == "chunked");
  19768. auto body = read_all(handle);
  19769. EXPECT_EQ("chunkchunkchunk", body);
  19770. }
  19771. TEST_F(SSLOpenStreamTest, Post) {
  19772. SSLClient cli("127.0.0.1", port_);
  19773. cli.enable_server_certificate_verification(false);
  19774. auto handle =
  19775. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  19776. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  19777. EXPECT_EQ(200, handle.response->status);
  19778. auto body = read_all(handle);
  19779. EXPECT_EQ("Hello SSL POST", body);
  19780. }
  19781. TEST_F(SSLOpenStreamTest, PostChunked) {
  19782. SSLClient cli("127.0.0.1", port_);
  19783. cli.enable_server_certificate_verification(false);
  19784. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  19785. "Chunked SSL Data", "text/plain");
  19786. ASSERT_TRUE(handle.is_valid());
  19787. EXPECT_EQ(200, handle.response->status);
  19788. auto body = read_all(handle);
  19789. EXPECT_EQ("Chunked SSL Data", body);
  19790. }
  19791. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  19792. // Content-Length is terminated by the server closing the connection. When the
  19793. // SSL peer sends a close_notify after the body, the client must treat it as a
  19794. // clean EOF and return a successful response rather than an error.
  19795. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  19796. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19797. ASSERT_TRUE(svr.is_valid());
  19798. svr.set_keep_alive_max_count(1);
  19799. const std::string expected_body = "Hello from connection-close response!";
  19800. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  19801. res.set_content_provider("text/plain",
  19802. [&](size_t offset, DataSink &sink) -> bool {
  19803. if (offset < expected_body.size()) {
  19804. sink.write(expected_body.data() + offset,
  19805. expected_body.size() - offset);
  19806. }
  19807. sink.done();
  19808. return true;
  19809. });
  19810. });
  19811. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  19812. auto se = detail::scope_exit([&] {
  19813. svr.stop();
  19814. listen_thread.join();
  19815. ASSERT_FALSE(svr.is_running());
  19816. });
  19817. svr.wait_until_ready();
  19818. SSLClient cli(HOST, PORT);
  19819. cli.enable_server_certificate_verification(false);
  19820. auto res = cli.Get("/no-content-length");
  19821. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  19822. EXPECT_EQ(StatusCode::OK_200, res->status);
  19823. EXPECT_EQ(expected_body, res->body);
  19824. }
  19825. #endif // CPPHTTPLIB_SSL_ENABLED
  19826. //==============================================================================
  19827. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  19828. // results for various scenarios.
  19829. //==============================================================================
  19830. TEST(ParityTest, GetVsOpenStream) {
  19831. Server svr;
  19832. const std::string path = "/parity";
  19833. const std::string content = "Parity test content: hello world";
  19834. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19835. res.set_content(content, "text/plain");
  19836. });
  19837. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19838. auto se = detail::scope_exit([&] {
  19839. svr.stop();
  19840. t.join();
  19841. ASSERT_FALSE(svr.is_running());
  19842. });
  19843. svr.wait_until_ready();
  19844. Client cli(HOST, PORT);
  19845. // Non-stream path
  19846. auto r1 = cli.Get(path);
  19847. ASSERT_TRUE(r1);
  19848. EXPECT_EQ(StatusCode::OK_200, r1->status);
  19849. // Stream path
  19850. auto h = cli.open_stream("GET", path);
  19851. ASSERT_TRUE(h.is_valid());
  19852. EXPECT_EQ(r1->body, read_all(h));
  19853. }
  19854. // Helper to compress data with provided compressor type T
  19855. template <typename Compressor>
  19856. static std::string compress_payload_for_parity(const std::string &in) {
  19857. std::string out;
  19858. Compressor compressor;
  19859. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  19860. [&](const char *data, size_t n) {
  19861. out.append(data, n);
  19862. return true;
  19863. });
  19864. EXPECT_TRUE(ok);
  19865. return out;
  19866. }
  19867. // Helper function for compression parity tests
  19868. template <typename Compressor>
  19869. static void test_compression_parity(const std::string &original,
  19870. const std::string &path,
  19871. const std::string &encoding) {
  19872. const std::string compressed =
  19873. compress_payload_for_parity<Compressor>(original);
  19874. Server svr;
  19875. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19876. res.set_content(compressed, "application/octet-stream");
  19877. res.set_header("Content-Encoding", encoding);
  19878. });
  19879. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  19880. auto se = detail::scope_exit([&] {
  19881. svr.stop();
  19882. t.join();
  19883. ASSERT_FALSE(svr.is_running());
  19884. });
  19885. svr.wait_until_ready();
  19886. Client cli(HOST, PORT);
  19887. // Non-streaming
  19888. {
  19889. auto res = cli.Get(path);
  19890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19891. EXPECT_EQ(StatusCode::OK_200, res->status);
  19892. EXPECT_EQ(original, res->body);
  19893. }
  19894. // Streaming
  19895. {
  19896. auto h = cli.open_stream("GET", path);
  19897. ASSERT_TRUE(h.is_valid());
  19898. EXPECT_EQ(original, read_all(h));
  19899. }
  19900. }
  19901. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19902. TEST(ParityTest, Gzip) {
  19903. test_compression_parity<detail::gzip_compressor>(
  19904. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  19905. }
  19906. #endif
  19907. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19908. TEST(ParityTest, Brotli) {
  19909. test_compression_parity<detail::brotli_compressor>(
  19910. "Hello, brotli parity test payload", "/parity-br", "br");
  19911. }
  19912. #endif
  19913. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19914. TEST(ParityTest, Zstd) {
  19915. test_compression_parity<detail::zstd_compressor>(
  19916. "Zstandard parity test payload", "/parity-zstd", "zstd");
  19917. }
  19918. #endif
  19919. //==============================================================================
  19920. // New Stream API Tests
  19921. //==============================================================================
  19922. inline std::string read_body(httplib::stream::Result &result) {
  19923. std::string body;
  19924. while (result.next()) {
  19925. body.append(result.data(), result.size());
  19926. }
  19927. return body;
  19928. }
  19929. TEST(ClientConnectionTest, Basic) {
  19930. httplib::ClientConnection conn;
  19931. EXPECT_FALSE(conn.is_open());
  19932. conn.sock = 1;
  19933. EXPECT_TRUE(conn.is_open());
  19934. httplib::ClientConnection conn2(std::move(conn));
  19935. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  19936. conn2.sock = INVALID_SOCKET;
  19937. }
  19938. // Unified test server for all stream::* tests
  19939. class StreamApiTest : public ::testing::Test {
  19940. protected:
  19941. void SetUp() override {
  19942. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19943. res.set_content("Hello World!", "text/plain");
  19944. });
  19945. svr_.Get("/echo-params",
  19946. [](const httplib::Request &req, httplib::Response &res) {
  19947. std::string r;
  19948. for (const auto &p : req.params) {
  19949. if (!r.empty()) r += "&";
  19950. r += p.first + "=" + p.second;
  19951. }
  19952. res.set_content(r, "text/plain");
  19953. });
  19954. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19955. res.set_content(req.body, req.get_header_value("Content-Type"));
  19956. });
  19957. svr_.Post("/echo-headers",
  19958. [](const httplib::Request &req, httplib::Response &res) {
  19959. std::string r;
  19960. for (const auto &h : req.headers)
  19961. r += h.first + ": " + h.second + "\n";
  19962. res.set_content(r, "text/plain");
  19963. });
  19964. svr_.Post("/echo-params",
  19965. [](const httplib::Request &req, httplib::Response &res) {
  19966. std::string r = "params:";
  19967. for (const auto &p : req.params)
  19968. r += p.first + "=" + p.second + ";";
  19969. res.set_content(r + " body:" + req.body, "text/plain");
  19970. });
  19971. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  19972. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  19973. });
  19974. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19975. res.set_content("PUT:" + req.body, "text/plain");
  19976. });
  19977. svr_.Patch("/echo",
  19978. [](const httplib::Request &req, httplib::Response &res) {
  19979. res.set_content("PATCH:" + req.body, "text/plain");
  19980. });
  19981. svr_.Delete(
  19982. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  19983. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  19984. "text/plain");
  19985. });
  19986. svr_.Get("/head-test",
  19987. [](const httplib::Request &, httplib::Response &res) {
  19988. res.set_content("body for HEAD", "text/plain");
  19989. });
  19990. svr_.Options("/options",
  19991. [](const httplib::Request &, httplib::Response &res) {
  19992. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  19993. });
  19994. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  19995. svr_.wait_until_ready();
  19996. }
  19997. void TearDown() override {
  19998. svr_.stop();
  19999. if (thread_.joinable()) thread_.join();
  20000. }
  20001. httplib::Server svr_;
  20002. std::thread thread_;
  20003. };
  20004. // stream::Get tests
  20005. TEST_F(StreamApiTest, GetBasic) {
  20006. httplib::Client cli(HOST, PORT);
  20007. auto result = httplib::stream::Get(cli, "/hello");
  20008. ASSERT_TRUE(result.is_valid());
  20009. EXPECT_EQ(200, result.status());
  20010. EXPECT_EQ("Hello World!", read_body(result));
  20011. }
  20012. TEST_F(StreamApiTest, GetWithParams) {
  20013. httplib::Client cli(HOST, PORT);
  20014. httplib::Params params{{"foo", "bar"}};
  20015. auto result = httplib::stream::Get(cli, "/echo-params", params);
  20016. ASSERT_TRUE(result.is_valid());
  20017. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  20018. }
  20019. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20020. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  20021. httplib::Client cli(HOST, PORT);
  20022. cli.set_payload_max_length(0);
  20023. auto result = httplib::stream::Get(cli, "/hello");
  20024. ASSERT_TRUE(result.is_valid());
  20025. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  20026. EXPECT_EQ("Hello World!", read_body(result));
  20027. }
  20028. #endif
  20029. TEST_F(StreamApiTest, GetConnectionError) {
  20030. httplib::Client cli(HOST, 9999);
  20031. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  20032. }
  20033. TEST_F(StreamApiTest, Get404) {
  20034. httplib::Client cli(HOST, PORT);
  20035. auto result = httplib::stream::Get(cli, "/nonexistent");
  20036. EXPECT_TRUE(result.is_valid());
  20037. EXPECT_EQ(404, result.status());
  20038. }
  20039. // stream::Post tests
  20040. TEST_F(StreamApiTest, PostBasic) {
  20041. httplib::Client cli(HOST, PORT);
  20042. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  20043. "application/json");
  20044. ASSERT_TRUE(result.is_valid());
  20045. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  20046. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  20047. }
  20048. TEST_F(StreamApiTest, PostWithHeaders) {
  20049. httplib::Client cli(HOST, PORT);
  20050. httplib::Headers headers{{"X-Custom", "value"}};
  20051. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  20052. "text/plain");
  20053. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  20054. }
  20055. TEST_F(StreamApiTest, PostWithParams) {
  20056. httplib::Client cli(HOST, PORT);
  20057. httplib::Params params{{"k", "v"}};
  20058. auto result =
  20059. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  20060. auto body = read_body(result);
  20061. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  20062. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  20063. }
  20064. TEST_F(StreamApiTest, PostLarge) {
  20065. httplib::Client cli(HOST, PORT);
  20066. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  20067. size_t total = 0;
  20068. while (result.next()) {
  20069. total += result.size();
  20070. }
  20071. EXPECT_EQ(100u * 1024u, total);
  20072. }
  20073. // stream::Put/Patch tests
  20074. TEST_F(StreamApiTest, PutAndPatch) {
  20075. httplib::Client cli(HOST, PORT);
  20076. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  20077. EXPECT_EQ("PUT:test", read_body(put));
  20078. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  20079. EXPECT_EQ("PATCH:test", read_body(patch));
  20080. }
  20081. // stream::Delete tests
  20082. TEST_F(StreamApiTest, Delete) {
  20083. httplib::Client cli(HOST, PORT);
  20084. auto del1 = httplib::stream::Delete(cli, "/resource");
  20085. EXPECT_EQ("Deleted", read_body(del1));
  20086. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  20087. EXPECT_EQ("Deleted:data", read_body(del2));
  20088. }
  20089. // stream::Head/Options tests
  20090. TEST_F(StreamApiTest, HeadAndOptions) {
  20091. httplib::Client cli(HOST, PORT);
  20092. auto head = httplib::stream::Head(cli, "/head-test");
  20093. EXPECT_TRUE(head.is_valid());
  20094. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  20095. auto opts = httplib::stream::Options(cli, "/options");
  20096. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  20097. }
  20098. // SSL stream::* tests
  20099. #ifdef CPPHTTPLIB_SSL_ENABLED
  20100. class SSLStreamApiTest : public ::testing::Test {
  20101. protected:
  20102. void SetUp() override {
  20103. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20104. res.set_content("Hello SSL!", "text/plain");
  20105. });
  20106. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20107. res.set_content(req.body, "text/plain");
  20108. });
  20109. port_ = svr_.bind_to_any_port("127.0.0.1");
  20110. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20111. svr_.wait_until_ready();
  20112. }
  20113. void TearDown() override {
  20114. svr_.stop();
  20115. if (thread_.joinable()) thread_.join();
  20116. }
  20117. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  20118. std::thread thread_;
  20119. int port_ = 0;
  20120. };
  20121. TEST_F(SSLStreamApiTest, GetAndPost) {
  20122. httplib::SSLClient cli("127.0.0.1", port_);
  20123. cli.enable_server_certificate_verification(false);
  20124. auto get = httplib::stream::Get(cli, "/hello");
  20125. EXPECT_EQ("Hello SSL!", read_body(get));
  20126. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  20127. EXPECT_EQ("test", read_body(post));
  20128. }
  20129. #endif
  20130. // Tests for Error::Timeout and Error::ConnectionClosed error types
  20131. // These errors are set in SocketStream/SSLSocketStream and propagated through
  20132. // BodyReader
  20133. TEST(ErrorHandlingTest, StreamReadTimeout) {
  20134. // Test that read timeout during streaming is detected
  20135. // Use a large content-length response where server delays mid-stream
  20136. Server svr;
  20137. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20138. // Send a large response with delay in the middle
  20139. res.set_content_provider(
  20140. 1000, // content_length
  20141. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  20142. if (offset < 100) {
  20143. // Send first 100 bytes immediately
  20144. std::string data(100, 'A');
  20145. sink.write(data.c_str(), data.size());
  20146. return true;
  20147. }
  20148. // Then delay longer than client timeout
  20149. std::this_thread::sleep_for(std::chrono::seconds(3));
  20150. std::string data(900, 'B');
  20151. sink.write(data.c_str(), data.size());
  20152. return true;
  20153. });
  20154. });
  20155. auto port = 8091;
  20156. std::thread t([&]() { svr.listen("localhost", port); });
  20157. svr.wait_until_ready();
  20158. Client cli("localhost", port);
  20159. cli.set_read_timeout(1, 0); // 1 second timeout
  20160. auto handle = cli.open_stream("GET", "/slow-stream");
  20161. ASSERT_TRUE(handle.is_valid());
  20162. char buf[256];
  20163. ssize_t total = 0;
  20164. ssize_t n;
  20165. bool got_error = false;
  20166. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20167. total += n;
  20168. }
  20169. if (n < 0) {
  20170. got_error = true;
  20171. // Should be timeout or read error
  20172. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20173. handle.get_read_error() == Error::Read)
  20174. << "Actual error: " << to_string(handle.get_read_error());
  20175. }
  20176. // Either we got an error, or we got less data than expected
  20177. EXPECT_TRUE(got_error || total < 1000)
  20178. << "Expected timeout but got all " << total << " bytes";
  20179. svr.stop();
  20180. t.join();
  20181. }
  20182. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  20183. // Test connection closed detection via BodyReader
  20184. Server svr;
  20185. std::atomic<bool> close_now{false};
  20186. svr.Get("/will-close", [&](const Request &, Response &res) {
  20187. res.set_content_provider(
  20188. 10000, // Large content_length that we won't fully send
  20189. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20190. if (offset < 100) {
  20191. std::string data(100, 'X');
  20192. sink.write(data.c_str(), data.size());
  20193. return true;
  20194. }
  20195. // Wait for signal then abort
  20196. while (!close_now) {
  20197. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20198. }
  20199. return false; // Abort - server will close connection
  20200. });
  20201. });
  20202. auto port = 8092;
  20203. std::thread t([&]() { svr.listen("localhost", port); });
  20204. svr.wait_until_ready();
  20205. Client cli("localhost", port);
  20206. auto handle = cli.open_stream("GET", "/will-close");
  20207. ASSERT_TRUE(handle.is_valid());
  20208. char buf[256];
  20209. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20210. EXPECT_GT(n, 0) << "First read should succeed";
  20211. // Signal server to close
  20212. close_now = true;
  20213. // Keep reading until error or EOF
  20214. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20215. // Keep reading
  20216. }
  20217. // Should get an error since content_length wasn't satisfied
  20218. if (n < 0) {
  20219. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20220. handle.get_read_error() == Error::Read)
  20221. << "Actual error: " << to_string(handle.get_read_error());
  20222. }
  20223. svr.stop();
  20224. t.join();
  20225. }
  20226. #ifdef CPPHTTPLIB_SSL_ENABLED
  20227. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  20228. // Test that read timeout during SSL streaming is detected
  20229. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20230. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20231. res.set_content_provider(
  20232. 1000, "text/plain",
  20233. [](size_t offset, size_t /*length*/, DataSink &sink) {
  20234. if (offset < 100) {
  20235. std::string data(100, 'A');
  20236. sink.write(data.c_str(), data.size());
  20237. return true;
  20238. }
  20239. std::this_thread::sleep_for(std::chrono::seconds(3));
  20240. std::string data(900, 'B');
  20241. sink.write(data.c_str(), data.size());
  20242. return true;
  20243. });
  20244. });
  20245. auto port = 8093;
  20246. std::thread t([&]() { svr.listen("localhost", port); });
  20247. svr.wait_until_ready();
  20248. SSLClient cli("localhost", port);
  20249. cli.enable_server_certificate_verification(false);
  20250. cli.set_read_timeout(1, 0); // 1 second timeout
  20251. auto handle = cli.open_stream("GET", "/slow-stream");
  20252. ASSERT_TRUE(handle.is_valid());
  20253. char buf[256];
  20254. ssize_t total = 0;
  20255. ssize_t n;
  20256. bool got_error = false;
  20257. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20258. total += n;
  20259. }
  20260. if (n < 0) {
  20261. got_error = true;
  20262. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20263. handle.get_read_error() == Error::Read)
  20264. << "Actual error: " << to_string(handle.get_read_error());
  20265. }
  20266. EXPECT_TRUE(got_error || total < 1000)
  20267. << "Expected timeout but got all " << total << " bytes";
  20268. svr.stop();
  20269. t.join();
  20270. }
  20271. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  20272. // Test SSL connection closed detection
  20273. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20274. std::atomic<bool> close_now{false};
  20275. svr.Get("/will-close", [&](const Request &, Response &res) {
  20276. res.set_content_provider(
  20277. 10000, "text/plain",
  20278. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20279. if (offset < 100) {
  20280. std::string data(100, 'X');
  20281. sink.write(data.c_str(), data.size());
  20282. return true;
  20283. }
  20284. while (!close_now) {
  20285. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20286. }
  20287. return false;
  20288. });
  20289. });
  20290. auto port = 8094;
  20291. std::thread t([&]() { svr.listen("localhost", port); });
  20292. svr.wait_until_ready();
  20293. SSLClient cli("localhost", port);
  20294. cli.enable_server_certificate_verification(false);
  20295. auto handle = cli.open_stream("GET", "/will-close");
  20296. ASSERT_TRUE(handle.is_valid());
  20297. char buf[256];
  20298. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20299. EXPECT_GT(n, 0);
  20300. // Signal server to close
  20301. close_now = true;
  20302. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20303. // Keep reading
  20304. }
  20305. if (n < 0) {
  20306. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20307. handle.get_read_error() == Error::Read)
  20308. << "Actual error: " << to_string(handle.get_read_error());
  20309. }
  20310. svr.stop();
  20311. t.join();
  20312. }
  20313. #endif
  20314. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  20315. using namespace httplib;
  20316. // Create a test file
  20317. const char *fname = "etag_testfile.txt";
  20318. const char *content = "etag-content";
  20319. {
  20320. std::ofstream ofs(fname);
  20321. ofs << content;
  20322. ASSERT_TRUE(ofs.good());
  20323. }
  20324. Server svr;
  20325. svr.set_mount_point("/static", ".");
  20326. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  20327. svr.wait_until_ready();
  20328. Client cli(HOST, PORT);
  20329. // First request: should get 200 with ETag header
  20330. auto res1 = cli.Get("/static/etag_testfile.txt");
  20331. ASSERT_TRUE(res1);
  20332. ASSERT_EQ(200, res1->status);
  20333. ASSERT_TRUE(res1->has_header("ETag"));
  20334. std::string etag = res1->get_header_value("ETag");
  20335. EXPECT_FALSE(etag.empty());
  20336. // Verify ETag format: W/"hex-hex"
  20337. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  20338. EXPECT_EQ('W', etag[0]);
  20339. EXPECT_EQ('/', etag[1]);
  20340. EXPECT_EQ('"', etag[2]);
  20341. EXPECT_EQ('"', etag.back());
  20342. // Exact match: expect 304 Not Modified
  20343. Headers h2 = {{"If-None-Match", etag}};
  20344. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  20345. ASSERT_TRUE(res2);
  20346. EXPECT_EQ(304, res2->status);
  20347. // Wildcard match: expect 304 Not Modified
  20348. Headers h3 = {{"If-None-Match", "*"}};
  20349. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  20350. ASSERT_TRUE(res3);
  20351. EXPECT_EQ(304, res3->status);
  20352. // Non-matching ETag: expect 200
  20353. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  20354. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  20355. ASSERT_TRUE(res4);
  20356. EXPECT_EQ(200, res4->status);
  20357. // Multiple ETags with one matching: expect 304
  20358. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  20359. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  20360. ASSERT_TRUE(res5);
  20361. EXPECT_EQ(304, res5->status);
  20362. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  20363. // that equivalent to the single comma-separated list above, so the match on
  20364. // the second line must still be found.
  20365. Headers h6;
  20366. h6.emplace("If-None-Match", "W/\"other\"");
  20367. h6.emplace("If-None-Match", etag);
  20368. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  20369. ASSERT_TRUE(res6);
  20370. EXPECT_EQ(304, res6->status);
  20371. svr.stop();
  20372. t.join();
  20373. std::remove(fname);
  20374. }
  20375. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  20376. using namespace httplib;
  20377. Server svr;
  20378. svr.set_mount_point("/static", ".");
  20379. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20380. svr.wait_until_ready();
  20381. Client cli(HOST, PORT);
  20382. // Send If-None-Match: * to a non-existent file
  20383. Headers h = {{"If-None-Match", "*"}};
  20384. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  20385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20386. EXPECT_EQ(404, res->status);
  20387. svr.stop();
  20388. t.join();
  20389. }
  20390. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  20391. using namespace httplib;
  20392. // Create a test file
  20393. const char *fname = "etag_boundary_testfile.txt";
  20394. const char *content = "boundary-test";
  20395. {
  20396. std::ofstream ofs(fname);
  20397. ofs << content;
  20398. ASSERT_TRUE(ofs.good());
  20399. }
  20400. Server svr;
  20401. svr.set_mount_point("/static", ".");
  20402. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  20403. svr.wait_until_ready();
  20404. Client cli(HOST, PORT);
  20405. // Get the actual ETag
  20406. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  20407. ASSERT_TRUE(res1);
  20408. ASSERT_EQ(200, res1->status);
  20409. ASSERT_TRUE(res1->has_header("ETag"));
  20410. std::string etag = res1->get_header_value("ETag");
  20411. // Test 1: Very long ETag value (longer than actual ETag)
  20412. // Should NOT match and return 200 (not trigger out-of-bounds read)
  20413. Headers h1 = {{"If-None-Match", "W/"
  20414. "\"very-long-etag-value-that-is-much-longer-"
  20415. "than-the-actual-etag-value\""}};
  20416. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  20417. ASSERT_TRUE(res2);
  20418. EXPECT_EQ(200, res2->status); // Should not match
  20419. // Test 2: Long string followed by wildcard
  20420. // Should match on "*" and return 304 (without out-of-bounds read on the long
  20421. // string)
  20422. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  20423. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  20424. ASSERT_TRUE(res3);
  20425. EXPECT_EQ(304, res3->status); // Should match on "*"
  20426. // Test 3: Wildcard followed by long string
  20427. // Should match on "*" immediately and return 304
  20428. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  20429. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  20430. ASSERT_TRUE(res4);
  20431. EXPECT_EQ(304, res4->status); // Should match on "*"
  20432. // Test 4: Multiple long non-matching values
  20433. // Should NOT match and return 200 (test that all comparisons are safe)
  20434. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  20435. "W/\"second-long-non-matching-value\", "
  20436. "W/\"third-long-non-matching-value\""}};
  20437. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  20438. ASSERT_TRUE(res5);
  20439. EXPECT_EQ(200, res5->status); // Should not match
  20440. // Test 5: Single character that is not "*" (edge case)
  20441. Headers h5 = {{"If-None-Match", "X"}};
  20442. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  20443. ASSERT_TRUE(res6);
  20444. EXPECT_EQ(200, res6->status); // Should not match
  20445. svr.stop();
  20446. t.join();
  20447. std::remove(fname);
  20448. }
  20449. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  20450. using namespace httplib;
  20451. // Create a test file
  20452. const char *fname = "ims_testfile.txt";
  20453. const char *content = "if-modified-since-test";
  20454. {
  20455. std::ofstream ofs(fname);
  20456. ofs << content;
  20457. ASSERT_TRUE(ofs.good());
  20458. }
  20459. Server svr;
  20460. svr.set_mount_point("/static", ".");
  20461. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20462. svr.wait_until_ready();
  20463. Client cli(HOST, PORT);
  20464. // First request: should get 200 with Last-Modified header
  20465. auto res1 = cli.Get("/static/ims_testfile.txt");
  20466. ASSERT_TRUE(res1);
  20467. ASSERT_EQ(200, res1->status);
  20468. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20469. std::string last_modified = res1->get_header_value("Last-Modified");
  20470. EXPECT_FALSE(last_modified.empty());
  20471. // If-Modified-Since with same time: expect 304
  20472. Headers h2 = {{"If-Modified-Since", last_modified}};
  20473. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  20474. ASSERT_TRUE(res2);
  20475. EXPECT_EQ(304, res2->status);
  20476. // If-Modified-Since with future time: expect 304
  20477. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20478. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  20479. ASSERT_TRUE(res3);
  20480. EXPECT_EQ(304, res3->status);
  20481. // If-Modified-Since with past time: expect 200
  20482. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20483. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  20484. ASSERT_TRUE(res4);
  20485. EXPECT_EQ(200, res4->status);
  20486. // If-None-Match takes precedence over If-Modified-Since
  20487. // (send matching ETag with old If-Modified-Since -> should still be 304)
  20488. ASSERT_TRUE(res1->has_header("ETag"));
  20489. std::string etag = res1->get_header_value("ETag");
  20490. Headers h5 = {{"If-None-Match", etag},
  20491. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20492. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  20493. ASSERT_TRUE(res5);
  20494. EXPECT_EQ(304, res5->status);
  20495. svr.stop();
  20496. t.join();
  20497. std::remove(fname);
  20498. }
  20499. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  20500. using namespace httplib;
  20501. Server svr;
  20502. // Endpoint that returns compressible content
  20503. svr.Get("/compressible", [](const Request &, Response &res) {
  20504. // Return a large enough body to trigger compression
  20505. std::string body(1000, 'a');
  20506. res.set_content(body, "text/plain");
  20507. });
  20508. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20509. svr.wait_until_ready();
  20510. Client cli(HOST, PORT);
  20511. // Request with gzip support: should get Vary header when compressed
  20512. cli.set_compress(true);
  20513. auto res1 = cli.Get("/compressible");
  20514. ASSERT_TRUE(res1);
  20515. EXPECT_EQ(200, res1->status);
  20516. // If Content-Encoding is set, Vary should also be set
  20517. if (res1->has_header("Content-Encoding")) {
  20518. EXPECT_TRUE(res1->has_header("Vary"));
  20519. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  20520. }
  20521. // Request without Accept-Encoding header: should not have compression
  20522. Headers h_no_compress;
  20523. auto res2 = cli.Get("/compressible", h_no_compress);
  20524. ASSERT_TRUE(res2);
  20525. EXPECT_EQ(200, res2->status);
  20526. // Verify Vary header is present when compression is applied
  20527. // (the exact behavior depends on server configuration)
  20528. svr.stop();
  20529. t.join();
  20530. }
  20531. TEST(ETagTest, IfRangeWithETag) {
  20532. using namespace httplib;
  20533. // Create a test file with known content
  20534. const char *fname = "if_range_testfile.txt";
  20535. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  20536. {
  20537. std::ofstream ofs(fname);
  20538. ofs << content;
  20539. ASSERT_TRUE(ofs.good());
  20540. }
  20541. Server svr;
  20542. svr.set_mount_point("/static", ".");
  20543. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20544. svr.wait_until_ready();
  20545. Client cli(HOST, PORT);
  20546. // First request: get ETag
  20547. auto res1 = cli.Get("/static/if_range_testfile.txt");
  20548. ASSERT_TRUE(res1);
  20549. ASSERT_EQ(200, res1->status);
  20550. ASSERT_TRUE(res1->has_header("ETag"));
  20551. std::string etag = res1->get_header_value("ETag");
  20552. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  20553. // Since our server generates weak ETags (W/"..."), If-Range with our
  20554. // ETag should NOT result in partial content - it should return full content.
  20555. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  20556. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  20557. ASSERT_TRUE(res2);
  20558. // Weak ETag in If-Range -> full content (200), not partial (206)
  20559. EXPECT_EQ(200, res2->status);
  20560. EXPECT_EQ(content, res2->body);
  20561. EXPECT_FALSE(res2->has_header("Content-Range"));
  20562. // Range request with non-matching If-Range (ETag): should get 200 (full
  20563. // content)
  20564. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  20565. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  20566. ASSERT_TRUE(res3);
  20567. EXPECT_EQ(200, res3->status);
  20568. EXPECT_EQ(content, res3->body);
  20569. EXPECT_FALSE(res3->has_header("Content-Range"));
  20570. // Range request with strong ETag (hypothetical - our server doesn't generate
  20571. // strong ETags, but if client sends a strong ETag that doesn't match, it
  20572. // should return full content)
  20573. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  20574. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  20575. ASSERT_TRUE(res4);
  20576. EXPECT_EQ(200, res4->status);
  20577. EXPECT_EQ(content, res4->body);
  20578. EXPECT_FALSE(res4->has_header("Content-Range"));
  20579. svr.stop();
  20580. t.join();
  20581. std::remove(fname);
  20582. }
  20583. TEST(ETagTest, IfRangeWithDate) {
  20584. using namespace httplib;
  20585. // Create a test file
  20586. const char *fname = "if_range_date_testfile.txt";
  20587. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  20588. {
  20589. std::ofstream ofs(fname);
  20590. ofs << content;
  20591. ASSERT_TRUE(ofs.good());
  20592. }
  20593. Server svr;
  20594. svr.set_mount_point("/static", ".");
  20595. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20596. svr.wait_until_ready();
  20597. Client cli(HOST, PORT);
  20598. // First request: get Last-Modified
  20599. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  20600. ASSERT_TRUE(res1);
  20601. ASSERT_EQ(200, res1->status);
  20602. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20603. std::string last_modified = res1->get_header_value("Last-Modified");
  20604. // Range request with matching If-Range (date): should get 206
  20605. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  20606. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  20607. ASSERT_TRUE(res2);
  20608. EXPECT_EQ(206, res2->status);
  20609. EXPECT_EQ("FGHIJ", res2->body);
  20610. // Range request with old If-Range date: should get 200 (full content)
  20611. Headers h3 = {{"Range", "bytes=5-9"},
  20612. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  20613. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  20614. ASSERT_TRUE(res3);
  20615. EXPECT_EQ(200, res3->status);
  20616. EXPECT_EQ(content, res3->body);
  20617. // Range request with future If-Range date: should get 206
  20618. Headers h4 = {{"Range", "bytes=0-4"},
  20619. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  20620. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  20621. ASSERT_TRUE(res4);
  20622. EXPECT_EQ(206, res4->status);
  20623. EXPECT_EQ("ABCDE", res4->body);
  20624. svr.stop();
  20625. t.join();
  20626. std::remove(fname);
  20627. }
  20628. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  20629. using namespace httplib;
  20630. const char *fname = "etag_malformed.txt";
  20631. const char *content = "malformed-etag";
  20632. {
  20633. std::ofstream ofs(fname);
  20634. ofs << content;
  20635. ASSERT_TRUE(ofs.good());
  20636. }
  20637. Server svr;
  20638. svr.set_mount_point("/static", ".");
  20639. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20640. svr.wait_until_ready();
  20641. Client cli(HOST, PORT);
  20642. // baseline: should get 200 and an ETag
  20643. auto res1 = cli.Get("/static/etag_malformed.txt");
  20644. ASSERT_TRUE(res1);
  20645. ASSERT_EQ(200, res1->status);
  20646. ASSERT_TRUE(res1->has_header("ETag"));
  20647. // Malformed ETag value (missing quotes) should be treated as non-matching
  20648. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  20649. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  20650. ASSERT_TRUE(res_bad);
  20651. EXPECT_EQ(200, res_bad->status);
  20652. // Whitespace-only header value should be considered invalid / non-matching
  20653. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  20654. "Host: localhost\r\n"
  20655. "If-None-Match: \r\n"
  20656. "Connection: close\r\n"
  20657. "\r\n";
  20658. std::string out;
  20659. ASSERT_TRUE(send_request(5, raw_req, &out));
  20660. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20661. svr.stop();
  20662. t.join();
  20663. std::remove(fname);
  20664. }
  20665. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  20666. using namespace httplib;
  20667. const char *fname = "ims_invalid_format.txt";
  20668. const char *content = "ims-bad-format";
  20669. {
  20670. std::ofstream ofs(fname);
  20671. ofs << content;
  20672. ASSERT_TRUE(ofs.good());
  20673. }
  20674. Server svr;
  20675. svr.set_mount_point("/static", ".");
  20676. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20677. svr.wait_until_ready();
  20678. Client cli(HOST, PORT);
  20679. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  20680. ASSERT_TRUE(res1);
  20681. ASSERT_EQ(200, res1->status);
  20682. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20683. // If-Modified-Since with invalid format should not result in 304
  20684. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  20685. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  20686. ASSERT_TRUE(res_bad);
  20687. EXPECT_EQ(200, res_bad->status);
  20688. // If-Range with invalid date format should be treated as mismatch -> full
  20689. // content (200)
  20690. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  20691. {"If-Range", "invalid-date"}};
  20692. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  20693. ASSERT_TRUE(res_ifrange);
  20694. EXPECT_EQ(200, res_ifrange->status);
  20695. svr.stop();
  20696. t.join();
  20697. std::remove(fname);
  20698. }
  20699. TEST(ETagTest, IfRangeWithMalformedETag) {
  20700. using namespace httplib;
  20701. const char *fname = "ifrange_malformed.txt";
  20702. const std::string content = "0123456789";
  20703. {
  20704. std::ofstream ofs(fname);
  20705. ofs << content;
  20706. ASSERT_TRUE(ofs.good());
  20707. }
  20708. Server svr;
  20709. svr.set_mount_point("/static", ".");
  20710. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20711. svr.wait_until_ready();
  20712. Client cli(HOST, PORT);
  20713. // First request: get ETag
  20714. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  20715. ASSERT_TRUE(res1);
  20716. ASSERT_EQ(200, res1->status);
  20717. ASSERT_TRUE(res1->has_header("ETag"));
  20718. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  20719. // full content (200)
  20720. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  20721. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  20722. ASSERT_TRUE(res2);
  20723. EXPECT_EQ(200, res2->status);
  20724. EXPECT_EQ(content, res2->body);
  20725. svr.stop();
  20726. t.join();
  20727. std::remove(fname);
  20728. }
  20729. TEST(ETagTest, ExtremeLargeDateValues) {
  20730. using namespace httplib;
  20731. const char *fname = "ims_extreme_date.txt";
  20732. const char *content = "ims-extreme-date";
  20733. {
  20734. std::ofstream ofs(fname);
  20735. ofs << content;
  20736. ASSERT_TRUE(ofs.good());
  20737. }
  20738. Server svr;
  20739. svr.set_mount_point("/static", ".");
  20740. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20741. svr.wait_until_ready();
  20742. Client cli(HOST, PORT);
  20743. auto res1 = cli.Get(std::string("/static/") + fname);
  20744. ASSERT_TRUE(res1);
  20745. ASSERT_EQ(200, res1->status);
  20746. ASSERT_TRUE(res1->has_header("Last-Modified"));
  20747. // Extremely large year that may overflow date parsing routines.
  20748. Headers h_large_date = {
  20749. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20750. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  20751. ASSERT_TRUE(res_bad);
  20752. // Expect server to treat this as invalid/mismatch and return full content
  20753. EXPECT_EQ(200, res_bad->status);
  20754. // If-Range with extremely large date should be treated as mismatch -> full
  20755. // content (200)
  20756. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  20757. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20758. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  20759. ASSERT_TRUE(res_ifrange);
  20760. EXPECT_EQ(200, res_ifrange->status);
  20761. svr.stop();
  20762. t.join();
  20763. std::remove(fname);
  20764. }
  20765. TEST(ETagTest, NegativeFileModificationTime) {
  20766. using namespace httplib;
  20767. const char *fname = "ims_negative_mtime.txt";
  20768. const std::string content = "negative-mtime";
  20769. {
  20770. std::ofstream ofs(fname);
  20771. ofs << content;
  20772. ASSERT_TRUE(ofs.good());
  20773. }
  20774. // Try to set file mtime to a negative value. This may fail on some
  20775. // platforms/filesystems; if it fails, the test will still verify server
  20776. // behaves safely by performing a regular conditional request.
  20777. #if defined(__APPLE__) || defined(__linux__)
  20778. bool set_negative = false;
  20779. do {
  20780. struct timeval times[2];
  20781. // access time: now
  20782. times[0].tv_sec = time(nullptr);
  20783. times[0].tv_usec = 0;
  20784. // modification time: negative (e.g., -1)
  20785. times[1].tv_sec = -1;
  20786. times[1].tv_usec = 0;
  20787. if (utimes(fname, times) == 0) { set_negative = true; }
  20788. } while (0);
  20789. #else
  20790. bool set_negative = false;
  20791. #endif
  20792. Server svr;
  20793. svr.set_mount_point("/static", ".");
  20794. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20795. svr.wait_until_ready();
  20796. Client cli(HOST, PORT);
  20797. auto res1 = cli.Get(std::string("/static/") + fname);
  20798. ASSERT_TRUE(res1);
  20799. ASSERT_EQ(200, res1->status);
  20800. bool has_last_modified = res1->has_header("Last-Modified");
  20801. std::string last_modified;
  20802. if (has_last_modified) {
  20803. last_modified = res1->get_header_value("Last-Modified");
  20804. }
  20805. if (set_negative) {
  20806. // If we successfully set a negative mtime, ensure server returns a
  20807. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  20808. // with an old date and ensure server handles it without crash.
  20809. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  20810. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  20811. ASSERT_TRUE(res2);
  20812. // Behavior may vary; at minimum ensure server responds (200 or 304).
  20813. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  20814. } else {
  20815. // Could not set negative mtime on this platform; fall back to verifying
  20816. // that normal invalid/malformed dates are treated safely (non-304).
  20817. Headers h_bad_date = {
  20818. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  20819. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  20820. ASSERT_TRUE(res_bad);
  20821. EXPECT_EQ(200, res_bad->status);
  20822. }
  20823. svr.stop();
  20824. t.join();
  20825. std::remove(fname);
  20826. }
  20827. //==============================================================================
  20828. // Integration Tests with Server
  20829. //==============================================================================
  20830. class SSEIntegrationTest : public ::testing::Test {
  20831. protected:
  20832. void SetUp() override {
  20833. stop_server_.store(false);
  20834. events_.clear();
  20835. server_ = httplib::detail::make_unique<Server>();
  20836. setup_server();
  20837. start_server();
  20838. }
  20839. void TearDown() override {
  20840. stop_server_.store(true);
  20841. event_cv_.notify_all();
  20842. server_->stop();
  20843. if (server_thread_.joinable()) { server_thread_.join(); }
  20844. }
  20845. void setup_server() {
  20846. // Simple SSE endpoint
  20847. server_->Get("/events", [this](const Request &req, Response &res) {
  20848. auto last_id = req.get_header_value("Last-Event-ID");
  20849. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  20850. res.set_chunked_content_provider(
  20851. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  20852. std::unique_lock<std::mutex> lock(event_mutex_);
  20853. if (event_cv_.wait_for(
  20854. lock, std::chrono::milliseconds(200), [this] {
  20855. return !events_.empty() || stop_server_.load();
  20856. })) {
  20857. if (stop_server_.load()) { return false; }
  20858. if (!events_.empty()) {
  20859. std::string event = events_.front();
  20860. events_.erase(events_.begin());
  20861. sink.write(event.data(), event.size());
  20862. return true;
  20863. }
  20864. }
  20865. return !stop_server_.load();
  20866. });
  20867. });
  20868. // Endpoint that returns error
  20869. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  20870. res.status = 500;
  20871. res.set_content("Internal Server Error", "text/plain");
  20872. });
  20873. // Endpoint for custom event types
  20874. server_->Get("/custom-events", [](const Request &, Response &res) {
  20875. res.set_chunked_content_provider(
  20876. "text/event-stream", [](size_t offset, DataSink &sink) {
  20877. if (offset == 0) {
  20878. std::string event = "event: update\ndata: updated\n\n"
  20879. "event: delete\ndata: deleted\n\n";
  20880. sink.write(event.data(), event.size());
  20881. }
  20882. return false; // End stream after sending
  20883. });
  20884. });
  20885. }
  20886. void start_server() {
  20887. port_ = server_->bind_to_any_port(HOST);
  20888. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20889. // Wait for server to start
  20890. while (!server_->is_running()) {
  20891. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20892. }
  20893. }
  20894. int get_port() const { return port_; }
  20895. void send_event(const std::string &event) {
  20896. std::lock_guard<std::mutex> lock(event_mutex_);
  20897. events_.push_back(event);
  20898. event_cv_.notify_all();
  20899. }
  20900. std::unique_ptr<Server> server_;
  20901. std::thread server_thread_;
  20902. std::mutex event_mutex_;
  20903. std::condition_variable event_cv_;
  20904. std::vector<std::string> events_;
  20905. std::atomic<bool> stop_server_{false};
  20906. std::string last_received_event_id_;
  20907. int port_ = 0;
  20908. };
  20909. //==============================================================================
  20910. // SSE Parsing Tests
  20911. //==============================================================================
  20912. class SSEParsingTest : public SSEIntegrationTest {
  20913. protected:
  20914. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  20915. // A trailing sentinel event tells when the whole stream has been parsed.
  20916. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  20917. auto body = stream + "event: end\ndata: end\n\n";
  20918. server_->Get("/parse", [body](const Request &, Response &res) {
  20919. res.set_content(body, "text/event-stream");
  20920. });
  20921. return collect("/parse");
  20922. }
  20923. // Runs SSEClient against path until an "end" event arrives and returns the
  20924. // messages dispatched before it
  20925. std::vector<sse::SSEMessage> collect(const std::string &path) {
  20926. Client client(HOST, get_port());
  20927. sse::SSEClient sse(client, path);
  20928. std::mutex mutex;
  20929. std::condition_variable cv;
  20930. std::vector<sse::SSEMessage> messages;
  20931. auto done = false;
  20932. sse.on_message([&](const sse::SSEMessage &msg) {
  20933. std::lock_guard<std::mutex> lock(mutex);
  20934. // Ignore a replay from a reconnect that races with stop()
  20935. if (!done) { messages.push_back(msg); }
  20936. });
  20937. sse.on_event("end", [&](const sse::SSEMessage &) {
  20938. std::lock_guard<std::mutex> lock(mutex);
  20939. done = true;
  20940. cv.notify_all();
  20941. });
  20942. sse.set_reconnect_interval(100);
  20943. sse.start_async();
  20944. {
  20945. std::unique_lock<std::mutex> lock(mutex);
  20946. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  20947. }
  20948. sse.stop();
  20949. EXPECT_TRUE(done);
  20950. return messages;
  20951. }
  20952. };
  20953. TEST_F(SSEParsingTest, SingleLineData) {
  20954. auto msgs = parse("data: hello\n\n");
  20955. ASSERT_EQ(msgs.size(), 1u);
  20956. EXPECT_EQ(msgs[0].data, "hello");
  20957. EXPECT_EQ(msgs[0].event, "message");
  20958. }
  20959. TEST_F(SSEParsingTest, MultiLineData) {
  20960. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  20961. ASSERT_EQ(msgs.size(), 1u);
  20962. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  20963. }
  20964. TEST_F(SSEParsingTest, CustomEventType) {
  20965. auto msgs = parse("event: update\ndata: payload\n\n");
  20966. ASSERT_EQ(msgs.size(), 1u);
  20967. EXPECT_EQ(msgs[0].event, "update");
  20968. EXPECT_EQ(msgs[0].data, "payload");
  20969. }
  20970. TEST_F(SSEParsingTest, EventIdHandling) {
  20971. auto msgs = parse("id: 12345\ndata: test\n\n");
  20972. ASSERT_EQ(msgs.size(), 1u);
  20973. EXPECT_EQ(msgs[0].id, "12345");
  20974. }
  20975. TEST_F(SSEParsingTest, EmptyEventId) {
  20976. auto msgs = parse("id:\ndata: test\n\n");
  20977. ASSERT_EQ(msgs.size(), 1u);
  20978. EXPECT_EQ(msgs[0].id, "");
  20979. }
  20980. TEST_F(SSEParsingTest, CommentsIgnored) {
  20981. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  20982. ASSERT_EQ(msgs.size(), 1u);
  20983. EXPECT_EQ(msgs[0].data, "hello");
  20984. EXPECT_EQ(msgs[0].event, "message");
  20985. }
  20986. TEST_F(SSEParsingTest, ColonInValue) {
  20987. auto msgs = parse("data: hello:world:test\n\n");
  20988. ASSERT_EQ(msgs.size(), 1u);
  20989. EXPECT_EQ(msgs[0].data, "hello:world:test");
  20990. }
  20991. TEST_F(SSEParsingTest, FieldNameOnly) {
  20992. // A line without a colon is a field name with an empty value
  20993. auto msgs = parse("data\n\n");
  20994. ASSERT_EQ(msgs.size(), 1u);
  20995. EXPECT_EQ(msgs[0].data, "");
  20996. }
  20997. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  20998. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  20999. ASSERT_EQ(msgs.size(), 1u);
  21000. EXPECT_EQ(msgs[0].event, "update");
  21001. EXPECT_EQ(msgs[0].data, "hello");
  21002. }
  21003. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  21004. auto msgs = parse("data\r\n\r\n");
  21005. ASSERT_EQ(msgs.size(), 1u);
  21006. EXPECT_EQ(msgs[0].data, "");
  21007. }
  21008. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  21009. auto msgs = parse("event: update\rdata: hello\r\r");
  21010. ASSERT_EQ(msgs.size(), 1u);
  21011. EXPECT_EQ(msgs[0].event, "update");
  21012. EXPECT_EQ(msgs[0].data, "hello");
  21013. }
  21014. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  21015. // Chunk boundaries fall inside every \r\n and right before the first one
  21016. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  21017. "\n\r", "\nevent: end\ndata: end\n\n"};
  21018. server_->Get("/split", [chunks](const Request &, Response &res) {
  21019. auto i = std::make_shared<size_t>(0);
  21020. res.set_chunked_content_provider(
  21021. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  21022. if (*i == chunks.size()) {
  21023. sink.done();
  21024. } else {
  21025. sink.write(chunks[*i].data(), chunks[*i].size());
  21026. (*i)++;
  21027. }
  21028. return true;
  21029. });
  21030. });
  21031. auto msgs = collect("/split");
  21032. ASSERT_EQ(msgs.size(), 1u);
  21033. EXPECT_EQ(msgs[0].event, "update");
  21034. EXPECT_EQ(msgs[0].data, "hello");
  21035. }
  21036. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  21037. // Only a BOM at the start of the stream is ignored
  21038. auto msgs = parse("\xEF\xBB\xBF"
  21039. "data: first\n\n"
  21040. "\xEF\xBB\xBF"
  21041. "data: second\n\n");
  21042. ASSERT_EQ(msgs.size(), 1u);
  21043. EXPECT_EQ(msgs[0].data, "first");
  21044. }
  21045. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  21046. auto msgs = parse("unknown: value\ndata: hello\n\n");
  21047. ASSERT_EQ(msgs.size(), 1u);
  21048. EXPECT_EQ(msgs[0].data, "hello");
  21049. EXPECT_EQ(msgs[0].event, "message");
  21050. }
  21051. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  21052. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  21053. ASSERT_EQ(msgs.size(), 2u);
  21054. EXPECT_EQ(msgs[0].data, "hello");
  21055. EXPECT_EQ(msgs[1].data, "hello");
  21056. }
  21057. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  21058. // An event without data is not dispatched, and its type must not leak
  21059. // into the next event
  21060. auto msgs = parse("event: update\n\ndata: hello\n\n");
  21061. ASSERT_EQ(msgs.size(), 1u);
  21062. EXPECT_EQ(msgs[0].event, "message");
  21063. EXPECT_EQ(msgs[0].data, "hello");
  21064. }
  21065. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  21066. // The first connection sends only an id; the second echoes back the
  21067. // Last-Event-ID it was reconnected with
  21068. std::atomic<int> connection_count{0};
  21069. server_->Get("/id-only", [&](const Request &req, Response &res) {
  21070. if (connection_count++ == 0) {
  21071. res.set_content("id: 42\n\n", "text/event-stream");
  21072. } else {
  21073. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21074. "\n\nevent: end\ndata: end\n\n",
  21075. "text/event-stream");
  21076. }
  21077. });
  21078. auto msgs = collect("/id-only");
  21079. ASSERT_EQ(msgs.size(), 1u);
  21080. EXPECT_EQ(msgs[0].data, "42");
  21081. }
  21082. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  21083. // The first connection sets an id and then clears it with an empty one; the
  21084. // second reports whether it was reconnected with a Last-Event-ID
  21085. std::atomic<int> connection_count{0};
  21086. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  21087. if (connection_count++ == 0) {
  21088. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  21089. "text/event-stream");
  21090. } else {
  21091. res.set_content(
  21092. std::string("data: ") +
  21093. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  21094. "\n\nevent: end\ndata: end\n\n",
  21095. "text/event-stream");
  21096. }
  21097. });
  21098. auto msgs = collect("/id-clear");
  21099. ASSERT_EQ(msgs.size(), 3u);
  21100. EXPECT_EQ(msgs[0].id, "1");
  21101. EXPECT_EQ(msgs[1].id, "");
  21102. EXPECT_EQ(msgs[2].data, "not sent");
  21103. }
  21104. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  21105. // The first connection sets an id and then sends ids that cannot be carried
  21106. // in a header; the second echoes back the Last-Event-ID it was reconnected
  21107. // with
  21108. std::atomic<int> connection_count{0};
  21109. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  21110. if (connection_count++ == 0) {
  21111. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  21112. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  21113. "text/event-stream");
  21114. } else {
  21115. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21116. "\n\nevent: end\ndata: end\n\n",
  21117. "text/event-stream");
  21118. }
  21119. });
  21120. auto msgs = collect("/id-unsendable");
  21121. ASSERT_EQ(msgs.size(), 1u);
  21122. EXPECT_EQ(msgs[0].data, "42");
  21123. }
  21124. TEST_F(SSEParsingTest, CompleteEventParsing) {
  21125. auto msgs = parse("event: notification\nid: evt-42\n"
  21126. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  21127. ASSERT_EQ(msgs.size(), 1u);
  21128. EXPECT_EQ(msgs[0].event, "notification");
  21129. EXPECT_EQ(msgs[0].id, "evt-42");
  21130. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  21131. }
  21132. TEST(SSEMessageTest, Clear) {
  21133. sse::SSEMessage msg;
  21134. msg.event = "custom";
  21135. msg.data = "some data";
  21136. msg.id = "123";
  21137. msg.clear();
  21138. EXPECT_EQ(msg.event, "message");
  21139. EXPECT_EQ(msg.data, "");
  21140. EXPECT_EQ(msg.id, "");
  21141. }
  21142. //==============================================================================
  21143. // SSE Integration Tests
  21144. //==============================================================================
  21145. // Test: Successful connection and on_open callback
  21146. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  21147. // Add a simple endpoint that sends one event and closes
  21148. server_->Get("/simple-event", [](const Request &, Response &res) {
  21149. res.set_chunked_content_provider(
  21150. "text/event-stream", [](size_t offset, DataSink &sink) {
  21151. if (offset == 0) {
  21152. std::string event = "data: hello\n\n";
  21153. sink.write(event.data(), event.size());
  21154. }
  21155. return false; // Close stream after sending
  21156. });
  21157. });
  21158. Client client("localhost", get_port());
  21159. sse::SSEClient sse(client, "/simple-event");
  21160. std::atomic<bool> open_called{false};
  21161. std::atomic<bool> message_received{false};
  21162. sse.on_open([&open_called]() { open_called.store(true); });
  21163. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  21164. if (msg.data == "hello") { message_received.store(true); }
  21165. });
  21166. sse.set_reconnect_interval(100);
  21167. sse.set_max_reconnect_attempts(1);
  21168. // Start async
  21169. sse.start_async();
  21170. // Wait for message to be processed
  21171. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21172. sse.stop();
  21173. EXPECT_TRUE(open_called.load());
  21174. EXPECT_TRUE(message_received.load());
  21175. }
  21176. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  21177. // A data line that never ends.
  21178. server_->Get("/endless-line", [](const Request &, Response &res) {
  21179. res.set_chunked_content_provider(
  21180. "text/event-stream", [](size_t offset, DataSink &sink) {
  21181. if (offset == 0) { sink.write("data: ", 6); }
  21182. std::string chunk(64 * 1024, 'A');
  21183. return sink.write(chunk.data(), chunk.size());
  21184. });
  21185. });
  21186. Client client("localhost", get_port());
  21187. sse::SSEClient sse(client, "/endless-line");
  21188. std::atomic<bool> too_long{false};
  21189. sse.on_error([&](Error err) {
  21190. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  21191. });
  21192. sse.set_max_reconnect_attempts(1);
  21193. sse.start_async();
  21194. for (int i = 0; i < 500 && !too_long; i++) {
  21195. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21196. }
  21197. sse.stop();
  21198. EXPECT_TRUE(too_long);
  21199. }
  21200. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  21201. // Far more in all than the client's payload limit below.
  21202. server_->Get("/many-events", [](const Request &, Response &res) {
  21203. res.set_chunked_content_provider(
  21204. "text/event-stream", [](size_t offset, DataSink &sink) {
  21205. if (offset == 0) {
  21206. std::string events;
  21207. for (int i = 0; i < 1000; i++) {
  21208. events += "data: message\n\n";
  21209. }
  21210. sink.write(events.data(), events.size());
  21211. }
  21212. return false;
  21213. });
  21214. });
  21215. Client client("localhost", get_port());
  21216. client.set_payload_max_length(1024);
  21217. sse::SSEClient sse(client, "/many-events");
  21218. std::atomic<int> messages{0};
  21219. std::atomic<bool> too_large{false};
  21220. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  21221. sse.on_error([&](Error err) {
  21222. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  21223. });
  21224. sse.set_max_reconnect_attempts(1);
  21225. sse.start_async();
  21226. for (int i = 0; i < 500 && messages < 1000; i++) {
  21227. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21228. }
  21229. sse.stop();
  21230. EXPECT_GE(messages.load(), 1000);
  21231. EXPECT_FALSE(too_large);
  21232. }
  21233. // Test: on_message callback
  21234. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  21235. // Endpoint that sends multiple events then closes
  21236. server_->Get("/multi-event", [](const Request &, Response &res) {
  21237. res.set_chunked_content_provider(
  21238. "text/event-stream", [](size_t offset, DataSink &sink) {
  21239. if (offset == 0) {
  21240. std::string events = "data: message1\n\ndata: message2\n\n";
  21241. sink.write(events.data(), events.size());
  21242. }
  21243. return false;
  21244. });
  21245. });
  21246. Client client("localhost", get_port());
  21247. sse::SSEClient sse(client, "/multi-event");
  21248. std::vector<std::string> received_messages;
  21249. std::mutex messages_mutex;
  21250. sse.on_message([&](const sse::SSEMessage &msg) {
  21251. std::lock_guard<std::mutex> lock(messages_mutex);
  21252. received_messages.push_back(msg.data);
  21253. });
  21254. sse.set_reconnect_interval(100);
  21255. sse.set_max_reconnect_attempts(1);
  21256. sse.start_async();
  21257. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21258. sse.stop();
  21259. std::lock_guard<std::mutex> lock(messages_mutex);
  21260. EXPECT_GE(received_messages.size(), 2u);
  21261. if (received_messages.size() >= 2) {
  21262. EXPECT_EQ(received_messages[0], "message1");
  21263. EXPECT_EQ(received_messages[1], "message2");
  21264. }
  21265. }
  21266. // Test: on_event for specific types
  21267. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  21268. Client client("localhost", get_port());
  21269. sse::SSEClient sse(client, "/custom-events");
  21270. std::atomic<bool> update_received{false};
  21271. std::atomic<bool> delete_received{false};
  21272. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  21273. if (msg.data == "updated") { update_received.store(true); }
  21274. });
  21275. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  21276. if (msg.data == "deleted") { delete_received.store(true); }
  21277. });
  21278. sse.set_max_reconnect_attempts(1);
  21279. sse.start_async();
  21280. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  21281. sse.stop();
  21282. EXPECT_TRUE(update_received.load());
  21283. EXPECT_TRUE(delete_received.load());
  21284. }
  21285. // Test: on_error callback on connection failure
  21286. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  21287. // Connect to a non-existent port
  21288. Client client("localhost", 59999);
  21289. sse::SSEClient sse(client, "/events");
  21290. std::atomic<bool> error_called{false};
  21291. Error received_error = Error::Success;
  21292. sse.on_error([&](Error err) {
  21293. error_called.store(true);
  21294. received_error = err;
  21295. });
  21296. sse.set_reconnect_interval(50);
  21297. sse.set_max_reconnect_attempts(1);
  21298. sse.start_async();
  21299. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21300. sse.stop();
  21301. EXPECT_TRUE(error_called.load());
  21302. EXPECT_NE(received_error, Error::Success);
  21303. }
  21304. // Test: Last-Event-ID header sent on reconnect
  21305. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  21306. // Endpoint that sends event with ID
  21307. server_->Get("/event-with-id", [](const Request &, Response &res) {
  21308. res.set_chunked_content_provider(
  21309. "text/event-stream", [](size_t offset, DataSink &sink) {
  21310. if (offset == 0) {
  21311. std::string event = "id: evt-123\ndata: test\n\n";
  21312. sink.write(event.data(), event.size());
  21313. }
  21314. return false;
  21315. });
  21316. });
  21317. Client client("localhost", get_port());
  21318. sse::SSEClient sse(client, "/event-with-id");
  21319. std::atomic<bool> id_received{false};
  21320. sse.on_message([&](const sse::SSEMessage &msg) {
  21321. if (!msg.id.empty()) { id_received.store(true); }
  21322. });
  21323. sse.set_reconnect_interval(100);
  21324. sse.set_max_reconnect_attempts(1);
  21325. sse.start_async();
  21326. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21327. sse.stop();
  21328. EXPECT_TRUE(id_received.load());
  21329. EXPECT_EQ(sse.last_event_id(), "evt-123");
  21330. }
  21331. // Test: Manual stop
  21332. TEST_F(SSEIntegrationTest, ManualStop) {
  21333. // Endpoint that sends one event and stays open briefly
  21334. std::atomic<bool> handler_running{true};
  21335. server_->Get("/stay-open", [&handler_running](const Request &,
  21336. Response &res) {
  21337. res.set_chunked_content_provider(
  21338. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  21339. if (offset == 0) {
  21340. std::string event = "data: connected\n\n";
  21341. sink.write(event.data(), event.size());
  21342. }
  21343. // Keep connection open while handler_running is true
  21344. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  21345. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21346. }
  21347. return false;
  21348. });
  21349. });
  21350. Client client("localhost", get_port());
  21351. sse::SSEClient sse(client, "/stay-open");
  21352. std::atomic<bool> connected{false};
  21353. sse.on_open([&connected]() { connected.store(true); });
  21354. sse.set_reconnect_interval(100);
  21355. sse.set_max_reconnect_attempts(1);
  21356. sse.start_async();
  21357. // Wait for connection to establish
  21358. for (int i = 0; i < 20 && !connected.load(); ++i) {
  21359. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21360. }
  21361. EXPECT_TRUE(connected.load());
  21362. EXPECT_TRUE(sse.is_connected());
  21363. // Signal handler to stop
  21364. handler_running.store(false);
  21365. // Stop SSE client
  21366. sse.stop();
  21367. EXPECT_FALSE(sse.is_connected());
  21368. }
  21369. // Test: SSEClient with custom headers
  21370. TEST_F(SSEIntegrationTest, CustomHeaders) {
  21371. // Setup a server endpoint that checks for custom header
  21372. std::atomic<bool> header_received{false};
  21373. server_->Get("/header-check", [&](const Request &req, Response &res) {
  21374. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  21375. header_received.store(true);
  21376. }
  21377. res.set_chunked_content_provider("text/event-stream",
  21378. [](size_t, DataSink &) { return false; });
  21379. });
  21380. Client client("localhost", get_port());
  21381. Headers headers = {{"X-Custom-Header", "custom-value"}};
  21382. sse::SSEClient sse(client, "/header-check", headers);
  21383. sse.set_max_reconnect_attempts(1);
  21384. sse.start_async();
  21385. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21386. sse.stop();
  21387. EXPECT_TRUE(header_received.load());
  21388. }
  21389. // Test: Reconnect interval configuration
  21390. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  21391. Client client("localhost", get_port());
  21392. sse::SSEClient sse(client, "/events");
  21393. auto &result = sse.set_reconnect_interval(500);
  21394. // Builder pattern should return reference to self
  21395. EXPECT_EQ(&result, &sse);
  21396. }
  21397. // Test: Max reconnect attempts
  21398. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  21399. // Connect to non-existent port to force reconnects
  21400. Client client("localhost", 59998);
  21401. sse::SSEClient sse(client, "/events");
  21402. std::atomic<int> error_count{0};
  21403. sse.on_error([&](Error) { error_count.fetch_add(1); });
  21404. sse.set_reconnect_interval(50);
  21405. sse.set_max_reconnect_attempts(2);
  21406. auto start = std::chrono::steady_clock::now();
  21407. sse.start(); // Blocking call
  21408. auto end = std::chrono::steady_clock::now();
  21409. // Should have stopped after 2 failed attempts
  21410. EXPECT_GE(error_count.load(), 2);
  21411. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  21412. auto duration =
  21413. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  21414. #ifdef _WIN32
  21415. // Windows is much slower for socket connection failures
  21416. EXPECT_LT(duration.count(), 7000);
  21417. #else
  21418. EXPECT_LT(duration.count(), 1000);
  21419. #endif
  21420. }
  21421. // Test: Multi-line data in integration
  21422. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  21423. // Endpoint with multi-line data
  21424. server_->Get("/multiline-data", [](const Request &, Response &res) {
  21425. res.set_chunked_content_provider(
  21426. "text/event-stream", [](size_t offset, DataSink &sink) {
  21427. if (offset == 0) {
  21428. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  21429. sink.write(event.data(), event.size());
  21430. }
  21431. return false;
  21432. });
  21433. });
  21434. Client client("localhost", get_port());
  21435. sse::SSEClient sse(client, "/multiline-data");
  21436. std::string received_data;
  21437. std::mutex data_mutex;
  21438. sse.on_message([&](const sse::SSEMessage &msg) {
  21439. std::lock_guard<std::mutex> lock(data_mutex);
  21440. received_data = msg.data;
  21441. });
  21442. sse.set_reconnect_interval(100);
  21443. sse.set_max_reconnect_attempts(1);
  21444. sse.start_async();
  21445. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21446. sse.stop();
  21447. std::lock_guard<std::mutex> lock(data_mutex);
  21448. EXPECT_EQ(received_data, "line1\nline2\nline3");
  21449. }
  21450. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  21451. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  21452. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  21453. DataSink &sink) {
  21454. if (offset == 0) {
  21455. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  21456. sink.write(events.data(), events.size());
  21457. }
  21458. return false;
  21459. });
  21460. });
  21461. Client client("localhost", get_port());
  21462. sse::SSEClient sse(client, "/empty-data-lines");
  21463. std::mutex mutex;
  21464. std::condition_variable cv;
  21465. std::vector<std::string> received;
  21466. sse.on_message([&](const sse::SSEMessage &msg) {
  21467. std::lock_guard<std::mutex> lock(mutex);
  21468. received.push_back(msg.data);
  21469. cv.notify_all();
  21470. });
  21471. sse.set_max_reconnect_attempts(1);
  21472. sse.start_async();
  21473. {
  21474. std::unique_lock<std::mutex> lock(mutex);
  21475. cv.wait_for(lock, std::chrono::seconds(2),
  21476. [&] { return received.size() >= 3; });
  21477. }
  21478. sse.stop();
  21479. ASSERT_GE(received.size(), 3u);
  21480. EXPECT_EQ(received[0], "");
  21481. EXPECT_EQ(received[1], "\nhello");
  21482. EXPECT_EQ(received[2], "");
  21483. }
  21484. // Test: Auto-reconnect after server disconnection
  21485. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  21486. std::atomic<int> connection_count{0};
  21487. std::atomic<int> message_count{0};
  21488. // Endpoint that sends one event and closes, forcing reconnect
  21489. server_->Get("/reconnect-test",
  21490. [&connection_count](const Request &, Response &res) {
  21491. connection_count.fetch_add(1);
  21492. res.set_chunked_content_provider(
  21493. "text/event-stream", [](size_t offset, DataSink &sink) {
  21494. if (offset == 0) {
  21495. std::string event = "data: hello\n\n";
  21496. sink.write(event.data(), event.size());
  21497. }
  21498. return false; // Close connection after sending
  21499. });
  21500. });
  21501. Client client("localhost", get_port());
  21502. sse::SSEClient sse(client, "/reconnect-test");
  21503. sse.on_message([&message_count](const sse::SSEMessage &) {
  21504. message_count.fetch_add(1);
  21505. });
  21506. sse.set_reconnect_interval(100);
  21507. sse.set_max_reconnect_attempts(3);
  21508. sse.start_async();
  21509. // Wait long enough for multiple reconnects
  21510. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21511. sse.stop();
  21512. // Should have connected multiple times (initial + reconnects)
  21513. EXPECT_GE(connection_count.load(), 2);
  21514. // Should have received messages from multiple connections
  21515. EXPECT_GE(message_count.load(), 2);
  21516. }
  21517. // Test: A retry field that is not all ASCII digits is ignored
  21518. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  21519. std::atomic<int> connection_count{0};
  21520. server_->Get("/bad-retry",
  21521. [&connection_count](const Request &, Response &res) {
  21522. connection_count.fetch_add(1);
  21523. res.set_chunked_content_provider(
  21524. "text/event-stream", [](size_t offset, DataSink &sink) {
  21525. if (offset == 0) {
  21526. std::string event = "retry: -1\ndata: hello\n\n";
  21527. sink.write(event.data(), event.size());
  21528. }
  21529. return false;
  21530. });
  21531. });
  21532. Client client("localhost", get_port());
  21533. sse::SSEClient sse(client, "/bad-retry");
  21534. sse.set_reconnect_interval(10000);
  21535. sse.start_async();
  21536. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21537. sse.stop();
  21538. EXPECT_EQ(connection_count.load(), 1);
  21539. }
  21540. // Test: A retry field of all ASCII digits sets the reconnection time
  21541. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  21542. std::mutex mutex;
  21543. std::condition_variable cv;
  21544. std::vector<std::chrono::steady_clock::time_point> connected_at;
  21545. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  21546. {
  21547. std::lock_guard<std::mutex> lock(mutex);
  21548. connected_at.push_back(std::chrono::steady_clock::now());
  21549. cv.notify_all();
  21550. }
  21551. res.set_chunked_content_provider(
  21552. "text/event-stream", [](size_t offset, DataSink &sink) {
  21553. if (offset == 0) {
  21554. std::string event = "retry: 0\ndata: hello\n\n";
  21555. sink.write(event.data(), event.size());
  21556. }
  21557. return false;
  21558. });
  21559. });
  21560. Client client("localhost", get_port());
  21561. sse::SSEClient sse(client, "/zero-retry");
  21562. sse.set_reconnect_interval(10000);
  21563. sse.start_async();
  21564. {
  21565. std::unique_lock<std::mutex> lock(mutex);
  21566. cv.wait_for(lock, std::chrono::seconds(5),
  21567. [&] { return connected_at.size() >= 2; });
  21568. }
  21569. sse.stop();
  21570. // The server-supplied interval is applied, but never below 100ms, so
  21571. // "retry: 0" does not cause a busy reconnect loop
  21572. std::lock_guard<std::mutex> lock(mutex);
  21573. ASSERT_GE(connected_at.size(), 2u);
  21574. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  21575. connected_at[1] - connected_at[0])
  21576. .count();
  21577. EXPECT_GE(interval_ms, 100);
  21578. }
  21579. // Test: Last-Event-ID sent on reconnect
  21580. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  21581. std::atomic<int> connection_count{0};
  21582. std::vector<std::string> received_last_event_ids;
  21583. std::mutex id_mutex;
  21584. // Endpoint that checks Last-Event-ID header and sends event with ID
  21585. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  21586. int conn = connection_count.fetch_add(1);
  21587. // Capture the Last-Event-ID header from each connection
  21588. {
  21589. std::lock_guard<std::mutex> lock(id_mutex);
  21590. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  21591. }
  21592. res.set_chunked_content_provider(
  21593. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  21594. if (offset == 0) {
  21595. std::string event =
  21596. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  21597. sink.write(event.data(), event.size());
  21598. }
  21599. return false;
  21600. });
  21601. });
  21602. Client client("localhost", get_port());
  21603. sse::SSEClient sse(client, "/reconnect-with-id");
  21604. sse.set_reconnect_interval(100);
  21605. sse.set_max_reconnect_attempts(3);
  21606. sse.start_async();
  21607. // Wait for at least 2 connections
  21608. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21609. sse.stop();
  21610. // Verify behavior
  21611. std::lock_guard<std::mutex> lock(id_mutex);
  21612. EXPECT_GE(received_last_event_ids.size(), 2u);
  21613. // First connection should have no Last-Event-ID
  21614. if (!received_last_event_ids.empty()) {
  21615. EXPECT_EQ(received_last_event_ids[0], "");
  21616. }
  21617. // Second connection should have Last-Event-ID from first connection
  21618. if (received_last_event_ids.size() >= 2) {
  21619. EXPECT_EQ(received_last_event_ids[1], "event-0");
  21620. }
  21621. }
  21622. // Test: set_headers updates headers used on reconnect
  21623. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  21624. std::vector<std::string> received_tokens;
  21625. std::mutex token_mutex;
  21626. // Endpoint that captures Authorization header
  21627. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  21628. {
  21629. std::lock_guard<std::mutex> lock(token_mutex);
  21630. received_tokens.push_back(req.get_header_value("Authorization"));
  21631. }
  21632. res.set_chunked_content_provider(
  21633. "text/event-stream", [](size_t offset, DataSink &sink) {
  21634. if (offset == 0) {
  21635. std::string event = "data: hello\n\n";
  21636. sink.write(event.data(), event.size());
  21637. }
  21638. return false; // Close connection to trigger reconnect
  21639. });
  21640. });
  21641. Client client("localhost", get_port());
  21642. Headers headers = {{"Authorization", "Bearer old-token"}};
  21643. sse::SSEClient sse(client, "/auth-check", headers);
  21644. // Update headers on each successful connection
  21645. sse.on_open(
  21646. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  21647. sse.set_reconnect_interval(100);
  21648. sse.set_max_reconnect_attempts(3);
  21649. sse.start_async();
  21650. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21651. sse.stop();
  21652. std::lock_guard<std::mutex> lock(token_mutex);
  21653. ASSERT_GE(received_tokens.size(), 2u);
  21654. // First connection uses original header
  21655. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  21656. // Second connection uses updated header from set_headers
  21657. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  21658. }
  21659. // Test: 401 allows reconnection (so on_error can refresh headers)
  21660. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  21661. std::atomic<int> connection_count{0};
  21662. // Endpoint: returns 401 on first attempt, 200 on second
  21663. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  21664. int conn = connection_count.fetch_add(1);
  21665. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  21666. res.status = StatusCode::Unauthorized_401;
  21667. res.set_content("Unauthorized", "text/plain");
  21668. return;
  21669. }
  21670. res.set_chunked_content_provider(
  21671. "text/event-stream", [](size_t offset, DataSink &sink) {
  21672. if (offset == 0) {
  21673. std::string event = "data: authenticated\n\n";
  21674. sink.write(event.data(), event.size());
  21675. }
  21676. return false;
  21677. });
  21678. });
  21679. Client client("localhost", get_port());
  21680. Headers headers = {{"Authorization", "Bearer expired"}};
  21681. sse::SSEClient sse(client, "/auth-retry", headers);
  21682. std::atomic<bool> message_received{false};
  21683. // Refresh token on error
  21684. sse.on_error(
  21685. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  21686. sse.on_message([&](const sse::SSEMessage &msg) {
  21687. if (msg.data == "authenticated") { message_received.store(true); }
  21688. });
  21689. sse.set_reconnect_interval(100);
  21690. sse.set_max_reconnect_attempts(3);
  21691. sse.start_async();
  21692. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  21693. sse.stop();
  21694. // Should have reconnected after 401 and succeeded with new token
  21695. EXPECT_GE(connection_count.load(), 2);
  21696. EXPECT_TRUE(message_received.load());
  21697. }
  21698. TEST(Issue2318Test, EmptyHostString) {
  21699. {
  21700. httplib::Client cli_empty("", PORT);
  21701. auto res = cli_empty.Get("/");
  21702. ASSERT_FALSE(res);
  21703. EXPECT_EQ(httplib::Error::Connection, res.error());
  21704. }
  21705. {
  21706. httplib::Client cli(" ", PORT);
  21707. auto res = cli.Get("/");
  21708. ASSERT_FALSE(res);
  21709. EXPECT_EQ(httplib::Error::Connection, res.error());
  21710. }
  21711. }
  21712. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21713. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  21714. Server svr;
  21715. // Set a small payload limit (1KB)
  21716. svr.set_payload_max_length(1024);
  21717. svr.Post("/test", [&](const Request &req, Response &res) {
  21718. res.set_content("Body size: " + std::to_string(req.body.size()),
  21719. "text/plain");
  21720. });
  21721. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  21722. auto se = detail::scope_exit([&] {
  21723. svr.stop();
  21724. listen_thread.join();
  21725. });
  21726. svr.wait_until_ready();
  21727. // Create data that compresses well but exceeds limit when decompressed
  21728. // 8KB of repeated null bytes compresses to a very small size
  21729. std::string original_data(8 * 1024, '\0');
  21730. // Compress the data using gzip
  21731. std::string compressed_data;
  21732. detail::gzip_compressor compressor;
  21733. compressor.compress(original_data.data(), original_data.size(), true,
  21734. [&](const char *data, size_t size) {
  21735. compressed_data.append(data, size);
  21736. return true;
  21737. });
  21738. // Verify compression worked (compressed should be much smaller)
  21739. ASSERT_LT(compressed_data.size(), original_data.size());
  21740. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  21741. // Send compressed data with Content-Encoding: gzip
  21742. Client cli(HOST, PORT);
  21743. Headers headers = {{"Content-Encoding", "gzip"}};
  21744. auto res =
  21745. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  21746. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  21747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21748. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  21749. }
  21750. #endif
  21751. // ============================================================================
  21752. // OpenSSL-Specific Tests
  21753. // ============================================================================
  21754. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  21755. X509 *readCertificate(const std::string &strFileName) {
  21756. std::ifstream inStream(strFileName);
  21757. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  21758. std::istreambuf_iterator<char>());
  21759. if (strCertPEM.empty()) return (nullptr);
  21760. BIO *pbCert = BIO_new(BIO_s_mem());
  21761. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  21762. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  21763. BIO_free(pbCert);
  21764. return (pCert);
  21765. }
  21766. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  21767. std::ifstream inStream(strFileName);
  21768. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  21769. std::istreambuf_iterator<char>());
  21770. if (strPrivateKeyPEM.empty()) return (nullptr);
  21771. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  21772. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  21773. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  21774. BIO_free(pbPrivKey);
  21775. return (pPrivateKey);
  21776. }
  21777. TEST(BindServerTest, UpdateCerts) {
  21778. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21779. int port = svr.bind_to_any_port("0.0.0.0");
  21780. ASSERT_TRUE(svr.is_valid());
  21781. ASSERT_TRUE(port > 0);
  21782. X509 *cert = readCertificate(SERVER_CERT_FILE);
  21783. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  21784. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  21785. ASSERT_TRUE(cert != nullptr);
  21786. ASSERT_TRUE(ca_cert != nullptr);
  21787. ASSERT_TRUE(key != nullptr);
  21788. X509_STORE *cert_store = X509_STORE_new();
  21789. X509_STORE_add_cert(cert_store, ca_cert);
  21790. // svr.update_certs(cert, key, cert_store); // deprecated
  21791. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  21792. CLIENT_CA_CERT_FILE);
  21793. ASSERT_TRUE(svr.is_valid());
  21794. svr.stop();
  21795. X509_STORE_free(cert_store);
  21796. X509_free(cert);
  21797. X509_free(ca_cert);
  21798. EVP_PKEY_free(key);
  21799. }
  21800. // Test that update_certs() updates client CA list correctly
  21801. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  21802. // Start with file-based constructor
  21803. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21804. ASSERT_TRUE(svr.is_valid());
  21805. // Initially no client CA list should be set
  21806. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  21807. ASSERT_TRUE(ssl_ctx != nullptr);
  21808. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  21809. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  21810. EXPECT_EQ(0, count_before);
  21811. // Now update with client CA (PEM string)
  21812. std::string cert_pem, key_pem, ca_pem;
  21813. read_file(SERVER_CERT_FILE, cert_pem);
  21814. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  21815. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  21816. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  21817. ASSERT_TRUE(svr.is_valid());
  21818. // Now client CA list should be set
  21819. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  21820. ASSERT_TRUE(ca_list_after != nullptr);
  21821. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  21822. }
  21823. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  21824. // Test that the file-path SSLServer constructor properly sets the client CA
  21825. // list that is sent to clients during the TLS handshake (CertificateRequest)
  21826. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21827. ASSERT_TRUE(svr.is_valid());
  21828. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  21829. ASSERT_TRUE(ssl_ctx != nullptr);
  21830. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  21831. ASSERT_TRUE(ca_list != nullptr);
  21832. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  21833. }
  21834. #endif
  21835. // ============================================================================
  21836. // MbedTLS-Specific Tests
  21837. // ============================================================================
  21838. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  21839. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  21840. using namespace httplib::tls;
  21841. // Track if callback was invoked
  21842. bool callback_invoked = false;
  21843. // The callback receives void* ctx which is actually MbedTlsContext*
  21844. // We can access the mbedtls_ssl_config via the context
  21845. auto setup_callback = [&callback_invoked](void *ctx) {
  21846. callback_invoked = true;
  21847. // Cast to MbedTlsContext* to access the ssl config
  21848. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  21849. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  21850. // Use static variables to hold certificate data (simplified for test)
  21851. static mbedtls_x509_crt own_cert;
  21852. static mbedtls_pk_context own_key;
  21853. static mbedtls_x509_crt ca_chain;
  21854. static bool initialized = false;
  21855. if (!initialized) {
  21856. mbedtls_x509_crt_init(&own_cert);
  21857. mbedtls_pk_init(&own_key);
  21858. mbedtls_x509_crt_init(&ca_chain);
  21859. // Load server certificate
  21860. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  21861. return false;
  21862. }
  21863. // Load server private key.
  21864. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  21865. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  21866. #if MBEDTLS_VERSION_MAJOR == 3
  21867. ,
  21868. mbedtls_ctr_drbg_random, nullptr
  21869. #endif
  21870. ) != 0) {
  21871. return false;
  21872. }
  21873. // Load CA chain for client verification
  21874. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  21875. return false;
  21876. }
  21877. initialized = true;
  21878. }
  21879. // Configure the SSL config
  21880. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  21881. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  21882. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  21883. // Set minimum TLS version using mbedTLS native API
  21884. #if MBEDTLS_VERSION_MAJOR >= 3
  21885. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  21886. #else
  21887. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  21888. MBEDTLS_SSL_MINOR_VERSION_3);
  21889. #endif
  21890. return true;
  21891. };
  21892. SSLServer svr(setup_callback);
  21893. ASSERT_TRUE(svr.is_valid());
  21894. ASSERT_TRUE(callback_invoked);
  21895. svr.Get("/test", [&](const Request &req, Response &res) {
  21896. res.set_content("test", "text/plain");
  21897. auto cert = req.peer_cert();
  21898. ASSERT_TRUE(static_cast<bool>(cert));
  21899. auto common_name = cert.subject_cn();
  21900. EXPECT_EQ("Common Name", common_name);
  21901. });
  21902. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21903. auto se = detail::scope_exit([&] {
  21904. svr.stop();
  21905. t.join();
  21906. ASSERT_FALSE(svr.is_running());
  21907. });
  21908. svr.wait_until_ready();
  21909. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  21910. cli.enable_server_certificate_verification(false);
  21911. cli.set_connection_timeout(30);
  21912. auto res = cli.Get("/test");
  21913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21914. ASSERT_EQ(StatusCode::OK_200, res->status);
  21915. }
  21916. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  21917. // context (owning mbedtls_ssl_config) before shutting down a still-open
  21918. // keep-alive SSL session, which reads through that config in
  21919. // mbedtls_ssl_close_notify.
  21920. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  21921. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21922. ASSERT_TRUE(svr.is_valid());
  21923. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  21924. res.set_content("test", "text/plain");
  21925. });
  21926. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21927. auto se = detail::scope_exit([&] {
  21928. svr.stop();
  21929. t.join();
  21930. ASSERT_FALSE(svr.is_running());
  21931. });
  21932. svr.wait_until_ready();
  21933. {
  21934. SSLClient cli(HOST, PORT);
  21935. cli.enable_server_certificate_verification(false);
  21936. cli.set_keep_alive(true);
  21937. auto res = cli.Get("/test");
  21938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21939. ASSERT_EQ(StatusCode::OK_200, res->status);
  21940. // cli is destructed here with the keep-alive SSL session still open.
  21941. }
  21942. }
  21943. #endif
  21944. // WebSocket Tests
  21945. TEST(WebSocketTest, RSVBitsMustBeZero) {
  21946. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  21947. // defining the meaning of these bits has been negotiated.
  21948. auto make_frame = [](uint8_t first_byte) {
  21949. std::string frame;
  21950. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  21951. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  21952. frame += "Hello";
  21953. return frame;
  21954. };
  21955. // RSV1 set (0x40)
  21956. {
  21957. detail::BufferStream strm;
  21958. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  21959. ws::Opcode opcode;
  21960. std::string payload;
  21961. bool fin;
  21962. EXPECT_EQ(
  21963. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21964. ws::impl::FrameRead::Fail);
  21965. }
  21966. // RSV2 set (0x20)
  21967. {
  21968. detail::BufferStream strm;
  21969. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  21970. ws::Opcode opcode;
  21971. std::string payload;
  21972. bool fin;
  21973. EXPECT_EQ(
  21974. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21975. ws::impl::FrameRead::Fail);
  21976. }
  21977. // RSV3 set (0x10)
  21978. {
  21979. detail::BufferStream strm;
  21980. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  21981. ws::Opcode opcode;
  21982. std::string payload;
  21983. bool fin;
  21984. EXPECT_EQ(
  21985. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21986. ws::impl::FrameRead::Fail);
  21987. }
  21988. // No RSV bits set - should succeed
  21989. {
  21990. detail::BufferStream strm;
  21991. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  21992. ws::Opcode opcode;
  21993. std::string payload;
  21994. bool fin;
  21995. EXPECT_EQ(
  21996. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21997. ws::impl::FrameRead::Ok);
  21998. EXPECT_EQ(ws::Opcode::Text, opcode);
  21999. EXPECT_EQ("Hello", payload);
  22000. EXPECT_TRUE(fin);
  22001. }
  22002. }
  22003. TEST(WebSocketTest, ControlFrameValidation) {
  22004. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  22005. // payload length <= 125.
  22006. // Ping with FIN=0 - must be rejected
  22007. {
  22008. detail::BufferStream strm;
  22009. std::string frame;
  22010. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  22011. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22012. strm.write(frame.data(), frame.size());
  22013. ws::Opcode opcode;
  22014. std::string payload;
  22015. bool fin;
  22016. EXPECT_EQ(
  22017. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22018. ws::impl::FrameRead::Fail);
  22019. }
  22020. // Close with FIN=0 - must be rejected
  22021. {
  22022. detail::BufferStream strm;
  22023. std::string frame;
  22024. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  22025. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22026. strm.write(frame.data(), frame.size());
  22027. ws::Opcode opcode;
  22028. std::string payload;
  22029. bool fin;
  22030. EXPECT_EQ(
  22031. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22032. ws::impl::FrameRead::Fail);
  22033. }
  22034. // Ping with payload_len=126 (extended length) - must be rejected
  22035. {
  22036. detail::BufferStream strm;
  22037. std::string frame;
  22038. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22039. frame += static_cast<char>(126); // payload_len=126 (>125)
  22040. frame += static_cast<char>(0x00); // extended length high byte
  22041. frame += static_cast<char>(126); // extended length low byte
  22042. frame += std::string(126, 'x');
  22043. strm.write(frame.data(), frame.size());
  22044. ws::Opcode opcode;
  22045. std::string payload;
  22046. bool fin;
  22047. EXPECT_EQ(
  22048. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22049. ws::impl::FrameRead::Fail);
  22050. }
  22051. // Ping with FIN=1 and payload_len=125 - should succeed
  22052. {
  22053. detail::BufferStream strm;
  22054. std::string frame;
  22055. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22056. frame += static_cast<char>(125); // payload_len=125
  22057. frame += std::string(125, 'x');
  22058. strm.write(frame.data(), frame.size());
  22059. ws::Opcode opcode;
  22060. std::string payload;
  22061. bool fin;
  22062. EXPECT_EQ(
  22063. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22064. ws::impl::FrameRead::Ok);
  22065. EXPECT_EQ(ws::Opcode::Ping, opcode);
  22066. EXPECT_EQ(125u, payload.size());
  22067. EXPECT_TRUE(fin);
  22068. }
  22069. }
  22070. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  22071. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  22072. // length MUST be 0.
  22073. // MSB set - must be rejected
  22074. {
  22075. detail::BufferStream strm;
  22076. std::string frame;
  22077. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22078. frame += static_cast<char>(127); // 64-bit extended length
  22079. frame += static_cast<char>(0x80); // MSB set (invalid)
  22080. frame += std::string(7, '\0'); // remaining 7 bytes of length
  22081. strm.write(frame.data(), frame.size());
  22082. ws::Opcode opcode;
  22083. std::string payload;
  22084. bool fin;
  22085. EXPECT_EQ(
  22086. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22087. ws::impl::FrameRead::Fail);
  22088. }
  22089. // MSB clear - should pass length parsing (will be rejected by max_len,
  22090. // but that's a different check; use a small length to verify)
  22091. {
  22092. detail::BufferStream strm;
  22093. std::string frame;
  22094. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22095. frame += static_cast<char>(127); // 64-bit extended length
  22096. frame += std::string(7, '\0'); // high bytes = 0
  22097. frame += static_cast<char>(0x03); // length = 3
  22098. frame += "abc";
  22099. strm.write(frame.data(), frame.size());
  22100. ws::Opcode opcode;
  22101. std::string payload;
  22102. bool fin;
  22103. EXPECT_EQ(
  22104. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22105. ws::impl::FrameRead::Ok);
  22106. EXPECT_EQ(ws::Opcode::Text, opcode);
  22107. EXPECT_EQ("abc", payload);
  22108. }
  22109. }
  22110. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  22111. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  22112. // Valid UTF-8
  22113. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  22114. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  22115. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  22116. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  22117. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  22118. // Invalid UTF-8
  22119. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  22120. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  22121. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  22122. EXPECT_FALSE(
  22123. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  22124. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  22125. }
  22126. TEST(WebSocketTest, ConnectAndDisconnect) {
  22127. Server svr;
  22128. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22129. std::string msg;
  22130. while (ws.read(msg)) {}
  22131. });
  22132. auto port = svr.bind_to_any_port(HOST);
  22133. std::thread t([&]() { svr.listen_after_bind(); });
  22134. svr.wait_until_ready();
  22135. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22136. auto res = client.connect();
  22137. ASSERT_TRUE(res);
  22138. EXPECT_EQ(Error::Success, res.error());
  22139. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  22140. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  22141. EXPECT_TRUE(client.is_open());
  22142. client.close();
  22143. EXPECT_FALSE(client.is_open());
  22144. svr.stop();
  22145. t.join();
  22146. }
  22147. TEST(WebSocketTest, ValidURL) {
  22148. ws::WebSocketClient ws1("ws://localhost:8080/path");
  22149. EXPECT_TRUE(ws1.is_valid());
  22150. ws::WebSocketClient ws2("ws://example.com/path");
  22151. EXPECT_TRUE(ws2.is_valid());
  22152. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  22153. EXPECT_TRUE(ws3.is_valid());
  22154. #ifdef CPPHTTPLIB_SSL_ENABLED
  22155. ws::WebSocketClient wss1("wss://example.com/path");
  22156. EXPECT_TRUE(wss1.is_valid());
  22157. ws::WebSocketClient wss2("wss://example.com:443/path");
  22158. EXPECT_TRUE(wss2.is_valid());
  22159. #endif
  22160. }
  22161. TEST(WebSocketTest, InvalidURL) {
  22162. // No scheme
  22163. ws::WebSocketClient ws1("localhost:8080/path");
  22164. EXPECT_FALSE(ws1.is_valid());
  22165. // No path
  22166. ws::WebSocketClient ws2("ws://localhost:8080");
  22167. EXPECT_FALSE(ws2.is_valid());
  22168. // Empty string
  22169. ws::WebSocketClient ws3("");
  22170. EXPECT_FALSE(ws3.is_valid());
  22171. // Missing host
  22172. ws::WebSocketClient ws4("ws://:8080/path");
  22173. EXPECT_FALSE(ws4.is_valid());
  22174. // Port number overflow — should not crash
  22175. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  22176. EXPECT_FALSE(ws5.is_valid());
  22177. // Port out of range
  22178. ws::WebSocketClient ws6("ws://localhost:99999/path");
  22179. EXPECT_FALSE(ws6.is_valid());
  22180. }
  22181. TEST(WebSocketTest, UnsupportedScheme) {
  22182. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  22183. ws::WebSocketClient ws1("http://localhost:8080/path");
  22184. EXPECT_FALSE(ws1.is_valid());
  22185. ws::WebSocketClient ws2("https://localhost:8080/path");
  22186. EXPECT_FALSE(ws2.is_valid());
  22187. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  22188. EXPECT_FALSE(ws3.is_valid());
  22189. #else
  22190. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  22191. std::invalid_argument);
  22192. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  22193. std::invalid_argument);
  22194. #endif
  22195. }
  22196. TEST(WebSocketTest, ConnectWhenInvalid) {
  22197. ws::WebSocketClient ws("not a valid url");
  22198. EXPECT_FALSE(ws.is_valid());
  22199. auto res = ws.connect();
  22200. EXPECT_FALSE(res);
  22201. EXPECT_EQ(Error::Connection, res.error());
  22202. EXPECT_EQ(-1, res.status());
  22203. }
  22204. TEST(WebSocketTest, ConnectRefusedReportsError) {
  22205. // Grab a port that is free, then close it again so nothing listens there
  22206. Server svr;
  22207. auto port = svr.bind_to_any_port(HOST);
  22208. svr.stop();
  22209. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22210. auto res = client.connect();
  22211. ASSERT_FALSE(res);
  22212. EXPECT_EQ(Error::Connection, res.error());
  22213. EXPECT_EQ(-1, res.status());
  22214. }
  22215. TEST(WebSocketTest, DefaultPort) {
  22216. ws::WebSocketClient ws1("ws://example.com/path");
  22217. EXPECT_TRUE(ws1.is_valid());
  22218. // ws:// defaults to port 80 (verified by successful parse)
  22219. #ifdef CPPHTTPLIB_SSL_ENABLED
  22220. ws::WebSocketClient ws2("wss://example.com/path");
  22221. EXPECT_TRUE(ws2.is_valid());
  22222. // wss:// defaults to port 443 (verified by successful parse)
  22223. #endif
  22224. }
  22225. TEST(WebSocketTest, IPv6LiteralAddress) {
  22226. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  22227. EXPECT_TRUE(ws1.is_valid());
  22228. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  22229. EXPECT_TRUE(ws2.is_valid());
  22230. }
  22231. TEST(WebSocketTest, ComplexPath) {
  22232. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  22233. EXPECT_TRUE(ws1.is_valid());
  22234. ws::WebSocketClient ws2("ws://localhost:8080/");
  22235. EXPECT_TRUE(ws2.is_valid());
  22236. }
  22237. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  22238. Server svr;
  22239. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22240. std::string msg;
  22241. while (ws.read(msg)) {}
  22242. });
  22243. auto port = svr.bind_to_any_port(HOST);
  22244. std::thread t([&]() { svr.listen_after_bind(); });
  22245. svr.wait_until_ready();
  22246. auto another_host = "example.com";
  22247. auto wrong_ip = "192.0.2.1";
  22248. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22249. client.set_hostname_addr_map({{another_host, wrong_ip}});
  22250. ASSERT_TRUE(client.connect());
  22251. EXPECT_TRUE(client.is_open());
  22252. client.close();
  22253. svr.stop();
  22254. t.join();
  22255. }
  22256. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  22257. Server svr;
  22258. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22259. std::string msg;
  22260. while (ws.read(msg)) {}
  22261. });
  22262. auto port = svr.bind_to_any_port(HOST);
  22263. std::thread t([&]() { svr.listen_after_bind(); });
  22264. svr.wait_until_ready();
  22265. auto wrong_ip = "192.0.2.1";
  22266. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22267. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  22268. client.set_connection_timeout(1);
  22269. client.set_read_timeout(1);
  22270. client.set_write_timeout(1);
  22271. EXPECT_FALSE(client.connect());
  22272. EXPECT_FALSE(client.is_open());
  22273. svr.stop();
  22274. t.join();
  22275. }
  22276. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  22277. // A mapped value that is not an IP literal must be resolved. HOST resolves
  22278. // from the hosts file, so this test needs no external DNS. "target.invalid"
  22279. // (RFC 6761) is only a map key and the Host header value.
  22280. auto host = "target.invalid";
  22281. Server svr;
  22282. std::string received_host;
  22283. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22284. received_host = req.get_header_value("Host");
  22285. std::string msg;
  22286. while (ws.read(msg)) {}
  22287. });
  22288. auto port = svr.bind_to_any_port(HOST);
  22289. std::thread t([&]() { svr.listen_after_bind(); });
  22290. // ASSERT_* below returns from the test body, which would leave t joinable
  22291. // and make ~thread call std::terminate.
  22292. auto se = detail::scope_exit([&] {
  22293. svr.stop();
  22294. if (t.joinable()) { t.join(); }
  22295. });
  22296. svr.wait_until_ready();
  22297. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  22298. std::to_string(port) + "/ws");
  22299. client.set_hostname_addr_map({{host, HOST}});
  22300. ASSERT_TRUE(client.connect());
  22301. EXPECT_TRUE(client.is_open());
  22302. client.close();
  22303. svr.stop();
  22304. t.join();
  22305. // The mapping only redirects the connection; the identity stays host_.
  22306. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  22307. }
  22308. class WebSocketIntegrationTest : public ::testing::Test {
  22309. protected:
  22310. void SetUp() override {
  22311. server_ = httplib::detail::make_unique<Server>();
  22312. setup_server();
  22313. start_server();
  22314. }
  22315. void TearDown() override {
  22316. server_->stop();
  22317. if (server_thread_.joinable()) { server_thread_.join(); }
  22318. }
  22319. void setup_server() {
  22320. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22321. std::string msg;
  22322. ws::ReadResult ret;
  22323. while ((ret = ws.read(msg))) {
  22324. if (ret == ws::Binary) {
  22325. ws.send(msg.data(), msg.size());
  22326. } else {
  22327. ws.send(msg);
  22328. }
  22329. }
  22330. });
  22331. server_->WebSocket("/ws-echo-string",
  22332. [](const Request &, ws::WebSocket &ws) {
  22333. std::string msg;
  22334. while (ws.read(msg)) {
  22335. ws.send("echo: " + msg);
  22336. }
  22337. });
  22338. server_->WebSocket(
  22339. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  22340. // Echo back request metadata
  22341. ws.send("path:" + req.path);
  22342. ws.send("header:" + req.get_header_value("X-Test-Header"));
  22343. std::string msg;
  22344. while (ws.read(msg)) {}
  22345. });
  22346. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  22347. std::string msg;
  22348. ws.read(msg); // wait for a message
  22349. ws.close();
  22350. });
  22351. server_->WebSocket("/ws-close-status",
  22352. [](const Request &, ws::WebSocket &ws) {
  22353. std::string msg;
  22354. ws.read(msg); // wait for a message
  22355. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  22356. });
  22357. server_->WebSocket(
  22358. "/ws-subprotocol",
  22359. [](const Request &, ws::WebSocket &ws) {
  22360. std::string msg;
  22361. while (ws.read(msg)) {
  22362. ws.send(msg);
  22363. }
  22364. },
  22365. [](const std::vector<std::string> &protocols) -> std::string {
  22366. for (const auto &p : protocols) {
  22367. if (p == "graphql-ws") { return p; }
  22368. }
  22369. return "";
  22370. });
  22371. server_->WebSocket(
  22372. "/ws-subprotocol-unoffered",
  22373. [](const Request &, ws::WebSocket &ws) {
  22374. std::string msg;
  22375. while (ws.read(msg)) {
  22376. ws.send(msg);
  22377. }
  22378. },
  22379. [](const std::vector<std::string> &) -> std::string {
  22380. return "admin";
  22381. });
  22382. }
  22383. void start_server() {
  22384. port_ = server_->bind_to_any_port(HOST);
  22385. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22386. server_->wait_until_ready();
  22387. }
  22388. std::unique_ptr<Server> server_;
  22389. std::thread server_thread_;
  22390. int port_ = 0;
  22391. };
  22392. TEST_F(WebSocketIntegrationTest, TextEcho) {
  22393. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22394. "/ws-echo");
  22395. ASSERT_TRUE(client.connect());
  22396. ASSERT_TRUE(client.is_open());
  22397. ASSERT_TRUE(client.send("Hello WebSocket"));
  22398. std::string msg;
  22399. EXPECT_EQ(ws::Text, client.read(msg));
  22400. EXPECT_EQ("Hello WebSocket", msg);
  22401. client.close();
  22402. }
  22403. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  22404. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22405. "/ws-echo");
  22406. ASSERT_TRUE(client.connect());
  22407. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  22408. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  22409. std::string msg;
  22410. EXPECT_EQ(ws::Binary, client.read(msg));
  22411. EXPECT_EQ(binary_data, msg);
  22412. client.close();
  22413. }
  22414. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  22415. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22416. "/ws-echo");
  22417. ASSERT_TRUE(client.connect());
  22418. for (int i = 0; i < 10; i++) {
  22419. auto text = "message " + std::to_string(i);
  22420. ASSERT_TRUE(client.send(text));
  22421. std::string msg;
  22422. ASSERT_TRUE(client.read(msg));
  22423. EXPECT_EQ(text, msg);
  22424. }
  22425. client.close();
  22426. }
  22427. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  22428. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22429. "/ws-close");
  22430. ASSERT_TRUE(client.connect());
  22431. // Send a message to trigger the server to close
  22432. ASSERT_TRUE(client.send("trigger close"));
  22433. // The server will close, so read should return false
  22434. std::string msg;
  22435. EXPECT_FALSE(client.read(msg));
  22436. EXPECT_FALSE(client.is_open());
  22437. }
  22438. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  22439. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22440. "/ws-echo");
  22441. ASSERT_TRUE(client.connect());
  22442. // 128KB message
  22443. std::string large_data(128 * 1024, 'X');
  22444. ASSERT_TRUE(client.send(large_data));
  22445. std::string msg;
  22446. ASSERT_TRUE(client.read(msg));
  22447. EXPECT_EQ(large_data, msg);
  22448. client.close();
  22449. }
  22450. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  22451. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22452. "/ws-echo");
  22453. ASSERT_TRUE(client.connect());
  22454. const int num_threads = 4;
  22455. std::vector<std::thread> threads;
  22456. std::atomic<int> send_count{0};
  22457. for (int t = 0; t < num_threads; t++) {
  22458. threads.emplace_back([&client, &send_count, t]() {
  22459. for (int i = 0; i < 5; i++) {
  22460. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  22461. if (client.send(text)) { send_count++; }
  22462. }
  22463. });
  22464. }
  22465. for (auto &th : threads) {
  22466. th.join();
  22467. }
  22468. int received = 0;
  22469. std::string msg;
  22470. while (received < send_count.load()) {
  22471. if (!client.read(msg)) { break; }
  22472. received++;
  22473. }
  22474. EXPECT_EQ(send_count.load(), received);
  22475. client.close();
  22476. }
  22477. TEST_F(WebSocketIntegrationTest, ReadString) {
  22478. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22479. "/ws-echo-string");
  22480. ASSERT_TRUE(client.connect());
  22481. ASSERT_TRUE(client.send("hello"));
  22482. std::string msg;
  22483. ASSERT_TRUE(client.read(msg));
  22484. EXPECT_EQ("echo: hello", msg);
  22485. ASSERT_TRUE(client.send("world"));
  22486. ASSERT_TRUE(client.read(msg));
  22487. EXPECT_EQ("echo: world", msg);
  22488. client.close();
  22489. }
  22490. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  22491. Headers headers = {{"X-Test-Header", "test-value"}};
  22492. ws::WebSocketClient client(
  22493. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  22494. ASSERT_TRUE(client.connect());
  22495. std::string msg;
  22496. ASSERT_TRUE(client.read(msg));
  22497. EXPECT_EQ("path:/ws-request-info", msg);
  22498. ASSERT_TRUE(client.read(msg));
  22499. EXPECT_EQ("header:test-value", msg);
  22500. client.close();
  22501. }
  22502. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  22503. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22504. "/ws-echo");
  22505. client.set_read_timeout(1, 0); // 1 second
  22506. ASSERT_TRUE(client.connect());
  22507. // Don't send anything — server echo handler waits for a message, so read()
  22508. // should time out. The connection survives it: nothing was consumed.
  22509. std::string msg;
  22510. EXPECT_EQ(client.read(msg), ws::Timeout);
  22511. EXPECT_TRUE(client.is_open());
  22512. // And it is still usable afterwards.
  22513. EXPECT_TRUE(client.send("after timeout"));
  22514. EXPECT_EQ(client.read(msg), ws::Text);
  22515. EXPECT_EQ(msg, "after timeout");
  22516. }
  22517. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  22518. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22519. "/ws-echo");
  22520. client.set_read_timeout(1, 0);
  22521. ASSERT_TRUE(client.connect());
  22522. ASSERT_TRUE(client.send("first"));
  22523. std::string msg;
  22524. ASSERT_EQ(client.read(msg), ws::Text);
  22525. ASSERT_EQ(msg, "first");
  22526. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  22527. // not be used with a read timeout: it would reprocess the previous message.
  22528. EXPECT_EQ(client.read(msg), ws::Timeout);
  22529. EXPECT_EQ(msg, "first");
  22530. }
  22531. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  22532. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22533. "/ws-echo");
  22534. ASSERT_TRUE(client.connect());
  22535. // Setting it once the connection is open reaches the live stream, not just
  22536. // the seed for the next connect().
  22537. client.set_read_timeout(1, 0);
  22538. std::string msg;
  22539. EXPECT_EQ(client.read(msg), ws::Timeout);
  22540. EXPECT_TRUE(client.is_open());
  22541. }
  22542. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  22543. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22544. "/ws-echo");
  22545. client.set_read_timeout(5, 0);
  22546. ASSERT_TRUE(client.connect());
  22547. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  22548. // The server should reject it and close the connection.
  22549. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  22550. client.send(oversized);
  22551. // The server's read() should have failed due to payload limit,
  22552. // so our read() should return false (connection closed).
  22553. std::string msg;
  22554. EXPECT_FALSE(client.read(msg));
  22555. }
  22556. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  22557. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22558. "/ws-echo");
  22559. client.set_read_timeout(10, 0);
  22560. ASSERT_TRUE(client.connect());
  22561. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  22562. // This should succeed.
  22563. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  22564. ASSERT_TRUE(client.send(at_limit));
  22565. std::string msg;
  22566. ASSERT_TRUE(client.read(msg));
  22567. EXPECT_EQ(at_limit.size(), msg.size());
  22568. client.close();
  22569. }
  22570. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  22571. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22572. "/nonexistent");
  22573. auto res = client.connect();
  22574. EXPECT_FALSE(res);
  22575. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22576. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  22577. EXPECT_FALSE(client.is_open());
  22578. }
  22579. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  22580. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22581. "/ws-echo");
  22582. ASSERT_TRUE(client.connect());
  22583. ASSERT_TRUE(client.send(""));
  22584. std::string msg;
  22585. EXPECT_EQ(ws::Text, client.read(msg));
  22586. EXPECT_EQ("", msg);
  22587. client.close();
  22588. }
  22589. TEST_F(WebSocketIntegrationTest, Reconnect) {
  22590. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22591. "/ws-echo");
  22592. // First connection
  22593. ASSERT_TRUE(client.connect());
  22594. ASSERT_TRUE(client.send("first"));
  22595. std::string msg;
  22596. ASSERT_TRUE(client.read(msg));
  22597. EXPECT_EQ("first", msg);
  22598. client.close();
  22599. EXPECT_FALSE(client.is_open());
  22600. // Reconnect using the same client object
  22601. ASSERT_TRUE(client.connect());
  22602. ASSERT_TRUE(client.is_open());
  22603. ASSERT_TRUE(client.send("second"));
  22604. ASSERT_TRUE(client.read(msg));
  22605. EXPECT_EQ("second", msg);
  22606. client.close();
  22607. }
  22608. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  22609. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22610. "/ws-close-status");
  22611. ASSERT_TRUE(client.connect());
  22612. // Trigger the server to close with GoingAway status
  22613. ASSERT_TRUE(client.send("trigger"));
  22614. // read() should return false after receiving the close frame
  22615. std::string msg;
  22616. EXPECT_FALSE(client.read(msg));
  22617. EXPECT_FALSE(client.is_open());
  22618. }
  22619. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  22620. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22621. "/ws-echo");
  22622. ASSERT_TRUE(client.connect());
  22623. client.close(ws::CloseStatus::GoingAway, "client leaving");
  22624. EXPECT_FALSE(client.is_open());
  22625. }
  22626. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  22627. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  22628. ws::WebSocketClient client(
  22629. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22630. ASSERT_TRUE(client.connect());
  22631. // Server should have selected graphql-ws
  22632. EXPECT_EQ("graphql-ws", client.subprotocol());
  22633. client.close();
  22634. }
  22635. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  22636. Headers headers;
  22637. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  22638. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  22639. ws::WebSocketClient client(
  22640. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22641. ASSERT_TRUE(client.connect());
  22642. // The offer on the second field line counts too, so graphql-ws is selected
  22643. EXPECT_EQ("graphql-ws", client.subprotocol());
  22644. client.close();
  22645. }
  22646. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  22647. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  22648. ws::WebSocketClient client(
  22649. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  22650. ASSERT_TRUE(client.connect());
  22651. // Server should not have selected any subprotocol
  22652. EXPECT_TRUE(client.subprotocol().empty());
  22653. client.close();
  22654. }
  22655. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  22656. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22657. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22658. "/ws-subprotocol-unoffered",
  22659. headers);
  22660. ASSERT_TRUE(client.connect());
  22661. EXPECT_TRUE(client.subprotocol().empty());
  22662. client.close();
  22663. }
  22664. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  22665. // Connect without requesting any subprotocol
  22666. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22667. "/ws-subprotocol");
  22668. ASSERT_TRUE(client.connect());
  22669. EXPECT_TRUE(client.subprotocol().empty());
  22670. client.close();
  22671. }
  22672. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  22673. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22674. "/ws-echo");
  22675. client.set_tcp_nodelay(true);
  22676. client.set_connection_timeout(3, 0);
  22677. bool socket_options_called = false;
  22678. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  22679. ASSERT_TRUE(client.connect());
  22680. ASSERT_TRUE(client.is_open());
  22681. EXPECT_TRUE(socket_options_called);
  22682. ASSERT_TRUE(client.send("hello"));
  22683. std::string msg;
  22684. auto result = client.read(msg);
  22685. EXPECT_EQ(result, ws::ReadResult::Text);
  22686. EXPECT_EQ(msg, "hello");
  22687. client.close();
  22688. }
  22689. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  22690. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  22691. "/ws-echo");
  22692. client.set_connection_timeout(std::chrono::seconds(3));
  22693. client.set_write_timeout(std::chrono::seconds(3));
  22694. // A sub-second remainder exercises the seconds/microseconds split.
  22695. client.set_read_timeout(std::chrono::milliseconds(1500));
  22696. ASSERT_TRUE(client.connect());
  22697. auto start = std::chrono::steady_clock::now();
  22698. std::string msg;
  22699. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  22700. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  22701. std::chrono::steady_clock::now() - start)
  22702. .count();
  22703. // Above 1s so that dropping the microseconds half of the split fails here.
  22704. // Ignoring the setter altogether would not reach this line at all: a client
  22705. // waits forever by default.
  22706. EXPECT_GE(elapsed, 1400);
  22707. EXPECT_LT(elapsed, 30000);
  22708. }
  22709. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  22710. Server svr;
  22711. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  22712. if (!req.has_header("Authorization")) {
  22713. res.status = StatusCode::Unauthorized_401;
  22714. res.set_content("Unauthorized", "text/plain");
  22715. return Server::HandlerResponse::Handled;
  22716. }
  22717. return Server::HandlerResponse::Unhandled;
  22718. });
  22719. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22720. std::string msg;
  22721. while (ws.read(msg)) {
  22722. ws.send(msg);
  22723. }
  22724. });
  22725. auto port = svr.bind_to_any_port("localhost");
  22726. std::thread t([&]() { svr.listen_after_bind(); });
  22727. svr.wait_until_ready();
  22728. // Without Authorization header - should be rejected before upgrade
  22729. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  22730. EXPECT_FALSE(client1.connect());
  22731. // The rejection is framed like any other HTTP response
  22732. {
  22733. Client cli("localhost", port);
  22734. Headers headers = {{"Upgrade", "websocket"},
  22735. {"Connection", "Upgrade"},
  22736. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22737. {"Sec-WebSocket-Version", "13"}};
  22738. auto res = cli.Get("/ws", headers);
  22739. ASSERT_TRUE(res);
  22740. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  22741. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  22742. EXPECT_EQ("Unauthorized", res->body);
  22743. }
  22744. // With Authorization header - should succeed
  22745. Headers headers = {{"Authorization", "Bearer token123"}};
  22746. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  22747. headers);
  22748. ASSERT_TRUE(client2.connect());
  22749. ASSERT_TRUE(client2.send("hello"));
  22750. std::string msg;
  22751. ASSERT_TRUE(client2.read(msg));
  22752. EXPECT_EQ("hello", msg);
  22753. client2.close();
  22754. svr.stop();
  22755. t.join();
  22756. }
  22757. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  22758. Server svr;
  22759. std::atomic<int> pre_request_calls{0};
  22760. std::atomic<bool> route_matched{false};
  22761. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  22762. pre_request_calls++;
  22763. if (req.matched_route == "/ws/:id") { route_matched = true; }
  22764. if (req.get_header_value("Authorization") != "Bearer token123") {
  22765. res.status = StatusCode::Unauthorized_401;
  22766. res.set_content("Unauthorized", "text/plain");
  22767. return Server::HandlerResponse::Handled;
  22768. }
  22769. return Server::HandlerResponse::Unhandled;
  22770. });
  22771. std::atomic<bool> handler_called{false};
  22772. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  22773. handler_called = true;
  22774. ws.send(req.matched_route + " " + req.path_params.at("id"));
  22775. });
  22776. auto port = svr.bind_to_any_port("localhost");
  22777. std::thread t([&]() { svr.listen_after_bind(); });
  22778. svr.wait_until_ready();
  22779. // Without Authorization header - should be rejected before upgrade
  22780. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  22781. "/ws/1");
  22782. EXPECT_FALSE(client1.connect());
  22783. EXPECT_FALSE(handler_called);
  22784. EXPECT_EQ(1, pre_request_calls);
  22785. EXPECT_TRUE(route_matched);
  22786. // The rejection is an ordinary HTTP response, not a protocol switch
  22787. {
  22788. Client cli("localhost", port);
  22789. Headers headers = {{"Upgrade", "websocket"},
  22790. {"Connection", "Upgrade"},
  22791. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22792. {"Sec-WebSocket-Version", "13"}};
  22793. auto res = cli.Get("/ws/1", headers);
  22794. ASSERT_TRUE(res);
  22795. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  22796. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  22797. EXPECT_EQ("Unauthorized", res->body);
  22798. }
  22799. EXPECT_FALSE(handler_called);
  22800. // With Authorization header - should succeed
  22801. Headers headers = {{"Authorization", "Bearer token123"}};
  22802. ws::WebSocketClient client2(
  22803. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  22804. ASSERT_TRUE(client2.connect());
  22805. std::string msg;
  22806. ASSERT_TRUE(client2.read(msg));
  22807. EXPECT_EQ("/ws/:id 2", msg);
  22808. EXPECT_TRUE(handler_called);
  22809. client2.close();
  22810. svr.stop();
  22811. t.join();
  22812. }
  22813. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  22814. Server svr;
  22815. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22816. // A read timeout is how a handler gets control back. Without it, a handler
  22817. // parked in read() can never write on the connection it is reading.
  22818. ws.set_read_timeout(std::chrono::milliseconds(100));
  22819. std::string msg;
  22820. while (ws.is_open()) {
  22821. auto r = ws.read(msg);
  22822. if (r == httplib::ws::Timeout) {
  22823. ws.send("tick");
  22824. continue;
  22825. }
  22826. if (r == httplib::ws::Fail) { break; }
  22827. ws.send(msg);
  22828. }
  22829. });
  22830. auto port = svr.bind_to_any_port("localhost");
  22831. std::thread t([&]() { svr.listen_after_bind(); });
  22832. svr.wait_until_ready();
  22833. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22834. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  22835. ASSERT_TRUE(client.connect());
  22836. // The client sends nothing, so anything it receives came out of the
  22837. // handler's timeout path.
  22838. std::string msg;
  22839. ASSERT_EQ(client.read(msg), ws::Text);
  22840. EXPECT_EQ("tick", msg);
  22841. client.close();
  22842. svr.stop();
  22843. t.join();
  22844. }
  22845. // Stream::read may return fewer bytes than asked for. This is that contract at
  22846. // its worst -- one byte per call -- which is what a frame header straddling a
  22847. // read buffer's boundary looks like to the frame parser.
  22848. class WsByteAtATimeStream : public Stream {
  22849. public:
  22850. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  22851. bool is_readable() const override { return true; }
  22852. bool wait_readable() const override { return true; }
  22853. bool wait_writable() const override { return true; }
  22854. ssize_t read(char *ptr, size_t size) override {
  22855. if (size == 0 || pos_ >= data_.size()) { return 0; }
  22856. *ptr = data_[pos_++];
  22857. return 1;
  22858. }
  22859. ssize_t write(const char *, size_t size) override {
  22860. return static_cast<ssize_t>(size);
  22861. }
  22862. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  22863. ip = "127.0.0.1";
  22864. port = 0;
  22865. }
  22866. void get_local_ip_and_port(std::string &ip, int &port) const override {
  22867. ip = "127.0.0.1";
  22868. port = 0;
  22869. }
  22870. socket_t socket() const override { return INVALID_SOCKET; }
  22871. time_t duration() const override { return 0; }
  22872. private:
  22873. std::string data_;
  22874. size_t pos_ = 0;
  22875. };
  22876. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  22877. // The payload uses the 16-bit extended length, so the header, the length
  22878. // and the mask key are all multi-byte fields here. Each used to be read
  22879. // with a single read() call, which fails as soon as one is split. The
  22880. // payload is also a little over one read chunk, so it is read in two.
  22881. std::string body;
  22882. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  22883. body += static_cast<char>(i % 251);
  22884. }
  22885. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  22886. std::string frame;
  22887. frame += static_cast<char>(0x81); // FIN + Text
  22888. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  22889. frame += static_cast<char>(body.size() >> 8);
  22890. frame += static_cast<char>(body.size() & 0xff);
  22891. for (size_t i = 0; i < 4; i++) {
  22892. frame += static_cast<char>(mask[i]);
  22893. }
  22894. for (size_t i = 0; i < body.size(); i++) {
  22895. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  22896. }
  22897. WsByteAtATimeStream strm(frame);
  22898. ws::Opcode opcode;
  22899. std::string payload;
  22900. bool fin = false;
  22901. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  22902. /*expect_masked=*/true, body.size()),
  22903. ws::impl::FrameRead::Ok);
  22904. EXPECT_TRUE(fin);
  22905. EXPECT_EQ(opcode, ws::Opcode::Text);
  22906. EXPECT_EQ(payload, body);
  22907. }
  22908. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  22909. std::string body(2000, 'x');
  22910. std::string frame;
  22911. frame += static_cast<char>(0x82); // FIN + Binary
  22912. frame += static_cast<char>(126); // 16-bit length follows
  22913. frame += static_cast<char>(body.size() >> 8);
  22914. frame += static_cast<char>(body.size() & 0xff);
  22915. frame += body;
  22916. detail::BufferStream strm;
  22917. strm.write(frame.data(), frame.size());
  22918. ws::Opcode opcode;
  22919. std::string payload;
  22920. bool fin;
  22921. EXPECT_EQ(
  22922. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  22923. ws::impl::FrameRead::Ok);
  22924. EXPECT_EQ(body, payload);
  22925. }
  22926. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  22927. // The header announces the largest payload allowed, and only 3 bytes of it
  22928. // ever arrive.
  22929. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  22930. std::string frame;
  22931. frame += static_cast<char>(0x82); // FIN + Binary
  22932. frame += static_cast<char>(127); // 64-bit length follows
  22933. for (int shift = 56; shift >= 0; shift -= 8) {
  22934. frame += static_cast<char>((len >> shift) & 0xff);
  22935. }
  22936. frame += "abc";
  22937. detail::BufferStream strm;
  22938. strm.write(frame.data(), frame.size());
  22939. ws::Opcode opcode;
  22940. std::string payload;
  22941. bool fin;
  22942. EXPECT_EQ(
  22943. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  22944. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  22945. ws::impl::FrameRead::Fail);
  22946. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  22947. }
  22948. TEST(WebSocketTest, QueryStringInHandshake) {
  22949. Server svr;
  22950. std::mutex mtx;
  22951. std::string received_target;
  22952. std::string received_token;
  22953. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22954. {
  22955. std::lock_guard<std::mutex> lock(mtx);
  22956. received_target = req.target;
  22957. if (req.has_param("token")) {
  22958. received_token = req.get_param_value("token");
  22959. }
  22960. }
  22961. std::string msg;
  22962. while (ws.read(msg)) {
  22963. ws.send(msg);
  22964. }
  22965. });
  22966. auto port = svr.bind_to_any_port("localhost");
  22967. std::thread t([&]() { svr.listen_after_bind(); });
  22968. svr.wait_until_ready();
  22969. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  22970. "/ws?token=ABC&session=123");
  22971. ASSERT_TRUE(client.connect());
  22972. // Round-trip ensures the handler has run and captured the request.
  22973. ASSERT_TRUE(client.send("hello"));
  22974. std::string msg;
  22975. ASSERT_TRUE(client.read(msg));
  22976. EXPECT_EQ("hello", msg);
  22977. client.close();
  22978. {
  22979. std::lock_guard<std::mutex> lock(mtx);
  22980. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  22981. EXPECT_EQ("ABC", received_token);
  22982. }
  22983. svr.stop();
  22984. t.join();
  22985. }
  22986. // Run a handshake against a throwaway server and hand the request the server
  22987. // received back to the caller, so tests can assert on the headers the client
  22988. // actually put on the wire.
  22989. static void capture_websocket_handshake_request(
  22990. const Headers &client_headers,
  22991. std::function<void(const Request &, int port)> verify) {
  22992. Server svr;
  22993. std::mutex mtx;
  22994. Request received;
  22995. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22996. {
  22997. std::lock_guard<std::mutex> lock(mtx);
  22998. received = req;
  22999. }
  23000. std::string msg;
  23001. while (ws.read(msg)) {
  23002. ws.send(msg);
  23003. }
  23004. });
  23005. auto port = svr.bind_to_any_port("localhost");
  23006. std::thread t([&]() { svr.listen_after_bind(); });
  23007. auto se = detail::scope_exit([&] {
  23008. svr.stop();
  23009. t.join();
  23010. });
  23011. svr.wait_until_ready();
  23012. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  23013. client_headers);
  23014. ASSERT_TRUE(client.connect());
  23015. ASSERT_TRUE(client.send("hello"));
  23016. std::string msg;
  23017. ASSERT_TRUE(client.read(msg));
  23018. client.close();
  23019. {
  23020. std::lock_guard<std::mutex> lock(mtx);
  23021. verify(received, port);
  23022. }
  23023. }
  23024. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  23025. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  23026. // Non-default port must be present in the Host header. Default ports
  23027. // (80/443) are omitted; that logic is covered by
  23028. // MakeHostAndPortStringTest.
  23029. EXPECT_EQ("localhost:" + std::to_string(port),
  23030. req.get_header_value("Host"));
  23031. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  23032. req.get_header_value("User-Agent"));
  23033. EXPECT_FALSE(req.has_header("Accept"));
  23034. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  23035. EXPECT_FALSE(req.has_header("Content-Length"));
  23036. });
  23037. }
  23038. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  23039. capture_websocket_handshake_request(
  23040. {{"Host", "example.com"},
  23041. {"User-Agent", "custom-agent"},
  23042. {"X-Custom", "value"}},
  23043. [](const Request &req, int) {
  23044. EXPECT_EQ("example.com", req.get_header_value("Host"));
  23045. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  23046. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  23047. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  23048. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  23049. });
  23050. }
  23051. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  23052. capture_websocket_handshake_request(
  23053. {{"Upgrade", "bogus"},
  23054. {"Connection", "close"},
  23055. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  23056. {"Sec-WebSocket-Version", "8"}},
  23057. [](const Request &req, int) {
  23058. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  23059. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  23060. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  23061. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  23062. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  23063. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  23064. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  23065. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  23066. req.get_header_value("Sec-WebSocket-Key"));
  23067. });
  23068. }
  23069. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  23070. // A header the client refuses to send must abort the handshake before any
  23071. // part of it reaches the wire; a lone request line would otherwise sit in
  23072. // the peer's buffer as a truncated request.
  23073. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  23074. ASSERT_NE(INVALID_SOCKET, srv);
  23075. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  23076. sockaddr_in addr{};
  23077. addr.sin_family = AF_INET;
  23078. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  23079. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23080. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  23081. ASSERT_EQ(0, ::listen(srv, 1));
  23082. sockaddr_in bound{};
  23083. socklen_t bound_len = sizeof(bound);
  23084. ASSERT_EQ(
  23085. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  23086. auto port = ntohs(bound.sin_port);
  23087. ssize_t received = -1;
  23088. std::thread t([&] {
  23089. // Bound every blocking call so a regression fails the test with a bad
  23090. // value instead of hanging the suite.
  23091. fd_set rfds;
  23092. FD_ZERO(&rfds);
  23093. FD_SET(srv, &rfds);
  23094. timeval tv{5, 0};
  23095. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  23096. 0) {
  23097. return;
  23098. }
  23099. sockaddr_in cli_addr{};
  23100. socklen_t cli_len = sizeof(cli_addr);
  23101. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  23102. if (cli == INVALID_SOCKET) { return; }
  23103. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  23104. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23105. char buf[4096];
  23106. received = ::recv(cli, buf, sizeof(buf), 0);
  23107. });
  23108. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  23109. // connect() has already shut the socket down by the time it returns false,
  23110. // so the peer sees EOF without waiting for the client to be destroyed.
  23111. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  23112. {{"X-Bad", "a\r\nInjected: 1"}});
  23113. EXPECT_FALSE(client.connect());
  23114. t.join();
  23115. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  23116. EXPECT_EQ(0, received);
  23117. }
  23118. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  23119. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  23120. // contains "upgrade" as a substring is a different token and must not
  23121. // start a WebSocket handshake.
  23122. auto make_request = [](const std::vector<std::string> &connection_values) {
  23123. Request req;
  23124. req.method = "GET";
  23125. req.headers.emplace("Upgrade", "websocket");
  23126. for (const auto &value : connection_values) {
  23127. req.headers.emplace("Connection", value);
  23128. }
  23129. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  23130. req.headers.emplace("Sec-WebSocket-Version", "13");
  23131. return req;
  23132. };
  23133. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  23134. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  23135. EXPECT_TRUE(
  23136. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  23137. EXPECT_TRUE(
  23138. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  23139. EXPECT_TRUE(
  23140. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  23141. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  23142. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  23143. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  23144. EXPECT_FALSE(
  23145. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  23146. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  23147. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  23148. }
  23149. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  23150. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  23151. // asks recipients to match each protocol-name case-insensitively, and RFC
  23152. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  23153. // client naming websocket alongside another protocol, or on a second field
  23154. // line, is offering websocket; a value that merely contains "websocket" as a
  23155. // substring is a different protocol name and is not.
  23156. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  23157. Request req;
  23158. req.method = "GET";
  23159. for (const auto &value : upgrade_values) {
  23160. req.headers.emplace("Upgrade", value);
  23161. }
  23162. req.headers.emplace("Connection", "Upgrade");
  23163. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  23164. req.headers.emplace("Sec-WebSocket-Version", "13");
  23165. return req;
  23166. };
  23167. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  23168. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  23169. EXPECT_TRUE(
  23170. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  23171. EXPECT_TRUE(
  23172. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  23173. EXPECT_TRUE(
  23174. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  23175. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  23176. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  23177. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  23178. EXPECT_FALSE(
  23179. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  23180. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  23181. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  23182. }
  23183. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  23184. Server svr;
  23185. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  23186. auto port = svr.bind_to_any_port("localhost");
  23187. std::thread t([&]() { svr.listen_after_bind(); });
  23188. auto se = detail::scope_exit([&] {
  23189. svr.stop();
  23190. t.join();
  23191. });
  23192. svr.wait_until_ready();
  23193. Headers headers = {{"Upgrade", "websocket"},
  23194. {"Connection", "notupgrade"},
  23195. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23196. {"Sec-WebSocket-Version", "13"}};
  23197. Client cli("localhost", port);
  23198. auto res = cli.Get("/ws", headers);
  23199. // The route exists only as a WebSocket route, so a request that fails the
  23200. // handshake check falls through to ordinary routing.
  23201. ASSERT_TRUE(res);
  23202. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  23203. }
  23204. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  23205. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  23206. // Connection value is the only thing left for the client to reject.
  23207. Server svr;
  23208. svr.Get("/ws", [](const Request &req, Response &res) {
  23209. res.status = StatusCode::SwitchingProtocol_101;
  23210. res.set_header("Upgrade", "websocket");
  23211. res.set_header("Connection", "notupgrade");
  23212. res.set_header("Sec-WebSocket-Accept",
  23213. detail::websocket_accept_key(
  23214. req.get_header_value("Sec-WebSocket-Key")));
  23215. });
  23216. auto port = svr.bind_to_any_port("localhost");
  23217. std::thread t([&]() { svr.listen_after_bind(); });
  23218. auto se = detail::scope_exit([&] {
  23219. svr.stop();
  23220. t.join();
  23221. });
  23222. svr.wait_until_ready();
  23223. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23224. auto res = client.connect();
  23225. EXPECT_FALSE(res);
  23226. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23227. EXPECT_FALSE(client.is_open());
  23228. }
  23229. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  23230. Server svr;
  23231. svr.Get("/ws", [](const Request &req, Response &res) {
  23232. res.status = StatusCode::SwitchingProtocol_101;
  23233. res.set_header("Upgrade", "websocket");
  23234. res.set_header("Connection", "Upgrade");
  23235. res.set_header("Sec-WebSocket-Accept",
  23236. detail::websocket_accept_key(
  23237. req.get_header_value("Sec-WebSocket-Key")));
  23238. res.set_header("Sec-WebSocket-Protocol", "admin");
  23239. });
  23240. auto port = svr.bind_to_any_port("localhost");
  23241. std::thread t([&]() { svr.listen_after_bind(); });
  23242. auto se = detail::scope_exit([&] {
  23243. svr.stop();
  23244. t.join();
  23245. });
  23246. svr.wait_until_ready();
  23247. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  23248. // Server selects a subprotocol the client never offered
  23249. {
  23250. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  23251. ws::WebSocketClient client(url, headers);
  23252. auto res = client.connect();
  23253. EXPECT_FALSE(res);
  23254. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23255. EXPECT_FALSE(client.is_open());
  23256. EXPECT_TRUE(client.subprotocol().empty());
  23257. }
  23258. // Client offered none but the server named one anyway
  23259. {
  23260. ws::WebSocketClient client(url);
  23261. auto res = client.connect();
  23262. EXPECT_FALSE(res);
  23263. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23264. EXPECT_FALSE(client.is_open());
  23265. EXPECT_TRUE(client.subprotocol().empty());
  23266. }
  23267. }
  23268. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  23269. // The socket path doubles as the URL host, so it must not contain '/'.
  23270. const char *shard = getenv("GTEST_SHARD_INDEX");
  23271. const std::string sock_path =
  23272. shard ? std::string("httplib-ws-") + shard + ".sock"
  23273. : std::string("httplib-ws.sock");
  23274. std::remove(sock_path.c_str());
  23275. Server svr;
  23276. std::mutex mtx;
  23277. std::string received_host;
  23278. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23279. {
  23280. std::lock_guard<std::mutex> lock(mtx);
  23281. received_host = req.get_header_value("Host");
  23282. }
  23283. std::string msg;
  23284. while (ws.read(msg)) {
  23285. ws.send(msg);
  23286. }
  23287. });
  23288. svr.set_address_family(AF_UNIX);
  23289. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  23290. auto se = detail::scope_exit([&] {
  23291. svr.stop();
  23292. t.join();
  23293. std::remove(sock_path.c_str());
  23294. });
  23295. svr.wait_until_ready();
  23296. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  23297. client.set_address_family(AF_UNIX);
  23298. ASSERT_TRUE(client.connect());
  23299. ASSERT_TRUE(client.send("hello"));
  23300. std::string msg;
  23301. ASSERT_TRUE(client.read(msg));
  23302. client.close();
  23303. {
  23304. std::lock_guard<std::mutex> lock(mtx);
  23305. // There is no host:port for a Unix socket, so the same "localhost"
  23306. // placeholder the HTTP client uses is expected.
  23307. EXPECT_EQ("localhost", received_host);
  23308. }
  23309. }
  23310. // Two threads must never parse WebSocket frames from the same stream.
  23311. // close() used to read the peer's Close reply with its own frame read, so it
  23312. // raced a reader thread that was in the middle of a payload: the payload loop
  23313. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  23314. // so bytes taken by close() were replaced with bytes from further along the
  23315. // stream. The message kept its length and silently changed content.
  23316. //
  23317. // The raw peer below sends a frame header plus part of the payload, waits for
  23318. // the handler to call close(), and only then sends the rest. Whichever thread
  23319. // would win the race for those bytes, the message must arrive intact, because
  23320. // close() must not touch the stream while read() owns it.
  23321. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  23322. #ifndef _WIN32
  23323. signal(SIGPIPE, SIG_IGN);
  23324. #endif
  23325. const size_t payload_len = 120; // fits the 7-bit length field
  23326. const size_t prefix_len = 8;
  23327. const int attempts = 8;
  23328. std::string expected(payload_len, '\0');
  23329. for (size_t i = 0; i < payload_len; i++) {
  23330. expected[i] = static_cast<char>('a' + i % 26);
  23331. }
  23332. std::atomic<bool> peer_stalled{false};
  23333. std::atomic<bool> handler_done{false};
  23334. std::mutex received_mutex;
  23335. std::vector<std::string> received;
  23336. // Bound every wait, so a regression fails the test instead of hanging the
  23337. // suite.
  23338. auto wait_for = [](const std::atomic<bool> &flag) {
  23339. for (int i = 0; i < 500 && !flag; i++) {
  23340. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23341. }
  23342. };
  23343. Server svr;
  23344. svr.set_websocket_ping_interval(0);
  23345. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23346. std::thread reader([&]() {
  23347. std::string msg;
  23348. while (ws.read(msg)) {
  23349. std::lock_guard<std::mutex> guard(received_mutex);
  23350. received.push_back(msg);
  23351. }
  23352. });
  23353. // Wait until the peer stalls mid-payload, so the reader thread is parked
  23354. // inside read_websocket_frame() when close() runs.
  23355. wait_for(peer_stalled);
  23356. ws.close();
  23357. reader.join();
  23358. handler_done = true;
  23359. });
  23360. auto port = svr.bind_to_any_port("127.0.0.1");
  23361. std::thread t([&]() { svr.listen_after_bind(); });
  23362. auto se = detail::scope_exit([&] {
  23363. svr.stop();
  23364. t.join();
  23365. });
  23366. svr.wait_until_ready();
  23367. auto send_bytes = [](socket_t s, const std::string &data) {
  23368. #ifdef _WIN32
  23369. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  23370. #else
  23371. auto n = ::send(s, data.data(), data.size(), 0);
  23372. #endif
  23373. return n == static_cast<decltype(n)>(data.size());
  23374. };
  23375. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  23376. // Every length used here fits the 7-bit length field.
  23377. auto masked_header = [](uint8_t first_byte, size_t len) {
  23378. std::string h;
  23379. h += static_cast<char>(first_byte);
  23380. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  23381. h.append(4, '\0'); // mask key
  23382. return h;
  23383. };
  23384. for (int attempt = 0; attempt < attempts; attempt++) {
  23385. peer_stalled = false;
  23386. handler_done = false;
  23387. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  23388. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  23389. auto se_sock = detail::scope_exit([&] {
  23390. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  23391. });
  23392. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23393. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  23394. sockaddr_in addr{};
  23395. addr.sin_family = AF_INET;
  23396. addr.sin_port = htons(static_cast<uint16_t>(port));
  23397. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23398. ASSERT_EQ(
  23399. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  23400. << "attempt " << attempt;
  23401. ASSERT_TRUE(send_bytes(sock,
  23402. "GET /ws HTTP/1.1\r\n"
  23403. "Host: 127.0.0.1\r\n"
  23404. "Upgrade: websocket\r\n"
  23405. "Connection: Upgrade\r\n"
  23406. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  23407. "Sec-WebSocket-Version: 13\r\n"
  23408. "\r\n"))
  23409. << "attempt " << attempt;
  23410. std::string response;
  23411. while (response.find("\r\n\r\n") == std::string::npos) {
  23412. char buf[512];
  23413. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  23414. if (n <= 0) { break; }
  23415. response.append(buf, static_cast<size_t>(n));
  23416. }
  23417. ASSERT_NE(std::string::npos, response.find(" 101 "))
  23418. << "attempt " << attempt;
  23419. // Send the header of a Binary message but only the first prefix_len bytes
  23420. // of its payload, leaving the reader thread stalled inside the payload.
  23421. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  23422. expected.substr(0, prefix_len)))
  23423. << "attempt " << attempt;
  23424. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23425. peer_stalled = true;
  23426. // Let close() send its Close frame and park in its own read before the
  23427. // rest of the payload arrives, so both threads are waiting for it.
  23428. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23429. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  23430. close_frame += static_cast<char>(0x03); // status 1000
  23431. close_frame += static_cast<char>(0xE8);
  23432. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  23433. << "attempt " << attempt;
  23434. // Closing the peer releases the reader thread even on the buggy path,
  23435. // where it waits for bytes another thread already consumed.
  23436. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23437. detail::close_socket(sock);
  23438. sock = INVALID_SOCKET;
  23439. wait_for(handler_done);
  23440. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  23441. }
  23442. std::lock_guard<std::mutex> guard(received_mutex);
  23443. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  23444. << "a message in flight when close() ran was dropped";
  23445. for (size_t i = 0; i < received.size(); i++) {
  23446. EXPECT_EQ(expected, received[i]) << "message " << i;
  23447. }
  23448. }
  23449. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  23450. // returning the socket, or INVALID_SOCKET.
  23451. static socket_t connect_raw_websocket(int port, const std::string &path) {
  23452. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  23453. if (sock == INVALID_SOCKET) { return sock; }
  23454. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  23455. sockaddr_in addr{};
  23456. addr.sin_family = AF_INET;
  23457. addr.sin_port = htons(static_cast<uint16_t>(port));
  23458. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  23459. std::string req = "GET " + path +
  23460. " HTTP/1.1\r\n"
  23461. "Host: 127.0.0.1\r\n"
  23462. "Upgrade: websocket\r\n"
  23463. "Connection: Upgrade\r\n"
  23464. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  23465. "Sec-WebSocket-Version: 13\r\n"
  23466. "\r\n";
  23467. std::string res;
  23468. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  23469. ::send(sock, req.data(), static_cast<int>(req.size()), 0) ==
  23470. static_cast<int>(req.size())) {
  23471. char c;
  23472. while (res.find("\r\n\r\n") == std::string::npos &&
  23473. ::recv(sock, &c, 1, 0) == 1) {
  23474. res += c;
  23475. }
  23476. }
  23477. if (res.find(" 101 ") == std::string::npos) {
  23478. detail::close_socket(sock);
  23479. return INVALID_SOCKET;
  23480. }
  23481. return sock;
  23482. }
  23483. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  23484. // The payload must fit the 7-bit length field.
  23485. static std::string masked_frame(uint8_t first_byte,
  23486. const std::string &payload) {
  23487. std::string f;
  23488. f += static_cast<char>(first_byte);
  23489. f += static_cast<char>(0x80 | payload.size());
  23490. f.append(4, '\0');
  23491. return f + payload;
  23492. }
  23493. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  23494. std::atomic<bool> done{false};
  23495. std::string received;
  23496. Server svr;
  23497. svr.set_websocket_ping_interval(0);
  23498. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23499. std::string msg;
  23500. if (ws.read(msg) == ws::Binary) { received = msg; }
  23501. done = true;
  23502. });
  23503. auto port = svr.bind_to_any_port("127.0.0.1");
  23504. std::thread t([&]() { svr.listen_after_bind(); });
  23505. auto se = detail::scope_exit([&] {
  23506. svr.stop();
  23507. t.join();
  23508. });
  23509. svr.wait_until_ready();
  23510. auto sock = connect_raw_websocket(port, "/ws");
  23511. ASSERT_NE(INVALID_SOCKET, sock);
  23512. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  23513. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  23514. masked_frame(0x89, "p") + // FIN + Ping
  23515. masked_frame(0x80, "lo"); // FIN + Continuation
  23516. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  23517. for (int i = 0; i < 500 && !done; i++) {
  23518. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23519. }
  23520. ASSERT_TRUE(done);
  23521. EXPECT_EQ("Hello", received);
  23522. // The Ping between the fragments is answered with a Pong.
  23523. char pong[3];
  23524. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  23525. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  23526. }
  23527. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  23528. Server svr;
  23529. svr.set_websocket_ping_interval(-1);
  23530. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23531. std::string msg;
  23532. while (ws.read(msg)) {}
  23533. });
  23534. auto port = svr.bind_to_any_port("127.0.0.1");
  23535. std::thread t([&]() { svr.listen_after_bind(); });
  23536. auto se = detail::scope_exit([&] {
  23537. svr.stop();
  23538. t.join();
  23539. });
  23540. svr.wait_until_ready();
  23541. auto sock = connect_raw_websocket(port, "/ws");
  23542. ASSERT_NE(INVALID_SOCKET, sock);
  23543. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  23544. // Nothing comes while the client stays quiet.
  23545. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  23546. char c;
  23547. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  23548. }
  23549. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  23550. Server svr;
  23551. svr.set_websocket_ping_interval(0);
  23552. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23553. std::string msg;
  23554. while (ws.read(msg)) {}
  23555. });
  23556. auto port = svr.bind_to_any_port("127.0.0.1");
  23557. std::thread t([&]() { svr.listen_after_bind(); });
  23558. auto se = detail::scope_exit([&] {
  23559. svr.stop();
  23560. t.join();
  23561. });
  23562. svr.wait_until_ready();
  23563. // Each Close payload and the reply it should get: an echo when valid, 1002
  23564. // otherwise.
  23565. std::vector<std::pair<std::string, std::string>> cases = {
  23566. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  23567. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  23568. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  23569. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  23570. };
  23571. // Also between the fragments of a message.
  23572. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  23573. for (const auto &c : cases) {
  23574. auto sock = connect_raw_websocket(port, "/ws");
  23575. ASSERT_NE(INVALID_SOCKET, sock);
  23576. auto frames = prefix + masked_frame(0x88, c.first);
  23577. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  23578. std::string reply;
  23579. char buf[256];
  23580. while (reply.size() < 2 + c.second.size()) {
  23581. auto n = ::recv(sock, buf, sizeof(buf), 0);
  23582. if (n <= 0) { break; }
  23583. reply.append(buf, static_cast<size_t>(n));
  23584. }
  23585. detail::close_socket(sock);
  23586. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  23587. c.second,
  23588. reply);
  23589. }
  23590. }
  23591. }
  23592. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  23593. class WebSocketSSLIntegrationTest : public ::testing::Test {
  23594. protected:
  23595. void SetUp() override {
  23596. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  23597. SERVER_PRIVATE_KEY_FILE);
  23598. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23599. std::string msg;
  23600. ws::ReadResult ret;
  23601. while ((ret = ws.read(msg))) {
  23602. if (ret == ws::Binary) {
  23603. ws.send(msg.data(), msg.size());
  23604. } else {
  23605. ws.send(msg);
  23606. }
  23607. }
  23608. });
  23609. port_ = server_->bind_to_any_port(HOST);
  23610. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23611. server_->wait_until_ready();
  23612. }
  23613. void TearDown() override {
  23614. server_->stop();
  23615. if (server_thread_.joinable()) { server_thread_.join(); }
  23616. }
  23617. std::unique_ptr<SSLServer> server_;
  23618. std::thread server_thread_;
  23619. int port_ = 0;
  23620. };
  23621. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  23622. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  23623. {
  23624. ws::WebSocketClient client(url);
  23625. client.enable_server_certificate_verification(false);
  23626. auto calls = 0;
  23627. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  23628. calls++;
  23629. return false;
  23630. });
  23631. EXPECT_FALSE(client.connect());
  23632. EXPECT_GT(calls, 0);
  23633. }
  23634. {
  23635. ws::WebSocketClient client(url);
  23636. client.enable_server_certificate_verification(false);
  23637. client.set_session_verifier([](tls::session_t) {
  23638. return SSLVerifierResponse::CertificateRejected;
  23639. });
  23640. EXPECT_FALSE(client.connect());
  23641. }
  23642. {
  23643. ws::WebSocketClient client(url);
  23644. client.enable_server_certificate_verification(false);
  23645. client.set_session_verifier([](tls::session_t) {
  23646. return SSLVerifierResponse::CertificateAccepted;
  23647. });
  23648. EXPECT_TRUE(client.connect());
  23649. }
  23650. }
  23651. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  23652. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23653. "/ws-echo");
  23654. client.enable_server_certificate_verification(false);
  23655. ASSERT_TRUE(client.connect());
  23656. ASSERT_TRUE(client.is_open());
  23657. ASSERT_TRUE(client.send("Hello WSS"));
  23658. std::string msg;
  23659. EXPECT_EQ(ws::Text, client.read(msg));
  23660. EXPECT_EQ("Hello WSS", msg);
  23661. client.close();
  23662. }
  23663. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  23664. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  23665. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  23666. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  23667. // client (without calling close() first) is the only path that runs
  23668. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  23669. // bug exactly.
  23670. //
  23671. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  23672. // when linked against an instrumented libssl; run under Valgrind to catch it
  23673. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  23674. // suite (the freed session otherwise stalls on the close handshake) — this test
  23675. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  23676. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  23677. {
  23678. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23679. "/ws-echo");
  23680. client.enable_server_certificate_verification(false);
  23681. client.set_read_timeout(2, 0);
  23682. client.set_write_timeout(2, 0);
  23683. ASSERT_TRUE(client.connect());
  23684. ASSERT_TRUE(client.is_open());
  23685. ASSERT_TRUE(client.send("still open"));
  23686. // Intentionally do NOT call client.close(): leaving scope runs
  23687. // shutdown_and_close() with the WebSocket still open, which must send the
  23688. // close frame while the TLS session is still alive.
  23689. }
  23690. }
  23691. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  23692. // shutdown_and_close() at the start of connect(), reproducing the same
  23693. // use-after-free within the test body rather than at scope exit. The second
  23694. // connect must succeed and echo, proving the close handshake ran over a live
  23695. // session. See the note above about memory-tool requirements.
  23696. TEST_F(WebSocketSSLIntegrationTest,
  23697. ReconnectWhileOpenSendsCloseOverLiveSession) {
  23698. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  23699. "/ws-echo");
  23700. client.enable_server_certificate_verification(false);
  23701. client.set_read_timeout(2, 0);
  23702. client.set_write_timeout(2, 0);
  23703. ASSERT_TRUE(client.connect());
  23704. ASSERT_TRUE(client.is_open());
  23705. ASSERT_TRUE(client.send("still open"));
  23706. // Reconnect without closing first: connect() calls shutdown_and_close() on
  23707. // the still-open connection, which must not touch a freed TLS session.
  23708. ASSERT_TRUE(client.connect());
  23709. ASSERT_TRUE(client.is_open());
  23710. ASSERT_TRUE(client.send("after reconnect"));
  23711. std::string msg;
  23712. EXPECT_EQ(ws::Text, client.read(msg));
  23713. EXPECT_EQ("after reconnect", msg);
  23714. client.close();
  23715. }
  23716. #endif
  23717. #ifdef CPPHTTPLIB_SSL_ENABLED
  23718. class WebSocketSSLCATest : public ::testing::Test {
  23719. protected:
  23720. void SetUp() override {
  23721. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  23722. SERVER_PRIVATE_KEY_FILE);
  23723. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23724. std::string msg;
  23725. while (ws.read(msg)) {
  23726. ws.send(msg);
  23727. }
  23728. });
  23729. port_ = server_->bind_to_any_port("127.0.0.1");
  23730. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23731. server_->wait_until_ready();
  23732. }
  23733. void TearDown() override {
  23734. server_->stop();
  23735. if (server_thread_.joinable()) { server_thread_.join(); }
  23736. }
  23737. std::string url() const {
  23738. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  23739. }
  23740. std::unique_ptr<SSLServer> server_;
  23741. std::thread server_thread_;
  23742. int port_ = 0;
  23743. };
  23744. // A custom CA loaded as PEM verifies the server with full certificate
  23745. // verification enabled
  23746. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  23747. ws::WebSocketClient client(url());
  23748. std::string cert;
  23749. read_file(SERVER_CERT2_FILE, cert);
  23750. client.load_ca_cert_store(cert.c_str(), cert.size());
  23751. ASSERT_TRUE(client.connect());
  23752. ASSERT_TRUE(client.send("hello"));
  23753. std::string msg;
  23754. EXPECT_EQ(ws::Text, client.read(msg));
  23755. EXPECT_EQ("hello", msg);
  23756. client.close();
  23757. }
  23758. // A custom CA that does not cover the server must fail verification (the
  23759. // custom CA is exclusive; system certs are not loaded alongside it)
  23760. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  23761. ws::WebSocketClient client(url());
  23762. std::string cert;
  23763. read_file(CLIENT_CA_CERT_FILE, cert);
  23764. client.load_ca_cert_store(cert.c_str(), cert.size());
  23765. auto res = client.connect();
  23766. ASSERT_FALSE(res);
  23767. EXPECT_EQ(Error::SSLServerVerification, res.error());
  23768. EXPECT_EQ(-1, res.status());
  23769. EXPECT_NE(0u, res.ssl_backend_error());
  23770. }
  23771. // The same CA as a file path rather than PEM in memory
  23772. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  23773. ws::WebSocketClient client(url());
  23774. client.set_ca_cert_path(SERVER_CERT2_FILE);
  23775. ASSERT_TRUE(client.connect());
  23776. ASSERT_TRUE(client.send("hello"));
  23777. std::string msg;
  23778. EXPECT_EQ(ws::Text, client.read(msg));
  23779. EXPECT_EQ("hello", msg);
  23780. client.close();
  23781. }
  23782. // ...and a CA file that does not cover the server still fails, so it is the
  23783. // path above that decides the outcome
  23784. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  23785. ws::WebSocketClient client(url());
  23786. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  23787. ASSERT_FALSE(client.connect());
  23788. }
  23789. // Regression test: reconnecting with a native custom CA store used to reuse
  23790. // a store handle the previous TLS context had already freed (use-after-free
  23791. // under the OpenSSL backend). The context now lives as long as the client.
  23792. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  23793. ws::WebSocketClient client(url());
  23794. std::string cert;
  23795. read_file(SERVER_CERT2_FILE, cert);
  23796. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  23797. ASSERT_TRUE(client.connect());
  23798. client.close();
  23799. ASSERT_TRUE(client.connect());
  23800. ASSERT_TRUE(client.send("again"));
  23801. std::string msg;
  23802. EXPECT_EQ(ws::Text, client.read(msg));
  23803. EXPECT_EQ("again", msg);
  23804. client.close();
  23805. }
  23806. // Regression test: a certificate with a trusted chain but no identity match
  23807. // for the server IP must be rejected. The Mbed TLS backend used to skip
  23808. // verification entirely for IP hosts, so this connection succeeded there.
  23809. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  23810. // chain verification while the identity check must still fail.
  23811. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  23812. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23813. ASSERT_TRUE(svr.is_valid());
  23814. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23815. std::string msg;
  23816. while (ws.read(msg)) {
  23817. ws.send(msg);
  23818. }
  23819. });
  23820. auto port = svr.bind_to_any_port("127.0.0.1");
  23821. auto t = std::thread([&]() { svr.listen_after_bind(); });
  23822. auto se = detail::scope_exit([&] {
  23823. svr.stop();
  23824. t.join();
  23825. });
  23826. svr.wait_until_ready();
  23827. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  23828. "/echo");
  23829. std::string cert;
  23830. read_file(SERVER_CERT_FILE, cert);
  23831. client.load_ca_cert_store(cert.c_str(), cert.size());
  23832. ASSERT_FALSE(client.connect());
  23833. }
  23834. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  23835. // SNI, so nothing binds the host name to the TLS session. These bind the
  23836. // server to "localhost" instead, the only shape that exercises the SNI and
  23837. // hostname-verification path with certificate verification left enabled.
  23838. class WebSocketSSLDnsHostTest : public ::testing::Test {
  23839. protected:
  23840. void Start(const char *cert_file) {
  23841. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  23842. SERVER_PRIVATE_KEY_FILE);
  23843. ASSERT_TRUE(server_->is_valid());
  23844. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  23845. std::string msg;
  23846. while (ws.read(msg)) {
  23847. ws.send(msg);
  23848. }
  23849. });
  23850. port_ = server_->bind_to_any_port("localhost");
  23851. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23852. server_->wait_until_ready();
  23853. }
  23854. void TearDown() override {
  23855. if (server_) { server_->stop(); }
  23856. if (server_thread_.joinable()) { server_thread_.join(); }
  23857. }
  23858. std::string url() const {
  23859. return "wss://localhost:" + std::to_string(port_) + "/echo";
  23860. }
  23861. std::unique_ptr<SSLServer> server_;
  23862. std::thread server_thread_;
  23863. int port_ = 0;
  23864. };
  23865. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  23866. // out and the connection is usable
  23867. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  23868. Start(SERVER_CERT2_FILE);
  23869. ws::WebSocketClient client(url());
  23870. client.set_ca_cert_path(SERVER_CERT2_FILE);
  23871. ASSERT_TRUE(client.connect());
  23872. ASSERT_TRUE(client.send("hello"));
  23873. std::string msg;
  23874. EXPECT_EQ(ws::Text, client.read(msg));
  23875. EXPECT_EQ("hello", msg);
  23876. client.close();
  23877. }
  23878. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  23879. // while the identity check must still reject "localhost"
  23880. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  23881. Start(SERVER_CERT_FILE);
  23882. ws::WebSocketClient client(url());
  23883. client.set_ca_cert_path(SERVER_CERT_FILE);
  23884. auto res = client.connect();
  23885. ASSERT_FALSE(res);
  23886. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  23887. EXPECT_EQ(-1, res.status());
  23888. }
  23889. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  23890. // disabled: the chain is still checked, only the identity check is skipped
  23891. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  23892. Start(SERVER_CERT_FILE);
  23893. ws::WebSocketClient client(url());
  23894. client.set_ca_cert_path(SERVER_CERT_FILE);
  23895. client.enable_server_hostname_verification(false);
  23896. ASSERT_TRUE(client.connect());
  23897. ASSERT_TRUE(client.send("hello"));
  23898. std::string msg;
  23899. EXPECT_EQ(ws::Text, client.read(msg));
  23900. EXPECT_EQ("hello", msg);
  23901. client.close();
  23902. }
  23903. // A CA that did not sign the server certificate fails the chain, even though
  23904. // the name would match
  23905. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  23906. Start(SERVER_CERT2_FILE);
  23907. ws::WebSocketClient client(url());
  23908. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  23909. ASSERT_FALSE(client.connect());
  23910. }
  23911. // With verification disabled, neither the chain nor the name is checked
  23912. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  23913. Start(SERVER_CERT_FILE);
  23914. ws::WebSocketClient client(url());
  23915. client.enable_server_certificate_verification(false);
  23916. ASSERT_TRUE(client.connect());
  23917. ASSERT_TRUE(client.send("hello"));
  23918. std::string msg;
  23919. EXPECT_EQ(ws::Text, client.read(msg));
  23920. EXPECT_EQ("hello", msg);
  23921. client.close();
  23922. }
  23923. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  23924. protected:
  23925. void SetUp() override {
  23926. server_ = httplib::detail::make_unique<SSLServer>(
  23927. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23928. ASSERT_TRUE(server_->is_valid());
  23929. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23930. std::string msg;
  23931. while (ws.read(msg)) {
  23932. ws.send(msg);
  23933. }
  23934. });
  23935. port_ = server_->bind_to_any_port("localhost");
  23936. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23937. server_->wait_until_ready();
  23938. }
  23939. void TearDown() override {
  23940. server_->stop();
  23941. if (server_thread_.joinable()) { server_thread_.join(); }
  23942. }
  23943. std::string url() const {
  23944. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  23945. }
  23946. void ConnectWithClientCert(const std::string &client_cert_file,
  23947. const std::string &client_private_key_file,
  23948. const char *private_key_password) {
  23949. std::string cert_pem, key_pem;
  23950. read_file(client_cert_file, cert_pem);
  23951. read_file(client_private_key_file, key_pem);
  23952. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  23953. key_pem.c_str(), key_pem.size(),
  23954. private_key_password};
  23955. ws::WebSocketClient client(url(), pem);
  23956. ASSERT_TRUE(client.is_valid());
  23957. client.enable_server_certificate_verification(false);
  23958. ASSERT_TRUE(client.connect());
  23959. ASSERT_TRUE(client.send("hello"));
  23960. std::string msg;
  23961. EXPECT_EQ(ws::Text, client.read(msg));
  23962. EXPECT_EQ("hello", msg);
  23963. client.close();
  23964. }
  23965. std::unique_ptr<SSLServer> server_;
  23966. std::thread server_thread_;
  23967. int port_ = 0;
  23968. };
  23969. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  23970. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  23971. }
  23972. // Control for the tests above: the fixture's server really does require a
  23973. // client certificate, so it is the PEM the constructor installed that decides
  23974. // the outcome.
  23975. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  23976. ws::WebSocketClient client(url());
  23977. ASSERT_TRUE(client.is_valid());
  23978. client.enable_server_certificate_verification(false);
  23979. EXPECT_FALSE(client.connect());
  23980. }
  23981. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  23982. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  23983. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  23984. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  23985. }
  23986. #endif
  23987. #if !defined(_WIN32)
  23988. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  23989. auto secret_dir = std::string("./symlink_test_secret");
  23990. auto served_dir = std::string("./symlink_test_served");
  23991. auto secret_file = secret_dir + "/secret.txt";
  23992. auto symlink_path = served_dir + "/escape";
  23993. // Setup: create directories and files
  23994. mkdir(secret_dir.c_str(), 0755);
  23995. mkdir(served_dir.c_str(), 0755);
  23996. {
  23997. std::ofstream ofs(secret_file);
  23998. ofs << "SECRET_DATA";
  23999. }
  24000. // Create symlink using absolute path so it resolves correctly
  24001. #ifdef PATH_MAX
  24002. char abs_secret[PATH_MAX];
  24003. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  24004. #else
  24005. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  24006. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  24007. ASSERT_NE(nullptr, abs_secret);
  24008. #endif
  24009. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  24010. auto se = detail::scope_exit([&] {
  24011. unlink(symlink_path.c_str());
  24012. unlink(secret_file.c_str());
  24013. rmdir(served_dir.c_str());
  24014. rmdir(secret_dir.c_str());
  24015. });
  24016. Server svr;
  24017. svr.set_mount_point("/", served_dir);
  24018. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  24019. auto se2 = detail::scope_exit([&] {
  24020. svr.stop();
  24021. listen_thread.join();
  24022. });
  24023. svr.wait_until_ready();
  24024. Client cli("localhost", PORT);
  24025. // Symlink pointing outside base dir should be blocked
  24026. auto res = cli.Get("/escape/secret.txt");
  24027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24028. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  24029. }
  24030. #endif
  24031. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  24032. // "GET /smuggled" request), reads the first response, and only then sends the
  24033. // embedded request as the body. Returns how many times /smuggled ran.
  24034. //
  24035. // The body is sent AFTER receiving the first response (as in the original
  24036. // PoC) so that the stream_line_reader cannot buffer it together with the
  24037. // headers of the first request.
  24038. static int count_smuggled_requests(const std::string &outer_head,
  24039. std::string &first_response) {
  24040. Server svr;
  24041. svr.set_mount_point("/", "./www");
  24042. std::atomic<int> smuggled_count(0);
  24043. svr.Get("/smuggled", [&](const Request &, Response &res) {
  24044. smuggled_count++;
  24045. res.set_content("oops", "text/plain");
  24046. });
  24047. svr.Post("/post", [&](const Request &req, Response &res) {
  24048. res.set_content(req.body, "text/plain");
  24049. });
  24050. auto port = svr.bind_to_any_port("localhost");
  24051. thread t = thread([&] { svr.listen_after_bind(); });
  24052. auto se = detail::scope_exit([&] {
  24053. svr.stop();
  24054. t.join();
  24055. });
  24056. svr.wait_until_ready();
  24057. auto error = Error::Success;
  24058. auto sock = detail::create_client_socket(
  24059. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  24060. /*connection_timeout_sec=*/2, 0,
  24061. /*read_timeout_sec=*/2, 0,
  24062. /*write_timeout_sec=*/2, 0, std::string(), error);
  24063. EXPECT_NE(INVALID_SOCKET, sock);
  24064. if (sock == INVALID_SOCKET) { return -1; }
  24065. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24066. // The "smuggled" request will be sent as the body of the outer request
  24067. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  24068. "Host: localhost\r\n"
  24069. "Connection: close\r\n"
  24070. "\r\n";
  24071. auto head = outer_head;
  24072. auto len = std::to_string(smuggled.size());
  24073. for (auto pos = head.find("{len}"); pos != std::string::npos;
  24074. pos = head.find("{len}", pos + len.size())) {
  24075. head.replace(pos, 5, len);
  24076. }
  24077. // Step 1: Send only the outer request headers (no body yet)
  24078. auto sent = send(sock, head.data(), head.size(), 0);
  24079. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  24080. // Step 2: Read the first response
  24081. char buf[4096];
  24082. for (;;) {
  24083. auto n = recv(sock, buf, sizeof(buf), 0);
  24084. if (n <= 0) break;
  24085. first_response.append(buf, static_cast<size_t>(n));
  24086. // Stop once we have a complete response (headers + body)
  24087. auto hdr_end = first_response.find("\r\n\r\n");
  24088. if (hdr_end != std::string::npos) {
  24089. // Check for Content-Length to know when the body is complete
  24090. auto cl_pos = first_response.find("Content-Length:");
  24091. if (cl_pos != std::string::npos) {
  24092. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  24093. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  24094. auto cl = std::stoul(
  24095. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  24096. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  24097. } else {
  24098. break; // No Content-Length, assume headers-only response
  24099. }
  24100. }
  24101. }
  24102. // Step 3: Now send the body, which looks like a new HTTP request. On a
  24103. // vulnerable server the keep-alive loop reads this as a second request. The
  24104. // server may already have closed the connection, so the result is ignored.
  24105. send(sock, smuggled.data(), smuggled.size(), 0);
  24106. // Half-close so that a server which drained the body sees EOF and closes,
  24107. // instead of the read below waiting for the read timeout.
  24108. #ifdef _WIN32
  24109. ::shutdown(sock, SD_SEND);
  24110. #else
  24111. ::shutdown(sock, SHUT_WR);
  24112. #endif
  24113. // Step 4: Read until the server closes the connection
  24114. for (;;) {
  24115. auto n = recv(sock, buf, sizeof(buf), 0);
  24116. if (n <= 0) break;
  24117. }
  24118. return smuggled_count.load();
  24119. }
  24120. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  24121. // A GET request with Content-Length to a static file handler must have its
  24122. // body drained before the keep-alive connection is reused. Otherwise the
  24123. // unread body bytes are interpreted as the next HTTP request.
  24124. std::string first_response;
  24125. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  24126. "Host: localhost\r\n"
  24127. "Content-Length: {len}\r\n"
  24128. "\r\n",
  24129. first_response));
  24130. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  24131. }
  24132. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  24133. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  24134. // be answered with 400 and the connection closed. Treating it as "no body"
  24135. // leaves the body to be parsed as the next request.
  24136. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  24137. const char *targets[] = {
  24138. "GET /file", // handler that never reads the body
  24139. "GET /not-found", // no handler matches (404)
  24140. "POST /post", // handler that reads the body
  24141. };
  24142. for (auto target : targets) {
  24143. for (auto value : values) {
  24144. std::string first_response;
  24145. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  24146. " HTTP/1.1\r\n"
  24147. "Host: localhost\r\n"
  24148. "Content-Length: " +
  24149. value + "\r\n\r\n",
  24150. first_response))
  24151. << target << " with Content-Length: " << value;
  24152. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  24153. << target << " with Content-Length: " << value;
  24154. }
  24155. }
  24156. }
  24157. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  24158. // A 400 for an unparseable request line leaves the rest of the message
  24159. // unread, so the connection must be closed rather than reused.
  24160. std::string first_response;
  24161. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  24162. "Host: localhost\r\n"
  24163. "Content-Length: {len}\r\n"
  24164. "\r\n",
  24165. first_response));
  24166. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  24167. }
  24168. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  24169. // Same as above for a header block that fails to parse.
  24170. std::string first_response;
  24171. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  24172. "Host: localhost\r\n"
  24173. "Bad Header\r\n"
  24174. "Content-Length: {len}\r\n"
  24175. "\r\n",
  24176. first_response));
  24177. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  24178. }
  24179. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  24180. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  24181. // server must not read another request on that connection, even when the
  24182. // request had no body to drain.
  24183. std::string first_response;
  24184. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  24185. "Host: localhost\r\n"
  24186. "\r\n",
  24187. first_response));
  24188. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  24189. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  24190. }
  24191. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  24192. // A content reader that stops early leaves the stream inside the body.
  24193. // Draining the whole Content-Length from there, or reading the body again,
  24194. // reads into the next request, and whatever follows is parsed as a request
  24195. // of its own.
  24196. Server svr;
  24197. std::atomic<int> smuggled_count(0);
  24198. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  24199. svr.Post("/upload", [](const Request &req, Response &res,
  24200. const ContentReader &content_reader) {
  24201. // Stop at the last chunk, so the whole body has been read however it
  24202. // arrives.
  24203. auto length = req.get_header_value_u64("Content-Length");
  24204. size_t total = 0;
  24205. auto consumed = content_reader([&](const char *, size_t n) {
  24206. total += n;
  24207. return total < length;
  24208. });
  24209. EXPECT_FALSE(consumed);
  24210. if (req.has_param("retry")) {
  24211. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  24212. }
  24213. // Replace the 400 the aborted read set, which would close the connection.
  24214. res.set_redirect("/done");
  24215. });
  24216. auto port = svr.bind_to_any_port(HOST);
  24217. thread t = thread([&] { svr.listen_after_bind(); });
  24218. auto se = detail::scope_exit([&] {
  24219. svr.stop();
  24220. t.join();
  24221. });
  24222. svr.wait_until_ready();
  24223. // A front end sees the second request as a POST whose body is the GET. The
  24224. // first body is as long as the POST's headers, so draining it again reads
  24225. // exactly those and leaves the GET to be parsed next.
  24226. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  24227. "Host: localhost\r\n"
  24228. "\r\n";
  24229. std::string second_head = "POST /post HTTP/1.1\r\n"
  24230. "Host: localhost\r\n"
  24231. "Content-Length: " +
  24232. std::to_string(inner.size()) +
  24233. "\r\n"
  24234. "\r\n";
  24235. for (auto target : {"/upload", "/upload?retry"}) {
  24236. smuggled_count = 0;
  24237. std::string request = "POST " + std::string(target) +
  24238. " HTTP/1.1\r\n"
  24239. "Host: localhost\r\n"
  24240. "Content-Length: " +
  24241. std::to_string(second_head.size()) +
  24242. "\r\n"
  24243. "\r\n" +
  24244. std::string(second_head.size(), 'A') + second_head +
  24245. inner;
  24246. std::string response;
  24247. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  24248. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  24249. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  24250. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  24251. EXPECT_EQ(0, smuggled_count.load()) << target;
  24252. }
  24253. }
  24254. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  24255. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  24256. // must be rejected with 400 Bad Request.
  24257. Server svr;
  24258. svr.Post("/test", [&](const Request &, Response &res) {
  24259. res.set_content("ok", "text/plain");
  24260. });
  24261. thread t = thread([&] { svr.listen(HOST, PORT); });
  24262. auto se = detail::scope_exit([&] {
  24263. svr.stop();
  24264. t.join();
  24265. ASSERT_FALSE(svr.is_running());
  24266. });
  24267. svr.wait_until_ready();
  24268. // Exact "chunked"
  24269. {
  24270. auto req = "POST /test HTTP/1.1\r\n"
  24271. "Host: localhost\r\n"
  24272. "Content-Length: 5\r\n"
  24273. "Transfer-Encoding: chunked\r\n"
  24274. "Connection: close\r\n"
  24275. "\r\n"
  24276. "hello";
  24277. std::string response;
  24278. ASSERT_TRUE(send_request(1, req, &response));
  24279. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24280. response.substr(0, response.find("\r\n")));
  24281. }
  24282. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  24283. {
  24284. auto req = "POST /test HTTP/1.1\r\n"
  24285. "Host: localhost\r\n"
  24286. "Content-Length: 5\r\n"
  24287. "Transfer-Encoding: gzip, chunked\r\n"
  24288. "Connection: close\r\n"
  24289. "\r\n"
  24290. "hello";
  24291. std::string response;
  24292. ASSERT_TRUE(send_request(1, req, &response));
  24293. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24294. response.substr(0, response.find("\r\n")));
  24295. }
  24296. }
  24297. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  24298. Server svr;
  24299. svr.Post("/test", [&](const Request &, Response &res) {
  24300. res.set_content("ok", "text/plain");
  24301. });
  24302. thread t = thread([&] { svr.listen(HOST, PORT); });
  24303. auto se = detail::scope_exit([&] {
  24304. svr.stop();
  24305. t.join();
  24306. ASSERT_FALSE(svr.is_running());
  24307. });
  24308. svr.wait_until_ready();
  24309. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  24310. // length cannot be determined, so the server must answer 400 and close
  24311. // rather than treat the request as bodyless and leave the body in the
  24312. // socket for the next request to pick up.
  24313. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  24314. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  24315. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  24316. std::string response;
  24317. ASSERT_TRUE(send_request(1, req, &response));
  24318. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24319. response.substr(0, response.find("\r\n")))
  24320. << transfer_encoding;
  24321. }
  24322. // RFC 9110 5.3: the codings may also be split across several
  24323. // Transfer-Encoding lines, which combine in the order they were received.
  24324. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  24325. // just like the single-line "chunked, gzip" above.
  24326. {
  24327. auto req = "POST /test HTTP/1.1\r\n"
  24328. "Host: localhost\r\n"
  24329. "Transfer-Encoding: chunked\r\n"
  24330. "Transfer-Encoding: gzip\r\n"
  24331. "\r\n"
  24332. "0\r\n\r\n";
  24333. std::string response;
  24334. ASSERT_TRUE(send_request(1, req, &response));
  24335. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  24336. response.substr(0, response.find("\r\n")));
  24337. }
  24338. // A sequence ending in chunked stays valid.
  24339. auto req = "POST /test HTTP/1.1\r\n"
  24340. "Host: localhost\r\n"
  24341. "Transfer-Encoding: gzip, chunked\r\n"
  24342. "Connection: close\r\n"
  24343. "\r\n"
  24344. "0\r\n\r\n";
  24345. std::string response;
  24346. ASSERT_TRUE(send_request(1, req, &response));
  24347. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  24348. // ...including when it is spread over several lines.
  24349. auto split_req = "POST /test HTTP/1.1\r\n"
  24350. "Host: localhost\r\n"
  24351. "Transfer-Encoding: gzip\r\n"
  24352. "Transfer-Encoding: chunked\r\n"
  24353. "Connection: close\r\n"
  24354. "\r\n"
  24355. "0\r\n\r\n";
  24356. std::string split_response;
  24357. ASSERT_TRUE(send_request(1, split_req, &split_response));
  24358. EXPECT_EQ("HTTP/1.1 200 OK",
  24359. split_response.substr(0, split_response.find("\r\n")));
  24360. }
  24361. // Regression for issue #2450: a DELETE without Content-Length on a
  24362. // keep-alive connection must not let the post-response drain consume the
  24363. // next request's bytes.
  24364. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  24365. Server svr;
  24366. std::atomic<int> delete_count(0);
  24367. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  24368. delete_count++;
  24369. res.status = StatusCode::NoContent_204;
  24370. });
  24371. auto port = svr.bind_to_any_port(HOST);
  24372. thread t = thread([&] { svr.listen_after_bind(); });
  24373. auto se = detail::scope_exit([&] {
  24374. svr.stop();
  24375. t.join();
  24376. });
  24377. svr.wait_until_ready();
  24378. auto error = Error::Success;
  24379. auto sock = detail::create_client_socket(
  24380. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  24381. /*connection_timeout_sec=*/2, 0,
  24382. /*read_timeout_sec=*/2, 0,
  24383. /*write_timeout_sec=*/2, 0, std::string(), error);
  24384. ASSERT_NE(INVALID_SOCKET, sock);
  24385. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24386. auto send_request_and_read_response = [&](const std::string &req,
  24387. std::string &out) -> bool {
  24388. auto sent = send(sock, req.data(), req.size(), 0);
  24389. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  24390. char buf[4096];
  24391. for (;;) {
  24392. auto n = recv(sock, buf, sizeof(buf), 0);
  24393. if (n <= 0) { return !out.empty(); }
  24394. out.append(buf, static_cast<size_t>(n));
  24395. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  24396. }
  24397. };
  24398. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  24399. "Host: localhost\r\n"
  24400. "\r\n";
  24401. std::string resp1;
  24402. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  24403. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  24404. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  24405. "Host: localhost\r\n"
  24406. "Connection: close\r\n"
  24407. "\r\n";
  24408. std::string resp2;
  24409. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  24410. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  24411. EXPECT_EQ(2, delete_count.load());
  24412. }
  24413. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  24414. Server svr;
  24415. svr.Post("/ingest", [&](const Request &, Response &res,
  24416. const ContentReader &content_reader) {
  24417. auto consumed = content_reader([](const char *, size_t) { return false; });
  24418. EXPECT_FALSE(consumed);
  24419. res.status = StatusCode::Conflict_409;
  24420. res.set_header("Connection", "close");
  24421. });
  24422. auto port = svr.bind_to_any_port(HOST);
  24423. thread t = thread([&] { svr.listen_after_bind(); });
  24424. auto se = detail::scope_exit([&] {
  24425. svr.stop();
  24426. t.join();
  24427. });
  24428. svr.wait_until_ready();
  24429. auto error = Error::Success;
  24430. auto sock = detail::create_client_socket(
  24431. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  24432. /*connection_timeout_sec=*/2, 0,
  24433. /*read_timeout_sec=*/1, 0,
  24434. /*write_timeout_sec=*/2, 0, std::string(), error);
  24435. ASSERT_NE(INVALID_SOCKET, sock);
  24436. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  24437. std::string request = "POST /ingest HTTP/1.1\r\n"
  24438. "Host: localhost\r\n"
  24439. "Transfer-Encoding: chunked\r\n"
  24440. "\r\n"
  24441. "4\r\n"
  24442. "data\r\n";
  24443. auto sent = send(sock, request.data(), request.size(), 0);
  24444. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  24445. std::string response;
  24446. ssize_t received = 0;
  24447. do {
  24448. char buf[4096];
  24449. received = recv(sock, buf, sizeof(buf), 0);
  24450. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  24451. } while (received > 0);
  24452. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  24453. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  24454. EXPECT_EQ(0, received);
  24455. }
  24456. namespace no_proxy_test {
  24457. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  24458. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  24459. // calling listen().
  24460. class ScopedServer {
  24461. public:
  24462. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  24463. ~ScopedServer() {
  24464. svr_.stop();
  24465. if (th_.joinable()) { th_.join(); }
  24466. }
  24467. Server &svr() { return svr_; }
  24468. int port() const { return port_; }
  24469. void listen() {
  24470. th_ = std::thread([this] { svr_.listen_after_bind(); });
  24471. svr_.wait_until_ready();
  24472. }
  24473. private:
  24474. Server svr_;
  24475. std::thread th_;
  24476. int port_ = 0;
  24477. };
  24478. class ProxyAndTargetServers {
  24479. public:
  24480. ProxyAndTargetServers() {
  24481. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  24482. proxy_hits_++;
  24483. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  24484. res.set_content("via-proxy", "text/plain");
  24485. });
  24486. target_.Get(".*", [this](const Request &req, Response &res) {
  24487. target_hits_++;
  24488. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  24489. res.set_content("direct", "text/plain");
  24490. });
  24491. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  24492. target_port_ = target_.bind_to_any_port("127.0.0.1");
  24493. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  24494. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  24495. proxy_mock_.wait_until_ready();
  24496. target_.wait_until_ready();
  24497. }
  24498. ~ProxyAndTargetServers() {
  24499. proxy_mock_.stop();
  24500. target_.stop();
  24501. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  24502. if (target_thread_.joinable()) { target_thread_.join(); }
  24503. }
  24504. Server &proxy_mock() { return proxy_mock_; }
  24505. Server &target() { return target_; }
  24506. int proxy_port() const { return proxy_port_; }
  24507. int target_port() const { return target_port_; }
  24508. int proxy_hits() const { return proxy_hits_.load(); }
  24509. int target_hits() const { return target_hits_.load(); }
  24510. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  24511. void reset_counters() {
  24512. proxy_hits_ = 0;
  24513. target_hits_ = 0;
  24514. last_had_proxy_authz_ = false;
  24515. }
  24516. private:
  24517. Server proxy_mock_;
  24518. Server target_;
  24519. std::thread proxy_thread_;
  24520. std::thread target_thread_;
  24521. int proxy_port_ = 0;
  24522. int target_port_ = 0;
  24523. std::atomic<int> proxy_hits_{0};
  24524. std::atomic<int> target_hits_{0};
  24525. std::atomic<bool> last_had_proxy_authz_{false};
  24526. };
  24527. inline std::unique_ptr<Client> make_client(const std::string &host,
  24528. ProxyAndTargetServers &s) {
  24529. auto cli = detail::make_unique<Client>(host, s.target_port());
  24530. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  24531. cli->set_proxy("127.0.0.1", s.proxy_port());
  24532. return cli;
  24533. }
  24534. } // namespace no_proxy_test
  24535. using no_proxy_test::make_client;
  24536. using no_proxy_test::ProxyAndTargetServers;
  24537. TEST(NoProxyTest, ExactHostnameBypasses) {
  24538. ProxyAndTargetServers s;
  24539. auto cli = make_client("example.com", s);
  24540. cli->set_no_proxy({"example.com"});
  24541. auto res = cli->Get("/");
  24542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24543. EXPECT_EQ(0, s.proxy_hits());
  24544. EXPECT_EQ(1, s.target_hits());
  24545. }
  24546. TEST(NoProxyTest, SubdomainBypasses) {
  24547. ProxyAndTargetServers s;
  24548. auto cli = make_client("foo.example.com", s);
  24549. cli->set_no_proxy({"example.com"});
  24550. auto res = cli->Get("/");
  24551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24552. EXPECT_EQ(0, s.proxy_hits());
  24553. EXPECT_EQ(1, s.target_hits());
  24554. }
  24555. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  24556. // Regression guard: "evilexample.com" must not be considered a subdomain
  24557. // of "example.com". Without the dot-boundary rule, a naive endsWith
  24558. // check would let traffic bypass the proxy and leak credentials direct
  24559. // to the attacker host.
  24560. ProxyAndTargetServers s;
  24561. auto cli = make_client("evilexample.com", s);
  24562. cli->set_no_proxy({"example.com"});
  24563. auto res = cli->Get("/");
  24564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24565. EXPECT_GE(s.proxy_hits(), 1);
  24566. EXPECT_EQ(0, s.target_hits());
  24567. }
  24568. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  24569. ProxyAndTargetServers s;
  24570. auto cli = make_client("example.com.evil.com", s);
  24571. cli->set_no_proxy({"example.com"});
  24572. auto res = cli->Get("/");
  24573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24574. EXPECT_GE(s.proxy_hits(), 1);
  24575. EXPECT_EQ(0, s.target_hits());
  24576. }
  24577. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  24578. ProxyAndTargetServers s;
  24579. auto cli = make_client("example.com", s);
  24580. cli->set_no_proxy({".example.com"});
  24581. auto res = cli->Get("/");
  24582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24583. EXPECT_EQ(0, s.proxy_hits());
  24584. EXPECT_EQ(1, s.target_hits());
  24585. }
  24586. TEST(NoProxyTest, CaseInsensitiveHostname) {
  24587. ProxyAndTargetServers s;
  24588. auto cli = make_client("Example.COM", s);
  24589. cli->set_no_proxy({"EXAMPLE.com"});
  24590. auto res = cli->Get("/");
  24591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24592. EXPECT_EQ(0, s.proxy_hits());
  24593. EXPECT_EQ(1, s.target_hits());
  24594. }
  24595. TEST(NoProxyTest, TrailingDotIsNormalized) {
  24596. ProxyAndTargetServers s;
  24597. auto cli = make_client("example.com.", s);
  24598. cli->set_no_proxy({"example.com"});
  24599. auto res = cli->Get("/");
  24600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24601. EXPECT_EQ(0, s.proxy_hits());
  24602. EXPECT_EQ(1, s.target_hits());
  24603. }
  24604. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  24605. // Trailing dots must be normalized on BOTH sides — host and entry.
  24606. // An implementation that only strips the host-side trailing dot would
  24607. // fail to match host "example.com" against entry "example.com." because
  24608. // a literal substring search would compare 11 chars against 12.
  24609. ProxyAndTargetServers s;
  24610. auto cli = make_client("example.com", s);
  24611. cli->set_no_proxy({"example.com."});
  24612. auto res = cli->Get("/");
  24613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24614. EXPECT_EQ(0, s.proxy_hits());
  24615. EXPECT_EQ(1, s.target_hits());
  24616. }
  24617. TEST(NoProxyTest, WildcardBypassesEverything) {
  24618. ProxyAndTargetServers s;
  24619. auto cli = make_client("anything.invalid.test", s);
  24620. cli->set_no_proxy({"*"});
  24621. auto res = cli->Get("/");
  24622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24623. EXPECT_EQ(0, s.proxy_hits());
  24624. EXPECT_EQ(1, s.target_hits());
  24625. }
  24626. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  24627. ProxyAndTargetServers s;
  24628. Client cli("127.0.0.1", s.target_port());
  24629. cli.set_proxy("127.0.0.1", s.proxy_port());
  24630. cli.set_no_proxy({"127.0.0.1"});
  24631. auto res = cli.Get("/");
  24632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24633. EXPECT_EQ(0, s.proxy_hits());
  24634. EXPECT_EQ(1, s.target_hits());
  24635. }
  24636. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  24637. ProxyAndTargetServers s;
  24638. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  24639. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  24640. cli.set_proxy("127.0.0.1", s.proxy_port());
  24641. cli.set_no_proxy({"::1"});
  24642. auto res = cli.Get("/");
  24643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24644. EXPECT_EQ(0, s.proxy_hits());
  24645. EXPECT_EQ(1, s.target_hits());
  24646. }
  24647. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  24648. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  24649. // must still be recognized as IPv6 for CIDR matching. Implementations
  24650. // that detect IPv6 only when the host begins with '[' would parse the
  24651. // host as a hostname and miss the match.
  24652. ProxyAndTargetServers s;
  24653. Client cli("fe80::1", s.target_port());
  24654. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  24655. cli.set_proxy("127.0.0.1", s.proxy_port());
  24656. cli.set_no_proxy({"fe80::/10"});
  24657. auto res = cli.Get("/");
  24658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24659. EXPECT_EQ(0, s.proxy_hits());
  24660. EXPECT_EQ(1, s.target_hits());
  24661. }
  24662. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  24663. ProxyAndTargetServers s;
  24664. Client cli("::1", s.target_port());
  24665. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  24666. cli.set_proxy("127.0.0.1", s.proxy_port());
  24667. cli.set_no_proxy({"[::1]"});
  24668. auto res = cli.Get("/");
  24669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24670. EXPECT_EQ(0, s.proxy_hits());
  24671. EXPECT_EQ(1, s.target_hits());
  24672. }
  24673. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  24674. ProxyAndTargetServers s;
  24675. Client cli("fe80::1", s.target_port());
  24676. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  24677. cli.set_proxy("127.0.0.1", s.proxy_port());
  24678. cli.set_no_proxy({"[fe80::]/10"});
  24679. auto res = cli.Get("/");
  24680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24681. EXPECT_EQ(0, s.proxy_hits());
  24682. EXPECT_EQ(1, s.target_hits());
  24683. }
  24684. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  24685. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  24686. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  24687. // tricks via address-family conversion.
  24688. ProxyAndTargetServers s;
  24689. Client cli("::ffff:127.0.0.1", s.target_port());
  24690. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  24691. cli.set_proxy("127.0.0.1", s.proxy_port());
  24692. cli.set_no_proxy({"127.0.0.1"});
  24693. auto res = cli.Get("/");
  24694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24695. EXPECT_GE(s.proxy_hits(), 1);
  24696. EXPECT_EQ(0, s.target_hits());
  24697. }
  24698. TEST(NoProxyTest, IPv4CidrMatch) {
  24699. ProxyAndTargetServers s;
  24700. Client cli("127.0.0.1", s.target_port());
  24701. cli.set_proxy("127.0.0.1", s.proxy_port());
  24702. cli.set_no_proxy({"127.0.0.0/8"});
  24703. auto res = cli.Get("/");
  24704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24705. EXPECT_EQ(0, s.proxy_hits());
  24706. EXPECT_EQ(1, s.target_hits());
  24707. }
  24708. TEST(NoProxyTest, IPv4CidrNonMatch) {
  24709. ProxyAndTargetServers s;
  24710. Client cli("127.0.0.1", s.target_port());
  24711. cli.set_proxy("127.0.0.1", s.proxy_port());
  24712. cli.set_no_proxy({"10.0.0.0/8"});
  24713. auto res = cli.Get("/");
  24714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24715. EXPECT_GE(s.proxy_hits(), 1);
  24716. EXPECT_EQ(0, s.target_hits());
  24717. }
  24718. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  24719. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  24720. // IPv4 target matches.
  24721. ProxyAndTargetServers s;
  24722. Client cli("127.0.0.1", s.target_port());
  24723. cli.set_proxy("127.0.0.1", s.proxy_port());
  24724. cli.set_no_proxy({"0.0.0.0/0"});
  24725. auto res = cli.Get("/");
  24726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24727. EXPECT_EQ(0, s.proxy_hits());
  24728. EXPECT_EQ(1, s.target_hits());
  24729. }
  24730. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  24731. ProxyAndTargetServers s;
  24732. Client cli("127.0.0.1", s.target_port());
  24733. cli.set_proxy("127.0.0.1", s.proxy_port());
  24734. cli.set_no_proxy({"127.0.0.1"});
  24735. auto res = cli.Get("/");
  24736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24737. EXPECT_EQ(0, s.proxy_hits());
  24738. EXPECT_EQ(1, s.target_hits());
  24739. }
  24740. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  24741. ProxyAndTargetServers s;
  24742. Client cli("127.0.0.1", s.target_port());
  24743. cli.set_proxy("127.0.0.1", s.proxy_port());
  24744. cli.set_no_proxy({"127.0.0.0/33"});
  24745. auto res = cli.Get("/");
  24746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24747. EXPECT_GE(s.proxy_hits(), 1);
  24748. EXPECT_EQ(0, s.target_hits());
  24749. }
  24750. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  24751. // Empty prefix after the slash must be rejected, not silently treated as /32.
  24752. ProxyAndTargetServers s;
  24753. Client cli("127.0.0.1", s.target_port());
  24754. cli.set_proxy("127.0.0.1", s.proxy_port());
  24755. cli.set_no_proxy({"127.0.0.1/"});
  24756. auto res = cli.Get("/");
  24757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24758. EXPECT_GE(s.proxy_hits(), 1);
  24759. EXPECT_EQ(0, s.target_hits());
  24760. }
  24761. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  24762. ProxyAndTargetServers s;
  24763. auto cli = make_client("internal.corp", s);
  24764. cli->set_proxy_basic_auth("u", "p");
  24765. cli->set_no_proxy({"internal.corp"});
  24766. auto res = cli->Get("/");
  24767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24768. EXPECT_EQ(1, s.target_hits());
  24769. EXPECT_EQ(0, s.proxy_hits());
  24770. EXPECT_FALSE(s.last_had_proxy_authz())
  24771. << "Proxy-Authorization must not be sent direct to the target";
  24772. }
  24773. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  24774. ProxyAndTargetServers s;
  24775. auto cli = make_client("public.example", s);
  24776. cli->set_proxy_basic_auth("u", "p");
  24777. cli->set_no_proxy({"internal.corp"}); // does not match
  24778. auto res = cli->Get("/");
  24779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24780. EXPECT_GE(s.proxy_hits(), 1);
  24781. EXPECT_TRUE(s.last_had_proxy_authz());
  24782. }
  24783. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  24784. std::atomic<int> hits{0};
  24785. std::atomic<int> hits_with_authz{0};
  24786. no_proxy_test::ScopedServer proxy_mock;
  24787. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  24788. hits++;
  24789. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  24790. if (req.target.find("/redir") != std::string::npos) {
  24791. res.set_redirect("http://other.example/landed");
  24792. } else {
  24793. res.set_content("via-proxy", "text/plain");
  24794. }
  24795. });
  24796. proxy_mock.listen();
  24797. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  24798. hits = 0;
  24799. hits_with_authz = 0;
  24800. Client cli("public.example", 80);
  24801. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24802. cli.set_proxy_basic_auth(c.first, c.second);
  24803. cli.set_follow_location(true);
  24804. // The redirect to another host goes through the proxy as well
  24805. auto res = cli.Get("/redir");
  24806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24807. EXPECT_EQ(2, hits.load());
  24808. EXPECT_EQ(2, hits_with_authz.load());
  24809. }
  24810. }
  24811. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  24812. ProxyAndTargetServers s;
  24813. auto cli = make_client("anything.test", s);
  24814. auto res = cli->Get("/");
  24815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24816. EXPECT_GE(s.proxy_hits(), 1);
  24817. EXPECT_EQ(0, s.target_hits());
  24818. }
  24819. TEST(NoProxyTest, PortSpecificEntryRejected) {
  24820. ProxyAndTargetServers s;
  24821. auto cli = make_client("example.com", s);
  24822. cli->set_no_proxy({"example.com:8080"});
  24823. auto res = cli->Get("/");
  24824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24825. EXPECT_GE(s.proxy_hits(), 1);
  24826. EXPECT_EQ(0, s.target_hits());
  24827. }
  24828. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  24829. ProxyAndTargetServers s;
  24830. auto cli = make_client("anything.test", s);
  24831. cli->set_no_proxy({"", " ", "\t"});
  24832. auto res = cli->Get("/");
  24833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24834. EXPECT_GE(s.proxy_hits(), 1);
  24835. EXPECT_EQ(0, s.target_hits());
  24836. }
  24837. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  24838. // An entry with leading/trailing whitespace must still match — env-style
  24839. // values are commonly pasted with stray spaces and an implementation
  24840. // that feeds the raw token directly to inet_pton would fail to match
  24841. // valid CIDRs because of the spaces.
  24842. ProxyAndTargetServers s;
  24843. Client cli("127.0.0.1", s.target_port());
  24844. cli.set_proxy("127.0.0.1", s.proxy_port());
  24845. cli.set_no_proxy({" 127.0.0.0/8 "});
  24846. auto res = cli.Get("/");
  24847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24848. EXPECT_EQ(0, s.proxy_hits());
  24849. EXPECT_EQ(1, s.target_hits());
  24850. }
  24851. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  24852. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  24853. // go direct and must NOT carry Proxy-Authorization.
  24854. std::atomic<int> proxy_hits{0};
  24855. std::atomic<int> target_hits{0};
  24856. std::atomic<bool> target_saw_authz{false};
  24857. no_proxy_test::ScopedServer proxy_mock, target;
  24858. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  24859. proxy_hits++;
  24860. res.status = 302;
  24861. res.set_header("Location", "http://127.0.0.1:" +
  24862. std::to_string(target.port()) + "/landed");
  24863. });
  24864. target.svr().Get(".*", [&](const Request &req, Response &res) {
  24865. target_hits++;
  24866. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  24867. res.set_content("direct", "text/plain");
  24868. });
  24869. proxy_mock.listen();
  24870. target.listen();
  24871. Client cli("public.example", target.port());
  24872. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24873. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24874. cli.set_proxy_basic_auth("u", "p");
  24875. cli.set_no_proxy({"127.0.0.1"});
  24876. cli.set_follow_location(true);
  24877. auto res = cli.Get("/redir");
  24878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24879. EXPECT_GE(proxy_hits.load(), 1);
  24880. EXPECT_GE(target_hits.load(), 1);
  24881. EXPECT_FALSE(target_saw_authz.load());
  24882. }
  24883. #ifdef CPPHTTPLIB_SSL_ENABLED
  24884. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  24885. // Direct origin replying 407 must not trigger the digest retry; otherwise
  24886. // proxy creds would be sent to the (possibly hostile) origin.
  24887. std::atomic<int> target_hits{0};
  24888. std::atomic<bool> target_saw_proxy_authz{false};
  24889. no_proxy_test::ScopedServer target;
  24890. target.svr().Get(".*", [&](const Request &req, Response &res) {
  24891. target_hits++;
  24892. if (req.has_header("Proxy-Authorization")) {
  24893. target_saw_proxy_authz = true;
  24894. }
  24895. res.status = StatusCode::ProxyAuthenticationRequired_407;
  24896. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  24897. "nonce=\"abc\", algorithm=MD5");
  24898. });
  24899. target.listen();
  24900. // The proxy address is set to the target's port: the bypass MUST kick in;
  24901. // if it doesn't, the test still routes "via proxy" to the same server and
  24902. // the Proxy-Authorization assertion below catches the leak.
  24903. Client cli("evil.example", target.port());
  24904. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  24905. cli.set_proxy("127.0.0.1", target.port());
  24906. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  24907. cli.set_no_proxy({"evil.example"});
  24908. auto res = cli.Get("/x");
  24909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24910. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  24911. EXPECT_EQ(1, target_hits.load());
  24912. EXPECT_FALSE(target_saw_proxy_authz.load());
  24913. }
  24914. #endif
  24915. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  24916. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  24917. std::atomic<int> proxy_hits{0};
  24918. std::atomic<int> bypass_hits{0};
  24919. std::atomic<bool> proxy_saw_c_url{false};
  24920. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  24921. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  24922. proxy_hits++;
  24923. if (req.path.find("/start") != std::string::npos) {
  24924. res.status = 302;
  24925. res.set_header("Location", "http://127.0.0.1:" +
  24926. std::to_string(bypass_server.port()) +
  24927. "/middle");
  24928. return;
  24929. }
  24930. if (req.path.find("/end") != std::string::npos) {
  24931. proxy_saw_c_url = true;
  24932. res.set_content("c-via-proxy", "text/plain");
  24933. return;
  24934. }
  24935. res.set_content("unexpected", "text/plain");
  24936. });
  24937. // public.example's "advertised" port is arbitrary (the request never lands
  24938. // there — it goes through the proxy), but use a dynamic value to stay
  24939. // friendly with sharded parallel runs.
  24940. int public_port = bypass_server.port();
  24941. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  24942. bypass_hits++;
  24943. res.status = 302;
  24944. res.set_header("Location", "http://public.example:" +
  24945. std::to_string(public_port) + "/end");
  24946. });
  24947. proxy_mock.listen();
  24948. bypass_server.listen();
  24949. Client cli("public.example", public_port);
  24950. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24951. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24952. cli.set_no_proxy({"127.0.0.1"});
  24953. cli.set_follow_location(true);
  24954. auto res = cli.Get("/start");
  24955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24956. EXPECT_EQ(StatusCode::OK_200, res->status);
  24957. EXPECT_EQ("c-via-proxy", res->body);
  24958. EXPECT_GE(proxy_hits.load(), 2);
  24959. EXPECT_GE(bypass_hits.load(), 1);
  24960. EXPECT_TRUE(proxy_saw_c_url.load());
  24961. }
  24962. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  24963. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  24964. // request reconnects to the correct endpoint.
  24965. std::atomic<int> proxy_hits{0};
  24966. std::atomic<int> target_hits{0};
  24967. no_proxy_test::ScopedServer proxy_mock, target;
  24968. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  24969. proxy_hits++;
  24970. res.set_content("via-proxy", "text/plain");
  24971. });
  24972. target.svr().Get(".*", [&](const Request &, Response &res) {
  24973. target_hits++;
  24974. res.set_content("direct", "text/plain");
  24975. });
  24976. proxy_mock.listen();
  24977. target.listen();
  24978. Client cli("public.example", target.port());
  24979. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24980. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24981. cli.set_keep_alive(true);
  24982. auto res1 = cli.Get("/a");
  24983. ASSERT_TRUE(res1);
  24984. EXPECT_EQ("via-proxy", res1->body);
  24985. EXPECT_EQ(1, proxy_hits.load());
  24986. EXPECT_EQ(0, target_hits.load());
  24987. cli.set_no_proxy({"public.example"});
  24988. auto res2 = cli.Get("/b");
  24989. ASSERT_TRUE(res2);
  24990. EXPECT_EQ("direct", res2->body);
  24991. EXPECT_EQ(1, proxy_hits.load());
  24992. EXPECT_EQ(1, target_hits.load());
  24993. }
  24994. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  24995. namespace proxy_tunnel_test {
  24996. // SSLServer counterpart to no_proxy_test::ScopedServer.
  24997. class ScopedSSLServer {
  24998. public:
  24999. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  25000. port_ = svr_.bind_to_any_port("127.0.0.1");
  25001. }
  25002. ~ScopedSSLServer() {
  25003. svr_.stop();
  25004. if (th_.joinable()) { th_.join(); }
  25005. }
  25006. SSLServer &svr() { return svr_; }
  25007. int port() const { return port_; }
  25008. void listen() {
  25009. th_ = std::thread([this] { svr_.listen_after_bind(); });
  25010. svr_.wait_until_ready();
  25011. }
  25012. private:
  25013. SSLServer svr_;
  25014. std::thread th_;
  25015. int port_ = 0;
  25016. };
  25017. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  25018. class ScopedConnectProxy {
  25019. public:
  25020. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  25021. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  25022. if (listen_fd_ < 0) { return; }
  25023. int yes = 1;
  25024. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  25025. sockaddr_in a{};
  25026. a.sin_family = AF_INET;
  25027. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  25028. a.sin_port = 0;
  25029. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  25030. return;
  25031. }
  25032. socklen_t alen = sizeof(a);
  25033. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  25034. 0) {
  25035. return;
  25036. }
  25037. port_ = ntohs(a.sin_port);
  25038. if (::listen(listen_fd_, 1) != 0) { return; }
  25039. th_ = std::thread([this] { run(); });
  25040. }
  25041. ~ScopedConnectProxy() {
  25042. stop_ = true;
  25043. if (listen_fd_ >= 0) {
  25044. ::shutdown(listen_fd_, SHUT_RDWR);
  25045. ::close(listen_fd_);
  25046. }
  25047. if (th_.joinable()) { th_.join(); }
  25048. }
  25049. int port() const { return port_; }
  25050. int connect_hits() const { return connect_hits_.load(); }
  25051. // Head of the last CONNECT request, as the proxy saw it on the wire.
  25052. std::string connect_request() const {
  25053. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  25054. return connect_request_;
  25055. }
  25056. private:
  25057. void run() {
  25058. while (!stop_.load()) {
  25059. fd_set rfds;
  25060. FD_ZERO(&rfds);
  25061. FD_SET(listen_fd_, &rfds);
  25062. timeval tv{0, 100 * 1000};
  25063. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  25064. if (sel <= 0) { continue; }
  25065. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  25066. if (client_fd < 0) { continue; }
  25067. std::string req;
  25068. char buf[2048];
  25069. while (req.find("\r\n\r\n") == std::string::npos) {
  25070. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  25071. if (n <= 0) { break; }
  25072. req.append(buf, static_cast<size_t>(n));
  25073. }
  25074. if (req.compare(0, 7, "CONNECT") != 0) {
  25075. ::close(client_fd);
  25076. continue;
  25077. }
  25078. connect_hits_++;
  25079. {
  25080. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  25081. connect_request_ = req;
  25082. }
  25083. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  25084. ::send(client_fd, ok, std::strlen(ok), 0);
  25085. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  25086. sockaddr_in o{};
  25087. o.sin_family = AF_INET;
  25088. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  25089. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  25090. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  25091. 0) {
  25092. ::close(client_fd);
  25093. ::close(origin_fd);
  25094. continue;
  25095. }
  25096. auto forward = [](int from, int to) {
  25097. char b[8192];
  25098. for (;;) {
  25099. ssize_t n = ::recv(from, b, sizeof(b), 0);
  25100. if (n <= 0) { break; }
  25101. ssize_t off = 0;
  25102. while (off < n) {
  25103. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  25104. if (s <= 0) {
  25105. off = n;
  25106. break;
  25107. }
  25108. off += s;
  25109. }
  25110. }
  25111. ::shutdown(to, SHUT_WR);
  25112. };
  25113. std::thread t1([&] { forward(client_fd, origin_fd); });
  25114. std::thread t2([&] { forward(origin_fd, client_fd); });
  25115. t1.join();
  25116. t2.join();
  25117. ::close(client_fd);
  25118. ::close(origin_fd);
  25119. }
  25120. }
  25121. int forward_port_ = -1;
  25122. int listen_fd_ = -1;
  25123. int port_ = 0;
  25124. std::thread th_;
  25125. std::atomic<bool> stop_{false};
  25126. std::atomic<int> connect_hits_{0};
  25127. mutable std::mutex connect_request_mutex_;
  25128. std::string connect_request_;
  25129. };
  25130. // Sends one request through the CONNECT proxy to the TLS origin with a
  25131. // credential configured for each hop, and checks that each credential reaches
  25132. // only the hop it was configured for: the proxy's on the CONNECT request, the
  25133. // origin's (every header in origin_headers) on the tunnelled request.
  25134. void CredentialsStayWithTheirHop(
  25135. const std::function<void(SSLClient &)> &set_credentials,
  25136. const std::string &scheme,
  25137. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  25138. std::atomic<int> origin_hits{0};
  25139. std::atomic<bool> origin_saw_proxy_authz{false};
  25140. std::atomic<bool> origin_saw_headers{false};
  25141. ScopedSSLServer origin;
  25142. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  25143. origin_hits++;
  25144. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  25145. origin_saw_headers =
  25146. std::all_of(origin_headers.begin(), origin_headers.end(),
  25147. [&](const std::string &h) { return req.has_header(h); });
  25148. res.set_content("ok", "text/plain");
  25149. });
  25150. origin.listen();
  25151. ScopedConnectProxy proxy(origin.port());
  25152. ASSERT_NE(0, proxy.port());
  25153. // Pinned to 127.0.0.1 for the same reason as the test below.
  25154. SSLClient cli("127.0.0.1", origin.port());
  25155. cli.enable_server_certificate_verification(false);
  25156. cli.set_proxy("127.0.0.1", proxy.port());
  25157. set_credentials(cli);
  25158. auto res = cli.Get("/x");
  25159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25160. EXPECT_EQ(StatusCode::OK_200, res->status);
  25161. EXPECT_EQ(1, origin_hits.load());
  25162. EXPECT_EQ(1, proxy.connect_hits());
  25163. EXPECT_TRUE(origin_saw_headers.load());
  25164. EXPECT_FALSE(origin_saw_proxy_authz.load())
  25165. << "Proxy-Authorization must not be sent inside the tunnel";
  25166. auto connect_req = proxy.connect_request();
  25167. EXPECT_NE(std::string::npos,
  25168. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  25169. for (const auto &h : origin_headers) {
  25170. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  25171. << h << " must not be sent to the proxy on CONNECT";
  25172. }
  25173. }
  25174. } // namespace proxy_tunnel_test
  25175. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  25176. proxy_tunnel_test::CredentialsStayWithTheirHop(
  25177. [](SSLClient &cli) {
  25178. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  25179. cli.set_basic_auth("origin-user", "origin-pass");
  25180. },
  25181. "Basic");
  25182. }
  25183. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  25184. proxy_tunnel_test::CredentialsStayWithTheirHop(
  25185. [](SSLClient &cli) {
  25186. cli.set_proxy_bearer_token_auth("proxy-token");
  25187. cli.set_bearer_token_auth("origin-token");
  25188. },
  25189. "Bearer");
  25190. }
  25191. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  25192. proxy_tunnel_test::CredentialsStayWithTheirHop(
  25193. [](SSLClient &cli) {
  25194. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  25195. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  25196. {"Cookie", "sid=origin-session"},
  25197. {"X-Api-Key", "origin-key"}});
  25198. },
  25199. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  25200. }
  25201. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  25202. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  25203. // retry; otherwise proxy creds would be sent to the origin.
  25204. std::atomic<int> origin_hits{0};
  25205. std::atomic<bool> origin_saw_proxy_authz{false};
  25206. proxy_tunnel_test::ScopedSSLServer origin;
  25207. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  25208. origin_hits++;
  25209. if (req.has_header("Proxy-Authorization")) {
  25210. origin_saw_proxy_authz = true;
  25211. }
  25212. res.status = StatusCode::ProxyAuthenticationRequired_407;
  25213. res.set_header("Proxy-Authenticate",
  25214. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  25215. "algorithm=MD5");
  25216. });
  25217. origin.listen();
  25218. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  25219. ASSERT_NE(0, proxy.port());
  25220. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  25221. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  25222. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  25223. // and answer with its own status, making this test flaky.
  25224. SSLClient cli("127.0.0.1", origin.port());
  25225. cli.enable_server_certificate_verification(false);
  25226. cli.set_proxy("127.0.0.1", proxy.port());
  25227. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  25228. auto res = cli.Get("/x");
  25229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25230. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  25231. EXPECT_EQ(1, origin_hits.load());
  25232. EXPECT_FALSE(origin_saw_proxy_authz.load());
  25233. EXPECT_EQ(1, proxy.connect_hits());
  25234. }
  25235. #endif