test.cc 938 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definition is linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. } // namespace tls
  68. } // namespace httplib
  69. #endif
  70. using namespace std;
  71. using namespace httplib;
  72. const char *HOST = "localhost";
  73. static int get_base_port() {
  74. const char *shard = getenv("GTEST_SHARD_INDEX");
  75. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  76. }
  77. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  78. // New standalone tests MUST use svr.bind_to_any_port() instead.
  79. const int PORT = get_base_port();
  80. const string LONG_QUERY_VALUE = string(25000, '@');
  81. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  82. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  83. const string TOO_LONG_QUERY_URL =
  84. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  85. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  86. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  87. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  88. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  89. return file.name == key;
  90. });
  91. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  92. return *it;
  93. #else
  94. if (it != items.end()) { return *it; }
  95. throw std::runtime_error("invalid multipart form data name error");
  96. #endif
  97. }
  98. static void read_file(const std::string &path, std::string &out) {
  99. std::ifstream fs(path, std::ios_base::binary);
  100. if (!fs) {
  101. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  102. return;
  103. #else
  104. throw std::runtime_error("File not found: " + path);
  105. #endif
  106. }
  107. fs.seekg(0, std::ios_base::end);
  108. auto size = fs.tellg();
  109. fs.seekg(0);
  110. out.resize(static_cast<size_t>(size));
  111. fs.read(&out[0], static_cast<std::streamsize>(size));
  112. }
  113. class UnixSocketTest : public ::testing::Test {
  114. protected:
  115. void TearDown() override { std::remove(pathname_.c_str()); }
  116. void client_GET(const std::string &addr) {
  117. httplib::Client cli{addr};
  118. cli.set_address_family(AF_UNIX);
  119. ASSERT_TRUE(cli.is_valid());
  120. const auto &result = cli.Get(pattern_);
  121. ASSERT_TRUE(result) << "error: " << result.error();
  122. const auto &resp = result.value();
  123. EXPECT_EQ(resp.status, StatusCode::OK_200);
  124. EXPECT_EQ(resp.body, content_);
  125. }
  126. static std::string make_sock_path() {
  127. const char *shard = getenv("GTEST_SHARD_INDEX");
  128. return shard ? std::string("./httplib-server-") + shard + ".sock"
  129. : "./httplib-server.sock";
  130. }
  131. const std::string pathname_{make_sock_path()};
  132. const std::string pattern_{"/hi"};
  133. const std::string content_{"Hello World!"};
  134. };
  135. TEST_F(UnixSocketTest, pathname) {
  136. httplib::Server svr;
  137. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  138. res.set_content(content_, "text/plain");
  139. });
  140. std::thread t{[&] {
  141. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  142. }};
  143. auto se = detail::scope_exit([&] {
  144. svr.stop();
  145. t.join();
  146. ASSERT_FALSE(svr.is_running());
  147. });
  148. svr.wait_until_ready();
  149. ASSERT_TRUE(svr.is_running());
  150. client_GET(pathname_);
  151. }
  152. #if defined(__linux__) || \
  153. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  154. TEST_F(UnixSocketTest, PeerPid) {
  155. httplib::Server svr;
  156. std::string remote_port_val;
  157. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  158. res.set_content(content_, "text/plain");
  159. remote_port_val = std::to_string(req.remote_port);
  160. });
  161. std::thread t{[&] {
  162. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  163. }};
  164. auto se = detail::scope_exit([&] {
  165. svr.stop();
  166. t.join();
  167. ASSERT_FALSE(svr.is_running());
  168. });
  169. svr.wait_until_ready();
  170. ASSERT_TRUE(svr.is_running());
  171. client_GET(pathname_);
  172. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  173. }
  174. #endif
  175. #ifdef __linux__
  176. TEST_F(UnixSocketTest, abstract) {
  177. constexpr char svr_path[]{"\x00httplib-server.sock"};
  178. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  179. httplib::Server svr;
  180. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  181. res.set_content(content_, "text/plain");
  182. });
  183. std::thread t{[&] {
  184. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  185. }};
  186. auto se = detail::scope_exit([&] {
  187. svr.stop();
  188. t.join();
  189. ASSERT_FALSE(svr.is_running());
  190. });
  191. svr.wait_until_ready();
  192. ASSERT_TRUE(svr.is_running());
  193. client_GET(abstract_addr);
  194. }
  195. #endif
  196. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  197. httplib::Server svr;
  198. std::string received_host_header;
  199. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  200. // Capture the Host header sent by the client
  201. auto host_iter = req.headers.find("Host");
  202. if (host_iter != req.headers.end()) {
  203. received_host_header = host_iter->second;
  204. }
  205. res.set_content(content_, "text/plain");
  206. });
  207. std::thread t{[&] {
  208. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  209. }};
  210. auto se = detail::scope_exit([&] {
  211. svr.stop();
  212. t.join();
  213. ASSERT_FALSE(svr.is_running());
  214. });
  215. svr.wait_until_ready();
  216. ASSERT_TRUE(svr.is_running());
  217. // Test that Host header is automatically set to "localhost" for Unix socket
  218. // connections
  219. httplib::Client cli{pathname_};
  220. cli.set_address_family(AF_UNIX);
  221. ASSERT_TRUE(cli.is_valid());
  222. const auto &result = cli.Get(pattern_);
  223. ASSERT_TRUE(result) << "error: " << result.error();
  224. const auto &resp = result.value();
  225. EXPECT_EQ(resp.status, StatusCode::OK_200);
  226. EXPECT_EQ(resp.body, content_);
  227. // Verify that Host header was automatically set to "localhost"
  228. EXPECT_EQ(received_host_header, "localhost");
  229. }
  230. #ifndef _WIN32
  231. TEST(SocketStream, wait_writable_UNIX) {
  232. int fds[2];
  233. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  234. const auto asSocketStream = [&](socket_t fd,
  235. std::function<bool(Stream &)> func) {
  236. return detail::process_client_socket(
  237. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  238. };
  239. asSocketStream(fds[0], [&](Stream &s0) {
  240. EXPECT_EQ(s0.socket(), fds[0]);
  241. EXPECT_TRUE(s0.wait_writable());
  242. EXPECT_TRUE(s0.is_peer_alive());
  243. EXPECT_EQ(0, close(fds[1]));
  244. EXPECT_FALSE(s0.is_peer_alive());
  245. return true;
  246. });
  247. EXPECT_EQ(0, close(fds[0]));
  248. }
  249. TEST(SocketStream, wait_writable_INET) {
  250. sockaddr_in addr;
  251. memset(&addr, 0, sizeof(addr));
  252. addr.sin_family = AF_INET;
  253. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  254. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  255. int disconnected_svr_sock = -1;
  256. std::thread svr{[&] {
  257. const int s = socket(AF_INET, SOCK_STREAM, 0);
  258. ASSERT_LE(0, s);
  259. // PORT + 1 is shared with the SSL redirect tests and with
  260. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  261. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  262. // because that happens on a worker thread the ASSERT does not stop the
  263. // test: it runs on and fails at the disconnected_svr_sock check instead.
  264. default_socket_options(s);
  265. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  266. ASSERT_EQ(0, listen(s, 1));
  267. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  268. ASSERT_EQ(0, close(s));
  269. }};
  270. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  271. std::thread cli{[&] {
  272. const int s = socket(AF_INET, SOCK_STREAM, 0);
  273. ASSERT_LE(0, s);
  274. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  275. ASSERT_EQ(0, close(s));
  276. }};
  277. cli.join();
  278. svr.join();
  279. ASSERT_NE(disconnected_svr_sock, -1);
  280. const auto asSocketStream = [&](socket_t fd,
  281. std::function<bool(Stream &)> func) {
  282. return detail::process_client_socket(
  283. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  284. };
  285. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  286. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  287. // wait_writable() returns true because select_write() only checks if the
  288. // send buffer has space. Peer disconnection is detected later by send().
  289. EXPECT_TRUE(ss.wait_writable());
  290. return true;
  291. });
  292. ASSERT_EQ(0, close(disconnected_svr_sock));
  293. }
  294. #endif // #ifndef _WIN32
  295. TEST(SetSocketOptTest, TcpNoDelay) {
  296. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  297. ASSERT_NE(sock, INVALID_SOCKET);
  298. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  299. int val = 0;
  300. socklen_t len = sizeof(val);
  301. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  302. reinterpret_cast<char *>(&val), &len));
  303. EXPECT_NE(val, 0);
  304. detail::close_socket(sock);
  305. }
  306. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  307. // accept() reports failures through WSAGetLastError() on Windows and through
  308. // errno everywhere else. Asking the wrong one is what made the accept loop
  309. // treat every recoverable failure as fatal on Windows.
  310. struct Classification {
  311. bool resource;
  312. bool transient;
  313. };
  314. auto classify = [](int err) {
  315. #ifdef _WIN32
  316. WSASetLastError(err);
  317. #else
  318. errno = err;
  319. #endif
  320. // Read both before asserting: an assertion may clobber the error slot.
  321. Classification c;
  322. c.resource = detail::is_accept_resource_error();
  323. c.transient = detail::is_accept_transient_error();
  324. return c;
  325. };
  326. #ifdef _WIN32
  327. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  328. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  329. WSAECONNRESET, WSAECONNABORTED};
  330. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  331. #else
  332. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  333. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  334. ECONNABORTED};
  335. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  336. #endif
  337. for (auto err : resource_errors) {
  338. const auto c = classify(err);
  339. EXPECT_TRUE(c.resource) << "error " << err;
  340. EXPECT_FALSE(c.transient) << "error " << err;
  341. }
  342. for (auto err : transient_errors) {
  343. const auto c = classify(err);
  344. EXPECT_TRUE(c.transient) << "error " << err;
  345. EXPECT_FALSE(c.resource) << "error " << err;
  346. }
  347. for (auto err : fatal_errors) {
  348. const auto c = classify(err);
  349. EXPECT_FALSE(c.resource) << "error " << err;
  350. EXPECT_FALSE(c.transient) << "error " << err;
  351. }
  352. #ifdef _WIN32
  353. WSASetLastError(0);
  354. #else
  355. errno = 0;
  356. #endif
  357. }
  358. TEST(ClientTest, MoveConstructible) {
  359. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  360. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  361. }
  362. TEST(ClientTest, MoveAssignable) {
  363. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  364. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  365. }
  366. #ifdef _WIN32
  367. TEST(StartupTest, WSAStartup) {
  368. WSADATA wsaData;
  369. int ret = WSAStartup(0x0002, &wsaData);
  370. ASSERT_EQ(0, ret);
  371. }
  372. #endif
  373. TEST(DecodePathTest, PercentCharacter) {
  374. EXPECT_EQ(
  375. decode_path_component(
  376. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  377. U8("descrip=Gastos áéíóúñÑ 6"));
  378. }
  379. TEST(DecodePathTest, PercentCharacterNUL) {
  380. string expected;
  381. expected.push_back('x');
  382. expected.push_back('\0');
  383. expected.push_back('x');
  384. EXPECT_EQ(decode_path_component("x%00x"), expected);
  385. }
  386. TEST(DecodePathTest, UnicodeEncoding) {
  387. // %u0041 = 'A' (1-byte UTF-8)
  388. EXPECT_EQ("A", decode_path_component("%u0041"));
  389. // %u00E9 = 'é' (2-byte UTF-8)
  390. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  391. // %u3042 = 'あ' (3-byte UTF-8)
  392. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  393. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  394. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  395. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  396. // neighbours)
  397. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  398. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  399. }
  400. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  401. // A sign or whitespace inside the two-character escape window must not be
  402. // accepted as a valid percent-encoding; the sequence is passed through
  403. // literally, matching decode_uri_component / decode_path_component.
  404. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  405. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  406. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  407. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  408. // Well-formed escapes still decode.
  409. EXPECT_EQ("-", decode_query_component("%2D", false));
  410. EXPECT_EQ("A", decode_query_component("%41", false));
  411. }
  412. TEST(SanitizeFilenameTest, VariousPatterns) {
  413. // Path traversal
  414. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  415. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  416. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  417. // Normal and edge cases
  418. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  419. EXPECT_EQ("filename.txt",
  420. httplib::sanitize_filename("/path/to/filename.txt"));
  421. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  422. EXPECT_EQ("", httplib::sanitize_filename(".."));
  423. EXPECT_EQ("", httplib::sanitize_filename(""));
  424. // Null bytes stripped
  425. EXPECT_EQ("safe.txt",
  426. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  427. // Whitespace-only rejected
  428. EXPECT_EQ("", httplib::sanitize_filename(" "));
  429. }
  430. // Forward declaration (see the base64_encode note below): split builds move the
  431. // definition into httplib.cc, so re-declaring it here lets the test link.
  432. namespace httplib {
  433. namespace detail {
  434. bool is_chunked_transfer_encoding(const Headers &headers);
  435. } // namespace detail
  436. } // namespace httplib
  437. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  438. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  439. auto make = [](std::initializer_list<const char *> lines) {
  440. Headers h;
  441. for (auto te : lines) {
  442. if (te) { h.emplace("Transfer-Encoding", te); }
  443. }
  444. return h;
  445. };
  446. // Sole coding, matched case-insensitively.
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  448. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  450. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  452. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  453. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  454. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  455. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  456. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  457. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  458. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  459. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  460. // were received, into one list. Headers preserves that order, so the answer
  461. // is decided by the last coding of the last line and the order the lines
  462. // arrived in is significant.
  463. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  464. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  465. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  466. // The split can fall anywhere in the list.
  467. EXPECT_TRUE(
  468. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  469. EXPECT_FALSE(
  470. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  471. // A trailing line naming no coding leaves the list ending in nothing, so it
  472. // must not inherit the chunked from the line before it.
  473. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  474. }
  475. // Forward declarations (see the base64_encode note below).
  476. namespace httplib {
  477. namespace detail {
  478. bool parse_status_line(const char *line, std::string &version, int &status,
  479. std::string &reason);
  480. std::string file_extension(const std::string &path);
  481. std::string
  482. find_content_type(const std::string &path,
  483. const std::map<std::string, std::string> &user_data,
  484. const std::string &default_content_type);
  485. bool can_compress_content_type(const std::string &content_type);
  486. bool is_prohibited_header_name(const std::string &name);
  487. #ifdef CPPHTTPLIB_SSL_ENABLED
  488. bool match_hostname(const std::string &pattern, const std::string &hostname);
  489. #endif
  490. } // namespace detail
  491. } // namespace httplib
  492. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  493. struct {
  494. const char *line;
  495. const char *version;
  496. int status;
  497. const char *reason;
  498. } cases[] = {
  499. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  500. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  501. // The reason phrase may be empty, or left out along with its space.
  502. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  503. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  504. };
  505. for (const auto &c : cases) {
  506. std::string version;
  507. int status = 0;
  508. std::string reason = "unset";
  509. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  510. << c.line;
  511. EXPECT_EQ(c.version, version);
  512. EXPECT_EQ(c.status, status);
  513. EXPECT_EQ(c.reason, reason);
  514. }
  515. }
  516. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  517. const char *lines[] = {
  518. "HTTP/2 200 OK\r\n",
  519. "HTTP/1.2 200 OK\r\n",
  520. "HTTP/1.1 20 OK\r\n",
  521. "HTTP/1.1 2000 OK\r\n",
  522. "HTTP/1.1 2x0 OK\r\n",
  523. "HTTP/1.1 200 OK\r\n",
  524. "HTTP/1.1 200OK\r\n",
  525. "HTTP/1.1 200 O\rK\r\n",
  526. "HTTP/1.1 200 OK",
  527. "HTTP/1.1 200 OK\r\nX",
  528. "",
  529. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  530. "HTTP/1.1 200 OK\n",
  531. #endif
  532. };
  533. for (auto line : lines) {
  534. std::string version;
  535. int status = 0;
  536. std::string reason;
  537. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  538. << line;
  539. }
  540. }
  541. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  542. // Long enough to overflow the stack when matched with std::regex.
  543. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  544. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  545. std::string version;
  546. int status = 0;
  547. std::string reason;
  548. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  549. EXPECT_EQ(200, status);
  550. EXPECT_EQ(long_reason, reason);
  551. }
  552. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  553. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  554. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  555. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  556. EXPECT_EQ("", detail::file_extension("noext"));
  557. EXPECT_EQ("", detail::file_extension("a."));
  558. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  559. EXPECT_EQ("", detail::file_extension("a.b-c"));
  560. // Long enough to overflow the stack when matched with std::regex.
  561. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  562. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  563. }
  564. #ifdef CPPHTTPLIB_SSL_ENABLED
  565. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  566. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  567. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  568. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  569. // A wildcard needs two labels after it, in the leftmost label only
  570. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  571. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  572. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  573. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  574. EXPECT_FALSE(
  575. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  576. // No name may have an empty label
  577. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  578. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  579. }
  580. #endif
  581. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  582. detail::case_ignore::hash hash;
  583. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  584. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  585. // Long enough to overflow the stack if hashed one call per character.
  586. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  587. }
  588. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  589. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  590. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  591. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  592. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  593. // Same 26-bit hash as html, svg and js.
  594. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  595. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  596. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  597. }
  598. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  599. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  600. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  601. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  602. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  603. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  604. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  605. // Same 26-bit hash as application/json.
  606. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  607. }
  608. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  609. Request req;
  610. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  611. EXPECT_TRUE(req.is_multipart_form_data());
  612. std::string boundary;
  613. EXPECT_TRUE(detail::parse_multipart_boundary(
  614. req.get_header_value("Content-Type"), boundary));
  615. EXPECT_EQ("x", boundary);
  616. }
  617. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  618. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  619. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  620. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  621. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  622. // Same 26-bit hash as REMOTE_ADDR.
  623. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  624. }
  625. // Forward declaration: in split builds split.py strips `inline` and moves the
  626. // definition into httplib.cc, so detail::base64_encode is not visible from the
  627. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  628. // in both header-only and split builds.
  629. namespace httplib {
  630. namespace detail {
  631. std::string base64_encode(const std::string &in);
  632. } // namespace detail
  633. } // namespace httplib
  634. TEST(Base64EncodeTest, KnownAnswers) {
  635. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  636. // where the accumulator's top bit is already set before the next shift.
  637. EXPECT_EQ("", detail::base64_encode(""));
  638. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  639. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  640. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  641. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  642. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  643. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  644. // High bytes keep the top bit set across several rounds.
  645. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  646. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  647. }
  648. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  649. string unescapedCharacters = "-_.!~*'()";
  650. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  651. }
  652. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  653. string reservedCharacters = ";,/?:@&=+$";
  654. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  655. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  656. }
  657. TEST(ClientQueryOrder, PreserveOrder) {
  658. // This test reproduces Issue #2259: client may reorder query parameters
  659. // when sending a GET request. The expected behavior is that the client
  660. // preserves the original query string order when the caller supplied it
  661. // as part of the path.
  662. Server svr;
  663. svr.Get("/", [&](const Request &req, Response &res) {
  664. // Echo back the raw target so the test can assert ordering
  665. res.set_content(req.target, "text/plain");
  666. });
  667. std::thread t{[&] { svr.listen(HOST, PORT); }};
  668. auto se = detail::scope_exit([&] {
  669. svr.stop();
  670. t.join();
  671. ASSERT_FALSE(svr.is_running());
  672. });
  673. svr.wait_until_ready();
  674. Client cli(HOST, PORT);
  675. ASSERT_TRUE(cli.is_valid());
  676. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  677. auto res = cli.Get(original);
  678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  679. // Expect the echoed target to exactly match the original path (order
  680. // preserved)
  681. EXPECT_EQ(res->body, original);
  682. }
  683. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  684. string chineseCharacters = U8("中国語");
  685. string russianCharacters = U8("дом");
  686. string brazilianCharacters = U8("óculos");
  687. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  688. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  689. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  690. "%D0%B4%D0%BE%D0%BC");
  691. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  692. }
  693. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  694. string unescapedCharacters = "-_.!~*'()";
  695. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  696. }
  697. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  698. string reservedCharacters = ";,/?:@&=+$";
  699. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  700. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  701. }
  702. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  703. string chineseCharacters = U8("中国語");
  704. string russianCharacters = U8("дом");
  705. string brazilianCharacters = U8("óculos");
  706. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  707. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  708. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  709. "%D0%B4%D0%BE%D0%BC");
  710. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  711. }
  712. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  713. // Issue #2082 use case: encoding path component with ampersand
  714. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  715. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  716. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  717. }
  718. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  719. string unescapedCharacters = "-_.!~*'()";
  720. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  721. }
  722. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  723. string reservedCharacters = ";,/?:@&=+$#";
  724. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  725. }
  726. TEST(EncodeUriTest, TestUTF8Characters) {
  727. string chineseCharacters = U8("中国語");
  728. string russianCharacters = U8("дом");
  729. string brazilianCharacters = U8("óculos");
  730. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  731. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  732. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  733. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  734. }
  735. TEST(EncodeUriTest, TestCompleteUri) {
  736. string uri =
  737. "https://example.com/path/to/resource?query=value&param=test#fragment";
  738. EXPECT_EQ(
  739. httplib::encode_uri(uri),
  740. "https://example.com/path/to/resource?query=value&param=test#fragment");
  741. }
  742. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  743. string uri =
  744. "https://example.com/path with spaces/file name.html?q=hello world";
  745. EXPECT_EQ(httplib::encode_uri(uri),
  746. "https://example.com/path%20with%20spaces/"
  747. "file%20name.html?q=hello%20world");
  748. }
  749. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  750. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  751. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  752. }
  753. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  754. string unescapedCharacters = "-_.!~*'()";
  755. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  756. }
  757. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  758. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  759. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  760. string encodedBrazilian = "%C3%B3culos";
  761. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  762. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  763. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  764. }
  765. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  766. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  767. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  768. "Piri Tommy Villiers - on & on");
  769. }
  770. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  771. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  772. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  773. }
  774. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  775. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  776. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  777. }
  778. TEST(DecodeUriTest, TestUTF8Characters) {
  779. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  780. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  781. string encodedBrazilian = "%C3%B3culos";
  782. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  783. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  784. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  785. }
  786. TEST(DecodeUriTest, TestCompleteUri) {
  787. string encodedUri = "https://example.com/path%20with%20spaces/"
  788. "file%20name.html?q=hello%20world";
  789. EXPECT_EQ(
  790. httplib::decode_uri(encodedUri),
  791. "https://example.com/path with spaces/file name.html?q=hello world");
  792. }
  793. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  794. string original =
  795. "https://example.com/path with spaces/file name.html?q=hello world";
  796. string encoded = httplib::encode_uri(original);
  797. string decoded = httplib::decode_uri(encoded);
  798. EXPECT_EQ(decoded, original);
  799. }
  800. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  801. // decode_uri is the inverse of encode_uri: an escaped reserved character
  802. // stays encoded so it is not promoted into a real delimiter, while
  803. // non-reserved escapes still decode (like JS decodeURI).
  804. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  805. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  806. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  807. "%3F%3A%40%26%3D%2B%24%2C%3B");
  808. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  809. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  810. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  811. "http://example.com/a%2Fb");
  812. // decode_uri_component still decodes the reserved character.
  813. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  814. }
  815. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  816. string original = "Piri Tommy Villiers - on & on";
  817. string encoded = httplib::encode_uri_component(original);
  818. string decoded = httplib::decode_uri_component(encoded);
  819. EXPECT_EQ(decoded, original);
  820. }
  821. TEST(TrimTests, TrimStringTests) {
  822. EXPECT_EQ("abc", detail::trim_copy("abc"));
  823. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  824. EXPECT_TRUE(detail::trim_copy("").empty());
  825. }
  826. TEST(AsciiTest, LocaleIndependentClassification) {
  827. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  828. // which consult the global C locale: std::isalnum(0xC5) can return true
  829. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  830. // helpers must classify every byte by the ASCII grammar alone.
  831. for (int i = 0; i < 256; i++) {
  832. auto c = static_cast<char>(i);
  833. auto is_digit = i >= '0' && i <= '9';
  834. auto is_upper = i >= 'A' && i <= 'Z';
  835. auto is_lower = i >= 'a' && i <= 'z';
  836. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  837. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  838. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  839. << "byte " << i;
  840. }
  841. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  842. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  843. // Non-ASCII bytes must be percent-encoded, never passed through as
  844. // alphanumeric.
  845. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  846. }
  847. TEST(FromCharsTest, Double) {
  848. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  849. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  850. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  851. auto parse = [](const std::string &s, double &v) {
  852. return detail::from_chars(s.data(), s.data() + s.size(), v);
  853. };
  854. double v = -1.0;
  855. // Representative quality values.
  856. EXPECT_EQ(parse("0", v).ec, std::errc{});
  857. EXPECT_DOUBLE_EQ(v, 0.0);
  858. EXPECT_EQ(parse("1", v).ec, std::errc{});
  859. EXPECT_DOUBLE_EQ(v, 1.0);
  860. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  861. EXPECT_DOUBLE_EQ(v, 0.8);
  862. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  863. EXPECT_DOUBLE_EQ(v, 0.001);
  864. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  865. EXPECT_DOUBLE_EQ(v, 1.0);
  866. // A missing integer or fractional part is tolerated.
  867. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  868. EXPECT_DOUBLE_EQ(v, 0.5);
  869. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  870. EXPECT_DOUBLE_EQ(v, 5.0);
  871. // Values outside [0, 1] still parse; the caller range-checks them.
  872. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  873. EXPECT_DOUBLE_EQ(v, 123.456);
  874. // Stops at the first byte that is not part of the number and reports where.
  875. std::string trailing = "0.9, text/html";
  876. auto r = parse(trailing, v);
  877. EXPECT_EQ(r.ec, std::errc{});
  878. EXPECT_DOUBLE_EQ(v, 0.9);
  879. EXPECT_EQ(*r.ptr, ',');
  880. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  881. // outright, and an 'e'/'E' simply ends the number.
  882. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  883. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  884. std::string exp_input = "1.5e3";
  885. r = parse(exp_input, v);
  886. EXPECT_EQ(r.ec, std::errc{});
  887. EXPECT_DOUBLE_EQ(v, 1.5);
  888. EXPECT_EQ(*r.ptr, 'e');
  889. // Invalid inputs.
  890. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  891. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  892. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  893. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  894. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  895. // Pathological but well-formed inputs must stay bounded (no overflow, no
  896. // out-of-bounds table access) and stay within [0, 1] for the caller.
  897. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  898. std::errc{});
  899. EXPECT_DOUBLE_EQ(v, 0.0);
  900. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  901. std::errc{});
  902. EXPECT_GE(v, 0.0);
  903. EXPECT_LE(v, 1.0);
  904. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  905. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  906. }
  907. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  908. // Simple case without quality values
  909. std::vector<std::string> result1;
  910. EXPECT_TRUE(detail::parse_accept_header(
  911. "text/html,application/json,text/plain", result1));
  912. EXPECT_EQ(result1.size(), 3U);
  913. EXPECT_EQ(result1[0], "text/html");
  914. EXPECT_EQ(result1[1], "application/json");
  915. EXPECT_EQ(result1[2], "text/plain");
  916. // With quality values
  917. std::vector<std::string> result2;
  918. EXPECT_TRUE(detail::parse_accept_header(
  919. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  920. EXPECT_EQ(result2.size(), 3U);
  921. EXPECT_EQ(result2[0], "application/json"); // highest q value
  922. EXPECT_EQ(result2[1], "text/html");
  923. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  924. }
  925. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  926. // Mixed with and without quality values
  927. std::vector<std::string> result;
  928. EXPECT_TRUE(detail::parse_accept_header(
  929. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  930. EXPECT_EQ(result.size(), 3U);
  931. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  932. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  933. EXPECT_EQ(result[2], "application/json"); // q=0.5
  934. }
  935. TEST(ParseAcceptHeaderTest, EdgeCases) {
  936. // Empty header
  937. std::vector<std::string> empty_result;
  938. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  939. EXPECT_TRUE(empty_result.empty());
  940. // Single type
  941. std::vector<std::string> single_result;
  942. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  943. EXPECT_EQ(single_result.size(), 1U);
  944. EXPECT_EQ(single_result[0], "application/json");
  945. // Wildcard types
  946. std::vector<std::string> wildcard_result;
  947. EXPECT_TRUE(detail::parse_accept_header(
  948. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  949. EXPECT_EQ(wildcard_result.size(), 3U);
  950. EXPECT_EQ(wildcard_result[0], "application/json");
  951. EXPECT_EQ(wildcard_result[1], "text/*");
  952. EXPECT_EQ(wildcard_result[2], "*/*");
  953. }
  954. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  955. // Common browser Accept header
  956. std::vector<std::string> browser_result;
  957. EXPECT_TRUE(
  958. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  959. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  960. browser_result));
  961. EXPECT_EQ(browser_result.size(), 6U);
  962. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  963. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  964. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  965. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  966. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  967. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  968. // API client header
  969. std::vector<std::string> api_result;
  970. EXPECT_TRUE(detail::parse_accept_header(
  971. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  972. api_result));
  973. EXPECT_EQ(api_result.size(), 3U);
  974. EXPECT_EQ(api_result[0], "application/json");
  975. EXPECT_EQ(api_result[1], "application/xml");
  976. EXPECT_EQ(api_result[2], "text/plain");
  977. }
  978. TEST(ParseAcceptHeaderTest, SpecialCases) {
  979. // Quality value with 3 decimal places
  980. std::vector<std::string> decimal_result;
  981. EXPECT_TRUE(detail::parse_accept_header(
  982. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  983. EXPECT_EQ(decimal_result.size(), 2U);
  984. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  985. EXPECT_EQ(decimal_result[1], "text/html");
  986. // Zero quality (should still be included but with lowest priority)
  987. std::vector<std::string> zero_q_result;
  988. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  989. zero_q_result));
  990. EXPECT_EQ(zero_q_result.size(), 2U);
  991. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  992. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  993. // No spaces around commas
  994. std::vector<std::string> no_space_result;
  995. EXPECT_TRUE(detail::parse_accept_header(
  996. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  997. no_space_result));
  998. EXPECT_EQ(no_space_result.size(), 3U);
  999. EXPECT_EQ(no_space_result[0], "text/html");
  1000. EXPECT_EQ(no_space_result[1], "application/json");
  1001. EXPECT_EQ(no_space_result[2], "text/plain");
  1002. }
  1003. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1004. // Quality values always use '.' as the decimal separator, so parsing must
  1005. // not depend on the process locale. An embedding application may have
  1006. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1007. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1008. std::string saved = cur ? cur : "C";
  1009. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1010. "fr_FR.UTF-8"};
  1011. bool switched = false;
  1012. for (const auto loc : comma_locales) {
  1013. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1014. std::localeconv()->decimal_point[0] == ',') {
  1015. switched = true;
  1016. break;
  1017. }
  1018. }
  1019. if (!switched) {
  1020. std::setlocale(LC_NUMERIC, saved.c_str());
  1021. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1022. }
  1023. // The higher-weighted type appears later in the list, so a correct parse
  1024. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1025. // sensitive parse reads both weights as 0 and leaves the original order.
  1026. std::vector<std::string> result;
  1027. EXPECT_TRUE(detail::parse_accept_header(
  1028. "application/json;q=0.1,text/html;q=0.9", result));
  1029. ASSERT_EQ(result.size(), 2U);
  1030. EXPECT_EQ(result[0], "text/html");
  1031. EXPECT_EQ(result[1], "application/json");
  1032. std::setlocale(LC_NUMERIC, saved.c_str());
  1033. }
  1034. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1035. std::vector<std::string> result;
  1036. // Invalid quality value (> 1.0)
  1037. EXPECT_FALSE(
  1038. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1039. // Invalid quality value (< 0.0)
  1040. EXPECT_FALSE(
  1041. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1042. // Invalid quality value (not a number)
  1043. EXPECT_FALSE(detail::parse_accept_header(
  1044. "text/html;q=invalid,application/json", result));
  1045. // A valid numeric prefix does not make the entire quality value valid.
  1046. EXPECT_FALSE(detail::parse_accept_header(
  1047. "text/html;q=0.5junk,application/json", result));
  1048. // Empty quality value
  1049. EXPECT_FALSE(
  1050. detail::parse_accept_header("text/html;q=,application/json", result));
  1051. // Invalid media type format (no slash and not wildcard)
  1052. EXPECT_FALSE(
  1053. detail::parse_accept_header("invalidtype,application/json", result));
  1054. // Valid cases should still work
  1055. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1056. EXPECT_EQ(result.size(), 1U);
  1057. EXPECT_EQ(result[0], "*/*");
  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("text/*", result));
  1062. EXPECT_EQ(result.size(), 1U);
  1063. EXPECT_EQ(result[0], "text/*");
  1064. }
  1065. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1066. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1067. // and must not be answered with 400 Bad Request.
  1068. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1069. struct {
  1070. const char *value;
  1071. std::vector<std::string> expected;
  1072. } cases[] = {
  1073. {",application/json", {"application/json"}},
  1074. {"text/html,", {"text/html"}},
  1075. {"text/html,,*/*", {"text/html", "*/*"}},
  1076. // An empty element may be spelled with whitespace in it
  1077. {"text/html, , application/json", {"text/html", "application/json"}},
  1078. // Nothing but empty elements is an empty list, which means the same
  1079. // thing as no Accept header at all
  1080. {",,,", {}},
  1081. // Quality values still apply across ignored empty elements
  1082. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1083. };
  1084. for (const auto &c : cases) {
  1085. std::vector<std::string> result;
  1086. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1087. << "value: " << c.value;
  1088. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1089. }
  1090. // An invalid entry is still rejected when empty elements surround it
  1091. std::vector<std::string> result;
  1092. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1093. }
  1094. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1095. // or ';' inside one does not end the list element or the parameter. Section
  1096. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1097. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1098. struct {
  1099. const char *value;
  1100. std::vector<std::string> expected;
  1101. } cases[] = {
  1102. {"text/html;profile=\"a,b\",application/json",
  1103. {"text/html", "application/json"}},
  1104. // A "q=" inside a quoted value is not the weight
  1105. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1106. {"text/html", "application/json"}},
  1107. // The weight after a quoted value still applies
  1108. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1109. {"application/json", "text/html"}},
  1110. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1111. {"application/json", "text/html"}},
  1112. {"text/html;profile=\"a\\\"b\",application/json",
  1113. {"text/html", "application/json"}},
  1114. // An escaped backslash does not escape the '"' after it
  1115. {"text/html;profile=\"a\\\\\",application/json",
  1116. {"text/html", "application/json"}},
  1117. };
  1118. for (const auto &c : cases) {
  1119. std::vector<std::string> result;
  1120. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1121. << "value: " << c.value;
  1122. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1123. }
  1124. }
  1125. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1126. Server svr;
  1127. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1128. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1129. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1130. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1131. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1132. res.set_content("ok", "text/plain");
  1133. });
  1134. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1135. EXPECT_TRUE(false);
  1136. res.set_content("bad request", "text/plain");
  1137. });
  1138. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1139. auto se = detail::scope_exit([&] {
  1140. svr.stop();
  1141. listen_thread.join();
  1142. ASSERT_FALSE(svr.is_running());
  1143. });
  1144. svr.wait_until_ready();
  1145. Client cli("localhost", PORT);
  1146. {
  1147. auto res = cli.Get(
  1148. "/accept_ok",
  1149. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1151. EXPECT_EQ(StatusCode::OK_200, res->status);
  1152. }
  1153. {
  1154. auto res = cli.Get("/accept_bad_request",
  1155. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1157. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1158. }
  1159. }
  1160. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1161. Server svr;
  1162. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1163. res.set_content("ok", "text/plain");
  1164. });
  1165. std::atomic<int> start_count{0};
  1166. std::atomic<bool> running_when_called{false};
  1167. svr.set_start_handler([&]() {
  1168. running_when_called = svr.is_running();
  1169. start_count++;
  1170. });
  1171. auto port = svr.bind_to_any_port(HOST);
  1172. std::thread t([&]() { svr.listen_after_bind(); });
  1173. auto se = detail::scope_exit([&] {
  1174. svr.stop();
  1175. t.join();
  1176. ASSERT_FALSE(svr.is_running());
  1177. });
  1178. svr.wait_until_ready();
  1179. // A successful request proves the accept loop is running, which the start
  1180. // handler precedes; so by now the handler must have run exactly once.
  1181. Client cli(HOST, port);
  1182. cli.set_connection_timeout(std::chrono::seconds(5));
  1183. auto res = cli.Get("/");
  1184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1185. EXPECT_EQ(StatusCode::OK_200, res->status);
  1186. EXPECT_EQ(1, start_count.load());
  1187. EXPECT_TRUE(running_when_called.load());
  1188. }
  1189. TEST(DivideTest, DivideStringTests) {
  1190. auto divide = [](const std::string &str, char d) {
  1191. std::string lhs;
  1192. std::string rhs;
  1193. detail::divide(str, d,
  1194. [&](const char *lhs_data, std::size_t lhs_size,
  1195. const char *rhs_data, std::size_t rhs_size) {
  1196. lhs.assign(lhs_data, lhs_size);
  1197. rhs.assign(rhs_data, rhs_size);
  1198. });
  1199. return std::make_pair(std::move(lhs), std::move(rhs));
  1200. };
  1201. {
  1202. const auto res = divide("", '=');
  1203. EXPECT_EQ(res.first, "");
  1204. EXPECT_EQ(res.second, "");
  1205. }
  1206. {
  1207. const auto res = divide("=", '=');
  1208. EXPECT_EQ(res.first, "");
  1209. EXPECT_EQ(res.second, "");
  1210. }
  1211. {
  1212. const auto res = divide(" ", '=');
  1213. EXPECT_EQ(res.first, " ");
  1214. EXPECT_EQ(res.second, "");
  1215. }
  1216. {
  1217. const auto res = divide("a", '=');
  1218. EXPECT_EQ(res.first, "a");
  1219. EXPECT_EQ(res.second, "");
  1220. }
  1221. {
  1222. const auto res = divide("a=", '=');
  1223. EXPECT_EQ(res.first, "a");
  1224. EXPECT_EQ(res.second, "");
  1225. }
  1226. {
  1227. const auto res = divide("=b", '=');
  1228. EXPECT_EQ(res.first, "");
  1229. EXPECT_EQ(res.second, "b");
  1230. }
  1231. {
  1232. const auto res = divide("a=b", '=');
  1233. EXPECT_EQ(res.first, "a");
  1234. EXPECT_EQ(res.second, "b");
  1235. }
  1236. {
  1237. const auto res = divide("a=b=", '=');
  1238. EXPECT_EQ(res.first, "a");
  1239. EXPECT_EQ(res.second, "b=");
  1240. }
  1241. {
  1242. const auto res = divide("a=b=c", '=');
  1243. EXPECT_EQ(res.first, "a");
  1244. EXPECT_EQ(res.second, "b=c");
  1245. }
  1246. }
  1247. TEST(SplitTest, ParseQueryString) {
  1248. string s = "key1=val1&key2=val2&key3=val3";
  1249. Params dic;
  1250. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1251. [&](const char *b, const char *e) {
  1252. string key, val;
  1253. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1254. if (key.empty()) {
  1255. key.assign(b2, e2);
  1256. } else {
  1257. val.assign(b2, e2);
  1258. }
  1259. });
  1260. dic.emplace(key, val);
  1261. });
  1262. EXPECT_EQ("val1", dic.find("key1")->second);
  1263. EXPECT_EQ("val2", dic.find("key2")->second);
  1264. EXPECT_EQ("val3", dic.find("key3")->second);
  1265. }
  1266. TEST(SplitTest, ParseInvalidQueryTests) {
  1267. {
  1268. string s = " ";
  1269. Params dict;
  1270. detail::parse_query_text(s, dict);
  1271. EXPECT_TRUE(dict.empty());
  1272. }
  1273. {
  1274. string s = " = =";
  1275. Params dict;
  1276. detail::parse_query_text(s, dict);
  1277. EXPECT_TRUE(dict.empty());
  1278. }
  1279. }
  1280. TEST(ParseQueryTest, ParseQueryString) {
  1281. {
  1282. std::string s = "key1=val1&key2=val2&key3=val3";
  1283. Params dic;
  1284. detail::parse_query_text(s, dic);
  1285. EXPECT_EQ("val1", dic.find("key1")->second);
  1286. EXPECT_EQ("val2", dic.find("key2")->second);
  1287. EXPECT_EQ("val3", dic.find("key3")->second);
  1288. }
  1289. {
  1290. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1291. Params dic;
  1292. detail::parse_query_text(s, dic);
  1293. EXPECT_EQ("", dic.find("key1")->second);
  1294. EXPECT_EQ("val1", dic.find("key2")->second);
  1295. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1296. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1297. }
  1298. }
  1299. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1300. Params dic;
  1301. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1302. dic.emplace("key1", "val1");
  1303. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1304. dic.emplace("key2", "val2");
  1305. dic.emplace("key3", "val3");
  1306. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1307. }
  1308. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1309. Params params;
  1310. params.emplace("a", "1");
  1311. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1312. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1313. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1314. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1315. // Long enough to overflow the stack when matched with std::regex.
  1316. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1317. EXPECT_EQ("/p?" + long_query + "&a=1",
  1318. append_query_params("/p?" + long_query, params));
  1319. }
  1320. // Joins every entry of a Headers or Params into "key=value " so a whole
  1321. // traversal can be compared in one assertion. Both are instantiations of the
  1322. // same insertion-ordered container, so one helper serves both.
  1323. template <typename Map> static std::string entries_to_string(const Map &m) {
  1324. std::string s;
  1325. for (const auto &entry : m) {
  1326. s += entry.first + "=" + entry.second + " ";
  1327. }
  1328. return s;
  1329. }
  1330. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1331. // Params used to be a std::multimap, which sorted by name and handed the
  1332. // caller's query back alphabetised. A client signing its query string could
  1333. // not reproduce the order it asked for.
  1334. Params dic;
  1335. dic.emplace("zulu", "1");
  1336. dic.emplace("alpha", "2");
  1337. dic.emplace("mike", "3");
  1338. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1339. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1340. }
  1341. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1342. Params dic;
  1343. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1344. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1345. }
  1346. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1347. Request req;
  1348. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1349. req.params);
  1350. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1351. EXPECT_EQ("first", req.get_param_value("tag"));
  1352. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1353. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1354. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1355. EXPECT_EQ("", req.get_param_value("tag", 3));
  1356. }
  1357. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1358. // Params shares its container with Headers, which matches field names
  1359. // case-insensitively. Parameter names must not pick that up.
  1360. Params dic;
  1361. dic.emplace("Key", "upper");
  1362. dic.emplace("key", "lower");
  1363. EXPECT_EQ(2U, dic.size());
  1364. EXPECT_EQ(1U, dic.count("Key"));
  1365. EXPECT_EQ(1U, dic.count("key"));
  1366. EXPECT_EQ("upper", dic.find("Key")->second);
  1367. EXPECT_EQ("lower", dic.find("key")->second);
  1368. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1369. }
  1370. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1371. Server svr;
  1372. std::string order;
  1373. svr.Get("/order", [&](const Request &req, Response &res) {
  1374. order = entries_to_string(req.params);
  1375. res.set_content("ok", "text/plain");
  1376. });
  1377. auto port = svr.bind_to_any_port(HOST);
  1378. thread t = thread([&] { svr.listen_after_bind(); });
  1379. auto se = detail::scope_exit([&] {
  1380. svr.stop();
  1381. t.join();
  1382. ASSERT_FALSE(svr.is_running());
  1383. });
  1384. svr.wait_until_ready();
  1385. Client cli(HOST, port);
  1386. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1387. ASSERT_TRUE(res);
  1388. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1389. }
  1390. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1391. Server svr;
  1392. std::string field_order, file_order;
  1393. svr.Post("/order", [&](const Request &req, Response &res) {
  1394. for (const auto &field : req.form.fields) {
  1395. field_order += field.first + "=" + field.second.content + " ";
  1396. }
  1397. for (const auto &file : req.form.files) {
  1398. file_order += file.first + "=" + file.second.filename + " ";
  1399. }
  1400. res.set_content("ok", "text/plain");
  1401. });
  1402. auto port = svr.bind_to_any_port(HOST);
  1403. thread t = thread([&] { svr.listen_after_bind(); });
  1404. auto se = detail::scope_exit([&] {
  1405. svr.stop();
  1406. t.join();
  1407. ASSERT_FALSE(svr.is_running());
  1408. });
  1409. svr.wait_until_ready();
  1410. UploadFormDataItems items = {
  1411. {"zulu", "1", "", ""},
  1412. {"alpha", "2", "", ""},
  1413. {"mike", "3", "", ""},
  1414. {"zebra", "z", "z.txt", "text/plain"},
  1415. {"apple", "a", "a.txt", "text/plain"},
  1416. };
  1417. Client cli(HOST, port);
  1418. auto res = cli.Post("/order", items);
  1419. ASSERT_TRUE(res);
  1420. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1421. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1422. }
  1423. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1424. Server svr;
  1425. std::vector<std::string> values;
  1426. std::string first, second, out_of_range, order;
  1427. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1428. values = req.form.get_fields("tag");
  1429. first = req.form.get_field("tag", 0);
  1430. second = req.form.get_field("tag", 1);
  1431. out_of_range = req.form.get_field("tag", 2);
  1432. for (const auto &field : req.form.fields) {
  1433. order += field.first + "=" + field.second.content + " ";
  1434. }
  1435. res.set_content("ok", "text/plain");
  1436. });
  1437. auto port = svr.bind_to_any_port(HOST);
  1438. thread t = thread([&] { svr.listen_after_bind(); });
  1439. auto se = detail::scope_exit([&] {
  1440. svr.stop();
  1441. t.join();
  1442. ASSERT_FALSE(svr.is_running());
  1443. });
  1444. svr.wait_until_ready();
  1445. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1446. // not adjacent in the container.
  1447. UploadFormDataItems items = {
  1448. {"tag", "first", "", ""},
  1449. {"other", "x", "", ""},
  1450. {"tag", "second", "", ""},
  1451. };
  1452. Client cli(HOST, port);
  1453. auto res = cli.Post("/repeated", items);
  1454. ASSERT_TRUE(res);
  1455. ASSERT_EQ(2U, values.size());
  1456. EXPECT_EQ("first", values[0]);
  1457. EXPECT_EQ("second", values[1]);
  1458. EXPECT_EQ("first", first);
  1459. EXPECT_EQ("second", second);
  1460. // std::multimap already kept entries sharing a name in insertion order, so
  1461. // everything above passes without this change too. The whole traversal is
  1462. // what tells the two apart: sorting by name would hoist "other" to the front
  1463. // and the two "tag" parts would end up adjacent.
  1464. EXPECT_EQ("tag=first other=x tag=second ", order);
  1465. // Advancing past the last entry of a name used to run off the container;
  1466. // the container's saturating increment makes it return the default instead.
  1467. EXPECT_EQ("", out_of_range);
  1468. }
  1469. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1470. // Server::read_content() keeps a FormFields::iterator alive across the
  1471. // content callbacks that fill the part it points at. The container is
  1472. // vector-backed, so a later emplace can reallocate and invalidate an older
  1473. // iterator; 64 parts grow the vector through seven reallocations, which
  1474. // checks that every part's content still lands in its own entry.
  1475. const size_t part_count = 64;
  1476. // One formula for both the parts sent and the values expected back, so the
  1477. // two cannot drift apart.
  1478. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1479. auto content_of = [](size_t i) {
  1480. return std::string(64, static_cast<char>('a' + (i % 26)));
  1481. };
  1482. Server svr;
  1483. std::vector<std::pair<std::string, std::string>> received;
  1484. svr.Post("/many", [&](const Request &req, Response &res) {
  1485. for (const auto &field : req.form.fields) {
  1486. received.emplace_back(field.first, field.second.content);
  1487. }
  1488. res.set_content("ok", "text/plain");
  1489. });
  1490. auto port = svr.bind_to_any_port(HOST);
  1491. thread t = thread([&] { svr.listen_after_bind(); });
  1492. auto se = detail::scope_exit([&] {
  1493. svr.stop();
  1494. t.join();
  1495. ASSERT_FALSE(svr.is_running());
  1496. });
  1497. svr.wait_until_ready();
  1498. UploadFormDataItems items;
  1499. for (size_t i = 0; i < part_count; i++) {
  1500. items.push_back({name_of(i), content_of(i), "", ""});
  1501. }
  1502. Client cli(HOST, port);
  1503. auto res = cli.Post("/many", items);
  1504. ASSERT_TRUE(res);
  1505. ASSERT_EQ(part_count, received.size());
  1506. for (size_t i = 0; i < part_count; i++) {
  1507. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1508. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1509. }
  1510. }
  1511. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1512. string content_type = "multipart/form-data; boundary=something";
  1513. string boundary;
  1514. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1515. EXPECT_TRUE(ret);
  1516. EXPECT_EQ(boundary, "something");
  1517. }
  1518. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1519. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1520. string boundary;
  1521. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1522. EXPECT_TRUE(ret);
  1523. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1524. }
  1525. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1526. string content_type =
  1527. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1528. string boundary;
  1529. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1530. EXPECT_TRUE(ret);
  1531. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1532. }
  1533. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1534. string content_type =
  1535. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1536. string boundary;
  1537. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1538. EXPECT_TRUE(ret);
  1539. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1540. }
  1541. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1542. const string boundary(70, 'a');
  1543. string content_type = "multipart/form-data; boundary=" + boundary;
  1544. string parsed;
  1545. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1546. EXPECT_TRUE(ret);
  1547. EXPECT_EQ(parsed, boundary);
  1548. }
  1549. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1550. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1551. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1552. string parsed;
  1553. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1554. EXPECT_FALSE(ret);
  1555. }
  1556. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1557. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1558. // is 72 characters on the wire and still valid.
  1559. const string boundary(70, 'a');
  1560. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1561. string parsed;
  1562. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1563. EXPECT_EQ(parsed, boundary);
  1564. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1565. parsed.clear();
  1566. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1567. }
  1568. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1569. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1570. // The parameter parser must not treat that '=' as the key/value separator.
  1571. string content_type =
  1572. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1573. "charset=UTF-8";
  1574. string parsed;
  1575. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1576. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1577. }
  1578. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1579. // A ';' inside the quoted-string is part of the value, not a parameter
  1580. // separator, so it must not truncate the boundary.
  1581. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1582. string parsed;
  1583. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1584. EXPECT_EQ(parsed, "a;b");
  1585. }
  1586. TEST(ParseDispositionParamsTest, QuotedValues) {
  1587. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1588. // ';' and '=' are ordinary characters inside one.
  1589. struct {
  1590. const char *value;
  1591. std::vector<std::pair<const char *, const char *>> expected;
  1592. } cases[] = {
  1593. {"name=\"file1\"; filename=\"a.txt\"",
  1594. {{"name", "file1"}, {"filename", "a.txt"}}},
  1595. // Whitespace around '=' and ';' is still trimmed
  1596. {"name=\"file2\" ;filename = \"a.html\"",
  1597. {{"name", "file2"}, {"filename", "a.html"}}},
  1598. // '=' inside the value used to leave only the text after the last one
  1599. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1600. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1601. {"name=\"x=y\"", {{"name", "x=y"}}},
  1602. // ';' inside the value used to truncate the pair and leave a bogus one
  1603. {"name=\"file3\"; filename=\"a;b.txt\"",
  1604. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1605. // An unquoted value keeps working, and so does filename*
  1606. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1607. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1608. // A parameter with no key is dropped rather than turned into one whose
  1609. // key is the value
  1610. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1611. // An escaped quote does not end the value
  1612. {"name=\"a\\\"; filename=evil.php\"",
  1613. {{"name", "a\"; filename=evil.php"}}},
  1614. // Other backslashes, as in a Windows path, are kept
  1615. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1616. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1617. };
  1618. for (const auto &c : cases) {
  1619. Params params;
  1620. detail::parse_disposition_params(c.value, params);
  1621. for (const auto &kv : c.expected) {
  1622. auto it = params.find(kv.first);
  1623. ASSERT_NE(it, params.end())
  1624. << "value: " << c.value << ", key: " << kv.first;
  1625. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1626. }
  1627. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1628. }
  1629. }
  1630. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1631. Server svr;
  1632. std::string filename;
  1633. std::string content;
  1634. svr.Post("/upload", [&](const Request &req, Response &) {
  1635. const auto &file = req.form.get_file("file");
  1636. filename = file.filename;
  1637. content = file.content;
  1638. });
  1639. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1640. auto se = detail::scope_exit([&] {
  1641. svr.stop();
  1642. thread.join();
  1643. ASSERT_FALSE(svr.is_running());
  1644. });
  1645. svr.wait_until_ready();
  1646. std::string body = "--B\r\n"
  1647. "Content-Disposition: form-data; name=\"file\"; "
  1648. "filename=\"a.txt\"\r\n"
  1649. "Content-Type: text/plain\r\n"
  1650. "\r\n"
  1651. "hello\r\n"
  1652. "--B--\r\n";
  1653. Client cli(HOST, PORT);
  1654. auto res = cli.Post(
  1655. "/upload",
  1656. [&](size_t offset, DataSink &sink) {
  1657. if (offset < body.size()) {
  1658. sink.write(&body[offset], 1);
  1659. } else {
  1660. sink.done();
  1661. }
  1662. return true;
  1663. },
  1664. "multipart/form-data; boundary=B");
  1665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1666. EXPECT_EQ(StatusCode::OK_200, res->status);
  1667. EXPECT_EQ("a.txt", filename);
  1668. EXPECT_EQ("hello", content);
  1669. }
  1670. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1671. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1672. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1673. Server svr;
  1674. std::string field_value, file_name, file_filename;
  1675. bool has_field = false, has_file = false;
  1676. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1677. has_field = req.form.has_field("x=y");
  1678. field_value = req.form.get_field("x=y");
  1679. has_file = req.form.has_file("file1");
  1680. const auto &file = req.form.get_file("file1");
  1681. file_name = file.name;
  1682. file_filename = file.filename;
  1683. res.set_content("ok", "text/plain");
  1684. });
  1685. auto port = svr.bind_to_any_port(HOST);
  1686. thread t = thread([&] { svr.listen_after_bind(); });
  1687. auto se = detail::scope_exit([&] {
  1688. svr.stop();
  1689. t.join();
  1690. ASSERT_FALSE(svr.is_running());
  1691. });
  1692. svr.wait_until_ready();
  1693. UploadFormDataItems items = {
  1694. {"x=y", "field-value", "", ""},
  1695. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1696. };
  1697. Client cli(HOST, port);
  1698. auto res = cli.Post("/quoted", items);
  1699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1700. ASSERT_EQ(StatusCode::OK_200, res->status);
  1701. EXPECT_TRUE(has_field);
  1702. EXPECT_EQ("field-value", field_value);
  1703. EXPECT_TRUE(has_file);
  1704. EXPECT_EQ("file1", file_name);
  1705. EXPECT_EQ("a;b=report.pdf", file_filename);
  1706. }
  1707. TEST(GetHeaderValueTest, DefaultValue) {
  1708. Headers headers = {{"Dummy", "Dummy"}};
  1709. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1710. EXPECT_STREQ("text/plain", val);
  1711. }
  1712. TEST(GetHeaderValueTest, DefaultValueInt) {
  1713. Headers headers = {{"Dummy", "Dummy"}};
  1714. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1715. EXPECT_EQ(100ull, val);
  1716. }
  1717. TEST(GetHeaderValueTest, RegularValue) {
  1718. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1719. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1720. EXPECT_STREQ("text/html", val);
  1721. }
  1722. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1723. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1724. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1725. EXPECT_STREQ("text/html", val);
  1726. }
  1727. TEST(GetHeaderValueTest, SetContent) {
  1728. Response res;
  1729. res.set_content("html", "text/html");
  1730. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1731. res.set_content("text", "text/plain");
  1732. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1733. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1734. }
  1735. TEST(GetHeaderValueTest, RegularValueInt) {
  1736. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1737. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1738. EXPECT_EQ(100ull, val);
  1739. }
  1740. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1741. Headers headers = {{"Content-Length", "x"}};
  1742. auto is_invalid_value = false;
  1743. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1744. is_invalid_value);
  1745. EXPECT_EQ(0ull, val);
  1746. EXPECT_TRUE(is_invalid_value);
  1747. }
  1748. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1749. // An all-digit value that overflows size_t must be reported as invalid, not
  1750. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1751. // a large length to a small one on 32-bit builds, leaving the framing length
  1752. // wrong while is_invalid_value stayed false.
  1753. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1754. auto is_invalid_value = false;
  1755. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1756. is_invalid_value);
  1757. EXPECT_TRUE(is_invalid_value);
  1758. // A well-formed length is unaffected.
  1759. Headers ok = {{"Content-Length", "1234"}};
  1760. is_invalid_value = false;
  1761. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1762. is_invalid_value);
  1763. EXPECT_EQ(1234ull, val);
  1764. EXPECT_FALSE(is_invalid_value);
  1765. }
  1766. TEST(GetHeaderValueTest, Range) {
  1767. {
  1768. Headers headers = {make_range_header({{1, -1}})};
  1769. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1770. EXPECT_STREQ("bytes=1-", val);
  1771. }
  1772. {
  1773. Headers headers = {make_range_header({{-1, 1}})};
  1774. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1775. EXPECT_STREQ("bytes=-1", val);
  1776. }
  1777. {
  1778. Headers headers = {make_range_header({{1, 10}})};
  1779. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1780. EXPECT_STREQ("bytes=1-10", val);
  1781. }
  1782. {
  1783. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1784. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1785. EXPECT_STREQ("bytes=1-10, 100-", val);
  1786. }
  1787. {
  1788. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1789. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1790. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1791. }
  1792. {
  1793. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1794. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1795. EXPECT_STREQ("bytes=0-0, -1", val);
  1796. }
  1797. }
  1798. TEST(BearerTokenAuthTest, SchemeValidation) {
  1799. // A value shorter than "Bearer " must not throw from the fixed-length
  1800. // substr, and a non-Bearer scheme must not be reported as a token.
  1801. struct {
  1802. const char *value;
  1803. const char *expected;
  1804. } cases[] = {
  1805. {"x", ""},
  1806. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1807. {"Bearer abc123", "abc123"},
  1808. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1809. };
  1810. for (const auto &c : cases) {
  1811. Request req;
  1812. req.set_header("Authorization", c.value);
  1813. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1814. }
  1815. }
  1816. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1817. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1818. // to depend on the standard library (libstdc++ handed back duplicates in
  1819. // reverse insertion order, libc++ in insertion order).
  1820. Request req;
  1821. req.set_header("Accept-Encoding", "gzip");
  1822. req.set_header("Accept-Encoding", "deflate");
  1823. req.set_header("Accept-Encoding", "br");
  1824. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1825. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1826. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1827. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1828. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1829. }
  1830. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1831. Request req;
  1832. req.set_header("X-Test", "only");
  1833. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1834. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1835. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1836. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1837. }
  1838. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1839. Request req;
  1840. req.set_header("X-First", "1");
  1841. req.set_header("X-Test", "2");
  1842. req.params.emplace("first", "1");
  1843. req.params.emplace("test", "2");
  1844. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1845. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1846. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1847. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1848. // The second one is negative when read as a signed value
  1849. const auto max_id = (std::numeric_limits<size_t>::max)();
  1850. for (auto id : {max_id / 2, max_id}) {
  1851. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1852. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1853. EXPECT_EQ("", req.get_param_value("test", id));
  1854. EXPECT_EQ("", req.form.get_field("test", id));
  1855. EXPECT_EQ("", req.form.get_file("test", id).content);
  1856. }
  1857. }
  1858. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1859. Headers headers;
  1860. headers.emplace("Host", "example.com");
  1861. headers.emplace("Accept-Encoding", "gzip");
  1862. headers.emplace("User-Agent", "test");
  1863. headers.emplace("Accept-Encoding", "deflate");
  1864. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1865. "Accept-Encoding=deflate ",
  1866. entries_to_string(headers));
  1867. }
  1868. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1869. Headers headers = {{"Content-Type", "text/html"},
  1870. {"CONTENT-TYPE", "text/xml"}};
  1871. EXPECT_EQ(2U, headers.count("content-type"));
  1872. auto it = headers.find("content-type");
  1873. ASSERT_TRUE(it != headers.end());
  1874. EXPECT_EQ("text/html", it->second);
  1875. }
  1876. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1877. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1878. // drop only those fields and leave everything positioned between them.
  1879. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1880. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1881. auto rng = headers.equal_range("a");
  1882. headers.erase(rng.first, rng.second);
  1883. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1884. }
  1885. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1886. Headers headers = {
  1887. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1888. EXPECT_EQ(3U, headers.erase("A"));
  1889. EXPECT_EQ(0U, headers.count("A"));
  1890. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1891. }
  1892. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1893. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1894. headers.emplace_front("Host", "example.com");
  1895. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1896. entries_to_string(headers));
  1897. }
  1898. TEST(ParseHeaderValueTest, Range) {
  1899. {
  1900. Ranges ranges;
  1901. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1902. EXPECT_TRUE(ret);
  1903. EXPECT_EQ(1u, ranges.size());
  1904. EXPECT_EQ(1u, ranges[0].first);
  1905. EXPECT_EQ(-1, ranges[0].second);
  1906. }
  1907. {
  1908. Ranges ranges;
  1909. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1910. EXPECT_TRUE(ret);
  1911. EXPECT_EQ(1u, ranges.size());
  1912. EXPECT_EQ(-1, ranges[0].first);
  1913. EXPECT_EQ(1u, ranges[0].second);
  1914. }
  1915. {
  1916. Ranges ranges;
  1917. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1918. EXPECT_TRUE(ret);
  1919. EXPECT_EQ(1u, ranges.size());
  1920. EXPECT_EQ(1u, ranges[0].first);
  1921. EXPECT_EQ(10u, ranges[0].second);
  1922. }
  1923. {
  1924. Ranges ranges;
  1925. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1926. EXPECT_FALSE(ret);
  1927. }
  1928. {
  1929. Ranges ranges;
  1930. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1931. EXPECT_TRUE(ret);
  1932. EXPECT_EQ(2u, ranges.size());
  1933. EXPECT_EQ(1u, ranges[0].first);
  1934. EXPECT_EQ(10u, ranges[0].second);
  1935. EXPECT_EQ(100u, ranges[1].first);
  1936. EXPECT_EQ(-1, ranges[1].second);
  1937. }
  1938. {
  1939. Ranges ranges;
  1940. auto ret =
  1941. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1942. EXPECT_TRUE(ret);
  1943. EXPECT_EQ(3u, ranges.size());
  1944. EXPECT_EQ(1u, ranges[0].first);
  1945. EXPECT_EQ(10u, ranges[0].second);
  1946. EXPECT_EQ(100u, ranges[1].first);
  1947. EXPECT_EQ(200u, ranges[1].second);
  1948. EXPECT_EQ(300u, ranges[2].first);
  1949. EXPECT_EQ(400u, ranges[2].second);
  1950. }
  1951. {
  1952. Ranges ranges;
  1953. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1954. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1955. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1956. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1957. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1958. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1959. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1960. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1961. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1962. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1963. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1964. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1965. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1966. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1967. EXPECT_FALSE(
  1968. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1969. EXPECT_TRUE(ranges.empty());
  1970. }
  1971. {
  1972. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1973. // remainder of the representation, so it stays accepted.
  1974. Ranges ranges;
  1975. auto ret =
  1976. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1977. EXPECT_TRUE(ret);
  1978. ASSERT_EQ(1u, ranges.size());
  1979. EXPECT_EQ(0, ranges[0].first);
  1980. EXPECT_EQ(-1, ranges[0].second);
  1981. }
  1982. // RFC 9110 14.1: range unit names are case-insensitive.
  1983. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  1984. Ranges ranges;
  1985. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  1986. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  1987. }
  1988. }
  1989. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1990. Request req;
  1991. req.set_header("Accept-Encoding", "gzip");
  1992. Response res;
  1993. res.set_header("Content-Type", "text/plain");
  1994. auto ret = detail::encoding_type(req, res);
  1995. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1996. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1997. #else
  1998. EXPECT_TRUE(ret == detail::EncodingType::None);
  1999. #endif
  2000. }
  2001. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2002. Request req;
  2003. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2004. Response res;
  2005. res.set_header("Content-Type", "text/plain");
  2006. auto ret = detail::encoding_type(req, res);
  2007. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2008. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2009. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2010. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2011. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2012. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2013. #else
  2014. EXPECT_TRUE(ret == detail::EncodingType::None);
  2015. #endif
  2016. }
  2017. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2018. Request req;
  2019. req.set_header("Accept-Encoding",
  2020. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2021. Response res;
  2022. res.set_header("Content-Type", "text/plain");
  2023. auto ret = detail::encoding_type(req, res);
  2024. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2025. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2026. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2027. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2028. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2029. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2030. #else
  2031. EXPECT_TRUE(ret == detail::EncodingType::None);
  2032. #endif
  2033. }
  2034. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2035. // All supported encodings rejected with q=0 should return None
  2036. Request req;
  2037. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2038. Response res;
  2039. res.set_header("Content-Type", "text/plain");
  2040. auto ret = detail::encoding_type(req, res);
  2041. EXPECT_TRUE(ret == detail::EncodingType::None);
  2042. }
  2043. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2044. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2045. Request req;
  2046. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2047. Response res;
  2048. res.set_header("Content-Type", "text/plain");
  2049. auto ret = detail::encoding_type(req, res);
  2050. EXPECT_TRUE(ret == detail::EncodingType::None);
  2051. }
  2052. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2053. Request req;
  2054. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2055. Response res;
  2056. res.set_header("Content-Type", "text/plain");
  2057. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2058. }
  2059. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2060. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2061. Request req;
  2062. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2063. Response res;
  2064. res.set_header("Content-Type", "text/plain");
  2065. auto ret = detail::encoding_type(req, res);
  2066. EXPECT_TRUE(ret == detail::EncodingType::None);
  2067. }
  2068. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2069. // RFC 7231: Accept-Encoding values are case-insensitive
  2070. Request req;
  2071. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2072. Response res;
  2073. res.set_header("Content-Type", "text/plain");
  2074. auto ret = detail::encoding_type(req, res);
  2075. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2076. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2077. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2078. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2079. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2080. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2081. #else
  2082. EXPECT_TRUE(ret == detail::EncodingType::None);
  2083. #endif
  2084. }
  2085. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2086. // q value should determine priority, not hardcoded order
  2087. Request req;
  2088. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2089. Response res;
  2090. res.set_header("Content-Type", "text/plain");
  2091. auto ret = detail::encoding_type(req, res);
  2092. // gzip has highest q=1.0, so it should be selected even though
  2093. // br and zstd are also supported
  2094. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2095. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2096. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2097. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2098. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2099. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2100. #else
  2101. EXPECT_TRUE(ret == detail::EncodingType::None);
  2102. #endif
  2103. }
  2104. TEST(BufferStreamTest, read) {
  2105. detail::BufferStream strm1;
  2106. Stream &strm = strm1;
  2107. EXPECT_EQ(5, strm.write("hello"));
  2108. char buf[512];
  2109. EXPECT_EQ(2, strm.read(buf, 2));
  2110. EXPECT_EQ('h', buf[0]);
  2111. EXPECT_EQ('e', buf[1]);
  2112. EXPECT_EQ(2, strm.read(buf, 2));
  2113. EXPECT_EQ('l', buf[0]);
  2114. EXPECT_EQ('l', buf[1]);
  2115. EXPECT_EQ(1, strm.read(buf, 1));
  2116. EXPECT_EQ('o', buf[0]);
  2117. EXPECT_EQ(0, strm.read(buf, 1));
  2118. }
  2119. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2120. auto host = "www.httpwatch.com";
  2121. auto ip = hosted_at(host);
  2122. EXPECT_EQ("23.96.13.243", ip);
  2123. std::vector<std::string> addrs;
  2124. hosted_at(host, addrs);
  2125. EXPECT_EQ(1u, addrs.size());
  2126. }
  2127. #if 0 // It depends on each test environment...
  2128. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2129. auto host = "www.youtube.com";
  2130. std::vector<std::string> addrs;
  2131. hosted_at(host, addrs);
  2132. EXPECT_EQ(20u, addrs.size());
  2133. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2134. EXPECT_TRUE(it != addrs.end());
  2135. }
  2136. #endif
  2137. class ChunkedEncodingTest : public ::testing::Test {
  2138. protected:
  2139. ChunkedEncodingTest()
  2140. : cli_(HOST, PORT)
  2141. #ifdef CPPHTTPLIB_SSL_ENABLED
  2142. ,
  2143. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2144. #endif
  2145. {
  2146. cli_.set_connection_timeout(2);
  2147. #ifdef CPPHTTPLIB_SSL_ENABLED
  2148. cli_.enable_server_certificate_verification(false);
  2149. #endif
  2150. }
  2151. virtual void SetUp() {
  2152. read_file("./image.jpg", image_data_);
  2153. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2154. res.set_content("Hello World!", "text/plain");
  2155. });
  2156. svr_.Get(
  2157. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2158. res.set_chunked_content_provider(
  2159. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2160. size_t remaining = image_data_.size() - offset;
  2161. if (remaining == 0) {
  2162. sink.done();
  2163. } else {
  2164. constexpr size_t CHUNK_SIZE = 1024;
  2165. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2166. sink.write(&image_data_[offset], send_size);
  2167. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2168. }
  2169. return true;
  2170. });
  2171. });
  2172. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2173. svr_.wait_until_ready();
  2174. }
  2175. virtual void TearDown() {
  2176. svr_.stop();
  2177. if (!request_threads_.empty()) {
  2178. std::this_thread::sleep_for(std::chrono::seconds(1));
  2179. for (auto &t : request_threads_) {
  2180. t.join();
  2181. }
  2182. }
  2183. t_.join();
  2184. }
  2185. #ifdef CPPHTTPLIB_SSL_ENABLED
  2186. SSLClient cli_;
  2187. SSLServer svr_;
  2188. #else
  2189. Client cli_;
  2190. Server svr_;
  2191. #endif
  2192. thread t_;
  2193. std::vector<thread> request_threads_;
  2194. std::string image_data_;
  2195. };
  2196. TEST_F(ChunkedEncodingTest, NormalGet) {
  2197. auto res = cli_.Get("/chunked");
  2198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2199. std::string out;
  2200. read_file("./image.jpg", out);
  2201. EXPECT_EQ(StatusCode::OK_200, res->status);
  2202. EXPECT_EQ(out, res->body);
  2203. }
  2204. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2205. std::string body;
  2206. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2207. body.append(data, data_length);
  2208. return true;
  2209. });
  2210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2211. std::string out;
  2212. read_file("./image.jpg", out);
  2213. EXPECT_EQ(StatusCode::OK_200, res->status);
  2214. EXPECT_EQ(out, body);
  2215. }
  2216. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2217. std::string body;
  2218. auto res = cli_.Get(
  2219. "/chunked",
  2220. [&](const Response &response) {
  2221. EXPECT_EQ(StatusCode::OK_200, response.status);
  2222. return true;
  2223. },
  2224. [&](const char *data, size_t data_length) {
  2225. body.append(data, data_length);
  2226. return true;
  2227. });
  2228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2229. std::string out;
  2230. read_file("./image.jpg", out);
  2231. EXPECT_EQ(StatusCode::OK_200, res->status);
  2232. EXPECT_EQ(out, body);
  2233. }
  2234. TEST(RangeTest, FromHTTPBin_Online) {
  2235. auto host = "httpbingo.org";
  2236. auto path = std::string{"/range/32"};
  2237. #ifdef CPPHTTPLIB_SSL_ENABLED
  2238. auto port = 443;
  2239. SSLClient cli(host, port);
  2240. #else
  2241. auto port = 80;
  2242. Client cli(host, port);
  2243. #endif
  2244. cli.set_connection_timeout(5);
  2245. {
  2246. auto res = cli.Get(path);
  2247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2248. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2249. EXPECT_EQ(StatusCode::OK_200, res->status);
  2250. }
  2251. {
  2252. Headers headers = {make_range_header({{1, -1}})};
  2253. auto res = cli.Get(path, headers);
  2254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2255. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2256. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2257. }
  2258. {
  2259. Headers headers = {make_range_header({{1, 10}})};
  2260. auto res = cli.Get(path, headers);
  2261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2262. EXPECT_EQ("bcdefghijk", res->body);
  2263. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2264. }
  2265. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2266. // entire resource, while the original httpbin returned 200. Both are
  2267. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2268. {
  2269. Headers headers = {make_range_header({{0, 31}})};
  2270. auto res = cli.Get(path, headers);
  2271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2272. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2273. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2274. res->status == StatusCode::PartialContent_206);
  2275. }
  2276. {
  2277. Headers headers = {make_range_header({{0, -1}})};
  2278. auto res = cli.Get(path, headers);
  2279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2280. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2281. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2282. res->status == StatusCode::PartialContent_206);
  2283. }
  2284. // go-httpbin returns 206 with clamped range for over-range requests,
  2285. // while the original httpbin returned 416. Both behaviors are observed
  2286. // in real servers, so we only verify the request succeeds.
  2287. {
  2288. Headers headers = {make_range_header({{0, 32}})};
  2289. auto res = cli.Get(path, headers);
  2290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2291. }
  2292. }
  2293. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2294. auto host = "unresolvableaddress.local";
  2295. auto path = std::string{"/"};
  2296. #ifdef CPPHTTPLIB_SSL_ENABLED
  2297. auto port = 443;
  2298. SSLClient cli(host, port);
  2299. #else
  2300. auto port = 80;
  2301. Client cli(host, port);
  2302. #endif
  2303. cli.set_connection_timeout(1);
  2304. {
  2305. auto res = cli.Get(path);
  2306. ASSERT_FALSE(res);
  2307. }
  2308. std::this_thread::sleep_for(std::chrono::seconds(8));
  2309. }
  2310. #if defined(__linux__) && defined(__GLIBC__) && \
  2311. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2312. // Forward declaration: in split builds split.py strips `inline` and moves the
  2313. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2314. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2315. // against the symbol in both header-only and split builds.
  2316. namespace httplib {
  2317. namespace detail {
  2318. int getaddrinfo_with_timeout(const char *node, const char *service,
  2319. const struct addrinfo *hints,
  2320. struct addrinfo **res, time_t timeout_sec);
  2321. } // namespace detail
  2322. } // namespace httplib
  2323. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2324. //
  2325. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2326. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2327. // gai_suspend() call hits the connection timeout the function calls
  2328. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2329. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2330. // still alive and still references the now-destroyed stack frame.
  2331. //
  2332. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2333. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2334. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2335. // and runs them in a container.
  2336. namespace {
  2337. bool should_run_issue_2431_tests() {
  2338. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2339. return v && *v && std::string(v) != "0";
  2340. }
  2341. std::string unique_unresolvable_host(int n) {
  2342. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2343. // glibc still asks the configured nameserver — which is exactly the path
  2344. // we want to exercise. A unique label per call avoids the resolver cache.
  2345. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2346. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2347. std::to_string(n) + ".invalid";
  2348. }
  2349. } // namespace
  2350. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2351. if (!should_run_issue_2431_tests()) {
  2352. GTEST_SKIP()
  2353. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2354. }
  2355. for (int i = 0; i < 8; ++i) {
  2356. struct addrinfo hints;
  2357. memset(&hints, 0, sizeof(hints));
  2358. hints.ai_family = AF_UNSPEC;
  2359. hints.ai_socktype = SOCK_STREAM;
  2360. auto host = unique_unresolvable_host(i);
  2361. struct addrinfo *result = nullptr;
  2362. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2363. &result, /*timeout_sec=*/1);
  2364. if (rc == 0 && result) { freeaddrinfo(result); }
  2365. }
  2366. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2367. // stack region they still believe holds their gaicb.
  2368. std::this_thread::sleep_for(std::chrono::seconds(3));
  2369. }
  2370. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2371. if (!should_run_issue_2431_tests()) {
  2372. GTEST_SKIP()
  2373. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2374. }
  2375. std::atomic<bool> stop{false};
  2376. std::vector<std::thread> threads;
  2377. for (int t = 0; t < 8; ++t) {
  2378. threads.emplace_back([t, &stop] {
  2379. int i = 0;
  2380. while (!stop.load(std::memory_order_relaxed)) {
  2381. struct addrinfo hints;
  2382. memset(&hints, 0, sizeof(hints));
  2383. hints.ai_family = AF_UNSPEC;
  2384. hints.ai_socktype = SOCK_STREAM;
  2385. auto host = unique_unresolvable_host(t * 100000 + i++);
  2386. struct addrinfo *result = nullptr;
  2387. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2388. &result, /*timeout_sec=*/1);
  2389. if (rc == 0 && result) { freeaddrinfo(result); }
  2390. }
  2391. });
  2392. }
  2393. std::this_thread::sleep_for(std::chrono::seconds(8));
  2394. stop.store(true, std::memory_order_relaxed);
  2395. for (auto &th : threads) {
  2396. th.join();
  2397. }
  2398. std::this_thread::sleep_for(std::chrono::seconds(3));
  2399. }
  2400. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2401. if (!should_run_issue_2431_tests()) {
  2402. GTEST_SKIP()
  2403. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2404. }
  2405. std::atomic<bool> stop{false};
  2406. std::vector<std::thread> threads;
  2407. for (int t = 0; t < 8; ++t) {
  2408. threads.emplace_back([t, &stop] {
  2409. int i = 0;
  2410. while (!stop.load(std::memory_order_relaxed)) {
  2411. auto host = unique_unresolvable_host(t * 100000 + i++);
  2412. Client cli(host, 80);
  2413. cli.set_connection_timeout(1, 0);
  2414. cli.set_read_timeout(1, 0);
  2415. cli.set_write_timeout(1, 0);
  2416. (void)cli.Get("/");
  2417. }
  2418. });
  2419. }
  2420. std::this_thread::sleep_for(std::chrono::seconds(8));
  2421. stop.store(true, std::memory_order_relaxed);
  2422. for (auto &th : threads) {
  2423. th.join();
  2424. }
  2425. std::this_thread::sleep_for(std::chrono::seconds(3));
  2426. }
  2427. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2428. TEST(ConnectionErrorTest, InvalidHost) {
  2429. auto host = "-abcde.com";
  2430. #ifdef CPPHTTPLIB_SSL_ENABLED
  2431. auto port = 443;
  2432. SSLClient cli(host, port);
  2433. #else
  2434. auto port = 80;
  2435. Client cli(host, port);
  2436. #endif
  2437. cli.set_connection_timeout(std::chrono::seconds(2));
  2438. auto res = cli.Get("/");
  2439. ASSERT_TRUE(!res);
  2440. EXPECT_EQ(Error::Connection, res.error());
  2441. }
  2442. TEST(ConnectionErrorTest, InvalidHost2) {
  2443. auto host = "httpcan.org/";
  2444. #ifdef CPPHTTPLIB_SSL_ENABLED
  2445. SSLClient cli(host);
  2446. #else
  2447. Client cli(host);
  2448. #endif
  2449. cli.set_connection_timeout(std::chrono::seconds(2));
  2450. auto res = cli.Get("/");
  2451. ASSERT_TRUE(!res);
  2452. EXPECT_EQ(Error::Connection, res.error());
  2453. }
  2454. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2455. auto host = "httpcan.org/";
  2456. #ifdef CPPHTTPLIB_SSL_ENABLED
  2457. SSLClient cli(host);
  2458. #else
  2459. Client cli(host);
  2460. #endif
  2461. cli.set_connection_timeout(std::chrono::seconds(2));
  2462. auto res = cli.Get("/");
  2463. ASSERT_TRUE(!res);
  2464. stringstream s;
  2465. s << "error code: " << res.error();
  2466. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2467. }
  2468. TEST(ConnectionErrorTest, InvalidPort) {
  2469. auto host = "localhost";
  2470. auto port = 44380;
  2471. #ifdef CPPHTTPLIB_SSL_ENABLED
  2472. SSLClient cli(host, port);
  2473. #else
  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_TRUE(Error::Connection == res.error() ||
  2480. Error::ConnectionTimeout == res.error());
  2481. }
  2482. TEST(ConnectionErrorTest, Timeout_Online) {
  2483. auto host = "google.com";
  2484. #ifdef CPPHTTPLIB_SSL_ENABLED
  2485. auto port = 44380;
  2486. SSLClient cli(host, port);
  2487. #else
  2488. auto port = 8080;
  2489. Client cli(host, port);
  2490. #endif
  2491. cli.set_connection_timeout(std::chrono::seconds(2));
  2492. // only probe one address type so that the error reason
  2493. // correlates to the timed-out IPv4, not the unsupported
  2494. // IPv6 connection attempt
  2495. cli.set_address_family(AF_INET);
  2496. auto res = cli.Get("/");
  2497. ASSERT_TRUE(!res);
  2498. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2499. }
  2500. TEST(CancelTest, NoCancel_Online) {
  2501. auto host = "httpbingo.org";
  2502. auto path = std::string{"/range/32"};
  2503. #ifdef CPPHTTPLIB_SSL_ENABLED
  2504. auto port = 443;
  2505. SSLClient cli(host, port);
  2506. #else
  2507. auto port = 80;
  2508. Client cli(host, port);
  2509. #endif
  2510. cli.set_connection_timeout(std::chrono::seconds(5));
  2511. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2513. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2514. EXPECT_EQ(StatusCode::OK_200, res->status);
  2515. }
  2516. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2517. // Use /bytes with a large payload so that the DownloadProgress callback
  2518. // (which only fires for Content-Length responses) is invoked before the
  2519. // entire body is received, giving cancellation a chance to fire.
  2520. auto host = "httpbingo.org";
  2521. auto path = std::string{"/bytes/524288"};
  2522. #ifdef CPPHTTPLIB_SSL_ENABLED
  2523. auto port = 443;
  2524. SSLClient cli(host, port);
  2525. #else
  2526. auto port = 80;
  2527. Client cli(host, port);
  2528. #endif
  2529. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2530. cli.set_connection_timeout(std::chrono::seconds(5));
  2531. ASSERT_TRUE(!res);
  2532. EXPECT_EQ(Error::Canceled, res.error());
  2533. }
  2534. TEST(CancelTest, WithCancelLargePayload_Online) {
  2535. auto host = "httpbingo.org";
  2536. auto path = std::string{"/bytes/524288"};
  2537. #ifdef CPPHTTPLIB_SSL_ENABLED
  2538. auto port = 443;
  2539. SSLClient cli(host, port);
  2540. #else
  2541. auto port = 80;
  2542. Client cli(host, port);
  2543. #endif
  2544. cli.set_connection_timeout(std::chrono::seconds(5));
  2545. uint32_t count = 0;
  2546. auto res =
  2547. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2548. ASSERT_TRUE(!res);
  2549. EXPECT_EQ(Error::Canceled, res.error());
  2550. }
  2551. TEST(CancelTest, NoCancelPost) {
  2552. Server svr;
  2553. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2554. res.set_content("Hello World!", "text/plain");
  2555. });
  2556. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2557. auto se = detail::scope_exit([&] {
  2558. svr.stop();
  2559. thread.join();
  2560. ASSERT_FALSE(svr.is_running());
  2561. });
  2562. svr.wait_until_ready();
  2563. Client cli(HOST, PORT);
  2564. cli.set_connection_timeout(std::chrono::seconds(5));
  2565. auto res =
  2566. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2567. "application/json", [](uint64_t, uint64_t) { return true; });
  2568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2569. EXPECT_EQ("Hello World!", res->body);
  2570. EXPECT_EQ(StatusCode::OK_200, res->status);
  2571. }
  2572. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2573. Server svr;
  2574. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2575. res.set_content("Hello World!", "text/plain");
  2576. });
  2577. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2578. auto se = detail::scope_exit([&] {
  2579. svr.stop();
  2580. thread.join();
  2581. ASSERT_FALSE(svr.is_running());
  2582. });
  2583. svr.wait_until_ready();
  2584. Client cli(HOST, PORT);
  2585. cli.set_connection_timeout(std::chrono::seconds(5));
  2586. auto res =
  2587. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2588. "application/json", [](uint64_t, uint64_t) { return false; });
  2589. ASSERT_TRUE(!res);
  2590. EXPECT_EQ(Error::Canceled, res.error());
  2591. }
  2592. TEST(CancelTest, WithCancelLargePayloadPost) {
  2593. Server svr;
  2594. svr.set_payload_max_length(200 * 1024 * 1024);
  2595. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2596. res.set_content(LARGE_DATA, "text/plain");
  2597. });
  2598. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2599. auto se = detail::scope_exit([&] {
  2600. svr.stop();
  2601. thread.join();
  2602. ASSERT_FALSE(svr.is_running());
  2603. });
  2604. svr.wait_until_ready();
  2605. Client cli(HOST, PORT);
  2606. cli.set_payload_max_length(200 * 1024 * 1024);
  2607. cli.set_connection_timeout(std::chrono::seconds(5));
  2608. auto res =
  2609. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2610. "application/json", [](uint64_t, uint64_t) { return false; });
  2611. ASSERT_TRUE(!res);
  2612. EXPECT_EQ(Error::Canceled, res.error());
  2613. }
  2614. TEST(CancelTest, NoCancelPut) {
  2615. Server svr;
  2616. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2617. res.set_content("Hello World!", "text/plain");
  2618. });
  2619. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2620. auto se = detail::scope_exit([&] {
  2621. svr.stop();
  2622. thread.join();
  2623. ASSERT_FALSE(svr.is_running());
  2624. });
  2625. svr.wait_until_ready();
  2626. Client cli(HOST, PORT);
  2627. cli.set_connection_timeout(std::chrono::seconds(5));
  2628. auto res =
  2629. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2630. "application/json", [](uint64_t, uint64_t) { return true; });
  2631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2632. EXPECT_EQ("Hello World!", res->body);
  2633. EXPECT_EQ(StatusCode::OK_200, res->status);
  2634. }
  2635. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2636. Server svr;
  2637. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2638. res.set_content("Hello World!", "text/plain");
  2639. });
  2640. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2641. auto se = detail::scope_exit([&] {
  2642. svr.stop();
  2643. thread.join();
  2644. ASSERT_FALSE(svr.is_running());
  2645. });
  2646. svr.wait_until_ready();
  2647. Client cli(HOST, PORT);
  2648. cli.set_connection_timeout(std::chrono::seconds(5));
  2649. auto res =
  2650. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2651. "application/json", [](uint64_t, uint64_t) { return false; });
  2652. ASSERT_TRUE(!res);
  2653. EXPECT_EQ(Error::Canceled, res.error());
  2654. }
  2655. TEST(CancelTest, WithCancelLargePayloadPut) {
  2656. Server svr;
  2657. svr.set_payload_max_length(200 * 1024 * 1024);
  2658. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2659. res.set_content(LARGE_DATA, "text/plain");
  2660. });
  2661. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2662. auto se = detail::scope_exit([&] {
  2663. svr.stop();
  2664. thread.join();
  2665. ASSERT_FALSE(svr.is_running());
  2666. });
  2667. svr.wait_until_ready();
  2668. Client cli(HOST, PORT);
  2669. cli.set_payload_max_length(200 * 1024 * 1024);
  2670. cli.set_connection_timeout(std::chrono::seconds(5));
  2671. auto res =
  2672. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2673. "application/json", [](uint64_t, uint64_t) { return false; });
  2674. ASSERT_TRUE(!res);
  2675. EXPECT_EQ(Error::Canceled, res.error());
  2676. }
  2677. TEST(CancelTest, NoCancelPatch) {
  2678. Server svr;
  2679. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2680. res.set_content("Hello World!", "text/plain");
  2681. });
  2682. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2683. auto se = detail::scope_exit([&] {
  2684. svr.stop();
  2685. thread.join();
  2686. ASSERT_FALSE(svr.is_running());
  2687. });
  2688. svr.wait_until_ready();
  2689. Client cli(HOST, PORT);
  2690. cli.set_connection_timeout(std::chrono::seconds(5));
  2691. auto res =
  2692. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2693. "application/json", [](uint64_t, uint64_t) { return true; });
  2694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2695. EXPECT_EQ("Hello World!", res->body);
  2696. EXPECT_EQ(StatusCode::OK_200, res->status);
  2697. }
  2698. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2699. Server svr;
  2700. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2701. res.set_content("Hello World!", "text/plain");
  2702. });
  2703. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2704. auto se = detail::scope_exit([&] {
  2705. svr.stop();
  2706. thread.join();
  2707. ASSERT_FALSE(svr.is_running());
  2708. });
  2709. svr.wait_until_ready();
  2710. Client cli(HOST, PORT);
  2711. cli.set_connection_timeout(std::chrono::seconds(5));
  2712. auto res =
  2713. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2714. "application/json", [](uint64_t, uint64_t) { return false; });
  2715. ASSERT_TRUE(!res);
  2716. EXPECT_EQ(Error::Canceled, res.error());
  2717. }
  2718. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2719. Server svr;
  2720. svr.set_payload_max_length(200 * 1024 * 1024);
  2721. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2722. res.set_content(LARGE_DATA, "text/plain");
  2723. });
  2724. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2725. auto se = detail::scope_exit([&] {
  2726. svr.stop();
  2727. thread.join();
  2728. ASSERT_FALSE(svr.is_running());
  2729. });
  2730. svr.wait_until_ready();
  2731. Client cli(HOST, PORT);
  2732. cli.set_payload_max_length(200 * 1024 * 1024);
  2733. cli.set_connection_timeout(std::chrono::seconds(5));
  2734. auto res =
  2735. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2736. "application/json", [](uint64_t, uint64_t) { return false; });
  2737. ASSERT_TRUE(!res);
  2738. EXPECT_EQ(Error::Canceled, res.error());
  2739. }
  2740. TEST(CancelTest, NoCancelDelete) {
  2741. Server svr;
  2742. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2743. res.set_content("Hello World!", "text/plain");
  2744. });
  2745. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2746. auto se = detail::scope_exit([&] {
  2747. svr.stop();
  2748. thread.join();
  2749. ASSERT_FALSE(svr.is_running());
  2750. });
  2751. svr.wait_until_ready();
  2752. Client cli(HOST, PORT);
  2753. cli.set_connection_timeout(std::chrono::seconds(5));
  2754. auto res =
  2755. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2756. "application/json", [](uint64_t, uint64_t) { return true; });
  2757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2758. EXPECT_EQ("Hello World!", res->body);
  2759. EXPECT_EQ(StatusCode::OK_200, res->status);
  2760. }
  2761. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2762. Server svr;
  2763. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2764. res.set_content("Hello World!", "text/plain");
  2765. });
  2766. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2767. auto se = detail::scope_exit([&] {
  2768. svr.stop();
  2769. thread.join();
  2770. ASSERT_FALSE(svr.is_running());
  2771. });
  2772. svr.wait_until_ready();
  2773. Client cli(HOST, PORT);
  2774. cli.set_connection_timeout(std::chrono::seconds(5));
  2775. auto res =
  2776. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2777. "application/json", [](uint64_t, uint64_t) { return false; });
  2778. ASSERT_TRUE(!res);
  2779. EXPECT_EQ(Error::Canceled, res.error());
  2780. }
  2781. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2782. Server svr;
  2783. svr.set_payload_max_length(200 * 1024 * 1024);
  2784. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2785. res.set_content(LARGE_DATA, "text/plain");
  2786. });
  2787. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2788. auto se = detail::scope_exit([&] {
  2789. svr.stop();
  2790. thread.join();
  2791. ASSERT_FALSE(svr.is_running());
  2792. });
  2793. svr.wait_until_ready();
  2794. Client cli(HOST, PORT);
  2795. cli.set_payload_max_length(200 * 1024 * 1024);
  2796. cli.set_connection_timeout(std::chrono::seconds(5));
  2797. auto res =
  2798. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2799. "application/json", [](uint64_t, uint64_t) { return false; });
  2800. ASSERT_TRUE(!res);
  2801. EXPECT_EQ(Error::Canceled, res.error());
  2802. }
  2803. static std::string remove_whitespace(const std::string &input) {
  2804. std::string output;
  2805. output.reserve(input.size());
  2806. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2807. [](unsigned char c) { return !std::isspace(c); });
  2808. return output;
  2809. }
  2810. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2811. auto host = "httpbingo.org";
  2812. auto path = std::string{"/basic-auth/hello/world"};
  2813. #ifdef CPPHTTPLIB_SSL_ENABLED
  2814. auto port = 443;
  2815. SSLClient cli(host, port);
  2816. #else
  2817. auto port = 80;
  2818. Client cli(host, port);
  2819. #endif
  2820. {
  2821. auto res = cli.Get(path);
  2822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2823. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2824. }
  2825. {
  2826. auto res = cli.Get(
  2827. path, Headers{make_basic_authentication_header("hello", "world")});
  2828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2829. auto body = remove_whitespace(res->body);
  2830. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2831. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2832. EXPECT_EQ(StatusCode::OK_200, res->status);
  2833. }
  2834. {
  2835. cli.set_basic_auth("hello", "world");
  2836. auto res = cli.Get(path);
  2837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2838. auto body = remove_whitespace(res->body);
  2839. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2840. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2841. EXPECT_EQ(StatusCode::OK_200, res->status);
  2842. }
  2843. {
  2844. cli.set_basic_auth("hello", "bad");
  2845. auto res = cli.Get(path);
  2846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2847. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2848. }
  2849. {
  2850. cli.set_basic_auth("bad", "world");
  2851. auto res = cli.Get(path);
  2852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2853. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2854. }
  2855. }
  2856. #ifdef CPPHTTPLIB_SSL_ENABLED
  2857. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2858. auto host = "httpbingo.org";
  2859. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2860. auto paths = std::vector<std::string>{
  2861. "/digest-auth/auth/hello/world/MD5",
  2862. "/digest-auth/auth/hello/world/SHA-256",
  2863. };
  2864. auto port = 443;
  2865. SSLClient cli(host, port);
  2866. {
  2867. auto res = cli.Get(unauth_path);
  2868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2869. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2870. }
  2871. {
  2872. cli.set_digest_auth("hello", "world");
  2873. for (const auto &path : paths) {
  2874. auto res = cli.Get(path.c_str());
  2875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2876. auto body = remove_whitespace(res->body);
  2877. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2878. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2879. EXPECT_EQ(StatusCode::OK_200, res->status);
  2880. }
  2881. cli.set_digest_auth("hello", "bad");
  2882. for (const auto &path : paths) {
  2883. auto res = cli.Get(path.c_str());
  2884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2885. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2886. }
  2887. }
  2888. }
  2889. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2890. // comma-separated list of challenges, and each challenge may itself carry a
  2891. // comma-separated auth-param list, so a server can legally offer Basic
  2892. // before Digest, either as two field lines or packed into one. Runs one 401
  2893. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2894. // value() joins them in receipt order) and checks that the retry carries a
  2895. // well-formed Digest Authorization header naming expected_realm.
  2896. static void
  2897. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2898. const std::string &expected_realm) {
  2899. std::atomic<int> hits{0};
  2900. Server svr;
  2901. svr.Get("/x", [&](const Request &req, Response &res) {
  2902. if (++hits == 1) {
  2903. res.status = StatusCode::Unauthorized_401;
  2904. for (const auto &challenge : challenges) {
  2905. res.set_header("WWW-Authenticate", challenge);
  2906. }
  2907. } else {
  2908. auto authorization = req.get_header_value("Authorization");
  2909. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2910. EXPECT_NE(std::string::npos,
  2911. authorization.find("realm=\"" + expected_realm + "\""));
  2912. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2913. res.set_content("ok", "text/plain");
  2914. }
  2915. });
  2916. auto port = svr.bind_to_any_port(HOST);
  2917. std::thread t([&]() { svr.listen_after_bind(); });
  2918. auto se = detail::scope_exit([&] {
  2919. svr.stop();
  2920. t.join();
  2921. });
  2922. svr.wait_until_ready();
  2923. Client cli(HOST, port);
  2924. cli.set_digest_auth("hello", "world");
  2925. auto res = cli.Get("/x");
  2926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2927. EXPECT_EQ(2, hits.load());
  2928. }
  2929. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2930. static const char *kDigestChallenge =
  2931. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2932. "algorithm=MD5";
  2933. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2934. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2935. "testrealm");
  2936. }
  2937. // Same challenge list with the schemes in the opposite order, to make sure
  2938. // the fix above didn't just special-case "Basic first".
  2939. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2940. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2941. "testrealm");
  2942. }
  2943. // A comma inside a quoted auth-param value must not be mistaken for the
  2944. // separator between two challenges (or two auth-params).
  2945. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2946. run_digest_challenge_list_test(
  2947. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2948. "algorithm=MD5"},
  2949. "test,realm");
  2950. }
  2951. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2952. // make_digest_authentication_header() dereferences both unconditionally, so
  2953. // a server sending a challenge missing either one must not be treated as
  2954. // usable -- doing so used to crash the client with std::out_of_range.
  2955. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2956. Server svr;
  2957. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2958. res.status = StatusCode::Unauthorized_401;
  2959. res.set_header("WWW-Authenticate", challenge);
  2960. });
  2961. auto port = svr.bind_to_any_port(HOST);
  2962. std::thread t([&]() { svr.listen_after_bind(); });
  2963. auto se = detail::scope_exit([&] {
  2964. svr.stop();
  2965. t.join();
  2966. });
  2967. svr.wait_until_ready();
  2968. Client cli(HOST, port);
  2969. cli.set_digest_auth("hello", "world");
  2970. auto res = cli.Get("/x");
  2971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2972. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2973. }
  2974. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2975. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2976. }
  2977. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2978. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2979. }
  2980. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2981. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2982. }
  2983. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  2984. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  2985. // when storing the values, so the header builder has to re-escape them (and
  2986. // keep algorithm a bare token); otherwise the value breaks out of its
  2987. // quoted-string and injects extra auth-params into the client's Authorization.
  2988. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  2989. std::atomic<int> hits{0};
  2990. std::string authorization;
  2991. Server svr;
  2992. svr.Get("/x", [&](const Request &req, Response &res) {
  2993. if (++hits == 1) {
  2994. res.status = StatusCode::Unauthorized_401;
  2995. // On the wire the quotes embedded in the values are backslash-escaped.
  2996. res.set_header("WWW-Authenticate",
  2997. "Digest realm=\"testrealm\", "
  2998. "nonce=\"n\\\"; injected=\\\"x\", "
  2999. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3000. } else {
  3001. authorization = req.get_header_value("Authorization");
  3002. res.set_content("ok", "text/plain");
  3003. }
  3004. });
  3005. auto port = svr.bind_to_any_port(HOST);
  3006. std::thread t([&]() { svr.listen_after_bind(); });
  3007. auto se = detail::scope_exit([&] {
  3008. svr.stop();
  3009. t.join();
  3010. });
  3011. svr.wait_until_ready();
  3012. Client cli(HOST, port);
  3013. cli.set_digest_auth("hello", "world");
  3014. auto res = cli.Get("/x");
  3015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3016. EXPECT_EQ(2, hits.load());
  3017. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3018. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3019. // inside its quoted-string rather than starting an "injected" auth-param.
  3020. EXPECT_NE(std::string::npos,
  3021. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3022. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3023. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3024. }
  3025. #endif
  3026. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3027. auto host = "google.com";
  3028. auto another_host = "example.com";
  3029. auto wrong_ip = "0.0.0.0";
  3030. #ifdef CPPHTTPLIB_SSL_ENABLED
  3031. SSLClient cli(host);
  3032. #else
  3033. Client cli(host);
  3034. #endif
  3035. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3036. auto res = cli.Get("/");
  3037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3038. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3039. }
  3040. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3041. auto host = "google.com";
  3042. auto wrong_ip = "0.0.0.0";
  3043. #ifdef CPPHTTPLIB_SSL_ENABLED
  3044. SSLClient cli(host);
  3045. #else
  3046. Client cli(host);
  3047. #endif
  3048. cli.set_hostname_addr_map({{host, wrong_ip}});
  3049. auto res = cli.Get("/");
  3050. ASSERT_TRUE(!res);
  3051. EXPECT_EQ(Error::Connection, res.error());
  3052. }
  3053. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3054. // A mapped value that is not an IP literal must be resolved. "localhost"
  3055. // resolves from the hosts file, so this test needs no external DNS.
  3056. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3057. auto host = "target.invalid";
  3058. Server svr;
  3059. std::string received_host;
  3060. svr.Get("/hi", [&](const Request &req, Response &res) {
  3061. received_host = req.get_header_value("Host");
  3062. res.set_content("Hello World!", "text/plain");
  3063. });
  3064. auto port = svr.bind_to_any_port(HOST);
  3065. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3066. auto se = detail::scope_exit([&] {
  3067. svr.stop();
  3068. thread.join();
  3069. ASSERT_FALSE(svr.is_running());
  3070. });
  3071. svr.wait_until_ready();
  3072. Client cli(host, port);
  3073. cli.set_hostname_addr_map({{host, HOST}});
  3074. auto res = cli.Get("/hi");
  3075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3076. EXPECT_EQ(StatusCode::OK_200, res->status);
  3077. // The mapping only redirects the connection; the identity stays host_.
  3078. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3079. }
  3080. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3081. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3082. auto host = "target.invalid";
  3083. Server svr;
  3084. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3085. res.set_content("Hello World!", "text/plain");
  3086. });
  3087. auto port = svr.bind_to_any_port("127.0.0.1");
  3088. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3089. auto se = detail::scope_exit([&] {
  3090. svr.stop();
  3091. thread.join();
  3092. ASSERT_FALSE(svr.is_running());
  3093. });
  3094. svr.wait_until_ready();
  3095. Client cli(host, port);
  3096. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3097. auto res = cli.Get("/hi");
  3098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3099. EXPECT_EQ(StatusCode::OK_200, res->status);
  3100. }
  3101. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3102. // An empty mapped value must leave host_ as the connection target. Without
  3103. // that guard the empty value would become the host argument, getaddrinfo
  3104. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3105. // loopback - silently connecting somewhere the caller never asked for.
  3106. // The server listens on loopback, so such a fallback would succeed and is
  3107. // therefore observable as a failure of this test.
  3108. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3109. Server svr;
  3110. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3111. res.set_content("Hello World!", "text/plain");
  3112. });
  3113. auto port = svr.bind_to_any_port(HOST);
  3114. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3115. auto se = detail::scope_exit([&] {
  3116. svr.stop();
  3117. thread.join();
  3118. ASSERT_FALSE(svr.is_running());
  3119. });
  3120. svr.wait_until_ready();
  3121. Client cli(blackhole, port);
  3122. cli.set_hostname_addr_map({{blackhole, ""}});
  3123. cli.set_connection_timeout(1);
  3124. auto res = cli.Get("/hi");
  3125. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3126. }
  3127. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3128. auto host = "httpbingo.org";
  3129. auto path = std::string{"/absolute-redirect/3"};
  3130. #ifdef CPPHTTPLIB_SSL_ENABLED
  3131. SSLClient cli(host);
  3132. #else
  3133. Client cli(host);
  3134. #endif
  3135. cli.set_follow_location(true);
  3136. auto res = cli.Get(path);
  3137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3138. EXPECT_EQ(StatusCode::OK_200, res->status);
  3139. }
  3140. TEST(RedirectTest, Redirect_Online) {
  3141. auto host = "httpbingo.org";
  3142. auto path = std::string{"/redirect/3"};
  3143. #ifdef CPPHTTPLIB_SSL_ENABLED
  3144. SSLClient cli(host);
  3145. #else
  3146. Client cli(host);
  3147. #endif
  3148. cli.set_follow_location(true);
  3149. auto res = cli.Get(path);
  3150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3151. EXPECT_EQ(StatusCode::OK_200, res->status);
  3152. }
  3153. TEST(RelativeRedirectTest, Redirect_Online) {
  3154. auto host = "httpbingo.org";
  3155. auto path = std::string{"/relative-redirect/3"};
  3156. #ifdef CPPHTTPLIB_SSL_ENABLED
  3157. SSLClient cli(host);
  3158. #else
  3159. Client cli(host);
  3160. #endif
  3161. cli.set_follow_location(true);
  3162. auto res = cli.Get(path);
  3163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3164. EXPECT_EQ(StatusCode::OK_200, res->status);
  3165. }
  3166. TEST(TooManyRedirectTest, Redirect_Online) {
  3167. auto host = "httpbingo.org";
  3168. auto path = std::string{"/redirect/21"};
  3169. #ifdef CPPHTTPLIB_SSL_ENABLED
  3170. SSLClient cli(host);
  3171. #else
  3172. Client cli(host);
  3173. #endif
  3174. cli.set_follow_location(true);
  3175. auto res = cli.Get(path);
  3176. ASSERT_TRUE(!res);
  3177. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3178. }
  3179. #ifdef CPPHTTPLIB_SSL_ENABLED
  3180. TEST(YahooRedirectTest, Redirect_Online) {
  3181. Client cli("yahoo.com");
  3182. auto res = cli.Get("/");
  3183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3184. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3185. cli.set_follow_location(true);
  3186. res = cli.Get("/");
  3187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3188. EXPECT_EQ(StatusCode::OK_200, res->status);
  3189. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3190. }
  3191. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3192. #define REDIR_HOST "httpbingo.org"
  3193. #define REDIR_PATH "/redirect-to"
  3194. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3195. SSLClient cli(REDIR_HOST);
  3196. cli.set_follow_location(true);
  3197. auto res =
  3198. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3200. EXPECT_EQ(StatusCode::OK_200, res->status);
  3201. }
  3202. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3203. SSLClient cli(REDIR_HOST);
  3204. cli.set_follow_location(true);
  3205. Params params;
  3206. params.emplace("url", "http://example.com");
  3207. params.emplace("status_code", "302");
  3208. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3210. EXPECT_EQ(StatusCode::OK_200, res->status);
  3211. }
  3212. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3213. SSLClient cli(REDIR_HOST);
  3214. cli.set_follow_location(true);
  3215. Params params;
  3216. params.emplace("url", "http://example.com");
  3217. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3219. EXPECT_EQ(StatusCode::OK_200, res->status);
  3220. }
  3221. TEST(UrlWithSpace, Redirect_Online) {
  3222. SSLClient cli("edge.forgecdn.net");
  3223. cli.set_follow_location(true);
  3224. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3226. EXPECT_EQ(StatusCode::OK_200, res->status);
  3227. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3228. }
  3229. #endif
  3230. #if !defined(_WIN32) && !defined(_WIN64)
  3231. TEST(ReceiveSignals, Signal) {
  3232. auto setupSignalHandlers = []() {
  3233. struct sigaction act;
  3234. sigemptyset(&act.sa_mask);
  3235. act.sa_flags = SA_SIGINFO;
  3236. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3237. switch (sig) {
  3238. case SIGINT:
  3239. default: break;
  3240. }
  3241. };
  3242. ::sigaction(SIGINT, &act, nullptr);
  3243. };
  3244. Server svr;
  3245. int port = 0;
  3246. auto thread = std::thread([&]() {
  3247. setupSignalHandlers();
  3248. port = svr.bind_to_any_port(HOST);
  3249. svr.listen_after_bind();
  3250. });
  3251. auto se = detail::scope_exit([&] {
  3252. svr.stop();
  3253. thread.join();
  3254. ASSERT_FALSE(svr.is_running());
  3255. });
  3256. svr.wait_until_ready();
  3257. ASSERT_TRUE(svr.is_running());
  3258. pthread_kill(thread.native_handle(), SIGINT);
  3259. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3260. ASSERT_TRUE(svr.is_running());
  3261. }
  3262. #endif
  3263. TEST(RedirectToDifferentPort, Redirect) {
  3264. Server svr1;
  3265. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3266. res.set_content("Hello World!", "text/plain");
  3267. });
  3268. int svr1_port = 0;
  3269. auto thread1 = std::thread([&]() {
  3270. svr1_port = svr1.bind_to_any_port(HOST);
  3271. svr1.listen_after_bind();
  3272. });
  3273. Server svr2;
  3274. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3275. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3276. });
  3277. int svr2_port = 0;
  3278. auto thread2 = std::thread([&]() {
  3279. svr2_port = svr2.bind_to_any_port(HOST);
  3280. svr2.listen_after_bind();
  3281. });
  3282. auto se = detail::scope_exit([&] {
  3283. svr2.stop();
  3284. thread2.join();
  3285. svr1.stop();
  3286. thread1.join();
  3287. ASSERT_FALSE(svr2.is_running());
  3288. ASSERT_FALSE(svr1.is_running());
  3289. });
  3290. svr1.wait_until_ready();
  3291. svr2.wait_until_ready();
  3292. Client cli("localhost", svr2_port);
  3293. cli.set_follow_location(true);
  3294. auto res = cli.Get("/2");
  3295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3296. EXPECT_EQ(StatusCode::OK_200, res->status);
  3297. EXPECT_EQ("Hello World!", res->body);
  3298. }
  3299. // GET /redir on one server redirects to /target on another port, so the
  3300. // client follows it with a new client.
  3301. static Result
  3302. GetThroughRedirectToDifferentPort(Server::Handler target,
  3303. const std::function<void(Client &)> &setup,
  3304. const Headers &headers = Headers()) {
  3305. Server target_svr;
  3306. target_svr.Get("/target", target);
  3307. int target_port = 0;
  3308. auto target_thread = std::thread([&]() {
  3309. target_port = target_svr.bind_to_any_port(HOST);
  3310. target_svr.listen_after_bind();
  3311. });
  3312. Server origin_svr;
  3313. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3314. res.set_redirect(
  3315. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3316. });
  3317. int origin_port = 0;
  3318. auto origin_thread = std::thread([&]() {
  3319. origin_port = origin_svr.bind_to_any_port(HOST);
  3320. origin_svr.listen_after_bind();
  3321. });
  3322. auto se = detail::scope_exit([&] {
  3323. origin_svr.stop();
  3324. origin_thread.join();
  3325. target_svr.stop();
  3326. target_thread.join();
  3327. });
  3328. target_svr.wait_until_ready();
  3329. origin_svr.wait_until_ready();
  3330. Client cli("localhost", origin_port);
  3331. cli.set_follow_location(true);
  3332. setup(cli);
  3333. return cli.Get("/redir", headers);
  3334. }
  3335. static void
  3336. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3337. std::string captured_authorization;
  3338. auto result = GetThroughRedirectToDifferentPort(
  3339. [&](const Request &req, Response &res) {
  3340. captured_authorization = req.get_header_value("Authorization");
  3341. res.set_content("OK", "text/plain");
  3342. },
  3343. set_auth);
  3344. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3345. EXPECT_EQ(StatusCode::OK_200, result->status);
  3346. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3347. EXPECT_TRUE(captured_authorization.empty());
  3348. }
  3349. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3350. TestDoNotForwardCredentialsOnRedirect(
  3351. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3352. }
  3353. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3354. TestDoNotForwardCredentialsOnRedirect(
  3355. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3356. }
  3357. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3358. std::string captured_cookie;
  3359. auto result = GetThroughRedirectToDifferentPort(
  3360. [&](const Request &req, Response &res) {
  3361. captured_cookie = req.get_header_value("Cookie");
  3362. res.set_content("OK", "text/plain");
  3363. },
  3364. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3365. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3366. EXPECT_EQ(StatusCode::OK_200, result->status);
  3367. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3368. EXPECT_TRUE(captured_cookie.empty());
  3369. }
  3370. TEST(RedirectToSamePort, ForwardCookie) {
  3371. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3372. // header so that ordinary session flows keep working.
  3373. Server svr;
  3374. std::string captured_cookie;
  3375. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3376. res.set_redirect("/target", 302);
  3377. });
  3378. svr.Get("/target", [&](const Request &req, Response &res) {
  3379. captured_cookie = req.get_header_value("Cookie");
  3380. res.set_content("OK", "text/plain");
  3381. });
  3382. auto port = svr.bind_to_any_port(HOST);
  3383. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3384. auto se = detail::scope_exit([&] {
  3385. svr.stop();
  3386. thread.join();
  3387. ASSERT_FALSE(svr.is_running());
  3388. });
  3389. svr.wait_until_ready();
  3390. Client cli(HOST, port);
  3391. cli.set_follow_location(true);
  3392. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3393. auto res = cli.Get("/redir", headers);
  3394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3395. EXPECT_EQ(StatusCode::OK_200, res->status);
  3396. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3397. }
  3398. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3399. std::string authorization;
  3400. std::string trace_id;
  3401. auto result = GetThroughRedirectToDifferentPort(
  3402. [&](const Request &req, Response &res) {
  3403. authorization = req.get_header_value("Authorization");
  3404. trace_id = req.get_header_value("X-Trace-Id");
  3405. res.set_content("OK", "text/plain");
  3406. },
  3407. [](Client &cli) {
  3408. cli.set_default_headers(
  3409. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3410. });
  3411. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3412. EXPECT_EQ(StatusCode::OK_200, result->status);
  3413. // Like a header given with the request, a default one goes along unless it
  3414. // carries credentials (RFC 9110 15.4).
  3415. EXPECT_TRUE(authorization.empty());
  3416. EXPECT_EQ("42", trace_id);
  3417. }
  3418. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3419. auto result = GetThroughRedirectToDifferentPort(
  3420. [](const Request &, Response &res) {
  3421. res.set_content(std::string(2048, 'x'), "text/plain");
  3422. },
  3423. [](Client &cli) { cli.set_payload_max_length(1024); });
  3424. EXPECT_FALSE(result);
  3425. }
  3426. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3427. auto result = GetThroughRedirectToDifferentPort(
  3428. [](const Request &req, Response &res) {
  3429. // Answer after a second, or once the client gives up.
  3430. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3431. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3432. }
  3433. res.set_content("late", "text/plain");
  3434. },
  3435. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3436. ASSERT_FALSE(result);
  3437. EXPECT_EQ(Error::Read, result.error());
  3438. }
  3439. #ifdef CPPHTTPLIB_SSL_ENABLED
  3440. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3441. auto result = GetThroughRedirectToDifferentPort(
  3442. [](const Request &, Response &res) {
  3443. res.status = StatusCode::Unauthorized_401;
  3444. res.set_header("WWW-Authenticate",
  3445. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3446. },
  3447. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3448. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3449. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3450. }
  3451. #endif
  3452. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3453. Server svr;
  3454. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3455. // Port number that overflows int — should not crash
  3456. res.set_redirect("http://localhost:99999999999999999999/target");
  3457. });
  3458. auto port = svr.bind_to_any_port(HOST);
  3459. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3460. auto se = detail::scope_exit([&] {
  3461. svr.stop();
  3462. thread.join();
  3463. ASSERT_FALSE(svr.is_running());
  3464. });
  3465. svr.wait_until_ready();
  3466. Client cli(HOST, port);
  3467. cli.set_follow_location(true);
  3468. auto res = cli.Get("/redir");
  3469. // Should fail gracefully, not crash (no valid response due to bad port)
  3470. EXPECT_FALSE(res);
  3471. }
  3472. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3473. Server svr;
  3474. auto port = svr.bind_to_any_port(HOST);
  3475. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3476. // The server's own port followed by junk must not be followed
  3477. res.set_redirect("http://" + std::string(HOST) + ":" +
  3478. std::to_string(port) + "junk/target");
  3479. });
  3480. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3481. res.set_content("target", "text/plain");
  3482. });
  3483. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3484. auto se = detail::scope_exit([&] {
  3485. svr.stop();
  3486. thread.join();
  3487. ASSERT_FALSE(svr.is_running());
  3488. });
  3489. svr.wait_until_ready();
  3490. Client cli(HOST, port);
  3491. cli.set_follow_location(true);
  3492. auto res = cli.Get("/redir");
  3493. EXPECT_FALSE(res);
  3494. }
  3495. TEST(RedirectFromPageWithContent, Redirect) {
  3496. Server svr;
  3497. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3498. res.set_content("___", "text/plain");
  3499. res.set_redirect("/2");
  3500. });
  3501. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3502. res.set_content("Hello World!", "text/plain");
  3503. });
  3504. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3505. auto se = detail::scope_exit([&] {
  3506. svr.stop();
  3507. th.join();
  3508. ASSERT_FALSE(svr.is_running());
  3509. });
  3510. svr.wait_until_ready();
  3511. {
  3512. Client cli("localhost", PORT);
  3513. cli.set_follow_location(true);
  3514. std::string body;
  3515. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3516. body.append(data, data_length);
  3517. return true;
  3518. });
  3519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3520. EXPECT_EQ(StatusCode::OK_200, res->status);
  3521. EXPECT_EQ("Hello World!", body);
  3522. }
  3523. {
  3524. Client cli("localhost", PORT);
  3525. std::string body;
  3526. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3527. body.append(data, data_length);
  3528. return true;
  3529. });
  3530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3531. EXPECT_EQ(StatusCode::Found_302, res->status);
  3532. EXPECT_EQ("___", body);
  3533. }
  3534. }
  3535. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3536. Server svr;
  3537. auto port_str = std::to_string(PORT);
  3538. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3539. auto expected_host = "[::1]:" + port_str;
  3540. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3541. res.set_content("___", "text/plain");
  3542. // res.set_redirect("/2");
  3543. res.set_redirect(redirect_url);
  3544. });
  3545. svr.Get("/2", [&](const Request &req, Response &res) {
  3546. auto host_header = req.headers.find("Host");
  3547. ASSERT_TRUE(host_header != req.headers.end());
  3548. EXPECT_EQ(expected_host, host_header->second);
  3549. res.set_content("Hello World!", "text/plain");
  3550. });
  3551. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3552. auto se = detail::scope_exit([&] {
  3553. svr.stop();
  3554. th.join();
  3555. ASSERT_FALSE(svr.is_running());
  3556. });
  3557. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3558. // actually starts anything, so the condition !svr.is_running() will
  3559. // always remain true, and the loop never stops.
  3560. // This basically counts how many milliseconds have passed since the
  3561. // call to svr.listen(), and if after 5 seconds nothing started yet
  3562. // aborts the test.
  3563. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3564. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3565. ASSERT_LT(milliseconds, 5000U);
  3566. }
  3567. {
  3568. Client cli("::1", PORT);
  3569. cli.set_follow_location(true);
  3570. std::string body;
  3571. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3572. body.append(data, data_length);
  3573. return true;
  3574. });
  3575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3576. EXPECT_EQ(StatusCode::OK_200, res->status);
  3577. EXPECT_EQ("Hello World!", body);
  3578. }
  3579. {
  3580. Client cli("::1", PORT);
  3581. std::string body;
  3582. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3583. body.append(data, data_length);
  3584. return true;
  3585. });
  3586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3587. EXPECT_EQ(StatusCode::Found_302, res->status);
  3588. EXPECT_EQ("___", body);
  3589. }
  3590. }
  3591. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3592. Server svr;
  3593. svr.Get("/foo", [](const Request &req, Response &res) {
  3594. auto a = req.params.find("a");
  3595. if (a != req.params.end()) {
  3596. res.set_content((*a).second, "text/plain");
  3597. res.status = StatusCode::OK_200;
  3598. } else {
  3599. res.status = StatusCode::BadRequest_400;
  3600. }
  3601. });
  3602. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3603. auto se = detail::scope_exit([&] {
  3604. svr.stop();
  3605. thread.join();
  3606. ASSERT_FALSE(svr.is_running());
  3607. });
  3608. svr.wait_until_ready();
  3609. {
  3610. Client cli(HOST, PORT);
  3611. cli.set_path_encode(false);
  3612. auto res = cli.Get("/foo?a=explicitly+encoded");
  3613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3614. EXPECT_EQ(StatusCode::OK_200, res->status);
  3615. // This expects it back with a space, as the `+` won't have been
  3616. // url-encoded, and server-side the params get decoded turning `+`
  3617. // into spaces.
  3618. EXPECT_EQ("explicitly encoded", res->body);
  3619. }
  3620. }
  3621. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3622. // When path encoding is disabled the client must transmit the supplied
  3623. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3624. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3625. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3626. // than a space (0x20). Assert on the raw wire target to catch this.
  3627. Server svr;
  3628. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3629. svr.Get("/foo", [&](const Request &req, Response &res) {
  3630. EXPECT_EQ(expected_target, req.target);
  3631. res.status = StatusCode::OK_200;
  3632. });
  3633. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3634. auto se = detail::scope_exit([&] {
  3635. svr.stop();
  3636. thread.join();
  3637. ASSERT_FALSE(svr.is_running());
  3638. });
  3639. svr.wait_until_ready();
  3640. {
  3641. Client cli(HOST, PORT);
  3642. cli.set_path_encode(false);
  3643. auto res = cli.Get(expected_target.c_str());
  3644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3645. EXPECT_EQ(StatusCode::OK_200, res->status);
  3646. }
  3647. }
  3648. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3649. // `open_stream()` used to skip the path encoding that the buffered send
  3650. // path applies, so the same `path` produced different bytes in the request
  3651. // line depending on which API was used. Assert the two agree.
  3652. Server svr;
  3653. std::string target;
  3654. svr.Get(".*", [&](const Request &req, Response &res) {
  3655. target = req.target;
  3656. res.status = StatusCode::OK_200;
  3657. });
  3658. auto port = svr.bind_to_any_port(HOST);
  3659. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3660. auto se = detail::scope_exit([&] {
  3661. svr.stop();
  3662. thread.join();
  3663. ASSERT_FALSE(svr.is_running());
  3664. });
  3665. svr.wait_until_ready();
  3666. struct {
  3667. const char *path;
  3668. const char *expected;
  3669. } cases[] = {
  3670. {"/a b?x=1", "/a%20b?x=1"},
  3671. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3672. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3673. };
  3674. for (const auto &c : cases) {
  3675. Client cli(HOST, port);
  3676. target.clear();
  3677. auto res = cli.Get(c.path);
  3678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3679. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3680. auto buffered_target = target;
  3681. target.clear();
  3682. auto handle = cli.open_stream("GET", c.path);
  3683. EXPECT_TRUE(handle.is_valid())
  3684. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3685. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3686. }
  3687. }
  3688. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3689. // The `set_path_encode(false)` contract — transmit the supplied target
  3690. // verbatim — must hold for the streaming API too.
  3691. Server svr;
  3692. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3693. std::string target;
  3694. svr.Get("/foo", [&](const Request &req, Response &res) {
  3695. target = req.target;
  3696. res.status = StatusCode::OK_200;
  3697. });
  3698. auto port = svr.bind_to_any_port(HOST);
  3699. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3700. auto se = detail::scope_exit([&] {
  3701. svr.stop();
  3702. thread.join();
  3703. ASSERT_FALSE(svr.is_running());
  3704. });
  3705. svr.wait_until_ready();
  3706. {
  3707. Client cli(HOST, port);
  3708. cli.set_path_encode(false);
  3709. auto handle = cli.open_stream("GET", expected_target);
  3710. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3711. EXPECT_EQ(expected_target, target);
  3712. }
  3713. }
  3714. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3715. // With path encoding enabled a CR/LF in the target is percent-encoded
  3716. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3717. // write_request_line still backstops `set_path_encode(false)`, which is
  3718. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3719. Server svr;
  3720. // Captured before routing: the decoded path contains a newline, which a
  3721. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3722. std::string target;
  3723. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3724. target = req.target;
  3725. res.status = StatusCode::OK_200;
  3726. return Server::HandlerResponse::Handled;
  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. {
  3737. Client cli(HOST, port);
  3738. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3739. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3740. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3741. }
  3742. }
  3743. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3744. // Every control character is percent-encoded, not just CR/LF, so the target
  3745. // passes the request-target check in write_request_line.
  3746. Server svr;
  3747. std::string target;
  3748. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3749. target = req.target;
  3750. res.status = StatusCode::OK_200;
  3751. return Server::HandlerResponse::Handled;
  3752. });
  3753. auto port = svr.bind_to_any_port(HOST);
  3754. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3755. auto se = detail::scope_exit([&] {
  3756. svr.stop();
  3757. thread.join();
  3758. ASSERT_FALSE(svr.is_running());
  3759. });
  3760. svr.wait_until_ready();
  3761. {
  3762. Client cli(HOST, port);
  3763. auto res = cli.Get("/a\tb\x1b\x7f");
  3764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3765. EXPECT_EQ("/a%09b%1B%7F", target);
  3766. }
  3767. }
  3768. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3769. // Nothing may reach the wire: a raw CR/LF target would split the request
  3770. // line and inject headers.
  3771. Server svr;
  3772. // Pre-routing so that "not called" means nothing reached the server at all,
  3773. // rather than merely failing to match a handler pattern.
  3774. auto handler_called = false;
  3775. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3776. handler_called = true;
  3777. res.status = StatusCode::OK_200;
  3778. return Server::HandlerResponse::Handled;
  3779. });
  3780. auto port = svr.bind_to_any_port(HOST);
  3781. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3782. auto se = detail::scope_exit([&] {
  3783. svr.stop();
  3784. thread.join();
  3785. ASSERT_FALSE(svr.is_running());
  3786. });
  3787. svr.wait_until_ready();
  3788. {
  3789. Client cli(HOST, port);
  3790. cli.set_path_encode(false);
  3791. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3792. EXPECT_FALSE(handle.is_valid());
  3793. EXPECT_EQ(Error::Write, handle.error);
  3794. EXPECT_FALSE(handler_called);
  3795. }
  3796. }
  3797. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3798. // Which of the two branches runs is decided by whether the query component
  3799. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3800. // an empty query and must still fall back to building one from
  3801. // `req.params`, while a non-empty query must win over `req.params`.
  3802. Server svr;
  3803. std::string target;
  3804. svr.Get("/foo", [&](const Request &req, Response &res) {
  3805. target = req.target;
  3806. res.status = StatusCode::OK_200;
  3807. });
  3808. auto port = svr.bind_to_any_port(HOST);
  3809. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3810. auto se = detail::scope_exit([&] {
  3811. svr.stop();
  3812. thread.join();
  3813. ASSERT_FALSE(svr.is_running());
  3814. });
  3815. svr.wait_until_ready();
  3816. {
  3817. // Trailing `?` -> empty query component -> `req.params` is used.
  3818. Client cli(HOST, port);
  3819. Request req;
  3820. req.method = "GET";
  3821. req.path = "/foo?";
  3822. req.params.emplace("a", "1");
  3823. target.clear();
  3824. auto res = cli.send(req);
  3825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3826. EXPECT_EQ("/foo?a=1", target);
  3827. }
  3828. {
  3829. // Non-empty query in `req.path` -> `req.params` is not appended.
  3830. Client cli(HOST, port);
  3831. Request req;
  3832. req.method = "GET";
  3833. req.path = "/foo?b=2";
  3834. req.params.emplace("a", "1");
  3835. target.clear();
  3836. auto res = cli.send(req);
  3837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3838. EXPECT_EQ("/foo?b=2", target);
  3839. }
  3840. }
  3841. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3842. Server svr;
  3843. svr.Get("/", [](const Request &req, Response &) {
  3844. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3845. });
  3846. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3847. auto se = detail::scope_exit([&] {
  3848. svr.stop();
  3849. thread.join();
  3850. ASSERT_FALSE(svr.is_running());
  3851. });
  3852. svr.wait_until_ready();
  3853. {
  3854. Client cli(HOST, PORT);
  3855. cli.set_path_encode(false);
  3856. auto res = cli.Get("/?something=%0A");
  3857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3858. EXPECT_EQ(StatusCode::OK_200, res->status);
  3859. }
  3860. }
  3861. TEST(BindServerTest, BindDualStack) {
  3862. Server svr;
  3863. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3864. res.set_content("Hello World!", "text/plain");
  3865. });
  3866. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3867. auto se = detail::scope_exit([&] {
  3868. svr.stop();
  3869. thread.join();
  3870. ASSERT_FALSE(svr.is_running());
  3871. });
  3872. svr.wait_until_ready();
  3873. {
  3874. Client cli("127.0.0.1", PORT);
  3875. auto res = cli.Get("/1");
  3876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3877. EXPECT_EQ(StatusCode::OK_200, res->status);
  3878. EXPECT_EQ("Hello World!", res->body);
  3879. }
  3880. {
  3881. Client cli("::1", PORT);
  3882. auto res = cli.Get("/1");
  3883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3884. EXPECT_EQ(StatusCode::OK_200, res->status);
  3885. EXPECT_EQ("Hello World!", res->body);
  3886. }
  3887. }
  3888. TEST(BindServerTest, BindAndListenSeparately) {
  3889. Server svr;
  3890. int port = svr.bind_to_any_port("0.0.0.0");
  3891. ASSERT_TRUE(svr.is_valid());
  3892. ASSERT_TRUE(port > 0);
  3893. svr.stop();
  3894. }
  3895. // Reports whether anything is still listening on a loopback port. A plain
  3896. // connect() is used instead of a Client request because a socket left bound by
  3897. // mistake accepts the connection into its backlog and never answers, which
  3898. // would hang the test instead of failing it.
  3899. static bool is_loopback_port_accepting(int port) {
  3900. sockaddr_in addr{};
  3901. addr.sin_family = AF_INET;
  3902. addr.sin_port = htons(static_cast<uint16_t>(port));
  3903. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3904. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3905. EXPECT_NE(sock, INVALID_SOCKET);
  3906. if (sock == INVALID_SOCKET) { return false; }
  3907. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3908. static_cast<socklen_t>(sizeof(addr)));
  3909. detail::close_socket(sock);
  3910. return ret == 0;
  3911. }
  3912. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3913. Server svr;
  3914. auto port = svr.bind_to_any_port("127.0.0.1");
  3915. ASSERT_TRUE(port > 0);
  3916. svr.stop();
  3917. // bind_to_any_port() already called listen(2), so until stop() closed the
  3918. // descriptor the port kept accepting connections into the backlog. ASSERT
  3919. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3920. // below blocks forever in the accept loop.
  3921. ASSERT_FALSE(is_loopback_port_accepting(port));
  3922. // Nothing is left to accept on, so listen_after_bind() must report failure
  3923. // instead of returning success without ever serving.
  3924. EXPECT_FALSE(svr.listen_after_bind());
  3925. // The failed listen marks the server decommissioned, so a waiter returns
  3926. // instead of spinning forever.
  3927. svr.wait_until_ready();
  3928. }
  3929. #ifdef CPPHTTPLIB_SSL_ENABLED
  3930. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3931. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3932. CLIENT_CA_CERT_DIR);
  3933. int port = svr.bind_to_any_port("0.0.0.0");
  3934. ASSERT_TRUE(svr.is_valid());
  3935. ASSERT_TRUE(port > 0);
  3936. svr.stop();
  3937. }
  3938. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3939. // or a rejected CustomRoute() registration would not stop the server binding.
  3940. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3941. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3942. CLIENT_CA_CERT_DIR);
  3943. ASSERT_TRUE(svr.is_valid());
  3944. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3945. EXPECT_FALSE(svr.is_valid());
  3946. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3947. }
  3948. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3949. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3950. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3951. int port = svr.bind_to_any_port("0.0.0.0");
  3952. ASSERT_TRUE(svr.is_valid());
  3953. ASSERT_TRUE(port > 0);
  3954. svr.stop();
  3955. }
  3956. TEST(BindServerTest, UpdateCertsPem) {
  3957. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3958. int port = svr.bind_to_any_port("0.0.0.0");
  3959. ASSERT_TRUE(svr.is_valid());
  3960. ASSERT_TRUE(port > 0);
  3961. // Read PEM files
  3962. std::string cert_pem, key_pem, ca_pem;
  3963. read_file(SERVER_CERT_FILE, cert_pem);
  3964. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3965. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3966. // Update server certificates using PEM API
  3967. ASSERT_TRUE(
  3968. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3969. ASSERT_TRUE(svr.is_valid());
  3970. svr.stop();
  3971. }
  3972. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3973. // Start server with client CA (enables client auth)
  3974. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3975. ASSERT_TRUE(svr.is_valid());
  3976. bool handler_called = false;
  3977. svr.Get("/test", [&](const Request &req, Response &res) {
  3978. handler_called = true;
  3979. // Verify client certificate is present
  3980. auto cert = req.peer_cert();
  3981. EXPECT_TRUE(static_cast<bool>(cert));
  3982. res.set_content("ok", "text/plain");
  3983. });
  3984. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3985. auto se = detail::scope_exit([&] {
  3986. svr.stop();
  3987. t.join();
  3988. ASSERT_FALSE(svr.is_running());
  3989. });
  3990. svr.wait_until_ready();
  3991. // Read PEM files
  3992. std::string cert_pem, key_pem, ca_pem;
  3993. read_file(SERVER_CERT_FILE, cert_pem);
  3994. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3995. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3996. // Update server certificates and client CA using PEM API while server running
  3997. ASSERT_TRUE(
  3998. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3999. // Connect with client certificate
  4000. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4001. cli.enable_server_certificate_verification(false);
  4002. cli.set_connection_timeout(30);
  4003. auto res = cli.Get("/test");
  4004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4005. ASSERT_EQ(StatusCode::OK_200, res->status);
  4006. ASSERT_TRUE(handler_called);
  4007. EXPECT_EQ("ok", res->body);
  4008. }
  4009. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4010. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4011. ASSERT_TRUE(svr.is_valid());
  4012. svr.Get("/test", [](const Request &, Response &res) {
  4013. res.set_content("ok", "text/plain");
  4014. });
  4015. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4016. auto se = detail::scope_exit([&] {
  4017. svr.stop();
  4018. t.join();
  4019. ASSERT_FALSE(svr.is_running());
  4020. });
  4021. svr.wait_until_ready();
  4022. auto get = [] {
  4023. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4024. cli.enable_server_certificate_verification(false);
  4025. return cli.Get("/test");
  4026. };
  4027. ASSERT_TRUE(get());
  4028. // A CA that did not sign the client's certificate takes the old one's place.
  4029. std::string cert_pem, key_pem, ca_pem;
  4030. read_file(SERVER_CERT_FILE, cert_pem);
  4031. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4032. read_file(SERVER_CERT2_FILE, ca_pem);
  4033. ASSERT_TRUE(
  4034. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4035. EXPECT_FALSE(get());
  4036. }
  4037. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4038. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4039. ASSERT_TRUE(svr.is_valid());
  4040. svr.Get("/test", [](const Request &, Response &res) {
  4041. res.set_content("ok", "text/plain");
  4042. });
  4043. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4044. auto se = detail::scope_exit([&] {
  4045. svr.stop();
  4046. t.join();
  4047. ASSERT_FALSE(svr.is_running());
  4048. });
  4049. svr.wait_until_ready();
  4050. // A connection that sends no ClientHello keeps its handshake in progress,
  4051. // once the server has had a moment to start it.
  4052. auto error = Error::Success;
  4053. auto sock = detail::create_client_socket(
  4054. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4055. /*connection_timeout_sec=*/5, 0,
  4056. /*read_timeout_sec=*/5, 0,
  4057. /*write_timeout_sec=*/5, 0, std::string(), error);
  4058. ASSERT_NE(INVALID_SOCKET, sock);
  4059. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4060. std::string cert_pem, key_pem;
  4061. read_file(SERVER_CERT_FILE, cert_pem);
  4062. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4063. auto update = std::async(std::launch::async, [&]() {
  4064. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4065. });
  4066. EXPECT_EQ(std::future_status::timeout,
  4067. update.wait_for(std::chrono::milliseconds(200)));
  4068. detail::close_socket(sock);
  4069. EXPECT_TRUE(update.get());
  4070. SSLClient cli(HOST, PORT);
  4071. cli.enable_server_certificate_verification(false);
  4072. auto res = cli.Get("/test");
  4073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4074. EXPECT_EQ(StatusCode::OK_200, res->status);
  4075. }
  4076. #endif
  4077. TEST(ErrorHandlerTest, ContentLength) {
  4078. Server svr;
  4079. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4080. res.status = StatusCode::OK_200;
  4081. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4082. "text/html"); // <= Content-Length still 13
  4083. });
  4084. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4085. res.set_content("Hello World!\n", "text/plain");
  4086. res.status = 524;
  4087. });
  4088. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4089. auto se = detail::scope_exit([&] {
  4090. svr.stop();
  4091. thread.join();
  4092. ASSERT_FALSE(svr.is_running());
  4093. });
  4094. svr.wait_until_ready();
  4095. {
  4096. Client cli(HOST, PORT);
  4097. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4099. EXPECT_EQ(StatusCode::OK_200, res->status);
  4100. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4101. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4102. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4103. }
  4104. }
  4105. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4106. TEST(ExceptionTest, WithoutExceptionHandler) {
  4107. Server svr;
  4108. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4109. throw std::runtime_error("exception...");
  4110. });
  4111. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4112. throw std::runtime_error("exception\r\n...");
  4113. });
  4114. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4115. auto se = detail::scope_exit([&] {
  4116. svr.stop();
  4117. listen_thread.join();
  4118. ASSERT_FALSE(svr.is_running());
  4119. });
  4120. svr.wait_until_ready();
  4121. Client cli("localhost", PORT);
  4122. {
  4123. auto res = cli.Get("/exception");
  4124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4125. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4126. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4127. }
  4128. {
  4129. auto res = cli.Get("/unknown");
  4130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4131. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4132. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4133. }
  4134. }
  4135. TEST(ExceptionTest, WithExceptionHandler) {
  4136. Server svr;
  4137. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4138. std::exception_ptr ep) {
  4139. EXPECT_FALSE(ep == nullptr);
  4140. try {
  4141. std::rethrow_exception(ep);
  4142. } catch (std::exception &e) {
  4143. EXPECT_EQ("abc", std::string(e.what()));
  4144. } catch (...) {}
  4145. res.status = StatusCode::InternalServerError_500;
  4146. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4147. "text/html"); // <= Content-Length still 13 at this point
  4148. });
  4149. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4150. res.set_content("Hello World!\n", "text/plain");
  4151. throw std::runtime_error("abc");
  4152. });
  4153. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4154. auto se = detail::scope_exit([&] {
  4155. svr.stop();
  4156. thread.join();
  4157. ASSERT_FALSE(svr.is_running());
  4158. });
  4159. svr.wait_until_ready();
  4160. for (size_t i = 0; i < 10; i++) {
  4161. Client cli(HOST, PORT);
  4162. for (size_t j = 0; j < 100; j++) {
  4163. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4165. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4166. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4167. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4168. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4169. }
  4170. cli.set_keep_alive(true);
  4171. for (size_t j = 0; j < 100; j++) {
  4172. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4174. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4175. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4176. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4177. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4178. }
  4179. }
  4180. }
  4181. TEST(ExceptionTest, AndErrorHandler) {
  4182. Server svr;
  4183. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4184. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4185. });
  4186. svr.set_exception_handler(
  4187. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4188. EXPECT_FALSE(ep == nullptr);
  4189. try {
  4190. std::rethrow_exception(ep);
  4191. } catch (std::exception &e) {
  4192. res.set_content(e.what(), "text/html");
  4193. } catch (...) {}
  4194. res.status = StatusCode::InternalServerError_500;
  4195. });
  4196. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4197. throw std::runtime_error("EXCEPTION");
  4198. });
  4199. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4200. res.set_content("ERROR", "text/html");
  4201. res.status = StatusCode::InternalServerError_500;
  4202. });
  4203. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4204. auto se = detail::scope_exit([&] {
  4205. svr.stop();
  4206. thread.join();
  4207. ASSERT_FALSE(svr.is_running());
  4208. });
  4209. svr.wait_until_ready();
  4210. Client cli(HOST, PORT);
  4211. {
  4212. auto res = cli.Get("/exception");
  4213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4214. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4215. EXPECT_EQ("EXCEPTION", res->body);
  4216. }
  4217. {
  4218. auto res = cli.Get("/error");
  4219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4220. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4221. EXPECT_EQ("ERROR", res->body);
  4222. }
  4223. {
  4224. auto res = cli.Get("/invalid");
  4225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4226. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4227. EXPECT_EQ("NOT_FOUND", res->body);
  4228. }
  4229. }
  4230. #endif
  4231. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4232. // process_request() wraps only routing() in a try/catch, so an exception from
  4233. // any other user callback used to unwind into the task queue - which does not
  4234. // catch - and terminate the process. Each test below runs the server on a
  4235. // single worker thread: a guard that catches the exception but still loses the
  4236. // thread would otherwise be hidden by a spare worker serving the follow-up
  4237. // request. Note that a regression here aborts the whole test binary rather
  4238. // than failing one test.
  4239. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4240. Server svr;
  4241. svr.new_task_queue = [] { return new ThreadPool(1); };
  4242. std::atomic<int> reported{0};
  4243. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4244. if (err == Error::UserCallbackException) { reported++; }
  4245. });
  4246. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4247. res.set_content_provider(
  4248. 1024, "text/plain",
  4249. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4250. sink.write("hello", 5);
  4251. throw std::runtime_error("from the content provider");
  4252. });
  4253. });
  4254. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4255. res.set_content("ok", "text/plain");
  4256. });
  4257. auto port = svr.bind_to_any_port(HOST);
  4258. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4259. auto se = detail::scope_exit([&] {
  4260. svr.stop();
  4261. listen_thread.join();
  4262. ASSERT_FALSE(svr.is_running());
  4263. });
  4264. svr.wait_until_ready();
  4265. {
  4266. Client cli(HOST, port);
  4267. cli.set_read_timeout(5, 0);
  4268. EXPECT_FALSE(cli.Get("/throw"));
  4269. }
  4270. EXPECT_TRUE(svr.is_running());
  4271. EXPECT_EQ(1, reported.load());
  4272. // A request on a fresh connection is still served.
  4273. {
  4274. Client cli(HOST, port);
  4275. auto res = cli.Get("/ok");
  4276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4277. EXPECT_EQ(StatusCode::OK_200, res->status);
  4278. EXPECT_EQ("ok", res->body);
  4279. }
  4280. }
  4281. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4282. Server svr;
  4283. svr.new_task_queue = [] { return new ThreadPool(1); };
  4284. std::atomic<bool> should_throw{true};
  4285. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4286. res.set_content("hi", "text/plain");
  4287. });
  4288. svr.set_post_routing_handler(
  4289. [&](const Request & /*req*/, Response & /*res*/) {
  4290. if (should_throw) {
  4291. throw std::runtime_error("from the post-routing handler");
  4292. }
  4293. });
  4294. auto port = svr.bind_to_any_port(HOST);
  4295. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4296. auto se = detail::scope_exit([&] {
  4297. svr.stop();
  4298. listen_thread.join();
  4299. ASSERT_FALSE(svr.is_running());
  4300. });
  4301. svr.wait_until_ready();
  4302. {
  4303. Client cli(HOST, port);
  4304. cli.set_read_timeout(5, 0);
  4305. EXPECT_FALSE(cli.Get("/hi"));
  4306. }
  4307. EXPECT_TRUE(svr.is_running());
  4308. should_throw = false;
  4309. {
  4310. Client cli(HOST, port);
  4311. auto res = cli.Get("/hi");
  4312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4313. EXPECT_EQ(StatusCode::OK_200, res->status);
  4314. EXPECT_EQ("hi", res->body);
  4315. }
  4316. }
  4317. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4318. // The guard reports the caught exception through the error logger, which is
  4319. // a user callback too. A logger that throws has to be contained as well, or
  4320. // the process would terminate from inside the catch.
  4321. Server svr;
  4322. svr.new_task_queue = [] { return new ThreadPool(1); };
  4323. std::atomic<int> reported{0};
  4324. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4325. if (err == Error::UserCallbackException) {
  4326. reported++;
  4327. throw std::runtime_error("from the error logger");
  4328. }
  4329. });
  4330. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4331. res.set_content_provider(
  4332. 1024, "text/plain",
  4333. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4334. sink.write("hello", 5);
  4335. throw std::runtime_error("from the content provider");
  4336. });
  4337. });
  4338. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4339. res.set_content("ok", "text/plain");
  4340. });
  4341. auto port = svr.bind_to_any_port(HOST);
  4342. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4343. auto se = detail::scope_exit([&] {
  4344. svr.stop();
  4345. listen_thread.join();
  4346. ASSERT_FALSE(svr.is_running());
  4347. });
  4348. svr.wait_until_ready();
  4349. {
  4350. Client cli(HOST, port);
  4351. cli.set_read_timeout(5, 0);
  4352. EXPECT_FALSE(cli.Get("/throw"));
  4353. }
  4354. EXPECT_TRUE(svr.is_running());
  4355. EXPECT_EQ(1, reported.load());
  4356. {
  4357. Client cli(HOST, port);
  4358. auto res = cli.Get("/ok");
  4359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4360. EXPECT_EQ(StatusCode::OK_200, res->status);
  4361. EXPECT_EQ("ok", res->body);
  4362. }
  4363. }
  4364. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4365. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4366. // so the exception unwinds through the ws::WebSocket object on its way to
  4367. // the guard. None of the HTTP cases above cross that.
  4368. Server svr;
  4369. svr.new_task_queue = [] { return new ThreadPool(1); };
  4370. std::atomic<int> reported{0};
  4371. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4372. if (err == Error::UserCallbackException) { reported++; }
  4373. });
  4374. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4375. throw std::runtime_error("from the WebSocket handler");
  4376. });
  4377. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4378. res.set_content("ok", "text/plain");
  4379. });
  4380. auto port = svr.bind_to_any_port(HOST);
  4381. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4382. auto se = detail::scope_exit([&] {
  4383. svr.stop();
  4384. listen_thread.join();
  4385. ASSERT_FALSE(svr.is_running());
  4386. });
  4387. svr.wait_until_ready();
  4388. {
  4389. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4390. "/ws");
  4391. auto res = client.connect();
  4392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4393. // The server dropped the connection instead of dying.
  4394. std::string msg;
  4395. EXPECT_FALSE(client.read(msg));
  4396. client.close();
  4397. }
  4398. EXPECT_TRUE(svr.is_running());
  4399. EXPECT_EQ(1, reported.load());
  4400. {
  4401. Client cli(HOST, port);
  4402. auto res = cli.Get("/ok");
  4403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4404. EXPECT_EQ(StatusCode::OK_200, res->status);
  4405. EXPECT_EQ("ok", res->body);
  4406. }
  4407. }
  4408. #ifdef CPPHTTPLIB_SSL_ENABLED
  4409. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4410. // SSLServer::process_and_close_socket() is a separate overload with its own
  4411. // guard, so it is exercised on its own.
  4412. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4413. ASSERT_TRUE(svr.is_valid());
  4414. svr.new_task_queue = [] { return new ThreadPool(1); };
  4415. std::atomic<int> reported{0};
  4416. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4417. if (err == Error::UserCallbackException) { reported++; }
  4418. });
  4419. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4420. res.set_content_provider(
  4421. 1024, "text/plain",
  4422. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4423. sink.write("hello", 5);
  4424. throw std::runtime_error("from the content provider");
  4425. });
  4426. });
  4427. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4428. res.set_content("ok", "text/plain");
  4429. });
  4430. auto port = svr.bind_to_any_port(HOST);
  4431. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4432. auto se = detail::scope_exit([&] {
  4433. svr.stop();
  4434. listen_thread.join();
  4435. ASSERT_FALSE(svr.is_running());
  4436. });
  4437. svr.wait_until_ready();
  4438. {
  4439. SSLClient cli(HOST, port);
  4440. cli.enable_server_certificate_verification(false);
  4441. cli.set_read_timeout(5, 0);
  4442. EXPECT_FALSE(cli.Get("/throw"));
  4443. }
  4444. EXPECT_TRUE(svr.is_running());
  4445. EXPECT_EQ(1, reported.load());
  4446. {
  4447. SSLClient cli(HOST, port);
  4448. cli.enable_server_certificate_verification(false);
  4449. auto res = cli.Get("/ok");
  4450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4451. EXPECT_EQ(StatusCode::OK_200, res->status);
  4452. EXPECT_EQ("ok", res->body);
  4453. }
  4454. }
  4455. #endif
  4456. #endif
  4457. TEST(NoContentTest, ContentLength) {
  4458. Server svr;
  4459. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4460. res.status = StatusCode::NoContent_204;
  4461. });
  4462. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4463. auto se = detail::scope_exit([&] {
  4464. svr.stop();
  4465. thread.join();
  4466. ASSERT_FALSE(svr.is_running());
  4467. });
  4468. svr.wait_until_ready();
  4469. {
  4470. Client cli(HOST, PORT);
  4471. auto res = cli.Get("/hi");
  4472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4473. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4474. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4475. }
  4476. }
  4477. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4478. #ifdef CPPHTTPLIB_SSL_ENABLED
  4479. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4480. ASSERT_TRUE(svr.is_valid());
  4481. #else
  4482. Server svr;
  4483. #endif
  4484. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4485. if (req.path == "/routing_handler") {
  4486. res.set_header("PRE_ROUTING", "on");
  4487. res.set_content("Routing Handler", "text/plain");
  4488. return httplib::Server::HandlerResponse::Handled;
  4489. }
  4490. return httplib::Server::HandlerResponse::Unhandled;
  4491. });
  4492. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4493. res.set_content("Error", "text/html");
  4494. });
  4495. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4496. if (req.path == "/routing_handler") {
  4497. res.set_header("POST_ROUTING", "on");
  4498. }
  4499. });
  4500. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4501. res.set_content("Hello World!\n", "text/plain");
  4502. });
  4503. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4504. auto se = detail::scope_exit([&] {
  4505. svr.stop();
  4506. thread.join();
  4507. ASSERT_FALSE(svr.is_running());
  4508. });
  4509. svr.wait_until_ready();
  4510. {
  4511. #ifdef CPPHTTPLIB_SSL_ENABLED
  4512. SSLClient cli(HOST, PORT);
  4513. cli.enable_server_certificate_verification(false);
  4514. #else
  4515. Client cli(HOST, PORT);
  4516. #endif
  4517. auto res = cli.Get("/routing_handler");
  4518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4519. EXPECT_EQ(StatusCode::OK_200, res->status);
  4520. EXPECT_EQ("Routing Handler", res->body);
  4521. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4522. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4523. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4524. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4525. }
  4526. {
  4527. #ifdef CPPHTTPLIB_SSL_ENABLED
  4528. SSLClient cli(HOST, PORT);
  4529. cli.enable_server_certificate_verification(false);
  4530. #else
  4531. Client cli(HOST, PORT);
  4532. #endif
  4533. auto res = cli.Get("/hi");
  4534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4535. EXPECT_EQ(StatusCode::OK_200, res->status);
  4536. EXPECT_EQ("Hello World!\n", res->body);
  4537. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4538. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4539. }
  4540. {
  4541. #ifdef CPPHTTPLIB_SSL_ENABLED
  4542. SSLClient cli(HOST, PORT);
  4543. cli.enable_server_certificate_verification(false);
  4544. #else
  4545. Client cli(HOST, PORT);
  4546. #endif
  4547. auto res = cli.Get("/aaa");
  4548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4549. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4550. EXPECT_EQ("Error", res->body);
  4551. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4552. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4553. }
  4554. }
  4555. TEST(RequestHandlerTest, PreRequestHandler) {
  4556. auto route_path = "/user/:user";
  4557. Server svr;
  4558. svr.Get("/hi", [](const Request &, Response &res) {
  4559. res.set_content("hi", "text/plain");
  4560. });
  4561. svr.Get(route_path, [](const Request &req, Response &res) {
  4562. res.set_content(req.path_params.at("user"), "text/plain");
  4563. });
  4564. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4565. if (req.matched_route == route_path) {
  4566. auto user = req.path_params.at("user");
  4567. if (user != "john") {
  4568. res.status = StatusCode::Forbidden_403;
  4569. res.set_content("error", "text/html");
  4570. return Server::HandlerResponse::Handled;
  4571. }
  4572. }
  4573. return Server::HandlerResponse::Unhandled;
  4574. });
  4575. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4576. auto se = detail::scope_exit([&] {
  4577. svr.stop();
  4578. thread.join();
  4579. ASSERT_FALSE(svr.is_running());
  4580. });
  4581. svr.wait_until_ready();
  4582. Client cli(HOST, PORT);
  4583. {
  4584. auto res = cli.Get("/hi");
  4585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4586. EXPECT_EQ(StatusCode::OK_200, res->status);
  4587. EXPECT_EQ("hi", res->body);
  4588. }
  4589. {
  4590. auto res = cli.Get("/user/john");
  4591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4592. EXPECT_EQ(StatusCode::OK_200, res->status);
  4593. EXPECT_EQ("john", res->body);
  4594. }
  4595. {
  4596. auto res = cli.Get("/user/invalid-user");
  4597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4598. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4599. EXPECT_EQ("error", res->body);
  4600. }
  4601. }
  4602. // The pre-request handler must run before the request body is read, so a
  4603. // rejected request never forces the server to buffer a (potentially large)
  4604. // body. Here the posted body is larger than the payload limit: if the body
  4605. // were read first the server would answer 413, but because the pre-request
  4606. // handler runs first it answers 403 and the body is never read.
  4607. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4608. Server svr;
  4609. svr.set_payload_max_length(8);
  4610. auto handler_ran = false;
  4611. svr.Post("/reject", [&](const Request &req, Response &res) {
  4612. handler_ran = true;
  4613. res.set_content(req.body, "text/plain");
  4614. });
  4615. svr.Post("/accept", [](const Request &req, Response &res) {
  4616. res.set_content(req.body, "text/plain");
  4617. });
  4618. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4619. if (req.matched_route == "/reject") {
  4620. res.status = StatusCode::Forbidden_403;
  4621. res.set_content("denied", "text/plain");
  4622. return Server::HandlerResponse::Handled;
  4623. }
  4624. return Server::HandlerResponse::Unhandled;
  4625. });
  4626. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4627. auto se = detail::scope_exit([&] {
  4628. svr.stop();
  4629. thread.join();
  4630. ASSERT_FALSE(svr.is_running());
  4631. });
  4632. svr.wait_until_ready();
  4633. Client cli(HOST, PORT);
  4634. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4635. // rejects with 403 before the body is read, so 413 is never reached.
  4636. {
  4637. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4639. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4640. EXPECT_EQ("denied", res->body);
  4641. EXPECT_FALSE(handler_ran);
  4642. }
  4643. // An approved route still reads the body and enforces the payload limit.
  4644. {
  4645. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4647. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4648. }
  4649. }
  4650. TEST(UserDataTest, BasicOperations) {
  4651. httplib::UserData ud;
  4652. // Initially empty
  4653. EXPECT_FALSE(ud.has("key"));
  4654. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4655. // set and get
  4656. ud.set("key", 42);
  4657. EXPECT_TRUE(ud.has("key"));
  4658. auto *p = ud.get<int>("key");
  4659. ASSERT_NE(nullptr, p);
  4660. EXPECT_EQ(42, *p);
  4661. // Type mismatch → nullptr
  4662. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4663. // Overwrite with different type
  4664. ud.set("key", std::string("hello"));
  4665. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4666. auto *s = ud.get<std::string>("key");
  4667. ASSERT_NE(nullptr, s);
  4668. EXPECT_EQ("hello", *s);
  4669. // erase
  4670. ud.erase("key");
  4671. EXPECT_FALSE(ud.has("key"));
  4672. // clear
  4673. ud.set("a", 1);
  4674. ud.set("b", 2);
  4675. ud.clear();
  4676. EXPECT_FALSE(ud.has("a"));
  4677. EXPECT_FALSE(ud.has("b"));
  4678. }
  4679. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4680. struct AuthCtx {
  4681. std::string user_id;
  4682. };
  4683. Server svr;
  4684. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4685. res.user_data.set("auth", AuthCtx{"alice"});
  4686. return Server::HandlerResponse::Unhandled;
  4687. });
  4688. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4689. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4690. ASSERT_NE(nullptr, ctx);
  4691. res.set_content("Hello " + ctx->user_id, "text/plain");
  4692. });
  4693. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4694. auto se = detail::scope_exit([&] {
  4695. svr.stop();
  4696. thread.join();
  4697. ASSERT_FALSE(svr.is_running());
  4698. });
  4699. svr.wait_until_ready();
  4700. Client cli(HOST, PORT);
  4701. auto res = cli.Get("/me");
  4702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4703. EXPECT_EQ(StatusCode::OK_200, res->status);
  4704. EXPECT_EQ("Hello alice", res->body);
  4705. }
  4706. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4707. struct RoleCtx {
  4708. std::string role;
  4709. };
  4710. Server svr;
  4711. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4712. res.user_data.set("role", RoleCtx{"admin"});
  4713. return Server::HandlerResponse::Unhandled;
  4714. });
  4715. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4716. auto *ctx = res.user_data.get<RoleCtx>("role");
  4717. ASSERT_NE(nullptr, ctx);
  4718. res.set_content(ctx->role, "text/plain");
  4719. });
  4720. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4721. auto se = detail::scope_exit([&] {
  4722. svr.stop();
  4723. thread.join();
  4724. ASSERT_FALSE(svr.is_running());
  4725. });
  4726. svr.wait_until_ready();
  4727. Client cli(HOST, PORT);
  4728. auto res = cli.Get("/role");
  4729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4730. EXPECT_EQ(StatusCode::OK_200, res->status);
  4731. EXPECT_EQ("admin", res->body);
  4732. }
  4733. TEST(InvalidFormatTest, StatusCode) {
  4734. Server svr;
  4735. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4736. res.set_content("Hello World!\n", "text/plain");
  4737. res.status = 9999; // Status should be a three-digit code...
  4738. });
  4739. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4740. auto se = detail::scope_exit([&] {
  4741. svr.stop();
  4742. thread.join();
  4743. ASSERT_FALSE(svr.is_running());
  4744. });
  4745. svr.wait_until_ready();
  4746. {
  4747. Client cli(HOST, PORT);
  4748. auto res = cli.Get("/hi");
  4749. ASSERT_FALSE(res);
  4750. }
  4751. }
  4752. TEST(URLFragmentTest, WithFragment) {
  4753. Server svr;
  4754. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4755. EXPECT_TRUE(req.target == "/hi");
  4756. });
  4757. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4758. auto se = detail::scope_exit([&] {
  4759. svr.stop();
  4760. thread.join();
  4761. ASSERT_FALSE(svr.is_running());
  4762. });
  4763. svr.wait_until_ready();
  4764. {
  4765. Client cli(HOST, PORT);
  4766. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4767. EXPECT_TRUE(res);
  4768. EXPECT_EQ(StatusCode::OK_200, res->status);
  4769. res = cli.Get("/hi%23key1=val1=key2=val2");
  4770. EXPECT_TRUE(res);
  4771. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4772. }
  4773. }
  4774. TEST(HeaderWriter, SetHeaderWriter) {
  4775. Server svr;
  4776. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4777. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4778. return detail::write_headers(strm, hdrs);
  4779. });
  4780. svr.Get("/hi", [](const Request &req, Response &res) {
  4781. auto it = req.headers.find("CustomClientHeader");
  4782. EXPECT_TRUE(it != req.headers.end());
  4783. EXPECT_EQ(it->second, "CustomClientValue");
  4784. res.set_content("Hello World!\n", "text/plain");
  4785. });
  4786. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4787. auto se = detail::scope_exit([&] {
  4788. svr.stop();
  4789. thread.join();
  4790. ASSERT_FALSE(svr.is_running());
  4791. });
  4792. svr.wait_until_ready();
  4793. {
  4794. Client cli(HOST, PORT);
  4795. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4796. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4797. return detail::write_headers(strm, hdrs);
  4798. });
  4799. auto res = cli.Get("/hi");
  4800. EXPECT_TRUE(res);
  4801. EXPECT_EQ(StatusCode::OK_200, res->status);
  4802. auto it = res->headers.find("CustomServerHeader");
  4803. EXPECT_TRUE(it != res->headers.end());
  4804. EXPECT_EQ(it->second, "CustomServerValue");
  4805. }
  4806. }
  4807. class ServerTest : public ::testing::Test {
  4808. protected:
  4809. ServerTest()
  4810. : cli_(HOST, PORT)
  4811. #ifdef CPPHTTPLIB_SSL_ENABLED
  4812. ,
  4813. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4814. #endif
  4815. {
  4816. #ifdef CPPHTTPLIB_SSL_ENABLED
  4817. cli_.enable_server_certificate_verification(false);
  4818. #endif
  4819. // Allow LARGE_DATA (100MB) responses
  4820. cli_.set_payload_max_length(200 * 1024 * 1024);
  4821. }
  4822. virtual void SetUp() {
  4823. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4824. svr_.set_payload_max_length(200 * 1024 * 1024);
  4825. svr_.set_mount_point("/", "./www");
  4826. svr_.set_mount_point("/mount", "./www2");
  4827. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4828. svr_.Get("/hi",
  4829. [&](const Request & /*req*/, Response &res) {
  4830. res.set_content("Hello World!", "text/plain");
  4831. })
  4832. .Get("/file_content",
  4833. [&](const Request & /*req*/, Response &res) {
  4834. res.set_file_content("./www/dir/test.html");
  4835. })
  4836. .Get("/file_content_with_content_type",
  4837. [&](const Request & /*req*/, Response &res) {
  4838. res.set_file_content("./www/file", "text/plain");
  4839. })
  4840. .Get("/invalid_file_content",
  4841. [&](const Request & /*req*/, Response &res) {
  4842. res.set_file_content("./www/dir/invalid_file_path");
  4843. })
  4844. .Get("/http_response_splitting",
  4845. [&](const Request & /*req*/, Response &res) {
  4846. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4847. EXPECT_EQ(0U, res.headers.size());
  4848. EXPECT_FALSE(res.has_header("a"));
  4849. res.set_header("a", "1\nSet-Cookie: a=1");
  4850. EXPECT_EQ(0U, res.headers.size());
  4851. EXPECT_FALSE(res.has_header("a"));
  4852. res.set_header("a", "1\rSet-Cookie: a=1");
  4853. EXPECT_EQ(0U, res.headers.size());
  4854. EXPECT_FALSE(res.has_header("a"));
  4855. res.set_header("a\r\nb", "0");
  4856. EXPECT_EQ(0U, res.headers.size());
  4857. EXPECT_FALSE(res.has_header("a"));
  4858. res.set_header("a\rb", "0");
  4859. EXPECT_EQ(0U, res.headers.size());
  4860. EXPECT_FALSE(res.has_header("a"));
  4861. res.set_header("a\nb", "0");
  4862. EXPECT_EQ(0U, res.headers.size());
  4863. EXPECT_FALSE(res.has_header("a"));
  4864. res.set_redirect("1\r\nSet-Cookie: a=1");
  4865. EXPECT_EQ(0U, res.headers.size());
  4866. EXPECT_FALSE(res.has_header("Location"));
  4867. })
  4868. .Get("/slow",
  4869. [&](const Request & /*req*/, Response &res) {
  4870. std::this_thread::sleep_for(std::chrono::seconds(4));
  4871. res.set_content("slow", "text/plain");
  4872. })
  4873. #if 0
  4874. .Post("/slowpost",
  4875. [&](const Request & /*req*/, Response &res) {
  4876. std::this_thread::sleep_for(std::chrono::seconds(2));
  4877. res.set_content("slow", "text/plain");
  4878. })
  4879. #endif
  4880. .Get("/remote_addr",
  4881. [&](const Request &req, Response &res) {
  4882. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4883. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4884. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4885. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4886. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4887. #endif
  4888. res.set_content(req.remote_addr, "text/plain");
  4889. })
  4890. .Get("/local_addr",
  4891. [&](const Request &req, Response &res) {
  4892. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4893. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4894. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4895. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4896. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4897. #endif
  4898. auto local_addr = req.local_addr;
  4899. auto local_port = std::to_string(req.local_port);
  4900. res.set_content(local_addr.append(":").append(local_port),
  4901. "text/plain");
  4902. })
  4903. .Get("/endwith%",
  4904. [&](const Request & /*req*/, Response &res) {
  4905. res.set_content("Hello World!", "text/plain");
  4906. })
  4907. .Get("/a\\+\\+b",
  4908. [&](const Request &req, Response &res) {
  4909. ASSERT_TRUE(req.has_param("a +b"));
  4910. auto val = req.get_param_value("a +b");
  4911. res.set_content(val, "text/plain");
  4912. })
  4913. .Get("/", [&](const Request & /*req*/,
  4914. Response &res) { res.set_redirect("/hi"); })
  4915. .Post("/1",
  4916. [](const Request & /*req*/, Response &res) {
  4917. res.set_redirect("/2", StatusCode::SeeOther_303);
  4918. })
  4919. .Get("/2",
  4920. [](const Request & /*req*/, Response &res) {
  4921. res.set_content("redirected.", "text/plain");
  4922. res.status = StatusCode::OK_200;
  4923. })
  4924. .Post("/person",
  4925. [&](const Request &req, Response &res) {
  4926. if (req.has_param("name") && req.has_param("note")) {
  4927. persons_[req.get_param_value("name")] =
  4928. req.get_param_value("note");
  4929. } else {
  4930. res.status = StatusCode::BadRequest_400;
  4931. }
  4932. })
  4933. .Put("/person",
  4934. [&](const Request &req, Response &res) {
  4935. if (req.has_param("name") && req.has_param("note")) {
  4936. persons_[req.get_param_value("name")] =
  4937. req.get_param_value("note");
  4938. } else {
  4939. res.status = StatusCode::BadRequest_400;
  4940. }
  4941. })
  4942. .Get("/person/(.*)",
  4943. [&](const Request &req, Response &res) {
  4944. string name = req.matches[1];
  4945. if (persons_.find(name) != persons_.end()) {
  4946. auto note = persons_[name];
  4947. res.set_content(note, "text/plain");
  4948. } else {
  4949. res.status = StatusCode::NotFound_404;
  4950. }
  4951. })
  4952. .Delete("/person",
  4953. [&](const Request &req, Response &res) {
  4954. if (req.has_param("name")) {
  4955. string name = req.get_param_value("name");
  4956. if (persons_.find(name) != persons_.end()) {
  4957. persons_.erase(name);
  4958. res.set_content("DELETED", "text/plain");
  4959. } else {
  4960. res.status = StatusCode::NotFound_404;
  4961. }
  4962. } else {
  4963. res.status = StatusCode::BadRequest_400;
  4964. }
  4965. })
  4966. .Post("/x-www-form-urlencoded-json",
  4967. [&](const Request &req, Response &res) {
  4968. auto json = req.get_param_value("json");
  4969. ASSERT_EQ(JSON_DATA, json);
  4970. res.set_content(json, "appliation/json");
  4971. res.status = StatusCode::OK_200;
  4972. })
  4973. .Get("/streamed-chunked",
  4974. [&](const Request & /*req*/, Response &res) {
  4975. res.set_chunked_content_provider(
  4976. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4977. sink.os << "123";
  4978. sink.os << "456";
  4979. sink.os << "789";
  4980. sink.done();
  4981. return true;
  4982. });
  4983. })
  4984. .Get("/streamed-chunked-with-prohibited-trailer",
  4985. [&](const Request & /*req*/, Response &res) {
  4986. auto i = new int(0);
  4987. // Declare both a prohibited trailer (Content-Length) and an
  4988. // allowed one
  4989. res.set_header("Trailer", "Content-Length, X-Allowed");
  4990. res.set_chunked_content_provider(
  4991. "text/plain",
  4992. [i](size_t /*offset*/, DataSink &sink) {
  4993. switch (*i) {
  4994. case 0: sink.os << "123"; break;
  4995. case 1: sink.os << "456"; break;
  4996. case 2: sink.os << "789"; break;
  4997. case 3: {
  4998. sink.done_with_trailer(
  4999. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5000. } break;
  5001. }
  5002. (*i)++;
  5003. return true;
  5004. },
  5005. [i](bool success) {
  5006. EXPECT_TRUE(success);
  5007. delete i;
  5008. });
  5009. })
  5010. .Get("/streamed-chunked2",
  5011. [&](const Request & /*req*/, Response &res) {
  5012. auto i = new int(0);
  5013. res.set_chunked_content_provider(
  5014. "text/plain",
  5015. [i](size_t /*offset*/, DataSink &sink) {
  5016. switch (*i) {
  5017. case 0: sink.os << "123"; break;
  5018. case 1: sink.os << "456"; break;
  5019. case 2: sink.os << "789"; break;
  5020. case 3: sink.done(); break;
  5021. }
  5022. (*i)++;
  5023. return true;
  5024. },
  5025. [i](bool success) {
  5026. EXPECT_TRUE(success);
  5027. delete i;
  5028. });
  5029. })
  5030. .Get("/streamed-chunked-with-trailer",
  5031. [&](const Request & /*req*/, Response &res) {
  5032. auto i = new int(0);
  5033. res.set_header("Trailer", "Dummy1, Dummy2");
  5034. res.set_chunked_content_provider(
  5035. "text/plain",
  5036. [i](size_t /*offset*/, DataSink &sink) {
  5037. switch (*i) {
  5038. case 0: sink.os << "123"; break;
  5039. case 1: sink.os << "456"; break;
  5040. case 2: sink.os << "789"; break;
  5041. case 3: {
  5042. sink.done_with_trailer(
  5043. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5044. } break;
  5045. }
  5046. (*i)++;
  5047. return true;
  5048. },
  5049. [i](bool success) {
  5050. EXPECT_TRUE(success);
  5051. delete i;
  5052. });
  5053. })
  5054. .Get("/streamed",
  5055. [&](const Request & /*req*/, Response &res) {
  5056. res.set_content_provider(
  5057. 6, "text/plain",
  5058. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5059. sink.os << (offset < 3 ? "a" : "b");
  5060. return true;
  5061. });
  5062. })
  5063. .Get("/streamed-without-length",
  5064. [&](const Request & /*req*/, Response &res) {
  5065. auto data = new std::string("abcdefg");
  5066. res.set_content_provider(
  5067. "text/plain",
  5068. [data](size_t offset, DataSink &sink) {
  5069. if (offset < data->size()) {
  5070. sink.os << data->substr(offset);
  5071. }
  5072. sink.done();
  5073. return true;
  5074. },
  5075. [data](bool success) {
  5076. EXPECT_TRUE(success);
  5077. delete data;
  5078. });
  5079. })
  5080. .Get("/streamed-with-range",
  5081. [&](const Request &req, Response &res) {
  5082. auto data = new std::string("abcdefg");
  5083. // An explicit status keeps the server from picking the 206 it
  5084. // would otherwise choose for a ranged request, so the response
  5085. // is not a partial representation.
  5086. auto status = req.get_param_value("status");
  5087. if (status == "200") {
  5088. res.status = StatusCode::OK_200;
  5089. } else if (status == "403") {
  5090. res.status = StatusCode::Forbidden_403;
  5091. }
  5092. res.set_content_provider(
  5093. data->size(), "text/plain",
  5094. [data](size_t offset, size_t length, DataSink &sink) {
  5095. size_t DATA_CHUNK_SIZE = 4;
  5096. const auto &d = *data;
  5097. auto out_len =
  5098. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5099. auto ret =
  5100. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5101. EXPECT_TRUE(ret);
  5102. return true;
  5103. },
  5104. [data, &req](bool success) {
  5105. EXPECT_EQ(success, !req.has_param("error"));
  5106. delete data;
  5107. });
  5108. })
  5109. .Get("/streamed-cancel",
  5110. [&](const Request & /*req*/, Response &res) {
  5111. res.set_content_provider(
  5112. size_t(-1), "text/plain",
  5113. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5114. sink.os << "data_chunk";
  5115. return true;
  5116. });
  5117. })
  5118. .Get("/regex-with-delimiter",
  5119. [&](const Request &req, Response & /*res*/) {
  5120. ASSERT_TRUE(req.has_param("key"));
  5121. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5122. })
  5123. .Get("/with-range",
  5124. [&](const Request & /*req*/, Response &res) {
  5125. res.set_content("abcdefg", "text/plain");
  5126. })
  5127. .Get("/test-start-time",
  5128. [&](const Request &req, Response & /*res*/) {
  5129. EXPECT_NE(req.start_time_,
  5130. std::chrono::steady_clock::time_point::min());
  5131. })
  5132. .Get("/with-range-customized-response",
  5133. [&](const Request & /*req*/, Response &res) {
  5134. res.status = StatusCode::BadRequest_400;
  5135. res.set_content(JSON_DATA, "application/json");
  5136. })
  5137. .Post("/chunked",
  5138. [&](const Request &req, Response & /*res*/) {
  5139. EXPECT_EQ(req.body, "dechunked post body");
  5140. })
  5141. .Post("/large-chunked",
  5142. [&](const Request &req, Response & /*res*/) {
  5143. std::string expected(6 * 30 * 1024u, 'a');
  5144. EXPECT_EQ(req.body, expected);
  5145. })
  5146. .Post("/multipart",
  5147. [&](const Request &req, Response & /*res*/) {
  5148. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5149. req.form.get_field_count("text2") +
  5150. req.form.get_field_count("file3") +
  5151. req.form.get_field_count("file4"));
  5152. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5153. req.form.get_file_count("file2"));
  5154. ASSERT_TRUE(!req.form.has_file("???"));
  5155. ASSERT_TRUE(!req.form.has_field("???"));
  5156. ASSERT_TRUE(req.body.empty());
  5157. {
  5158. const auto &text = req.form.get_field("text1");
  5159. EXPECT_EQ("text default", text);
  5160. }
  5161. {
  5162. const auto &text = req.form.get_field("text2");
  5163. EXPECT_EQ("aωb", text);
  5164. }
  5165. {
  5166. const auto &file = req.form.get_file("file1");
  5167. EXPECT_EQ("hello.txt", file.filename);
  5168. EXPECT_EQ("text/plain", file.content_type);
  5169. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5170. }
  5171. {
  5172. const auto &file = req.form.get_file("file2");
  5173. EXPECT_EQ("world.json", file.filename);
  5174. EXPECT_EQ("application/json", file.content_type);
  5175. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5176. }
  5177. {
  5178. const auto &text = req.form.get_field("file3");
  5179. EXPECT_EQ(0u, text.size());
  5180. }
  5181. {
  5182. const auto &text = req.form.get_field("file4");
  5183. EXPECT_EQ(0u, text.size());
  5184. }
  5185. })
  5186. .Post("/multipart/multi_file_values",
  5187. [&](const Request &req, Response & /*res*/) {
  5188. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5189. req.form.get_field_count("multi_text1"));
  5190. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5191. ASSERT_TRUE(!req.form.has_file("???"));
  5192. ASSERT_TRUE(!req.form.has_field("???"));
  5193. ASSERT_TRUE(req.body.empty());
  5194. {
  5195. const auto &text = req.form.get_field("text");
  5196. EXPECT_EQ("default text", text);
  5197. }
  5198. {
  5199. const auto &text1_values = req.form.get_fields("multi_text1");
  5200. EXPECT_EQ(2u, text1_values.size());
  5201. EXPECT_EQ("aaaaa", text1_values[0]);
  5202. EXPECT_EQ("bbbbb", text1_values[1]);
  5203. }
  5204. {
  5205. const auto &file1_values = req.form.get_files("multi_file1");
  5206. EXPECT_EQ(2u, file1_values.size());
  5207. auto file1 = file1_values[0];
  5208. EXPECT_EQ(file1.filename, "hello.txt");
  5209. EXPECT_EQ(file1.content_type, "text/plain");
  5210. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5211. auto file2 = file1_values[1];
  5212. EXPECT_EQ(file2.filename, "world.json");
  5213. EXPECT_EQ(file2.content_type, "application/json");
  5214. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5215. }
  5216. })
  5217. .Post("/empty",
  5218. [&](const Request &req, Response &res) {
  5219. EXPECT_EQ(req.body, "");
  5220. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5221. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5222. res.set_content("empty", "text/plain");
  5223. })
  5224. .Post("/empty-no-content-type",
  5225. [&](const Request &req, Response &res) {
  5226. EXPECT_EQ(req.body, "");
  5227. EXPECT_FALSE(req.has_header("Content-Type"));
  5228. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5229. res.set_content("empty-no-content-type", "text/plain");
  5230. })
  5231. .Post("/path-only",
  5232. [&](const Request &req, Response &res) {
  5233. EXPECT_EQ(req.body, "");
  5234. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5235. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5236. res.set_content("path-only", "text/plain");
  5237. })
  5238. .Post("/path-headers-only",
  5239. [&](const Request &req, Response &res) {
  5240. EXPECT_EQ(req.body, "");
  5241. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5242. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5243. EXPECT_EQ("world", req.get_header_value("hello"));
  5244. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5245. res.set_content("path-headers-only", "text/plain");
  5246. })
  5247. .Post("/post-large",
  5248. [&](const Request &req, Response &res) {
  5249. EXPECT_EQ(req.body, LARGE_DATA);
  5250. res.set_content(req.body, "text/plain");
  5251. })
  5252. .Post("/post-loopback",
  5253. [&](const Request &, Response &res,
  5254. ContentReader const &content_reader) {
  5255. std::string body;
  5256. content_reader([&](const char *data, size_t data_length) {
  5257. body.append(data, data_length);
  5258. return true;
  5259. });
  5260. res.set_content(body, "text/plain");
  5261. })
  5262. .Put("/put-loopback",
  5263. [&](const Request &, Response &res,
  5264. ContentReader const &content_reader) {
  5265. std::string body;
  5266. content_reader([&](const char *data, size_t data_length) {
  5267. body.append(data, data_length);
  5268. return true;
  5269. });
  5270. res.set_content(body, "text/plain");
  5271. })
  5272. .Patch("/patch-loopback",
  5273. [&](const Request &, Response &res,
  5274. ContentReader const &content_reader) {
  5275. std::string body;
  5276. content_reader([&](const char *data, size_t data_length) {
  5277. body.append(data, data_length);
  5278. return true;
  5279. });
  5280. res.set_content(body, "text/plain");
  5281. })
  5282. .Put("/empty-no-content-type",
  5283. [&](const Request &req, Response &res) {
  5284. EXPECT_EQ(req.body, "");
  5285. EXPECT_FALSE(req.has_header("Content-Type"));
  5286. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5287. res.set_content("empty-no-content-type", "text/plain");
  5288. })
  5289. .Put("/put",
  5290. [&](const Request &req, Response &res) {
  5291. EXPECT_EQ(req.body, "PUT");
  5292. res.set_content(req.body, "text/plain");
  5293. })
  5294. .Put("/put-large",
  5295. [&](const Request &req, Response &res) {
  5296. EXPECT_EQ(req.body, LARGE_DATA);
  5297. res.set_content(req.body, "text/plain");
  5298. })
  5299. .Patch("/patch",
  5300. [&](const Request &req, Response &res) {
  5301. EXPECT_EQ(req.body, "PATCH");
  5302. res.set_content(req.body, "text/plain");
  5303. })
  5304. .Delete("/delete",
  5305. [&](const Request & /*req*/, Response &res) {
  5306. res.set_content("DELETE", "text/plain");
  5307. })
  5308. .Delete("/delete-body",
  5309. [&](const Request &req, Response &res) {
  5310. EXPECT_EQ(req.body, "content");
  5311. res.set_content(req.body, "text/plain");
  5312. })
  5313. .Options(R"(\*)",
  5314. [&](const Request & /*req*/, Response &res) {
  5315. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5316. })
  5317. .CustomRoute("PROPFIND", "/dav/:id",
  5318. [&](const Request &req, Response &res) {
  5319. res.set_header("x-body-size",
  5320. std::to_string(req.body.size()));
  5321. res.set_header("x-matched-route", req.matched_route);
  5322. res.set_header("x-dav-id", req.path_params.at("id"));
  5323. res.status = StatusCode::MultiStatus_207;
  5324. res.set_content(req.body, "application/xml");
  5325. })
  5326. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5327. [&](const Request &req, Response &res) {
  5328. res.set_header("x-dav-match", req.matches[1]);
  5329. res.status = StatusCode::MultiStatus_207;
  5330. })
  5331. .CustomRoute("MKCOL", "/dav-mkcol",
  5332. [&](const Request &req, Response &res) {
  5333. EXPECT_TRUE(req.body.empty());
  5334. res.status = StatusCode::Created_201;
  5335. })
  5336. .CustomRoute(
  5337. "REPORT", "/dav-report",
  5338. [&](const Request & /*req*/, Response &res,
  5339. const ContentReader &content_reader) {
  5340. std::string body;
  5341. content_reader([&](const char *data, size_t data_length) {
  5342. body.append(data, data_length);
  5343. return true;
  5344. });
  5345. res.set_header("x-body-size", std::to_string(body.size()));
  5346. res.status = StatusCode::MultiStatus_207;
  5347. res.set_content(body, "application/xml");
  5348. })
  5349. .Get("/request-target",
  5350. [&](const Request &req, Response & /*res*/) {
  5351. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5352. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5353. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5354. })
  5355. .Get("/long-query-value",
  5356. [&](const Request &req, Response & /*res*/) {
  5357. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5358. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5359. })
  5360. .Get("/too-long-query-value",
  5361. [&](const Request &req, Response & /*res*/) {
  5362. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5363. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5364. })
  5365. .Get("/array-param",
  5366. [&](const Request &req, Response & /*res*/) {
  5367. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5368. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5369. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5370. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5371. })
  5372. .Get("/array-param-values",
  5373. [&](const Request &req, Response & /*res*/) {
  5374. auto values = req.get_param_values("array");
  5375. EXPECT_EQ(3u, values.size());
  5376. EXPECT_EQ("value1", values[0]);
  5377. EXPECT_EQ("value2", values[1]);
  5378. EXPECT_EQ("value3", values[2]);
  5379. auto empty = req.get_param_values("nonexistent");
  5380. EXPECT_TRUE(empty.empty());
  5381. })
  5382. .Post("/validate-no-multiple-headers",
  5383. [&](const Request &req, Response & /*res*/) {
  5384. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5385. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5386. })
  5387. .Post("/content_receiver",
  5388. [&](const Request &req, Response &res,
  5389. const ContentReader &content_reader) {
  5390. if (req.is_multipart_form_data()) {
  5391. std::vector<FormData> items;
  5392. content_reader(
  5393. [&](const FormData &file) {
  5394. items.push_back(file);
  5395. return true;
  5396. },
  5397. [&](const char *data, size_t data_length) {
  5398. items.back().content.append(data, data_length);
  5399. return true;
  5400. });
  5401. EXPECT_EQ(5u, items.size());
  5402. {
  5403. const auto &file = get_file_value(items, "text1");
  5404. EXPECT_TRUE(file.filename.empty());
  5405. EXPECT_EQ("text default", file.content);
  5406. }
  5407. {
  5408. const auto &file = get_file_value(items, "text2");
  5409. EXPECT_TRUE(file.filename.empty());
  5410. EXPECT_EQ("aωb", file.content);
  5411. }
  5412. {
  5413. const auto &file = get_file_value(items, "file1");
  5414. EXPECT_EQ("hello.txt", file.filename);
  5415. EXPECT_EQ("text/plain", file.content_type);
  5416. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5417. }
  5418. {
  5419. const auto &file = get_file_value(items, "file2");
  5420. EXPECT_EQ("world.json", file.filename);
  5421. EXPECT_EQ("application/json", file.content_type);
  5422. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5423. }
  5424. {
  5425. const auto &file = get_file_value(items, "file3");
  5426. EXPECT_TRUE(file.filename.empty());
  5427. EXPECT_EQ("application/octet-stream", file.content_type);
  5428. EXPECT_EQ(0u, file.content.size());
  5429. }
  5430. } else {
  5431. std::string body;
  5432. content_reader([&](const char *data, size_t data_length) {
  5433. EXPECT_EQ(7U, data_length);
  5434. body.append(data, data_length);
  5435. return true;
  5436. });
  5437. EXPECT_EQ(body, "content");
  5438. res.set_content(body, "text/plain");
  5439. }
  5440. })
  5441. .Put("/content_receiver",
  5442. [&](const Request & /*req*/, Response &res,
  5443. const ContentReader &content_reader) {
  5444. std::string body;
  5445. content_reader([&](const char *data, size_t data_length) {
  5446. body.append(data, data_length);
  5447. return true;
  5448. });
  5449. EXPECT_EQ(body, "content");
  5450. res.set_content(body, "text/plain");
  5451. })
  5452. .Patch("/content_receiver",
  5453. [&](const Request & /*req*/, Response &res,
  5454. const ContentReader &content_reader) {
  5455. std::string body;
  5456. content_reader([&](const char *data, size_t data_length) {
  5457. body.append(data, data_length);
  5458. return true;
  5459. });
  5460. EXPECT_EQ(body, "content");
  5461. res.set_content(body, "text/plain");
  5462. })
  5463. .Post("/query-string-and-body",
  5464. [&](const Request &req, Response & /*res*/) {
  5465. ASSERT_TRUE(req.has_param("key"));
  5466. EXPECT_EQ(req.get_param_value("key"), "value");
  5467. EXPECT_EQ(req.body, "content");
  5468. })
  5469. .Get("/last-request",
  5470. [&](const Request &req, Response & /*res*/) {
  5471. EXPECT_EQ("close", req.get_header_value("Connection"));
  5472. })
  5473. .Get(R"(/redirect/(\d+))",
  5474. [&](const Request &req, Response &res) {
  5475. auto num = std::stoi(req.matches[1]) + 1;
  5476. std::string url = "/redirect/" + std::to_string(num);
  5477. res.set_redirect(url);
  5478. })
  5479. .Post("/binary",
  5480. [&](const Request &req, Response &res) {
  5481. EXPECT_EQ(4U, req.body.size());
  5482. EXPECT_EQ("application/octet-stream",
  5483. req.get_header_value("Content-Type"));
  5484. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5485. res.set_content(req.body, "application/octet-stream");
  5486. })
  5487. .Put("/binary",
  5488. [&](const Request &req, Response &res) {
  5489. EXPECT_EQ(4U, req.body.size());
  5490. EXPECT_EQ("application/octet-stream",
  5491. req.get_header_value("Content-Type"));
  5492. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5493. res.set_content(req.body, "application/octet-stream");
  5494. })
  5495. .Patch("/binary",
  5496. [&](const Request &req, Response &res) {
  5497. EXPECT_EQ(4U, req.body.size());
  5498. EXPECT_EQ("application/octet-stream",
  5499. req.get_header_value("Content-Type"));
  5500. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5501. res.set_content(req.body, "application/octet-stream");
  5502. })
  5503. .Delete("/binary",
  5504. [&](const Request &req, Response &res) {
  5505. EXPECT_EQ(4U, req.body.size());
  5506. EXPECT_EQ("application/octet-stream",
  5507. req.get_header_value("Content-Type"));
  5508. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5509. res.set_content(req.body, "application/octet-stream");
  5510. })
  5511. .Get("/issue1772",
  5512. [&](const Request & /*req*/, Response &res) {
  5513. res.status = 401;
  5514. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5515. })
  5516. .Delete("/issue609",
  5517. [](const httplib::Request &, httplib::Response &res,
  5518. const httplib::ContentReader &) {
  5519. res.set_content("ok", "text/plain");
  5520. })
  5521. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5522. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5523. .Get("/compress",
  5524. [&](const Request & /*req*/, Response &res) {
  5525. res.set_content(
  5526. "12345678901234567890123456789012345678901234567890123456789"
  5527. "01234567890123456789012345678901234567890",
  5528. "text/plain");
  5529. })
  5530. .Get("/compress-with-charset",
  5531. [&](const Request & /*req*/, Response &res) {
  5532. res.set_content(
  5533. "12345678901234567890123456789012345678901234567890123456789"
  5534. "01234567890123456789012345678901234567890",
  5535. "application/json; charset=utf-8");
  5536. })
  5537. .Get("/nocompress",
  5538. [&](const Request & /*req*/, Response &res) {
  5539. res.set_content(
  5540. "12345678901234567890123456789012345678901234567890123456789"
  5541. "01234567890123456789012345678901234567890",
  5542. "application/octet-stream");
  5543. })
  5544. .Post("/compress-multipart",
  5545. [&](const Request &req, Response & /*res*/) {
  5546. EXPECT_EQ(2u, req.form.fields.size());
  5547. ASSERT_TRUE(!req.form.has_field("???"));
  5548. {
  5549. const auto &text = req.form.get_field("key1");
  5550. EXPECT_EQ("test", text);
  5551. }
  5552. {
  5553. const auto &text = req.form.get_field("key2");
  5554. EXPECT_EQ("--abcdefg123", text);
  5555. }
  5556. })
  5557. #endif
  5558. ;
  5559. persons_["john"] = "programmer";
  5560. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5561. svr_.wait_until_ready();
  5562. }
  5563. virtual void TearDown() {
  5564. svr_.stop();
  5565. if (!request_threads_.empty()) {
  5566. std::this_thread::sleep_for(std::chrono::seconds(1));
  5567. for (auto &t : request_threads_) {
  5568. t.join();
  5569. }
  5570. }
  5571. t_.join();
  5572. }
  5573. map<string, string> persons_;
  5574. #ifdef CPPHTTPLIB_SSL_ENABLED
  5575. SSLClient cli_;
  5576. SSLServer svr_;
  5577. #else
  5578. Client cli_;
  5579. Server svr_;
  5580. #endif
  5581. thread t_;
  5582. std::vector<thread> request_threads_;
  5583. };
  5584. TEST_F(ServerTest, GetMethod200) {
  5585. auto res = cli_.Get("/hi");
  5586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5587. EXPECT_EQ("HTTP/1.1", res->version);
  5588. EXPECT_EQ(StatusCode::OK_200, res->status);
  5589. EXPECT_EQ("OK", res->reason);
  5590. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5591. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5592. EXPECT_EQ("Hello World!", res->body);
  5593. }
  5594. TEST_F(ServerTest, GetEmptyFile) {
  5595. auto res = cli_.Get("/empty_file");
  5596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5597. EXPECT_EQ(StatusCode::OK_200, res->status);
  5598. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5599. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5600. EXPECT_EQ("", res->body);
  5601. }
  5602. TEST_F(ServerTest, GetFileContent) {
  5603. auto res = cli_.Get("/file_content");
  5604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5605. EXPECT_EQ(StatusCode::OK_200, res->status);
  5606. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5607. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5608. EXPECT_EQ("test.html", res->body);
  5609. }
  5610. TEST_F(ServerTest, GetFileContentWithRange) {
  5611. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5613. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5614. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5615. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5616. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5617. EXPECT_EQ("est", res->body);
  5618. }
  5619. TEST_F(ServerTest, GetFileContentWithContentType) {
  5620. auto res = cli_.Get("/file_content_with_content_type");
  5621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5622. EXPECT_EQ(StatusCode::OK_200, res->status);
  5623. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5624. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5625. EXPECT_EQ("file\n", res->body);
  5626. }
  5627. TEST_F(ServerTest, GetInvalidFileContent) {
  5628. auto res = cli_.Get("/invalid_file_content");
  5629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5630. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5631. }
  5632. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5633. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5635. EXPECT_EQ("HTTP/1.1", res->version);
  5636. EXPECT_EQ(StatusCode::OK_200, res->status);
  5637. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5638. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5639. EXPECT_EQ("Hello World!", res->body);
  5640. }
  5641. TEST_F(ServerTest, GetMethod302) {
  5642. auto res = cli_.Get("/");
  5643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5644. EXPECT_EQ(StatusCode::Found_302, res->status);
  5645. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5646. }
  5647. TEST_F(ServerTest, GetMethod302Redirect) {
  5648. cli_.set_follow_location(true);
  5649. auto res = cli_.Get("/");
  5650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5651. EXPECT_EQ(StatusCode::OK_200, res->status);
  5652. EXPECT_EQ("Hello World!", res->body);
  5653. EXPECT_EQ("/hi", res->location);
  5654. }
  5655. TEST_F(ServerTest, GetMethod404) {
  5656. auto res = cli_.Get("/invalid");
  5657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5658. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5659. }
  5660. TEST_F(ServerTest, HeadMethod200) {
  5661. auto res = cli_.Head("/hi");
  5662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5663. EXPECT_EQ(StatusCode::OK_200, res->status);
  5664. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5665. EXPECT_TRUE(res->body.empty());
  5666. }
  5667. TEST_F(ServerTest, HeadMethod200Static) {
  5668. auto res = cli_.Head("/mount/dir/index.html");
  5669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5670. EXPECT_EQ(StatusCode::OK_200, res->status);
  5671. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5672. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5673. EXPECT_TRUE(res->body.empty());
  5674. }
  5675. TEST_F(ServerTest, HeadMethod404) {
  5676. auto res = cli_.Head("/invalid");
  5677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5678. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5679. EXPECT_TRUE(res->body.empty());
  5680. }
  5681. TEST_F(ServerTest, GetMethodPersonJohn) {
  5682. auto res = cli_.Get("/person/john");
  5683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5684. EXPECT_EQ(StatusCode::OK_200, res->status);
  5685. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5686. EXPECT_EQ("programmer", res->body);
  5687. }
  5688. TEST_F(ServerTest, PostMethod1) {
  5689. auto res = cli_.Get("/person/john1");
  5690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5691. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5692. res = cli_.Post("/person", "name=john1&note=coder",
  5693. "application/x-www-form-urlencoded");
  5694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5695. ASSERT_EQ(StatusCode::OK_200, res->status);
  5696. res = cli_.Get("/person/john1");
  5697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5698. ASSERT_EQ(StatusCode::OK_200, res->status);
  5699. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5700. ASSERT_EQ("coder", res->body);
  5701. }
  5702. TEST_F(ServerTest, PostMethod2) {
  5703. auto res = cli_.Get("/person/john2");
  5704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5705. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5706. Params params;
  5707. params.emplace("name", "john2");
  5708. params.emplace("note", "coder");
  5709. res = cli_.Post("/person", params);
  5710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5711. ASSERT_EQ(StatusCode::OK_200, res->status);
  5712. res = cli_.Get("/person/john2");
  5713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5714. ASSERT_EQ(StatusCode::OK_200, res->status);
  5715. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5716. ASSERT_EQ("coder", res->body);
  5717. }
  5718. TEST_F(ServerTest, PutMethod3) {
  5719. auto res = cli_.Get("/person/john3");
  5720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5721. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5722. Params params;
  5723. params.emplace("name", "john3");
  5724. params.emplace("note", "coder");
  5725. res = cli_.Put("/person", params);
  5726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5727. ASSERT_EQ(StatusCode::OK_200, res->status);
  5728. res = cli_.Get("/person/john3");
  5729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5730. ASSERT_EQ(StatusCode::OK_200, res->status);
  5731. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5732. ASSERT_EQ("coder", res->body);
  5733. }
  5734. TEST_F(ServerTest, DeleteMethod1) {
  5735. auto res = cli_.Get("/person/john4");
  5736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5737. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5738. Params params;
  5739. params.emplace("name", "john4");
  5740. params.emplace("note", "coder");
  5741. res = cli_.Post("/person", params);
  5742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5743. ASSERT_EQ(StatusCode::OK_200, res->status);
  5744. res = cli_.Get("/person/john4");
  5745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5746. ASSERT_EQ(StatusCode::OK_200, res->status);
  5747. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5748. ASSERT_EQ("coder", res->body);
  5749. Params delete_params;
  5750. delete_params.emplace("name", "john4");
  5751. res = cli_.Delete("/person", delete_params);
  5752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5753. ASSERT_EQ(StatusCode::OK_200, res->status);
  5754. ASSERT_EQ("DELETED", res->body);
  5755. res = cli_.Get("/person/john4");
  5756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5757. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5758. }
  5759. TEST_F(ServerTest, DeleteMethod2) {
  5760. auto res = cli_.Get("/person/john5");
  5761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5762. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5763. Params params;
  5764. params.emplace("name", "john5");
  5765. params.emplace("note", "developer");
  5766. res = cli_.Post("/person", params);
  5767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5768. ASSERT_EQ(StatusCode::OK_200, res->status);
  5769. res = cli_.Get("/person/john5");
  5770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5771. ASSERT_EQ(StatusCode::OK_200, res->status);
  5772. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5773. ASSERT_EQ("developer", res->body);
  5774. Params delete_params;
  5775. delete_params.emplace("name", "john5");
  5776. Headers headers;
  5777. headers.emplace("Custom-Header", "test-value");
  5778. res = cli_.Delete("/person", headers, delete_params);
  5779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5780. ASSERT_EQ(StatusCode::OK_200, res->status);
  5781. ASSERT_EQ("DELETED", res->body);
  5782. res = cli_.Get("/person/john5");
  5783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5784. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5785. }
  5786. TEST_F(ServerTest, DeleteMethod3) {
  5787. auto res = cli_.Get("/person/john6");
  5788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5789. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5790. Params params;
  5791. params.emplace("name", "john6");
  5792. params.emplace("note", "tester");
  5793. res = cli_.Post("/person", params);
  5794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5795. ASSERT_EQ(StatusCode::OK_200, res->status);
  5796. res = cli_.Get("/person/john6");
  5797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5798. ASSERT_EQ(StatusCode::OK_200, res->status);
  5799. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5800. ASSERT_EQ("tester", res->body);
  5801. Params delete_params;
  5802. delete_params.emplace("name", "john6");
  5803. Headers headers;
  5804. headers.emplace("Custom-Header", "test-value");
  5805. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5807. ASSERT_EQ(StatusCode::OK_200, res->status);
  5808. ASSERT_EQ("DELETED", res->body);
  5809. res = cli_.Get("/person/john6");
  5810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5811. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5812. }
  5813. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5814. Params params;
  5815. params.emplace("json", JSON_DATA);
  5816. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5818. ASSERT_EQ(StatusCode::OK_200, res->status);
  5819. ASSERT_EQ(JSON_DATA, res->body);
  5820. }
  5821. TEST_F(ServerTest, PostEmptyContent) {
  5822. auto res = cli_.Post("/empty", "", "text/plain");
  5823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5824. ASSERT_EQ(StatusCode::OK_200, res->status);
  5825. ASSERT_EQ("empty", res->body);
  5826. }
  5827. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5828. auto res = cli_.Post("/empty-no-content-type");
  5829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5830. ASSERT_EQ(StatusCode::OK_200, res->status);
  5831. ASSERT_EQ("empty-no-content-type", res->body);
  5832. }
  5833. TEST_F(ServerTest, PostPathOnly) {
  5834. auto res = cli_.Post("/path-only");
  5835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5836. ASSERT_EQ(StatusCode::OK_200, res->status);
  5837. ASSERT_EQ("path-only", res->body);
  5838. }
  5839. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5840. auto res = cli_.Post("/path-headers-only",
  5841. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5843. ASSERT_EQ(StatusCode::OK_200, res->status);
  5844. ASSERT_EQ("path-headers-only", res->body);
  5845. }
  5846. TEST_F(ServerTest, PostLarge) {
  5847. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5849. ASSERT_EQ(StatusCode::OK_200, res->status);
  5850. EXPECT_EQ(LARGE_DATA, res->body);
  5851. }
  5852. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5853. auto res = cli_.Put("/empty-no-content-type");
  5854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5855. ASSERT_EQ(StatusCode::OK_200, res->status);
  5856. ASSERT_EQ("empty-no-content-type", res->body);
  5857. }
  5858. TEST_F(ServerTest, GetMethodDir) {
  5859. auto res = cli_.Get("/dir/");
  5860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5861. EXPECT_EQ(StatusCode::OK_200, res->status);
  5862. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5863. auto body = R"(<html>
  5864. <head>
  5865. </head>
  5866. <body>
  5867. <a href="/dir/test.html">Test</a>
  5868. <a href="/hi">hi</a>
  5869. </body>
  5870. </html>
  5871. )";
  5872. EXPECT_EQ(body, res->body);
  5873. }
  5874. TEST_F(ServerTest, GetMethodDirTest) {
  5875. auto res = cli_.Get("/dir/test.html");
  5876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5877. EXPECT_EQ(StatusCode::OK_200, res->status);
  5878. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5879. EXPECT_EQ("test.html", res->body);
  5880. }
  5881. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5882. auto res = cli_.Get("/dir/../dir/test.html");
  5883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5884. EXPECT_EQ(StatusCode::OK_200, res->status);
  5885. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5886. EXPECT_EQ("test.html", res->body);
  5887. }
  5888. TEST_F(ServerTest, GetMethodInvalidPath) {
  5889. auto res = cli_.Get("/dir/../test.html");
  5890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5891. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5892. }
  5893. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5894. auto res = cli_.Get("/../www/dir/test.html");
  5895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5896. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5897. }
  5898. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5899. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5901. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5902. }
  5903. TEST_F(ServerTest, GetMethodDirMountTest) {
  5904. auto res = cli_.Get("/mount/dir/test.html");
  5905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5906. EXPECT_EQ(StatusCode::OK_200, res->status);
  5907. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5908. EXPECT_EQ("test.html", res->body);
  5909. }
  5910. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5911. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5913. EXPECT_EQ(StatusCode::OK_200, res->status);
  5914. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5915. EXPECT_EQ("test.html", res->body);
  5916. }
  5917. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5918. auto res = cli_.Get("/mount/dir/../test.html");
  5919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5920. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5921. }
  5922. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5923. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5925. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5926. }
  5927. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5928. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5930. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5931. }
  5932. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5933. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5935. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5936. }
  5937. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5938. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5940. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5941. }
  5942. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  5943. auto res = cli_.Get("/mount/dir");
  5944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5945. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5946. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5947. }
  5948. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  5949. auto res = cli_.Get("//dir");
  5950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5951. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5952. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5953. }
  5954. TEST_F(ServerTest, PostMethod303) {
  5955. auto res = cli_.Post("/1", "body", "text/plain");
  5956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5957. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5958. EXPECT_EQ("/2", res->get_header_value("Location"));
  5959. }
  5960. TEST_F(ServerTest, PostMethod303Redirect) {
  5961. cli_.set_follow_location(true);
  5962. auto res = cli_.Post("/1", "body", "text/plain");
  5963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5964. EXPECT_EQ(StatusCode::OK_200, res->status);
  5965. EXPECT_EQ("redirected.", res->body);
  5966. EXPECT_EQ("/2", res->location);
  5967. }
  5968. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5969. auto res = cli_.Get("/dir/test.abcde");
  5970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5971. EXPECT_EQ(StatusCode::OK_200, res->status);
  5972. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5973. EXPECT_EQ("abcde", res->body);
  5974. }
  5975. TEST_F(ServerTest, StaticFileRange) {
  5976. auto res =
  5977. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5979. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5980. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5981. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5982. EXPECT_EQ(true, res->has_header("Content-Range"));
  5983. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5984. EXPECT_EQ(std::string("cd"), res->body);
  5985. }
  5986. TEST_F(ServerTest, StaticFileRanges) {
  5987. auto res = cli_.Get("/dir/test.abcde",
  5988. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5990. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5991. EXPECT_TRUE(
  5992. res->get_header_value("Content-Type")
  5993. .find(
  5994. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5995. 0);
  5996. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5997. }
  5998. TEST_F(ServerTest, StaticFileRangeHead) {
  5999. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6001. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6002. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6003. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6004. EXPECT_EQ(true, res->has_header("Content-Range"));
  6005. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6006. }
  6007. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6008. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6010. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6011. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6012. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6013. EXPECT_EQ(true, res->has_header("Content-Range"));
  6014. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6015. res->get_header_value("Content-Range"));
  6016. EXPECT_EQ("LAST\n", res->body);
  6017. }
  6018. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6019. auto res =
  6020. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6022. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6023. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6024. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6025. EXPECT_EQ(true, res->has_header("Content-Range"));
  6026. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6027. }
  6028. TEST_F(ServerTest, StaticFileBigFile) {
  6029. auto res = cli_.Get("/dir/1MB.txt");
  6030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6031. EXPECT_EQ(StatusCode::OK_200, res->status);
  6032. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6033. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6034. }
  6035. TEST_F(ServerTest, InvalidBaseDirMount) {
  6036. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6037. }
  6038. TEST_F(ServerTest, Binary) {
  6039. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6040. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6041. "application/octet-stream");
  6042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6043. ASSERT_EQ(StatusCode::OK_200, res->status);
  6044. ASSERT_EQ(4U, res->body.size());
  6045. res = cli_.Put("/binary", binary.data(), binary.size(),
  6046. "application/octet-stream");
  6047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6048. ASSERT_EQ(StatusCode::OK_200, res->status);
  6049. ASSERT_EQ(4U, res->body.size());
  6050. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6051. "application/octet-stream");
  6052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6053. ASSERT_EQ(StatusCode::OK_200, res->status);
  6054. ASSERT_EQ(4U, res->body.size());
  6055. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6056. "application/octet-stream");
  6057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6058. ASSERT_EQ(StatusCode::OK_200, res->status);
  6059. ASSERT_EQ(4U, res->body.size());
  6060. }
  6061. TEST_F(ServerTest, BinaryString) {
  6062. auto binary = std::string("\x00\x01\x02\x03", 4);
  6063. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6065. ASSERT_EQ(StatusCode::OK_200, res->status);
  6066. ASSERT_EQ(4U, res->body.size());
  6067. res = cli_.Put("/binary", binary, "application/octet-stream");
  6068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6069. ASSERT_EQ(StatusCode::OK_200, res->status);
  6070. ASSERT_EQ(4U, res->body.size());
  6071. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6073. ASSERT_EQ(StatusCode::OK_200, res->status);
  6074. ASSERT_EQ(4U, res->body.size());
  6075. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6077. ASSERT_EQ(StatusCode::OK_200, res->status);
  6078. ASSERT_EQ(4U, res->body.size());
  6079. }
  6080. TEST_F(ServerTest, EmptyRequest) {
  6081. auto res = cli_.Get("");
  6082. ASSERT_TRUE(!res);
  6083. EXPECT_EQ(Error::Connection, res.error());
  6084. }
  6085. TEST_F(ServerTest, LongRequest) {
  6086. std::string request;
  6087. for (size_t i = 0; i < 545; i++) {
  6088. request += "/TooLongRequest";
  6089. }
  6090. request += "OK";
  6091. auto res = cli_.Get(request.c_str());
  6092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6093. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6094. }
  6095. TEST_F(ServerTest, TooLongRequest) {
  6096. std::string request;
  6097. for (size_t i = 0; i < 546; i++) {
  6098. request += "/TooLongRequest";
  6099. }
  6100. request += "_NG";
  6101. auto start = std::chrono::high_resolution_clock::now();
  6102. cli_.set_keep_alive(true);
  6103. auto res = cli_.Get(request.c_str());
  6104. auto end = std::chrono::high_resolution_clock::now();
  6105. auto elapsed =
  6106. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6107. .count();
  6108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6109. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6110. EXPECT_LE(elapsed, 1000);
  6111. EXPECT_EQ("close", res->get_header_value("Connection"));
  6112. EXPECT_FALSE(cli_.is_socket_open());
  6113. }
  6114. TEST_F(ServerTest, AlmostTooLongRequest) {
  6115. // test for #2046 - URI length check shouldn't include other content on req
  6116. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6117. // leading /, space, HTTP/1.1)
  6118. std::string request =
  6119. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6120. auto res = cli_.Get(request.c_str());
  6121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6122. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6123. }
  6124. TEST_F(ServerTest, LongHeader) {
  6125. Request req;
  6126. req.method = "GET";
  6127. req.path = "/hi";
  6128. std::string host_and_port;
  6129. host_and_port += HOST;
  6130. host_and_port += ":";
  6131. host_and_port += std::to_string(PORT);
  6132. req.headers.emplace("Host", host_and_port.c_str());
  6133. req.headers.emplace("Accept", "*/*");
  6134. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6135. req.headers.emplace(
  6136. "Header-Name",
  6137. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6138. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6139. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6140. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6141. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6142. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6143. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6144. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6145. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6146. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6147. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6148. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6149. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6150. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6151. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6152. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6153. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6154. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6155. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6156. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6157. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6158. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6159. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6160. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6161. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6162. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6163. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6164. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6165. "@@@@@@@@@@@@@@@@");
  6166. auto res = std::make_shared<Response>();
  6167. auto error = Error::Success;
  6168. auto ret = cli_.send(req, *res, error);
  6169. ASSERT_TRUE(ret);
  6170. EXPECT_EQ(StatusCode::OK_200, res->status);
  6171. }
  6172. TEST_F(ServerTest, LongQueryValue) {
  6173. auto start = std::chrono::high_resolution_clock::now();
  6174. cli_.set_keep_alive(true);
  6175. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6176. auto end = std::chrono::high_resolution_clock::now();
  6177. auto elapsed =
  6178. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6179. .count();
  6180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6181. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6182. EXPECT_LE(elapsed, 1000);
  6183. EXPECT_EQ("close", res->get_header_value("Connection"));
  6184. EXPECT_FALSE(cli_.is_socket_open());
  6185. }
  6186. TEST_F(ServerTest, TooLongQueryValue) {
  6187. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6188. ASSERT_FALSE(res);
  6189. EXPECT_EQ(Error::Read, res.error());
  6190. }
  6191. TEST_F(ServerTest, TooLongHeader) {
  6192. Request req;
  6193. req.method = "GET";
  6194. req.path = "/hi";
  6195. std::string host_and_port;
  6196. host_and_port += HOST;
  6197. host_and_port += ":";
  6198. host_and_port += std::to_string(PORT);
  6199. req.headers.emplace("Host", host_and_port.c_str());
  6200. req.headers.emplace("Accept", "*/*");
  6201. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6202. req.headers.emplace(
  6203. "Header-Name",
  6204. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6205. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6206. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6207. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6208. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6209. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6210. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6211. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6212. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6213. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6214. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6215. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6216. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6217. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6218. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6219. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6220. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6221. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6222. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6223. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6224. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6225. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6226. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6227. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6228. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6229. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6230. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6231. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6232. "@@@@@@@@@@@@@@@@@");
  6233. auto res = std::make_shared<Response>();
  6234. auto error = Error::Success;
  6235. auto ret = cli_.send(req, *res, error);
  6236. ASSERT_TRUE(ret);
  6237. EXPECT_EQ(StatusCode::OK_200, res->status);
  6238. }
  6239. TEST_F(ServerTest, HeaderCountAtLimit) {
  6240. // Test with headers just under the 100 limit
  6241. httplib::Headers headers;
  6242. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6243. // This should keep us just under the 100 header limit
  6244. for (int i = 0; i < 95; i++) {
  6245. std::string name = "X-Test-Header-" + std::to_string(i);
  6246. std::string value = "value" + std::to_string(i);
  6247. headers.emplace(name, value);
  6248. }
  6249. // This should work fine as we're under the limit
  6250. auto res = cli_.Get("/hi", headers);
  6251. EXPECT_TRUE(res);
  6252. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6253. }
  6254. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6255. // Test with many headers to exceed the 100 limit
  6256. httplib::Headers headers;
  6257. // Add 150 headers to definitely exceed the 100 limit
  6258. for (int i = 0; i < 150; i++) {
  6259. std::string name = "X-Test-Header-" + std::to_string(i);
  6260. std::string value = "value" + std::to_string(i);
  6261. headers.emplace(name, value);
  6262. }
  6263. // This should fail due to exceeding header count limit
  6264. cli_.set_keep_alive(true);
  6265. auto res = cli_.Get("/hi", headers);
  6266. // The server should respond with 400 Bad Request
  6267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6268. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6269. EXPECT_EQ("close", res->get_header_value("Connection"));
  6270. EXPECT_FALSE(cli_.is_socket_open());
  6271. }
  6272. TEST_F(ServerTest, PercentEncoding) {
  6273. auto res = cli_.Get("/e%6edwith%");
  6274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6275. EXPECT_EQ(StatusCode::OK_200, res->status);
  6276. }
  6277. TEST_F(ServerTest, PercentEncodingUnicode) {
  6278. auto res = cli_.Get("/e%u006edwith%");
  6279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6280. EXPECT_EQ(StatusCode::OK_200, res->status);
  6281. }
  6282. TEST_F(ServerTest, InvalidPercentEncoding) {
  6283. auto res = cli_.Get("/%endwith%");
  6284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6285. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6286. }
  6287. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6288. auto res = cli_.Get("/%uendwith%");
  6289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6290. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6291. }
  6292. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6293. auto res = cli_.Get("/hello?aaa=bbb%");
  6294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6295. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6296. }
  6297. TEST_F(ServerTest, PlusSignEncoding) {
  6298. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6300. EXPECT_EQ(StatusCode::OK_200, res->status);
  6301. EXPECT_EQ("a +b", res->body);
  6302. }
  6303. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6304. // This test simulates a potential DoS attack using many headers
  6305. // to verify our security fix prevents memory exhaustion
  6306. httplib::Headers attack_headers;
  6307. // Attempt to add many headers like an attacker would (200 headers to far
  6308. // exceed limit)
  6309. for (int i = 0; i < 200; i++) {
  6310. std::string name = "X-Attack-Header-" + std::to_string(i);
  6311. std::string value = "attack_payload_" + std::to_string(i);
  6312. attack_headers.emplace(name, value);
  6313. }
  6314. // Try to POST with excessive headers
  6315. cli_.set_keep_alive(true);
  6316. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6317. // Should either fail or return 400 Bad Request due to security limit
  6318. if (res) {
  6319. // If we get a response, it should be 400 Bad Request
  6320. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6321. EXPECT_EQ("close", res->get_header_value("Connection"));
  6322. }
  6323. EXPECT_FALSE(cli_.is_socket_open());
  6324. }
  6325. TEST_F(ServerTest, MultipartFormData) {
  6326. UploadFormDataItems items = {
  6327. {"text1", "text default", "", ""},
  6328. {"text2", "aωb", "", ""},
  6329. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6330. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6331. {"file3", "", "", "application/octet-stream"},
  6332. {"file4", "", "", " application/json tmp-string "}};
  6333. auto res = cli_.Post("/multipart", items);
  6334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6335. EXPECT_EQ(StatusCode::OK_200, res->status);
  6336. }
  6337. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6338. UploadFormDataItems items = {
  6339. {"text", "default text", "", ""},
  6340. {"multi_text1", "aaaaa", "", ""},
  6341. {"multi_text1", "bbbbb", "", ""},
  6342. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6343. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6344. "application/json"},
  6345. };
  6346. auto res = cli_.Post("/multipart/multi_file_values", items);
  6347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6348. EXPECT_EQ(StatusCode::OK_200, res->status);
  6349. }
  6350. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6351. auto res = cli_.Get("/hi");
  6352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6353. EXPECT_EQ(StatusCode::OK_200, res->status);
  6354. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6355. EXPECT_EQ("Hello World!", res->body);
  6356. }
  6357. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6358. Request req;
  6359. req.method = "POST";
  6360. req.path = "/chunked";
  6361. std::string host_and_port;
  6362. host_and_port += HOST;
  6363. host_and_port += ":";
  6364. host_and_port += std::to_string(PORT);
  6365. req.headers.emplace("Host", host_and_port.c_str());
  6366. req.headers.emplace("Accept", "*/*");
  6367. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6368. req.headers.emplace("Content-Type", "text/plain");
  6369. req.headers.emplace("Content-Length", "0");
  6370. req.headers.emplace(
  6371. "Transfer-Encoding",
  6372. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6373. // Client does not chunk, so make a chunked body manually.
  6374. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6375. auto res = std::make_shared<Response>();
  6376. auto error = Error::Success;
  6377. auto ret = cli_.send(req, *res, error);
  6378. ASSERT_TRUE(ret);
  6379. EXPECT_EQ(StatusCode::OK_200, res->status);
  6380. }
  6381. template <typename ClientT>
  6382. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6383. int expected_status) {
  6384. Request req;
  6385. req.method = "POST";
  6386. req.path = "/chunked";
  6387. std::string host_and_port;
  6388. host_and_port += HOST;
  6389. host_and_port += ":";
  6390. host_and_port += std::to_string(PORT);
  6391. req.headers.emplace("Host", host_and_port.c_str());
  6392. req.headers.emplace("Content-Length", "0");
  6393. req.headers.emplace("Transfer-Encoding", "chunked");
  6394. req.body = body;
  6395. auto res = std::make_shared<Response>();
  6396. auto error = Error::Success;
  6397. ASSERT_TRUE(cli.send(req, *res, error));
  6398. EXPECT_EQ(expected_status, res->status);
  6399. }
  6400. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6401. // rather than treat them as valid lengths.
  6402. template <typename ClientT>
  6403. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6404. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6405. }
  6406. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6407. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6408. }
  6409. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6410. expect_chunked_body_rejected(
  6411. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6412. }
  6413. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6414. // chunk-size line carries no CR, LF or other control character ahead of its
  6415. // terminator. Such a line must be refused rather than read as extension text.
  6416. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6417. expect_chunked_body_rejected(
  6418. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6419. }
  6420. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6421. expect_chunked_body_rejected(
  6422. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6423. }
  6424. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6425. expect_chunked_body_rejected(
  6426. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6427. }
  6428. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6429. // The literal stays split: a hex escape consumes every hex digit that
  6430. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6431. expect_chunked_body_rejected(
  6432. cli_, "4;a\x01"
  6433. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6434. }
  6435. TEST_F(ServerTest, AcceptsChunkExtension) {
  6436. expect_chunked_body_status(cli_,
  6437. "4;name=value\r\ndech\r\n"
  6438. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6439. "0;last\r\n\r\n",
  6440. StatusCode::OK_200);
  6441. }
  6442. TEST_F(ServerTest, GetStreamed2) {
  6443. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6445. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6446. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6447. EXPECT_EQ(true, res->has_header("Content-Range"));
  6448. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6449. EXPECT_EQ(std::string("ab"), res->body);
  6450. }
  6451. TEST_F(ServerTest, GetStreamed) {
  6452. auto res = cli_.Get("/streamed");
  6453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6454. EXPECT_EQ(StatusCode::OK_200, res->status);
  6455. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6456. EXPECT_EQ(std::string("aaabbb"), res->body);
  6457. }
  6458. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6459. auto res = cli_.Get("/streamed-without-length",
  6460. Headers{make_range_header({{0, -1}})});
  6461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6462. EXPECT_EQ(StatusCode::OK_200, res->status);
  6463. EXPECT_EQ(false, res->has_header("Content-Length"));
  6464. EXPECT_EQ(false, res->has_header("Content-Range"));
  6465. EXPECT_EQ(std::string("abcdefg"), res->body);
  6466. }
  6467. TEST_F(ServerTest, GetStreamedWithRange1) {
  6468. auto res =
  6469. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6471. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6472. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6473. EXPECT_EQ(true, res->has_header("Content-Range"));
  6474. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6475. EXPECT_EQ(std::string("def"), res->body);
  6476. }
  6477. TEST_F(ServerTest, GetStreamedWithRange2) {
  6478. auto res =
  6479. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6481. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6482. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6483. EXPECT_EQ(true, res->has_header("Content-Range"));
  6484. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6485. EXPECT_EQ(std::string("bcdefg"), res->body);
  6486. }
  6487. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6488. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6490. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6491. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6492. EXPECT_EQ(true, res->has_header("Content-Range"));
  6493. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6494. EXPECT_EQ(std::string("efg"), res->body);
  6495. }
  6496. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6497. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6498. // the entire representation.
  6499. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6500. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6502. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6503. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6504. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6505. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6506. }
  6507. }
  6508. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6509. auto res =
  6510. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6512. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6513. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6514. EXPECT_EQ(false, res->has_header("Content-Range"));
  6515. EXPECT_EQ(0U, res->body.size());
  6516. }
  6517. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6518. // Only a 206 is served as a partial representation. Under any other status
  6519. // `apply_ranges()` reported the full content length, so the body must match
  6520. // that header, and the content provider must never be asked for an offset
  6521. // outside the representation.
  6522. auto check = [&](int status, const char *range) {
  6523. auto path =
  6524. std::string("/streamed-with-range?status=") + std::to_string(status);
  6525. auto ctx = path + " Range: " + range;
  6526. auto res = cli_.Get(path, Headers{{"Range", range}});
  6527. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6528. EXPECT_EQ(status, res->status) << ctx;
  6529. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6530. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6531. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6532. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6533. };
  6534. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6535. check(403, "bytes=3-5");
  6536. // The offset is far past the representation.
  6537. check(403, "bytes=100000-100200");
  6538. // `first_pos` is still -1 here, and the bounds asserts in
  6539. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6540. check(403, "bytes=-3");
  6541. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6542. // multipart branch would have written one that is empty.
  6543. check(403, "bytes=1-2, 4-5");
  6544. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6545. // covers the whole representation.
  6546. check(200, "bytes=3-5");
  6547. check(200, "bytes=1-2, 4-5");
  6548. }
  6549. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6550. auto res =
  6551. cli_.Get("/streamed-with-range",
  6552. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6553. "92233720368547758079223372036854775807"}});
  6554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6555. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6556. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6557. EXPECT_EQ(false, res->has_header("Content-Range"));
  6558. EXPECT_EQ(0U, res->body.size());
  6559. }
  6560. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6561. auto res = cli_.Get(
  6562. "/with-range",
  6563. Headers{{"Range",
  6564. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6565. {"Accept-Encoding", ""}});
  6566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6567. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6568. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6569. EXPECT_EQ(true, res->has_header("Content-Range"));
  6570. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6571. EXPECT_EQ(std::string("abcdefg"), res->body);
  6572. }
  6573. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6574. auto res = cli_.Get("/with-range", Headers{
  6575. {"Range", "bytes=0-"},
  6576. {"Accept-Encoding", ""},
  6577. });
  6578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6579. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6580. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6581. EXPECT_EQ(true, res->has_header("Content-Range"));
  6582. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6583. EXPECT_EQ(std::string("abcdefg"), res->body);
  6584. }
  6585. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6586. auto res = cli_.Get("/streamed-with-range",
  6587. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6589. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6590. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6591. EXPECT_EQ(false, res->has_header("Content-Range"));
  6592. EXPECT_EQ(267U, res->body.size());
  6593. // Check that both range contents are present
  6594. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6595. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6596. // Check that Content-Range headers are present for both ranges
  6597. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6598. std::string::npos);
  6599. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6600. std::string::npos);
  6601. }
  6602. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6603. Ranges ranges;
  6604. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6605. ranges.emplace_back(0, -1);
  6606. }
  6607. auto res = cli_.Get("/streamed-with-range?error",
  6608. Headers{{make_range_header(ranges)}});
  6609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6610. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6611. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6612. EXPECT_EQ(false, res->has_header("Content-Range"));
  6613. EXPECT_EQ(0U, res->body.size());
  6614. }
  6615. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6616. auto res = cli_.Get("/streamed-with-range",
  6617. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6619. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6620. EXPECT_EQ(5U, res->body.size());
  6621. // Check that overlapping ranges are coalesced into a single range
  6622. EXPECT_EQ("bcdef", res->body);
  6623. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6624. // Should be single range, not multipart
  6625. EXPECT_TRUE(res->has_header("Content-Range"));
  6626. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6627. }
  6628. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6629. auto res = cli_.Get("/streamed-with-range",
  6630. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6632. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6633. EXPECT_EQ(268U, res->body.size());
  6634. // Check that both range contents are present
  6635. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6636. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6637. // Check that Content-Range headers are present for both ranges
  6638. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6639. std::string::npos);
  6640. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6641. std::string::npos);
  6642. }
  6643. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6644. auto res = cli_.Get("/streamed-with-range",
  6645. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6647. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6648. EXPECT_EQ(269U, res->body.size());
  6649. // Check that both duplicate range contents are present
  6650. size_t first_abc = res->body.find("abc\r\n");
  6651. EXPECT_TRUE(first_abc != std::string::npos);
  6652. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6653. EXPECT_TRUE(second_abc != std::string::npos);
  6654. // Check that Content-Range headers are present for both ranges
  6655. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6656. EXPECT_TRUE(first_range != std::string::npos);
  6657. size_t second_range =
  6658. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6659. EXPECT_TRUE(second_range != std::string::npos);
  6660. }
  6661. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6662. auto res =
  6663. cli_.Get("/streamed-with-range?error",
  6664. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6666. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6667. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6668. EXPECT_EQ(false, res->has_header("Content-Range"));
  6669. EXPECT_EQ(0U, res->body.size());
  6670. }
  6671. TEST_F(ServerTest, GetStreamedEndless) {
  6672. uint64_t offset = 0;
  6673. auto res = cli_.Get("/streamed-cancel",
  6674. [&](const char * /*data*/, uint64_t data_length) {
  6675. if (offset < 100) {
  6676. offset += data_length;
  6677. return true;
  6678. }
  6679. return false;
  6680. });
  6681. ASSERT_TRUE(!res);
  6682. EXPECT_EQ(Error::Canceled, res.error());
  6683. }
  6684. TEST_F(ServerTest, ClientStop) {
  6685. std::atomic_size_t count{4};
  6686. std::vector<std::thread> threads;
  6687. for (auto i = count.load(); i != 0; --i) {
  6688. threads.emplace_back([&]() {
  6689. auto res = cli_.Get("/streamed-cancel",
  6690. [&](const char *, uint64_t) { return true; });
  6691. --count;
  6692. ASSERT_TRUE(!res);
  6693. EXPECT_TRUE(res.error() == Error::Canceled ||
  6694. res.error() == Error::Read || res.error() == Error::Write);
  6695. });
  6696. }
  6697. std::this_thread::sleep_for(std::chrono::seconds(2));
  6698. while (count != 0) {
  6699. cli_.stop();
  6700. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6701. }
  6702. for (auto &t : threads) {
  6703. t.join();
  6704. }
  6705. }
  6706. TEST_F(ServerTest, GetWithRange1) {
  6707. auto res = cli_.Get("/with-range", Headers{
  6708. make_range_header({{3, 5}}),
  6709. {"Accept-Encoding", ""},
  6710. });
  6711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6712. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6713. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6714. EXPECT_EQ(true, res->has_header("Content-Range"));
  6715. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6716. EXPECT_EQ(std::string("def"), res->body);
  6717. }
  6718. TEST_F(ServerTest, GetWithRange2) {
  6719. auto res = cli_.Get("/with-range", Headers{
  6720. make_range_header({{1, -1}}),
  6721. {"Accept-Encoding", ""},
  6722. });
  6723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6724. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6725. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6726. EXPECT_EQ(true, res->has_header("Content-Range"));
  6727. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6728. EXPECT_EQ(std::string("bcdefg"), res->body);
  6729. }
  6730. TEST_F(ServerTest, GetWithRange3) {
  6731. auto res = cli_.Get("/with-range", Headers{
  6732. make_range_header({{0, 0}}),
  6733. {"Accept-Encoding", ""},
  6734. });
  6735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6736. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6737. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6738. EXPECT_EQ(true, res->has_header("Content-Range"));
  6739. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6740. EXPECT_EQ(std::string("a"), res->body);
  6741. }
  6742. TEST_F(ServerTest, GetWithRange4) {
  6743. auto res = cli_.Get("/with-range", Headers{
  6744. make_range_header({{-1, 2}}),
  6745. {"Accept-Encoding", ""},
  6746. });
  6747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6748. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6749. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6750. EXPECT_EQ(true, res->has_header("Content-Range"));
  6751. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6752. EXPECT_EQ(std::string("fg"), res->body);
  6753. }
  6754. TEST_F(ServerTest, GetWithRange5) {
  6755. auto res = cli_.Get("/with-range", Headers{
  6756. make_range_header({{0, 5}}),
  6757. {"Accept-Encoding", ""},
  6758. });
  6759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6760. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6761. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6762. EXPECT_EQ(true, res->has_header("Content-Range"));
  6763. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6764. EXPECT_EQ(std::string("abcdef"), res->body);
  6765. }
  6766. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6767. auto res =
  6768. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6770. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6771. }
  6772. TEST_F(ServerTest, GetWithRangeMultipart) {
  6773. auto res =
  6774. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6776. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6777. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6778. EXPECT_EQ(false, res->has_header("Content-Range"));
  6779. EXPECT_EQ(267U, res->body.size());
  6780. }
  6781. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6782. auto res = cli_.Get("/with-range",
  6783. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6785. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6786. }
  6787. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6788. auto res = cli_.Get("/with-range-customized-response",
  6789. Headers{{make_range_header({{1, 2}})}});
  6790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6791. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6792. EXPECT_EQ(true, res->has_header("Content-Length"));
  6793. EXPECT_EQ(false, res->has_header("Content-Range"));
  6794. EXPECT_EQ(JSON_DATA, res->body);
  6795. }
  6796. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6797. auto res = cli_.Get("/with-range-customized-response",
  6798. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6800. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6801. EXPECT_EQ(true, res->has_header("Content-Length"));
  6802. EXPECT_EQ(false, res->has_header("Content-Range"));
  6803. EXPECT_EQ(JSON_DATA, res->body);
  6804. }
  6805. TEST_F(ServerTest, Issue1772) {
  6806. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6808. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6809. }
  6810. TEST_F(ServerTest, Issue609) {
  6811. auto res = cli_.Delete("/issue609");
  6812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6813. EXPECT_EQ(StatusCode::OK_200, res->status);
  6814. EXPECT_EQ(std::string("ok"), res->body);
  6815. }
  6816. TEST_F(ServerTest, GetStreamedChunked) {
  6817. auto res = cli_.Get("/streamed-chunked");
  6818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6819. EXPECT_EQ(StatusCode::OK_200, res->status);
  6820. EXPECT_EQ(std::string("123456789"), res->body);
  6821. }
  6822. TEST_F(ServerTest, GetStreamedChunked2) {
  6823. auto res = cli_.Get("/streamed-chunked2");
  6824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6825. EXPECT_EQ(StatusCode::OK_200, res->status);
  6826. EXPECT_EQ(std::string("123456789"), res->body);
  6827. }
  6828. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6829. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6831. EXPECT_EQ(StatusCode::OK_200, res->status);
  6832. EXPECT_EQ(std::string("123456789"), res->body);
  6833. EXPECT_TRUE(res->has_header("Trailer"));
  6834. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6835. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6836. // Trailers are now stored separately from headers (security fix)
  6837. EXPECT_EQ(2U, res->trailers.size());
  6838. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6839. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6840. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6841. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6842. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6843. // Verify trailers are NOT in headers (security verification)
  6844. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6845. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6846. }
  6847. TEST_F(ServerTest, LargeChunkedPost) {
  6848. Request req;
  6849. req.method = "POST";
  6850. req.path = "/large-chunked";
  6851. std::string host_and_port;
  6852. host_and_port += HOST;
  6853. host_and_port += ":";
  6854. host_and_port += std::to_string(PORT);
  6855. req.headers.emplace("Host", host_and_port.c_str());
  6856. req.headers.emplace("Accept", "*/*");
  6857. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6858. req.headers.emplace("Content-Type", "text/plain");
  6859. req.headers.emplace("Content-Length", "0");
  6860. req.headers.emplace("Transfer-Encoding", "chunked");
  6861. std::string long_string(30 * 1024u, 'a');
  6862. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6863. // Attempt to make a large enough post to exceed OS buffers, to test that
  6864. // the server handles short reads if the full chunk data isn't available.
  6865. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6866. auto res = std::make_shared<Response>();
  6867. auto error = Error::Success;
  6868. auto ret = cli_.send(req, *res, error);
  6869. ASSERT_TRUE(ret);
  6870. EXPECT_EQ(StatusCode::OK_200, res->status);
  6871. }
  6872. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6873. auto res = cli_.Get("/remote_addr");
  6874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6875. EXPECT_EQ(StatusCode::OK_200, res->status);
  6876. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6877. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6878. }
  6879. TEST_F(ServerTest, GetMethodLocalAddr) {
  6880. auto res = cli_.Get("/local_addr");
  6881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6882. EXPECT_EQ(StatusCode::OK_200, res->status);
  6883. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6884. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6885. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6886. }
  6887. TEST_F(ServerTest, HTTPResponseSplitting) {
  6888. auto res = cli_.Get("/http_response_splitting");
  6889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6890. EXPECT_EQ(StatusCode::OK_200, res->status);
  6891. }
  6892. TEST_F(ServerTest, SlowRequest) {
  6893. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6894. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6895. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6896. }
  6897. #if 0
  6898. TEST_F(ServerTest, SlowPost) {
  6899. char buffer[64 * 1024];
  6900. memset(buffer, 0x42, sizeof(buffer));
  6901. auto res = cli_.Post(
  6902. "/slowpost", 64 * 1024 * 1024,
  6903. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6904. auto ret = sink.write(buffer, sizeof(buffer));
  6905. EXPECT_TRUE(ret);
  6906. return true;
  6907. },
  6908. "text/plain");
  6909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6910. EXPECT_EQ(StatusCode::OK_200, res->status);
  6911. }
  6912. TEST_F(ServerTest, SlowPostFail) {
  6913. char buffer[64 * 1024];
  6914. memset(buffer, 0x42, sizeof(buffer));
  6915. cli_.set_write_timeout(std::chrono::seconds(0));
  6916. auto res = cli_.Post(
  6917. "/slowpost", 64 * 1024 * 1024,
  6918. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6919. sink.write(buffer, sizeof(buffer));
  6920. return true;
  6921. },
  6922. "text/plain");
  6923. ASSERT_TRUE(!res);
  6924. EXPECT_EQ(Error::Write, res.error());
  6925. }
  6926. #endif
  6927. TEST_F(ServerTest, Put) {
  6928. auto res = cli_.Put("/put", "PUT", "text/plain");
  6929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6930. EXPECT_EQ(StatusCode::OK_200, res->status);
  6931. EXPECT_EQ("PUT", res->body);
  6932. }
  6933. TEST_F(ServerTest, PutWithContentProvider) {
  6934. auto res = cli_.Put(
  6935. "/put", 3,
  6936. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6937. sink.os << "PUT";
  6938. return true;
  6939. },
  6940. "text/plain");
  6941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6942. EXPECT_EQ(StatusCode::OK_200, res->status);
  6943. EXPECT_EQ("PUT", res->body);
  6944. }
  6945. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6946. auto res = cli_.Post(
  6947. "/post", 42,
  6948. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6949. return false;
  6950. },
  6951. "text/plain");
  6952. ASSERT_TRUE(!res);
  6953. EXPECT_EQ(Error::Canceled, res.error());
  6954. }
  6955. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6956. auto res = cli_.Put(
  6957. "/put",
  6958. [](size_t /*offset*/, DataSink &sink) {
  6959. sink.os << "PUT";
  6960. sink.done();
  6961. return true;
  6962. },
  6963. "text/plain");
  6964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6965. EXPECT_EQ(StatusCode::OK_200, res->status);
  6966. EXPECT_EQ("PUT", res->body);
  6967. }
  6968. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6969. auto res = cli_.Post(
  6970. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6971. "text/plain");
  6972. ASSERT_TRUE(!res);
  6973. EXPECT_EQ(Error::Canceled, res.error());
  6974. }
  6975. TEST_F(ServerTest, PostLoopBack) {
  6976. std::string body;
  6977. auto res = cli_.Post(
  6978. "/post-loopback", 9,
  6979. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6980. EXPECT_EQ(9u, length);
  6981. sink.write("123", 3);
  6982. sink.write("456", 3);
  6983. sink.write("789", 3);
  6984. return true;
  6985. },
  6986. "text/plain",
  6987. [&body](const char *data, size_t data_length) {
  6988. body.append(data, data_length);
  6989. return true;
  6990. });
  6991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6992. EXPECT_EQ(StatusCode::OK_200, res->status);
  6993. EXPECT_EQ("123456789", body);
  6994. }
  6995. TEST_F(ServerTest, PutLoopBack) {
  6996. std::string body;
  6997. auto res = cli_.Put(
  6998. "/put-loopback", 9,
  6999. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7000. EXPECT_EQ(9u, length);
  7001. sink.write("123", 3);
  7002. sink.write("456", 3);
  7003. sink.write("789", 3);
  7004. return true;
  7005. },
  7006. "text/plain",
  7007. [&body](const char *data, size_t data_length) {
  7008. body.append(data, data_length);
  7009. return true;
  7010. });
  7011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7012. EXPECT_EQ(StatusCode::OK_200, res->status);
  7013. EXPECT_EQ("123456789", body);
  7014. }
  7015. TEST_F(ServerTest, PatchLoopBack) {
  7016. std::string body;
  7017. auto res = cli_.Patch(
  7018. "/patch-loopback", 9,
  7019. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7020. EXPECT_EQ(9u, length);
  7021. sink.write("123", 3);
  7022. sink.write("456", 3);
  7023. sink.write("789", 3);
  7024. return true;
  7025. },
  7026. "text/plain",
  7027. [&body](const char *data, size_t data_length) {
  7028. body.append(data, data_length);
  7029. return true;
  7030. });
  7031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7032. EXPECT_EQ(StatusCode::OK_200, res->status);
  7033. EXPECT_EQ("123456789", body);
  7034. }
  7035. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7036. std::string body;
  7037. auto res = cli_.Post(
  7038. "/post-loopback",
  7039. [](size_t /*offset*/, DataSink &sink) {
  7040. sink.write("123", 3);
  7041. sink.write("456", 3);
  7042. sink.write("789", 3);
  7043. sink.done();
  7044. return true;
  7045. },
  7046. "text/plain",
  7047. [&body](const char *data, size_t data_length) {
  7048. body.append(data, data_length);
  7049. return true;
  7050. });
  7051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7052. EXPECT_EQ(StatusCode::OK_200, res->status);
  7053. EXPECT_EQ("123456789", body);
  7054. }
  7055. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7056. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7057. cli_.set_compress(true);
  7058. auto res = cli_.Put(
  7059. "/put", 3,
  7060. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7061. sink.os << "PUT";
  7062. return true;
  7063. },
  7064. "text/plain");
  7065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7066. EXPECT_EQ(StatusCode::OK_200, res->status);
  7067. EXPECT_EQ("PUT", res->body);
  7068. }
  7069. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7070. cli_.set_compress(true);
  7071. auto res = cli_.Post(
  7072. "/post", 42,
  7073. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7074. return false;
  7075. },
  7076. "text/plain");
  7077. ASSERT_TRUE(!res);
  7078. EXPECT_EQ(Error::Canceled, res.error());
  7079. }
  7080. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7081. cli_.set_compress(true);
  7082. auto res = cli_.Put(
  7083. "/put",
  7084. [](size_t /*offset*/, DataSink &sink) {
  7085. sink.os << "PUT";
  7086. sink.done();
  7087. return true;
  7088. },
  7089. "text/plain");
  7090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7091. EXPECT_EQ(StatusCode::OK_200, res->status);
  7092. EXPECT_EQ("PUT", res->body);
  7093. }
  7094. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7095. cli_.set_compress(true);
  7096. auto res = cli_.Post(
  7097. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7098. "text/plain");
  7099. ASSERT_TRUE(!res);
  7100. EXPECT_EQ(Error::Canceled, res.error());
  7101. }
  7102. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7103. cli_.set_compress(true);
  7104. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7106. EXPECT_EQ(StatusCode::OK_200, res->status);
  7107. EXPECT_EQ(LARGE_DATA, res->body);
  7108. }
  7109. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7110. #ifdef CPPHTTPLIB_SSL_ENABLED
  7111. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7112. Client cli(s.c_str());
  7113. cli.enable_server_certificate_verification(false);
  7114. #else
  7115. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7116. Client cli(s.c_str());
  7117. #endif
  7118. cli.set_compress(true);
  7119. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7121. EXPECT_EQ(StatusCode::OK_200, res->status);
  7122. EXPECT_EQ(LARGE_DATA, res->body);
  7123. // The compressed size should be less than a 10th of the original. May vary
  7124. // depending on the zlib library.
  7125. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7126. static_cast<uint64_t>(10 * 1024 * 1024));
  7127. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7128. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7129. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7130. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7131. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7132. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7133. #endif
  7134. }
  7135. TEST_F(ServerTest, PutContentWithDeflate) {
  7136. cli_.set_compress(false);
  7137. Headers headers;
  7138. headers.emplace("Content-Encoding", "deflate");
  7139. // PUT in deflate format:
  7140. auto res = cli_.Put("/put", headers,
  7141. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7143. EXPECT_EQ(StatusCode::OK_200, res->status);
  7144. EXPECT_EQ("PUT", res->body);
  7145. }
  7146. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7147. Headers headers;
  7148. headers.emplace("Accept-Encoding", "gzip, deflate");
  7149. auto res = cli_.Get("/streamed-chunked", headers);
  7150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7151. EXPECT_EQ(StatusCode::OK_200, res->status);
  7152. EXPECT_EQ(std::string("123456789"), res->body);
  7153. }
  7154. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7155. Headers headers;
  7156. headers.emplace("Accept-Encoding", "gzip, deflate");
  7157. auto res = cli_.Get("/streamed-chunked2", headers);
  7158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7159. EXPECT_EQ(StatusCode::OK_200, res->status);
  7160. EXPECT_EQ(std::string("123456789"), res->body);
  7161. }
  7162. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7163. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7165. EXPECT_EQ(StatusCode::OK_200, res->status);
  7166. }
  7167. TEST(GzipDecompressor, ChunkedDecompression) {
  7168. std::string data;
  7169. for (size_t i = 0; i < 32 * 1024; ++i) {
  7170. data.push_back(static_cast<char>('a' + i % 26));
  7171. }
  7172. std::string compressed_data;
  7173. {
  7174. httplib::detail::gzip_compressor compressor;
  7175. bool result = compressor.compress(
  7176. data.data(), data.size(),
  7177. /*last=*/true,
  7178. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7179. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7180. compressed_data_size);
  7181. return true;
  7182. });
  7183. ASSERT_TRUE(result);
  7184. }
  7185. std::string decompressed_data;
  7186. {
  7187. httplib::detail::gzip_decompressor decompressor;
  7188. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7189. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7190. size_t chunk_size = 130;
  7191. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7192. chunk_begin += chunk_size) {
  7193. size_t current_chunk_size =
  7194. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7195. bool result = decompressor.decompress(
  7196. compressed_data.data() + chunk_begin, current_chunk_size,
  7197. [&](const char *decompressed_data_chunk,
  7198. size_t decompressed_data_chunk_size) {
  7199. decompressed_data.insert(decompressed_data.size(),
  7200. decompressed_data_chunk,
  7201. decompressed_data_chunk_size);
  7202. return true;
  7203. });
  7204. ASSERT_TRUE(result);
  7205. }
  7206. }
  7207. ASSERT_EQ(data, decompressed_data);
  7208. }
  7209. TEST(GzipDecompressor, DeflateDecompression) {
  7210. std::string original_text = "Raw deflate without gzip";
  7211. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7212. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7213. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7214. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7215. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7216. std::string decompressed_data;
  7217. {
  7218. httplib::detail::gzip_decompressor decompressor;
  7219. bool result = decompressor.decompress(
  7220. compressed_data.data(), compressed_data.size(),
  7221. [&](const char *decompressed_data_chunk,
  7222. size_t decompressed_data_chunk_size) {
  7223. decompressed_data.insert(decompressed_data.size(),
  7224. decompressed_data_chunk,
  7225. decompressed_data_chunk_size);
  7226. return true;
  7227. });
  7228. ASSERT_TRUE(result);
  7229. }
  7230. ASSERT_EQ(original_text, decompressed_data);
  7231. }
  7232. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7233. std::string original_text = "Raw deflate without gzip";
  7234. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7235. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7236. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7237. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7238. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7239. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7240. std::string decompressed_data;
  7241. {
  7242. httplib::detail::gzip_decompressor decompressor;
  7243. bool result = decompressor.decompress(
  7244. compressed_data.data(), compressed_data.size(),
  7245. [&](const char *decompressed_data_chunk,
  7246. size_t decompressed_data_chunk_size) {
  7247. decompressed_data.insert(decompressed_data.size(),
  7248. decompressed_data_chunk,
  7249. decompressed_data_chunk_size);
  7250. return true;
  7251. });
  7252. ASSERT_TRUE(result);
  7253. }
  7254. ASSERT_EQ(original_text, decompressed_data);
  7255. }
  7256. #endif
  7257. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7258. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7259. Headers headers;
  7260. headers.emplace("Accept-Encoding", "br");
  7261. auto res = cli_.Get("/streamed-chunked", headers);
  7262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7263. EXPECT_EQ(StatusCode::OK_200, res->status);
  7264. EXPECT_EQ(std::string("123456789"), res->body);
  7265. }
  7266. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7267. Headers headers;
  7268. headers.emplace("Accept-Encoding", "br");
  7269. auto res = cli_.Get("/streamed-chunked2", headers);
  7270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7271. EXPECT_EQ(StatusCode::OK_200, res->status);
  7272. EXPECT_EQ(std::string("123456789"), res->body);
  7273. }
  7274. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7275. cli_.set_compress(true);
  7276. auto res = cli_.Put(
  7277. "/put", 3,
  7278. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7279. sink.os << "PUT";
  7280. return true;
  7281. },
  7282. "text/plain");
  7283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7284. EXPECT_EQ(StatusCode::OK_200, res->status);
  7285. EXPECT_EQ("PUT", res->body);
  7286. }
  7287. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7288. cli_.set_compress(true);
  7289. auto res = cli_.Put(
  7290. "/put",
  7291. [](size_t /*offset*/, DataSink &sink) {
  7292. sink.os << "PUT";
  7293. sink.done();
  7294. return true;
  7295. },
  7296. "text/plain");
  7297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7298. EXPECT_EQ(StatusCode::OK_200, res->status);
  7299. EXPECT_EQ("PUT", res->body);
  7300. }
  7301. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7302. cli_.set_compress(true);
  7303. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7305. EXPECT_EQ(StatusCode::OK_200, res->status);
  7306. EXPECT_EQ(LARGE_DATA, res->body);
  7307. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7308. }
  7309. #endif
  7310. TEST_F(ServerTest, Patch) {
  7311. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7313. EXPECT_EQ(StatusCode::OK_200, res->status);
  7314. EXPECT_EQ("PATCH", res->body);
  7315. }
  7316. TEST_F(ServerTest, Delete) {
  7317. auto res = cli_.Delete("/delete");
  7318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7319. EXPECT_EQ(StatusCode::OK_200, res->status);
  7320. EXPECT_EQ("DELETE", res->body);
  7321. }
  7322. TEST_F(ServerTest, DeleteContentReceiver) {
  7323. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7325. EXPECT_EQ(StatusCode::OK_200, res->status);
  7326. EXPECT_EQ("content", res->body);
  7327. }
  7328. TEST_F(ServerTest, Options) {
  7329. auto res = cli_.Options("*");
  7330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7331. EXPECT_EQ(StatusCode::OK_200, res->status);
  7332. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7333. EXPECT_TRUE(res->body.empty());
  7334. }
  7335. TEST_F(ServerTest, URL) {
  7336. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7338. EXPECT_EQ(StatusCode::OK_200, res->status);
  7339. }
  7340. TEST_F(ServerTest, ArrayParam) {
  7341. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7343. EXPECT_EQ(StatusCode::OK_200, res->status);
  7344. }
  7345. TEST_F(ServerTest, ArrayParamValues) {
  7346. auto res =
  7347. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7349. EXPECT_EQ(StatusCode::OK_200, res->status);
  7350. }
  7351. TEST_F(ServerTest, NoMultipleHeaders) {
  7352. Headers headers = {{"Content-Length", "5"}};
  7353. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7354. "text/plain");
  7355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7356. EXPECT_EQ(StatusCode::OK_200, res->status);
  7357. }
  7358. TEST_F(ServerTest, PostContentReceiver) {
  7359. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7361. ASSERT_EQ(StatusCode::OK_200, res->status);
  7362. ASSERT_EQ("content", res->body);
  7363. }
  7364. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7365. UploadFormDataItems items = {
  7366. {"text1", "text default", "", ""},
  7367. {"text2", "aωb", "", ""},
  7368. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7369. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7370. {"file3", "", "", "application/octet-stream"},
  7371. };
  7372. auto res = cli_.Post("/content_receiver", items);
  7373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7374. EXPECT_EQ(StatusCode::OK_200, res->status);
  7375. }
  7376. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7377. UploadFormDataItems items = {
  7378. {"text1", "text default", "", ""},
  7379. {"text2", "aωb", "", ""},
  7380. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7381. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7382. {"file3", "", "", "application/octet-stream"},
  7383. };
  7384. auto boundary = std::string("+++++");
  7385. std::string body;
  7386. for (const auto &item : items) {
  7387. body += "--" + boundary + "\r\n";
  7388. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7389. if (!item.filename.empty()) {
  7390. body += "; filename=\"" + item.filename + "\"";
  7391. }
  7392. body += "\r\n";
  7393. if (!item.content_type.empty()) {
  7394. body += "Content-Type: " + item.content_type + "\r\n";
  7395. }
  7396. body += "\r\n";
  7397. body += item.content + "\r\n";
  7398. }
  7399. body += "--" + boundary + "--\r\n";
  7400. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7401. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7403. EXPECT_EQ(StatusCode::OK_200, res->status);
  7404. }
  7405. TEST(MultipartFormDataTest, FieldEscaping) {
  7406. Server svr;
  7407. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7408. const ContentReader &content_reader) {
  7409. ASSERT_TRUE(req.is_multipart_form_data());
  7410. std::vector<FormData> received;
  7411. content_reader(
  7412. [&](const FormData &file) {
  7413. received.push_back(file);
  7414. return true;
  7415. },
  7416. [&](const char *data, size_t data_length) {
  7417. received.back().content.append(data, data_length);
  7418. return true;
  7419. });
  7420. // '"', CR and LF in names and filenames are escaped following the
  7421. // WHATWG HTML standard, so each part still parses as a single part
  7422. // with no injected headers. Content types get CR/LF escaped too,
  7423. // while '"' (legal there, e.g. quoted charset) is preserved.
  7424. ASSERT_EQ(4U, received.size());
  7425. EXPECT_EQ("na%22me", received[0].name);
  7426. EXPECT_EQ("quoted name", received[0].content);
  7427. EXPECT_EQ("file", received[1].name);
  7428. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7429. received[1].filename);
  7430. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7431. EXPECT_EQ("injected", received[1].content);
  7432. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7433. EXPECT_EQ("my%22file.txt", received[2].filename);
  7434. EXPECT_EQ("cr lf name", received[2].content);
  7435. EXPECT_EQ("typed", received[3].name);
  7436. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7437. received[3].content_type);
  7438. EXPECT_EQ("typed content", received[3].content);
  7439. });
  7440. auto port = svr.bind_to_any_port("localhost");
  7441. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7442. auto se = detail::scope_exit([&] {
  7443. svr.stop();
  7444. t.join();
  7445. ASSERT_FALSE(svr.is_running());
  7446. });
  7447. svr.wait_until_ready();
  7448. Client cli("localhost", port);
  7449. UploadFormDataItems items = {
  7450. {"na\"me", "quoted name", "", ""},
  7451. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7452. "application/octet-stream"},
  7453. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7454. {"typed", "typed content", "",
  7455. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7456. };
  7457. auto res = cli.Post("/post", items);
  7458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7459. EXPECT_EQ(StatusCode::OK_200, res->status);
  7460. }
  7461. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7462. const UploadFormDataItems items = {
  7463. {"name1", "Content 1", "", ""},
  7464. {"name2", "Content 2", "file2.txt", "text/plain"},
  7465. };
  7466. Server svr;
  7467. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7468. const ContentReader &content_reader) {
  7469. ASSERT_TRUE(req.is_multipart_form_data());
  7470. std::vector<FormData> received;
  7471. content_reader(
  7472. [&](const FormData &file) {
  7473. received.push_back(file);
  7474. return true;
  7475. },
  7476. [&](const char *data, size_t data_length) {
  7477. received.back().content.append(data, data_length);
  7478. return true;
  7479. });
  7480. ASSERT_EQ(2U, received.size());
  7481. EXPECT_EQ("name1", received[0].name);
  7482. EXPECT_EQ("Content 1", received[0].content);
  7483. EXPECT_EQ("name2", received[1].name);
  7484. EXPECT_EQ("Content 2", received[1].content);
  7485. EXPECT_EQ("file2.txt", received[1].filename);
  7486. EXPECT_EQ("text/plain", received[1].content_type);
  7487. });
  7488. auto port = svr.bind_to_any_port("localhost");
  7489. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7490. auto se = detail::scope_exit([&] {
  7491. svr.stop();
  7492. t.join();
  7493. ASSERT_FALSE(svr.is_running());
  7494. });
  7495. svr.wait_until_ready();
  7496. Client cli("localhost", port);
  7497. // Whole-body serialization with a generated boundary
  7498. {
  7499. MultipartFormDataWriter writer;
  7500. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7501. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7502. writer.content_type());
  7503. auto body = writer.serialize(items);
  7504. EXPECT_EQ(body.size(), writer.content_length(items));
  7505. auto res = cli.Post("/post", body, writer.content_type());
  7506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7507. EXPECT_EQ(StatusCode::OK_200, res->status);
  7508. }
  7509. // Per-part framing with a custom boundary via a content provider
  7510. {
  7511. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7512. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7513. MultipartFormDataWriter writer("custom-boundary_123");
  7514. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7515. std::string body;
  7516. for (const auto &item : items) {
  7517. body += writer.item_begin(item);
  7518. body += item.content;
  7519. body += MultipartFormDataWriter::item_end();
  7520. }
  7521. body += writer.finish();
  7522. EXPECT_EQ(body.size(), writer.content_length(items));
  7523. auto res = cli.Post(
  7524. "/post", body.size(),
  7525. [&](size_t offset, size_t length, DataSink &sink) {
  7526. sink.write(body.data() + offset, length);
  7527. return true;
  7528. },
  7529. writer.content_type());
  7530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7531. EXPECT_EQ(StatusCode::OK_200, res->status);
  7532. }
  7533. }
  7534. TEST_F(ServerTest, PostContentReceiverGzip) {
  7535. cli_.set_compress(true);
  7536. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7538. ASSERT_EQ(StatusCode::OK_200, res->status);
  7539. ASSERT_EQ("content", res->body);
  7540. }
  7541. TEST_F(ServerTest, PutContentReceiver) {
  7542. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7544. ASSERT_EQ(StatusCode::OK_200, res->status);
  7545. ASSERT_EQ("content", res->body);
  7546. }
  7547. TEST_F(ServerTest, PatchContentReceiver) {
  7548. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7550. ASSERT_EQ(StatusCode::OK_200, res->status);
  7551. ASSERT_EQ("content", res->body);
  7552. }
  7553. template <typename ClientType>
  7554. void TestWithHeadersAndContentReceiver(
  7555. ClientType &cli,
  7556. std::function<Result(ClientType &, const std::string &, const Headers &,
  7557. const std::string &, const std::string &,
  7558. ContentReceiver, DownloadProgress)>
  7559. request_func) {
  7560. Headers headers;
  7561. headers.emplace("X-Custom-Header", "test-value");
  7562. std::string received_body;
  7563. auto res = request_func(
  7564. cli, "/content_receiver", headers, "content", "application/json",
  7565. [&](const char *data, size_t data_length) {
  7566. received_body.append(data, data_length);
  7567. return true;
  7568. },
  7569. nullptr);
  7570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7571. EXPECT_EQ(StatusCode::OK_200, res->status);
  7572. EXPECT_EQ("content", received_body);
  7573. }
  7574. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7575. #ifdef CPPHTTPLIB_SSL_ENABLED
  7576. using ClientT = SSLClient;
  7577. #else
  7578. using ClientT = Client;
  7579. #endif
  7580. TestWithHeadersAndContentReceiver<ClientT>(
  7581. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7582. const std::string &body, const std::string &content_type,
  7583. ContentReceiver receiver, DownloadProgress progress) {
  7584. return cli.Post(path, headers, body, content_type, receiver, progress);
  7585. });
  7586. }
  7587. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7588. #ifdef CPPHTTPLIB_SSL_ENABLED
  7589. using ClientT = SSLClient;
  7590. #else
  7591. using ClientT = Client;
  7592. #endif
  7593. TestWithHeadersAndContentReceiver<ClientT>(
  7594. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7595. const std::string &body, const std::string &content_type,
  7596. ContentReceiver receiver, DownloadProgress progress) {
  7597. return cli.Put(path, headers, body, content_type, receiver, progress);
  7598. });
  7599. }
  7600. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7601. #ifdef CPPHTTPLIB_SSL_ENABLED
  7602. using ClientT = SSLClient;
  7603. #else
  7604. using ClientT = Client;
  7605. #endif
  7606. TestWithHeadersAndContentReceiver<ClientT>(
  7607. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7608. const std::string &body, const std::string &content_type,
  7609. ContentReceiver receiver, DownloadProgress progress) {
  7610. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7611. });
  7612. }
  7613. template <typename ClientType>
  7614. void TestWithHeadersAndContentReceiverWithProgress(
  7615. ClientType &cli,
  7616. std::function<Result(ClientType &, const std::string &, const Headers &,
  7617. const std::string &, const std::string &,
  7618. ContentReceiver, DownloadProgress)>
  7619. request_func) {
  7620. Headers headers;
  7621. headers.emplace("X-Test-Header", "progress-test");
  7622. std::string received_body;
  7623. auto progress_called = false;
  7624. auto res = request_func(
  7625. cli, "/content_receiver", headers, "content", "text/plain",
  7626. [&](const char *data, size_t data_length) {
  7627. received_body.append(data, data_length);
  7628. return true;
  7629. },
  7630. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7631. progress_called = true;
  7632. return true;
  7633. });
  7634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7635. EXPECT_EQ(StatusCode::OK_200, res->status);
  7636. EXPECT_EQ("content", received_body);
  7637. EXPECT_TRUE(progress_called);
  7638. }
  7639. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7640. #ifdef CPPHTTPLIB_SSL_ENABLED
  7641. using ClientT = SSLClient;
  7642. #else
  7643. using ClientT = Client;
  7644. #endif
  7645. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7646. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7647. const std::string &body, const std::string &content_type,
  7648. ContentReceiver receiver, DownloadProgress progress) {
  7649. return cli.Post(path, headers, body, content_type, receiver, progress);
  7650. });
  7651. }
  7652. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7653. #ifdef CPPHTTPLIB_SSL_ENABLED
  7654. using ClientT = SSLClient;
  7655. #else
  7656. using ClientT = Client;
  7657. #endif
  7658. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7659. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7660. const std::string &body, const std::string &content_type,
  7661. ContentReceiver receiver, DownloadProgress progress) {
  7662. return cli.Put(path, headers, body, content_type, receiver, progress);
  7663. });
  7664. }
  7665. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7666. #ifdef CPPHTTPLIB_SSL_ENABLED
  7667. using ClientT = SSLClient;
  7668. #else
  7669. using ClientT = Client;
  7670. #endif
  7671. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7672. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7673. const std::string &body, const std::string &content_type,
  7674. ContentReceiver receiver, DownloadProgress progress) {
  7675. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7676. });
  7677. }
  7678. template <typename ClientType>
  7679. void TestWithHeadersAndContentReceiverError(
  7680. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7681. const Headers &, const std::string &,
  7682. const std::string &, ContentReceiver)>
  7683. request_func) {
  7684. Headers headers;
  7685. headers.emplace("X-Error-Test", "true");
  7686. std::string received_body;
  7687. auto receiver_failed = false;
  7688. auto res =
  7689. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7690. [&](const char *data, size_t data_length) {
  7691. received_body.append(data, data_length);
  7692. receiver_failed = true;
  7693. return false;
  7694. });
  7695. ASSERT_FALSE(res);
  7696. EXPECT_TRUE(receiver_failed);
  7697. }
  7698. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7699. #ifdef CPPHTTPLIB_SSL_ENABLED
  7700. using ClientT = SSLClient;
  7701. #else
  7702. using ClientT = Client;
  7703. #endif
  7704. TestWithHeadersAndContentReceiverError<ClientT>(
  7705. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7706. const std::string &body, const std::string &content_type,
  7707. ContentReceiver receiver) {
  7708. return cli.Post(path, headers, body, content_type, receiver);
  7709. });
  7710. }
  7711. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7712. #ifdef CPPHTTPLIB_SSL_ENABLED
  7713. using ClientT = SSLClient;
  7714. #else
  7715. using ClientT = Client;
  7716. #endif
  7717. TestWithHeadersAndContentReceiverError<ClientT>(
  7718. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7719. const std::string &body, const std::string &content_type,
  7720. ContentReceiver receiver) {
  7721. return cli.Put(path, headers, body, content_type, receiver);
  7722. });
  7723. }
  7724. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7725. #ifdef CPPHTTPLIB_SSL_ENABLED
  7726. using ClientT = SSLClient;
  7727. #else
  7728. using ClientT = Client;
  7729. #endif
  7730. TestWithHeadersAndContentReceiverError<ClientT>(
  7731. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7732. const std::string &body, const std::string &content_type,
  7733. ContentReceiver receiver) {
  7734. return cli.Patch(path, headers, body, content_type, receiver);
  7735. });
  7736. }
  7737. TEST_F(ServerTest, PostQueryStringAndBody) {
  7738. auto res =
  7739. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7741. ASSERT_EQ(StatusCode::OK_200, res->status);
  7742. }
  7743. TEST_F(ServerTest, HTTP2Magic) {
  7744. Request req;
  7745. req.method = "PRI";
  7746. req.path = "*";
  7747. req.body = "SM";
  7748. auto res = std::make_shared<Response>();
  7749. auto error = Error::Success;
  7750. auto ret = cli_.send(req, *res, error);
  7751. ASSERT_TRUE(ret);
  7752. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7753. }
  7754. TEST_F(ServerTest, KeepAlive) {
  7755. auto res = cli_.Get("/hi");
  7756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7757. EXPECT_EQ(StatusCode::OK_200, res->status);
  7758. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7759. EXPECT_EQ("Hello World!", res->body);
  7760. res = cli_.Get("/hi");
  7761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7762. EXPECT_EQ(StatusCode::OK_200, res->status);
  7763. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7764. EXPECT_EQ("Hello World!", res->body);
  7765. res = cli_.Get("/hi");
  7766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7767. EXPECT_EQ(StatusCode::OK_200, res->status);
  7768. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7769. EXPECT_EQ("Hello World!", res->body);
  7770. res = cli_.Get("/not-exist");
  7771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7772. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7773. res = cli_.Post("/empty", "", "text/plain");
  7774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7775. EXPECT_EQ(StatusCode::OK_200, res->status);
  7776. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7777. EXPECT_EQ("empty", res->body);
  7778. EXPECT_EQ("close", res->get_header_value("Connection"));
  7779. res = cli_.Post(
  7780. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7781. "text/plain");
  7782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7783. EXPECT_EQ(StatusCode::OK_200, res->status);
  7784. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7785. EXPECT_EQ("empty", res->body);
  7786. cli_.set_keep_alive(false);
  7787. res = cli_.Get("/last-request");
  7788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7789. EXPECT_EQ(StatusCode::OK_200, res->status);
  7790. EXPECT_EQ("close", res->get_header_value("Connection"));
  7791. }
  7792. TEST_F(ServerTest, TooManyRedirect) {
  7793. cli_.set_follow_location(true);
  7794. auto res = cli_.Get("/redirect/0");
  7795. ASSERT_TRUE(!res);
  7796. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7797. }
  7798. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7799. Request req;
  7800. req.method = "FOOBAR";
  7801. req.path = "/hi";
  7802. cli_.set_keep_alive(true);
  7803. auto res = cli_.send(req);
  7804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7805. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7806. EXPECT_EQ("close", res->get_header_value("Connection"));
  7807. EXPECT_FALSE(cli_.is_socket_open());
  7808. }
  7809. TEST_F(ServerTest, CustomRouteReadsBody) {
  7810. const std::string xml =
  7811. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7812. Request req;
  7813. req.method = "PROPFIND";
  7814. req.path = "/dav/dir";
  7815. req.set_header("Depth", "1");
  7816. req.body = xml;
  7817. auto res = cli_.send(req);
  7818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7819. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7820. EXPECT_EQ(xml, res->body);
  7821. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7822. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7823. }
  7824. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7825. Request req;
  7826. req.method = "PROPFIND";
  7827. req.path = "/dav/42";
  7828. auto res = cli_.send(req);
  7829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7830. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7831. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7832. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7833. }
  7834. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7835. Request req;
  7836. req.method = "PROPFIND";
  7837. req.path = "/dav-re/123";
  7838. auto res = cli_.send(req);
  7839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7840. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7841. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7842. }
  7843. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7844. Request req;
  7845. req.method = "MKCOL";
  7846. req.path = "/dav-mkcol";
  7847. auto res = cli_.send(req);
  7848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7849. EXPECT_EQ(StatusCode::Created_201, res->status);
  7850. }
  7851. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7852. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7853. Request req;
  7854. req.method = "REPORT";
  7855. req.path = "/dav-report";
  7856. req.body = xml;
  7857. auto res = cli_.send(req);
  7858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7859. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7860. EXPECT_EQ(xml, res->body);
  7861. }
  7862. // A content reader route must fire even when the request carries no body,
  7863. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7864. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7865. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7866. Request req;
  7867. req.method = "REPORT";
  7868. req.path = "/dav-report";
  7869. auto res = cli_.send(req);
  7870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7871. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7872. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7873. }
  7874. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7875. Request req;
  7876. req.method = "PROPFIND";
  7877. req.path = "/not-dav";
  7878. auto res = cli_.send(req);
  7879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7880. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7881. }
  7882. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7883. Request req;
  7884. req.method = "UNLOCK";
  7885. req.path = "/dav/dir";
  7886. cli_.set_keep_alive(true);
  7887. auto res = cli_.send(req);
  7888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7889. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7890. EXPECT_EQ("close", res->get_header_value("Connection"));
  7891. EXPECT_FALSE(cli_.is_socket_open());
  7892. }
  7893. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7894. // The mount point serves this path, but only for GET and HEAD.
  7895. auto get_res = cli_.Get("/dir/index.html");
  7896. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7897. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7898. Request req;
  7899. req.method = "PROPFIND";
  7900. req.path = "/dir/index.html";
  7901. auto res = cli_.send(req);
  7902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7903. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7904. }
  7905. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7906. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7907. cli_.set_keep_alive(true);
  7908. for (auto i = 0; i < 2; i++) {
  7909. Request req;
  7910. req.method = "PROPFIND";
  7911. req.path = "/dav/dir";
  7912. req.body = xml;
  7913. auto res = cli_.send(req);
  7914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7915. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7916. EXPECT_EQ(xml, res->body);
  7917. EXPECT_TRUE(cli_.is_socket_open());
  7918. }
  7919. // A built-in method must still be served on the same connection.
  7920. cli_.set_keep_alive(false);
  7921. auto res = cli_.Get("/hi");
  7922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7923. EXPECT_EQ(StatusCode::OK_200, res->status);
  7924. EXPECT_EQ("close", res->get_header_value("Connection"));
  7925. }
  7926. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7927. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7928. Request req;
  7929. req.method = "PROPFIND";
  7930. req.path = "/dav/dir";
  7931. req.set_header("Expect", "100-continue");
  7932. req.body = xml;
  7933. auto res = cli_.send(req);
  7934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7935. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7936. EXPECT_EQ(xml, res->body);
  7937. }
  7938. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7939. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7940. TEST_F(ServerTest, Gzip) {
  7941. Headers headers;
  7942. headers.emplace("Accept-Encoding", "gzip, deflate");
  7943. auto res = cli_.Get("/compress", headers);
  7944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7945. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7946. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7947. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7948. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7949. "7890123456789012345678901234567890",
  7950. res->body);
  7951. EXPECT_EQ(StatusCode::OK_200, res->status);
  7952. }
  7953. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7954. Headers headers;
  7955. headers.emplace("Accept-Encoding", "gzip, deflate");
  7956. auto res = cli_.Get("/compress-with-charset", headers);
  7957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7958. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7959. EXPECT_EQ("application/json; charset=utf-8",
  7960. res->get_header_value("Content-Type"));
  7961. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7962. "7890123456789012345678901234567890",
  7963. res->body);
  7964. EXPECT_EQ(StatusCode::OK_200, res->status);
  7965. }
  7966. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7967. Headers headers;
  7968. headers.emplace("Accept-Encoding", "");
  7969. auto res = cli_.Get("/compress", headers);
  7970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7971. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7972. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7973. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7974. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7975. "7890123456789012345678901234567890",
  7976. res->body);
  7977. EXPECT_EQ(StatusCode::OK_200, res->status);
  7978. }
  7979. TEST_F(ServerTest, GzipWithContentReceiver) {
  7980. Headers headers;
  7981. headers.emplace("Accept-Encoding", "gzip, deflate");
  7982. std::string body;
  7983. auto res = cli_.Get("/compress", headers,
  7984. [&](const char *data, uint64_t data_length) {
  7985. EXPECT_EQ(100U, data_length);
  7986. body.append(data, data_length);
  7987. return true;
  7988. });
  7989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7990. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7991. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7992. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7993. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7994. "7890123456789012345678901234567890",
  7995. body);
  7996. EXPECT_EQ(StatusCode::OK_200, res->status);
  7997. }
  7998. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7999. Headers headers;
  8000. headers.emplace("Accept-Encoding", "gzip, deflate");
  8001. cli_.set_decompress(false);
  8002. auto res = cli_.Get("/compress", headers);
  8003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8004. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8005. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8006. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8007. EXPECT_EQ(33U, res->body.size());
  8008. EXPECT_EQ(StatusCode::OK_200, res->status);
  8009. }
  8010. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8011. Headers headers;
  8012. headers.emplace("Accept-Encoding", "");
  8013. std::string body;
  8014. auto res = cli_.Get("/compress", headers,
  8015. [&](const char *data, uint64_t data_length) {
  8016. EXPECT_EQ(100U, data_length);
  8017. body.append(data, data_length);
  8018. return true;
  8019. });
  8020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8021. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8022. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8023. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8024. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8025. "7890123456789012345678901234567890",
  8026. body);
  8027. EXPECT_EQ(StatusCode::OK_200, res->status);
  8028. }
  8029. TEST_F(ServerTest, NoGzip) {
  8030. Headers headers;
  8031. headers.emplace("Accept-Encoding", "gzip, deflate");
  8032. auto res = cli_.Get("/nocompress", headers);
  8033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8034. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8035. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8036. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8037. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8038. "7890123456789012345678901234567890",
  8039. res->body);
  8040. EXPECT_EQ(StatusCode::OK_200, res->status);
  8041. }
  8042. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8043. Headers headers;
  8044. headers.emplace("Accept-Encoding", "gzip, deflate");
  8045. std::string body;
  8046. auto res = cli_.Get("/nocompress", headers,
  8047. [&](const char *data, uint64_t data_length) {
  8048. EXPECT_EQ(100U, data_length);
  8049. body.append(data, data_length);
  8050. return true;
  8051. });
  8052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8053. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8054. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8055. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8056. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8057. "7890123456789012345678901234567890",
  8058. body);
  8059. EXPECT_EQ(StatusCode::OK_200, res->status);
  8060. }
  8061. TEST_F(ServerTest, MultipartFormDataGzip) {
  8062. UploadFormDataItems items = {
  8063. {"key1", "test", "", ""},
  8064. {"key2", "--abcdefg123", "", ""},
  8065. };
  8066. cli_.set_compress(true);
  8067. auto res = cli_.Post("/compress-multipart", items);
  8068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8069. EXPECT_EQ(StatusCode::OK_200, res->status);
  8070. }
  8071. #endif
  8072. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8073. // Static file compression is opt-in, so these run their own server rather than
  8074. // flipping it on for the shared ServerTest fixture, which would silently
  8075. // rewrite what every other static file test is asserting.
  8076. class StaticFileCompressionTest : public ::testing::Test {
  8077. protected:
  8078. void TearDown() override {
  8079. if (t_.joinable()) {
  8080. svr_.stop();
  8081. t_.join();
  8082. }
  8083. }
  8084. int start(const std::function<void(Server &)> &configure = nullptr) {
  8085. // Serves the same tree as a directory of build-time compressed assets
  8086. // would be served: the mount point names the coding the files are already
  8087. // stored in. Registered before "/" so it is the one that matches.
  8088. svr_.set_mount_point("/pre-encoded", "./www",
  8089. {{"Content-Encoding", "gzip"}});
  8090. svr_.set_mount_point("/", "./www");
  8091. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8092. res.set_file_content("./www/dir/index.html", "text/html");
  8093. });
  8094. svr_.Get("/pre-encoded-file-content",
  8095. [](const Request & /*req*/, Response &res) {
  8096. res.set_header("Content-Encoding", "gzip");
  8097. res.set_file_content("./www/dir/index.html", "text/html");
  8098. });
  8099. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8100. res.set_content_provider(
  8101. 6, "text/plain",
  8102. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8103. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8104. return true;
  8105. });
  8106. });
  8107. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8108. res.set_content_provider(
  8109. 1000, "text/plain",
  8110. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8111. if (offset < 100) {
  8112. std::string data(100, 'A');
  8113. sink.write(data.data(), data.size());
  8114. return true;
  8115. }
  8116. std::this_thread::sleep_for(std::chrono::seconds(2));
  8117. std::string data(900, 'B');
  8118. sink.write(data.data(), data.size());
  8119. return true;
  8120. });
  8121. });
  8122. if (configure) { configure(svr_); }
  8123. auto port = svr_.bind_to_any_port(HOST);
  8124. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8125. svr_.wait_until_ready();
  8126. return port;
  8127. }
  8128. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8129. // Every file under ./www except 1MB.txt is smaller than the default
  8130. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8131. // it out of the way.
  8132. static void enable_without_floor(Server &svr) {
  8133. svr.set_static_file_compression(true);
  8134. svr.set_static_file_compression_min_length(0);
  8135. }
  8136. Server svr_;
  8137. std::thread t_;
  8138. };
  8139. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8140. auto port = start();
  8141. Client cli(HOST, port);
  8142. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8144. EXPECT_EQ(StatusCode::OK_200, res->status);
  8145. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8146. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8147. EXPECT_EQ(1048576U, res->body.size());
  8148. }
  8149. TEST_F(StaticFileCompressionTest, MountPoint) {
  8150. auto port = start(enable);
  8151. Client cli(HOST, port);
  8152. cli.set_decompress(false);
  8153. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8155. EXPECT_EQ(StatusCode::OK_200, res->status);
  8156. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8157. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8158. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8159. // The response stays self-delimiting: a length, not a chunked body.
  8160. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8161. EXPECT_EQ(std::to_string(res->body.size()),
  8162. res->get_header_value("Content-Length"));
  8163. EXPECT_LT(res->body.size(), 1048576U);
  8164. EXPECT_FALSE(res->body.empty());
  8165. }
  8166. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8167. auto port = start(enable);
  8168. Client cli(HOST, port);
  8169. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8171. EXPECT_EQ(StatusCode::OK_200, res->status);
  8172. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8173. EXPECT_EQ(1048576U, res->body.size());
  8174. }
  8175. TEST_F(StaticFileCompressionTest, FileContent) {
  8176. auto port = start(enable_without_floor);
  8177. Client cli(HOST, port);
  8178. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8180. EXPECT_EQ(StatusCode::OK_200, res->status);
  8181. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8182. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8183. EXPECT_EQ(104U, res->body.size());
  8184. }
  8185. // A handler that serves an already-encoded file names the coding itself. The
  8186. // file-backed path decided its coding from Accept-Encoding and the content
  8187. // type alone, so it compressed the stored bytes a second time and appended a
  8188. // second Content-Encoding field line.
  8189. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8190. auto port = start(enable_without_floor);
  8191. Client cli(HOST, port);
  8192. cli.set_decompress(false);
  8193. auto res = cli.Get("/pre-encoded-file-content",
  8194. Headers{{"Accept-Encoding", "gzip"}});
  8195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8196. EXPECT_EQ(StatusCode::OK_200, res->status);
  8197. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8198. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8199. // Vary belongs to a coding the server chose, and it chose none here.
  8200. EXPECT_FALSE(res->has_header("Vary"));
  8201. // The file travels exactly as it is stored on disk.
  8202. EXPECT_EQ(104U, res->body.size());
  8203. }
  8204. // The 1MB file clears the default floor, so this one runs the configuration a
  8205. // deployment would actually have.
  8206. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8207. auto port = start(enable);
  8208. Client cli(HOST, port);
  8209. cli.set_decompress(false);
  8210. auto res =
  8211. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8213. EXPECT_EQ(StatusCode::OK_200, res->status);
  8214. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8215. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8216. EXPECT_FALSE(res->has_header("Vary"));
  8217. EXPECT_EQ(1048576U, res->body.size());
  8218. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8219. }
  8220. TEST_F(StaticFileCompressionTest, Head) {
  8221. auto port = start(enable);
  8222. Client cli(HOST, port);
  8223. cli.set_decompress(false);
  8224. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8225. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8226. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8228. EXPECT_EQ(StatusCode::OK_200, res->status);
  8229. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8230. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8231. // HEAD still reports the size a GET would return.
  8232. EXPECT_EQ(get->get_header_value("Content-Length"),
  8233. res->get_header_value("Content-Length"));
  8234. EXPECT_TRUE(res->body.empty());
  8235. }
  8236. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8237. auto port = start(enable);
  8238. Client cli(HOST, port);
  8239. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8240. {"Accept-Encoding", "gzip"}});
  8241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8242. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8243. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8244. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8245. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8246. EXPECT_EQ("cd", res->body);
  8247. }
  8248. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8249. auto port = start(enable);
  8250. Client cli(HOST, port);
  8251. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8253. EXPECT_EQ(StatusCode::OK_200, res->status);
  8254. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8255. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8256. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8257. }
  8258. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8259. auto port = start(enable);
  8260. Client cli(HOST, port);
  8261. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8263. EXPECT_EQ(StatusCode::OK_200, res->status);
  8264. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8265. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8266. EXPECT_TRUE(res->body.empty());
  8267. }
  8268. TEST_F(StaticFileCompressionTest, MinLength) {
  8269. auto port = start(enable);
  8270. Client cli(HOST, port);
  8271. // 104 bytes, well under the default floor. Compressing it would add the
  8272. // gzip header and trailer to a body that already fits in one packet.
  8273. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8275. EXPECT_EQ(StatusCode::OK_200, res->status);
  8276. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8277. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8278. }
  8279. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8280. auto port = start([](Server &svr) {
  8281. svr.set_static_file_compression(true);
  8282. svr.set_static_file_compression_min_length(1);
  8283. });
  8284. Client cli(HOST, port);
  8285. cli.set_decompress(false);
  8286. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8288. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8289. // A 9-byte file comes back larger than it went in, because gzip's header and
  8290. // trailer outweigh anything deflate can save. That is the end of the range
  8291. // the floor exists to keep out.
  8292. EXPECT_GT(res->body.size(), 9U);
  8293. }
  8294. TEST_F(StaticFileCompressionTest, MaxLength) {
  8295. auto port = start([](Server &svr) {
  8296. svr.set_static_file_compression(true);
  8297. svr.set_static_file_compression_min_length(0);
  8298. svr.set_static_file_compression_max_length(1024);
  8299. });
  8300. Client cli(HOST, port);
  8301. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8302. // defines `small` as a macro on Windows.
  8303. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8304. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8305. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8306. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8307. // Under it: compressed.
  8308. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8309. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8310. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8311. }
  8312. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8313. auto port = start(enable_without_floor);
  8314. Client cli(HOST, port);
  8315. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8316. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8317. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8318. auto identity_etag = identity->get_header_value("ETag");
  8319. ASSERT_FALSE(identity_etag.empty());
  8320. auto gzipped =
  8321. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8322. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8323. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8324. auto gzip_etag = gzipped->get_header_value("ETag");
  8325. ASSERT_FALSE(gzip_etag.empty());
  8326. // Two representations, two validators.
  8327. EXPECT_NE(identity_etag, gzip_etag);
  8328. // Each one revalidates against the request that would produce it...
  8329. auto fresh =
  8330. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8331. {"If-None-Match", gzip_etag}});
  8332. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8333. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8334. auto fresh_identity =
  8335. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8336. {"If-None-Match", identity_etag}});
  8337. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8338. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8339. // ...and not against the other representation.
  8340. auto crossed =
  8341. cli.Get("/dir/index.html",
  8342. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8343. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8344. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8345. }
  8346. // The opt-in covers responses the server reads off disk itself. A caller's own
  8347. // known-length provider keeps its Content-Length and, more importantly, keeps
  8348. // delivering incrementally: routing it through a compressor would hold every
  8349. // write back until zlib's window filled.
  8350. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8351. auto port = start(enable);
  8352. Client cli(HOST, port);
  8353. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8355. EXPECT_EQ(StatusCode::OK_200, res->status);
  8356. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8357. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8358. EXPECT_EQ("aaabbb", res->body);
  8359. }
  8360. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8361. auto port = start(enable);
  8362. Client cli(HOST, port);
  8363. cli.set_read_timeout(1, 0);
  8364. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8365. Headers{{"Accept-Encoding", "gzip"}});
  8366. ASSERT_TRUE(handle.is_valid());
  8367. // The provider writes 100 bytes and then stalls for longer than the read
  8368. // timeout. Those first bytes have to arrive anyway: run the response through
  8369. // a compressor and zlib holds them until its window fills, so the read would
  8370. // come back empty instead.
  8371. char buf[256];
  8372. auto n = handle.read(buf, sizeof(buf));
  8373. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8374. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8375. }
  8376. #endif
  8377. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8378. TEST_F(ServerTest, Brotli) {
  8379. Headers headers;
  8380. headers.emplace("Accept-Encoding", "br");
  8381. auto res = cli_.Get("/compress", headers);
  8382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8383. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8384. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8385. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8386. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8387. "7890123456789012345678901234567890",
  8388. res->body);
  8389. EXPECT_EQ(StatusCode::OK_200, res->status);
  8390. }
  8391. #endif
  8392. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8393. TEST_F(ServerTest, Zstd) {
  8394. Headers headers;
  8395. headers.emplace("Accept-Encoding", "zstd");
  8396. auto res = cli_.Get("/compress", headers);
  8397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8398. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8399. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8400. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8401. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8402. "7890123456789012345678901234567890",
  8403. res->body);
  8404. EXPECT_EQ(StatusCode::OK_200, res->status);
  8405. }
  8406. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8407. Headers headers;
  8408. headers.emplace("Accept-Encoding", "");
  8409. auto res = cli_.Get("/compress", headers);
  8410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8411. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8412. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8413. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8414. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8415. "7890123456789012345678901234567890",
  8416. res->body);
  8417. EXPECT_EQ(StatusCode::OK_200, res->status);
  8418. }
  8419. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8420. Headers headers;
  8421. headers.emplace("Accept-Encoding", "zstd");
  8422. std::string body;
  8423. auto res = cli_.Get("/compress", headers,
  8424. [&](const char *data, uint64_t data_length) {
  8425. EXPECT_EQ(100U, data_length);
  8426. body.append(data, data_length);
  8427. return true;
  8428. });
  8429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8430. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8431. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8432. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8433. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8434. "7890123456789012345678901234567890",
  8435. body);
  8436. EXPECT_EQ(StatusCode::OK_200, res->status);
  8437. }
  8438. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8439. Headers headers;
  8440. headers.emplace("Accept-Encoding", "zstd");
  8441. cli_.set_decompress(false);
  8442. auto res = cli_.Get("/compress", headers);
  8443. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8444. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8445. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8446. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8448. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8449. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8450. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8451. EXPECT_EQ(StatusCode::OK_200, res->status);
  8452. ASSERT_EQ(26U, res->body.size());
  8453. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8454. 0);
  8455. }
  8456. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8457. Headers headers;
  8458. headers.emplace("Accept-Encoding", "");
  8459. std::string body;
  8460. auto res = cli_.Get("/compress", headers,
  8461. [&](const char *data, uint64_t data_length) {
  8462. EXPECT_EQ(100U, data_length);
  8463. body.append(data, data_length);
  8464. return true;
  8465. });
  8466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8467. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8468. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8469. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8470. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8471. "7890123456789012345678901234567890",
  8472. body);
  8473. EXPECT_EQ(StatusCode::OK_200, res->status);
  8474. }
  8475. TEST_F(ServerTest, NoZstd) {
  8476. Headers headers;
  8477. headers.emplace("Accept-Encoding", "zstd");
  8478. auto res = cli_.Get("/nocompress", headers);
  8479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8480. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8481. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8482. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8483. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8484. "7890123456789012345678901234567890",
  8485. res->body);
  8486. EXPECT_EQ(StatusCode::OK_200, res->status);
  8487. }
  8488. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8489. Headers headers;
  8490. headers.emplace("Accept-Encoding", "zstd");
  8491. std::string body;
  8492. auto res = cli_.Get("/nocompress", headers,
  8493. [&](const char *data, uint64_t data_length) {
  8494. EXPECT_EQ(100U, data_length);
  8495. body.append(data, data_length);
  8496. return true;
  8497. });
  8498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8499. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8500. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8501. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8502. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8503. "7890123456789012345678901234567890",
  8504. body);
  8505. EXPECT_EQ(StatusCode::OK_200, res->status);
  8506. }
  8507. // TODO: How to enable zstd ??
  8508. TEST_F(ServerTest, MultipartFormDataZstd) {
  8509. UploadFormDataItems items = {
  8510. {"key1", "test", "", ""},
  8511. {"key2", "--abcdefg123", "", ""},
  8512. };
  8513. Headers headers;
  8514. headers.emplace("Accept-Encoding", "zstd");
  8515. cli_.set_compress(true);
  8516. auto res = cli_.Post("/compress-multipart", headers, items);
  8517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8518. EXPECT_EQ(StatusCode::OK_200, res->status);
  8519. }
  8520. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8521. Headers headers;
  8522. headers.emplace("Accept-Encoding", "zstd");
  8523. cli_.set_compress(true);
  8524. auto res = cli_.Put(
  8525. "/put", headers, 3,
  8526. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8527. sink.os << "PUT";
  8528. return true;
  8529. },
  8530. "text/plain");
  8531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8532. EXPECT_EQ(StatusCode::OK_200, res->status);
  8533. EXPECT_EQ("PUT", res->body);
  8534. }
  8535. // Pre-compression logging tests
  8536. TEST_F(ServerTest, PreCompressionLogging) {
  8537. // Test data for compression (matches the actual /compress endpoint content)
  8538. const std::string test_content =
  8539. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8540. "3456789012345678901234567890";
  8541. // Variables to capture logging data
  8542. std::string pre_compression_body;
  8543. std::string pre_compression_content_type;
  8544. std::string pre_compression_content_encoding;
  8545. std::string post_compression_body;
  8546. std::string post_compression_content_type;
  8547. std::string post_compression_content_encoding;
  8548. // Set up pre-compression logger
  8549. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8550. const Response &res) {
  8551. pre_compression_body = res.body;
  8552. pre_compression_content_type = res.get_header_value("Content-Type");
  8553. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8554. });
  8555. // Set up post-compression logger
  8556. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8557. post_compression_body = res.body;
  8558. post_compression_content_type = res.get_header_value("Content-Type");
  8559. post_compression_content_encoding =
  8560. res.get_header_value("Content-Encoding");
  8561. });
  8562. // Test with gzip compression
  8563. Headers headers;
  8564. headers.emplace("Accept-Encoding", "gzip");
  8565. auto res = cli_.Get("/compress", headers);
  8566. // Verify response was compressed
  8567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8568. EXPECT_EQ(StatusCode::OK_200, res->status);
  8569. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8570. // Verify pre-compression logger captured uncompressed content
  8571. EXPECT_EQ(test_content, pre_compression_body);
  8572. EXPECT_EQ("text/plain", pre_compression_content_type);
  8573. EXPECT_TRUE(pre_compression_content_encoding
  8574. .empty()); // No encoding header before compression
  8575. // Verify post-compression logger captured compressed content
  8576. EXPECT_NE(test_content,
  8577. post_compression_body); // Should be different after compression
  8578. EXPECT_EQ("text/plain", post_compression_content_type);
  8579. EXPECT_EQ("gzip", post_compression_content_encoding);
  8580. // Verify compressed content is smaller
  8581. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8582. }
  8583. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8584. const std::string test_content =
  8585. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8586. "3456789012345678901234567890";
  8587. std::string pre_compression_body;
  8588. std::string post_compression_body;
  8589. svr_.set_pre_compression_logger(
  8590. [&](const Request & /*req*/, const Response &res) {
  8591. pre_compression_body = res.body;
  8592. });
  8593. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8594. post_compression_body = res.body;
  8595. });
  8596. Headers headers;
  8597. headers.emplace("Accept-Encoding", "br");
  8598. auto res = cli_.Get("/compress", headers);
  8599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8600. EXPECT_EQ(StatusCode::OK_200, res->status);
  8601. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8602. // Verify pre-compression content is uncompressed
  8603. EXPECT_EQ(test_content, pre_compression_body);
  8604. // Verify post-compression content is compressed
  8605. EXPECT_NE(test_content, post_compression_body);
  8606. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8607. }
  8608. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8609. const std::string test_content =
  8610. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8611. "3456789012345678901234567890";
  8612. std::string pre_compression_body;
  8613. std::string post_compression_body;
  8614. svr_.set_pre_compression_logger(
  8615. [&](const Request & /*req*/, const Response &res) {
  8616. pre_compression_body = res.body;
  8617. });
  8618. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8619. post_compression_body = res.body;
  8620. });
  8621. // Request without compression (use /nocompress endpoint)
  8622. Headers headers;
  8623. auto res = cli_.Get("/nocompress", headers);
  8624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8625. EXPECT_EQ(StatusCode::OK_200, res->status);
  8626. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8627. // Pre-compression logger should not be called when no compression is applied
  8628. EXPECT_TRUE(
  8629. pre_compression_body.empty()); // Pre-compression logger not called
  8630. EXPECT_EQ(
  8631. test_content,
  8632. post_compression_body); // Post-compression logger captures final content
  8633. }
  8634. TEST_F(ServerTest, LoggerSeesContentLength) {
  8635. size_t logged_content_length = 0;
  8636. std::string logged_content_length_header;
  8637. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8638. logged_content_length = res.content_length_;
  8639. logged_content_length_header = res.get_header_value("Content-Length");
  8640. });
  8641. auto res = cli_.Get("/nocompress");
  8642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8643. EXPECT_EQ(StatusCode::OK_200, res->status);
  8644. EXPECT_EQ(res->body.size(), logged_content_length);
  8645. EXPECT_EQ(std::to_string(logged_content_length),
  8646. logged_content_length_header);
  8647. }
  8648. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8649. const std::string test_content =
  8650. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8651. "3456789012345678901234567890";
  8652. std::string pre_compression_body;
  8653. bool pre_logger_called = false;
  8654. // Set only pre-compression logger
  8655. svr_.set_pre_compression_logger(
  8656. [&](const Request & /*req*/, const Response &res) {
  8657. pre_compression_body = res.body;
  8658. pre_logger_called = true;
  8659. });
  8660. Headers headers;
  8661. headers.emplace("Accept-Encoding", "gzip");
  8662. auto res = cli_.Get("/compress", headers);
  8663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8664. EXPECT_EQ(StatusCode::OK_200, res->status);
  8665. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8666. // Verify pre-compression logger was called
  8667. EXPECT_TRUE(pre_logger_called);
  8668. EXPECT_EQ(test_content, pre_compression_body);
  8669. }
  8670. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8671. {
  8672. // Test with Expect: 100-continue header - success case
  8673. // Server returns 100 Continue, client sends body, server returns 200 OK
  8674. Request req;
  8675. req.method = "POST";
  8676. req.path = "/post-large";
  8677. req.set_header("Expect", "100-continue");
  8678. req.body = LARGE_DATA;
  8679. Response res;
  8680. auto error = Error::Success;
  8681. cli_.set_keep_alive(true);
  8682. auto ret = cli_.send(req, res, error);
  8683. EXPECT_TRUE(ret);
  8684. EXPECT_EQ(StatusCode::OK_200, res.status);
  8685. EXPECT_EQ(LARGE_DATA, res.body);
  8686. }
  8687. {
  8688. // Test with Expect: 100-continue header - error case
  8689. // Client should not send the body when server returns an error
  8690. Request req;
  8691. req.method = "POST";
  8692. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8693. req.set_header("Expect", "100-continue");
  8694. req.body = LARGE_DATA;
  8695. Response res;
  8696. auto error = Error::Success;
  8697. auto start = std::chrono::high_resolution_clock::now();
  8698. cli_.set_keep_alive(true);
  8699. auto ret = cli_.send(req, res, error);
  8700. auto end = std::chrono::high_resolution_clock::now();
  8701. auto elapsed =
  8702. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8703. .count();
  8704. // With Expect: 100-continue, request completes successfully but with error
  8705. EXPECT_TRUE(ret);
  8706. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8707. EXPECT_EQ("close", res.get_header_value("Connection"));
  8708. EXPECT_FALSE(cli_.is_socket_open());
  8709. EXPECT_LE(elapsed, 2000);
  8710. }
  8711. {
  8712. // Send an extra GET request to ensure error recovery without hanging
  8713. Request req;
  8714. req.method = "GET";
  8715. req.path = "/hi";
  8716. auto start = std::chrono::high_resolution_clock::now();
  8717. auto res = cli_.send(req);
  8718. auto end = std::chrono::high_resolution_clock::now();
  8719. auto elapsed =
  8720. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8721. .count();
  8722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8723. EXPECT_EQ(StatusCode::OK_200, res->status);
  8724. EXPECT_EQ("Hello World!", res->body);
  8725. EXPECT_LE(elapsed, 500);
  8726. }
  8727. }
  8728. TEST(ZstdDecompressor, ChunkedDecompression) {
  8729. std::string data;
  8730. for (size_t i = 0; i < 32 * 1024; ++i) {
  8731. data.push_back(static_cast<char>('a' + i % 26));
  8732. }
  8733. std::string compressed_data;
  8734. {
  8735. httplib::detail::zstd_compressor compressor;
  8736. bool result = compressor.compress(
  8737. data.data(), data.size(),
  8738. /*last=*/true,
  8739. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8740. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8741. compressed_data_size);
  8742. return true;
  8743. });
  8744. ASSERT_TRUE(result);
  8745. }
  8746. std::string decompressed_data;
  8747. {
  8748. httplib::detail::zstd_decompressor decompressor;
  8749. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8750. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8751. size_t chunk_size = 130;
  8752. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8753. chunk_begin += chunk_size) {
  8754. size_t current_chunk_size =
  8755. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8756. bool result = decompressor.decompress(
  8757. compressed_data.data() + chunk_begin, current_chunk_size,
  8758. [&](const char *decompressed_data_chunk,
  8759. size_t decompressed_data_chunk_size) {
  8760. decompressed_data.insert(decompressed_data.size(),
  8761. decompressed_data_chunk,
  8762. decompressed_data_chunk_size);
  8763. return true;
  8764. });
  8765. ASSERT_TRUE(result);
  8766. }
  8767. }
  8768. ASSERT_EQ(data, decompressed_data);
  8769. }
  8770. TEST(ZstdDecompressor, Decompress) {
  8771. std::string original_text = "Compressed with ZSTD";
  8772. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8773. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8774. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8775. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8776. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8777. std::string decompressed_data;
  8778. {
  8779. httplib::detail::zstd_decompressor decompressor;
  8780. bool result = decompressor.decompress(
  8781. compressed_data.data(), compressed_data.size(),
  8782. [&](const char *decompressed_data_chunk,
  8783. size_t decompressed_data_chunk_size) {
  8784. decompressed_data.insert(decompressed_data.size(),
  8785. decompressed_data_chunk,
  8786. decompressed_data_chunk_size);
  8787. return true;
  8788. });
  8789. ASSERT_TRUE(result);
  8790. }
  8791. ASSERT_EQ(original_text, decompressed_data);
  8792. }
  8793. #endif
  8794. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8795. // separate chunks so that the server sees each part in its own read(). Used to
  8796. // place a read boundary at a specific offset of a request body.
  8797. static bool send_request_in_parts(time_t read_timeout_sec,
  8798. const std::vector<std::string> &parts,
  8799. std::string *resp = nullptr,
  8800. int port = PORT) {
  8801. auto error = Error::Success;
  8802. auto client_sock = detail::create_client_socket(
  8803. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8804. /*connection_timeout_sec=*/5, 0,
  8805. /*read_timeout_sec=*/5, 0,
  8806. /*write_timeout_sec=*/5, 0, std::string(), error);
  8807. if (client_sock == INVALID_SOCKET) { return false; }
  8808. auto ret = detail::process_client_socket(
  8809. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8810. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8811. for (size_t i = 0; i < parts.size(); i++) {
  8812. const auto &part = parts[i];
  8813. if (part.size() !=
  8814. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8815. return false;
  8816. }
  8817. if (i + 1 < parts.size()) {
  8818. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8819. }
  8820. }
  8821. char buf[512];
  8822. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8823. while (line_reader.getline()) {
  8824. if (resp) { *resp += line_reader.ptr(); }
  8825. }
  8826. return true;
  8827. });
  8828. detail::close_socket(client_sock);
  8829. return ret;
  8830. }
  8831. // Sends a raw request to a server listening at HOST:PORT.
  8832. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8833. std::string *resp = nullptr, int port = PORT) {
  8834. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8835. }
  8836. #ifdef CPPHTTPLIB_SSL_ENABLED
  8837. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  8838. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8839. ASSERT_TRUE(svr.is_valid());
  8840. svr.set_read_timeout(1, 0);
  8841. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8842. auto se = detail::scope_exit([&] {
  8843. svr.stop();
  8844. t.join();
  8845. ASSERT_FALSE(svr.is_running());
  8846. });
  8847. svr.wait_until_ready();
  8848. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  8849. // keeps each wait well within the read timeout. The server gives up a
  8850. // second in, so the bytes sent after that fail.
  8851. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  8852. parts.resize(26, std::string(1, '\0'));
  8853. EXPECT_FALSE(send_request_in_parts(5, parts));
  8854. }
  8855. #endif
  8856. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8857. Server svr;
  8858. std::string header_value;
  8859. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8860. header_value = req.get_header_value("foo");
  8861. res.set_content("ok", "text/plain");
  8862. });
  8863. thread t = thread([&] { svr.listen(HOST, PORT); });
  8864. auto se = detail::scope_exit([&] {
  8865. svr.stop();
  8866. t.join();
  8867. ASSERT_FALSE(svr.is_running());
  8868. });
  8869. svr.wait_until_ready();
  8870. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8871. // like characters are not treated the same - use vertical tab and escape.
  8872. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8873. "foo: \t \v bar \x1B\t \r\n"
  8874. "Connection: close\r\n"
  8875. "\r\n";
  8876. std::string res;
  8877. ASSERT_TRUE(send_request(5, req, &res));
  8878. EXPECT_EQ(header_value, "");
  8879. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8880. }
  8881. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8882. Server svr;
  8883. std::string received;
  8884. svr.Get("/order", [&](const Request &req, Response &res) {
  8885. received = entries_to_string(req.headers);
  8886. res.set_content("ok", "text/plain");
  8887. });
  8888. auto port = svr.bind_to_any_port(HOST);
  8889. thread t = thread([&] { svr.listen_after_bind(); });
  8890. auto se = detail::scope_exit([&] {
  8891. svr.stop();
  8892. t.join();
  8893. ASSERT_FALSE(svr.is_running());
  8894. });
  8895. svr.wait_until_ready();
  8896. const std::string req = "GET /order HTTP/1.1\r\n"
  8897. "Host: localhost\r\n"
  8898. "X-First: 1\r\n"
  8899. "X-Dup: a\r\n"
  8900. "X-Second: 2\r\n"
  8901. "X-Dup: b\r\n"
  8902. "Connection: close\r\n"
  8903. "\r\n";
  8904. std::string res;
  8905. ASSERT_TRUE(send_request(5, req, &res, port));
  8906. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8907. EXPECT_EQ(
  8908. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  8909. received);
  8910. }
  8911. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8912. Server svr;
  8913. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8914. res.set_header("Set-Cookie", "first=1");
  8915. res.set_header("X-Between", "y");
  8916. res.set_header("Set-Cookie", "second=2");
  8917. res.set_content("ok", "text/plain");
  8918. });
  8919. auto port = svr.bind_to_any_port(HOST);
  8920. thread t = thread([&] { svr.listen_after_bind(); });
  8921. auto se = detail::scope_exit([&] {
  8922. svr.stop();
  8923. t.join();
  8924. ASSERT_FALSE(svr.is_running());
  8925. });
  8926. svr.wait_until_ready();
  8927. Client cli(HOST, port);
  8928. auto res = cli.Get("/cookies");
  8929. ASSERT_TRUE(res);
  8930. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8931. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8932. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8933. }
  8934. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8935. Server svr;
  8936. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8937. auto i = new int(0);
  8938. res.set_header("Trailer", "X-Safe, X-Reflected");
  8939. res.set_chunked_content_provider(
  8940. "text/plain",
  8941. [i](size_t /*offset*/, DataSink &sink) {
  8942. if (*i == 0) {
  8943. sink.os << "body";
  8944. } else {
  8945. Headers trailer;
  8946. // A valid trailer that must survive.
  8947. trailer.emplace("X-Safe", "safe");
  8948. // Attacker-controlled value carrying CR/LF (response splitting).
  8949. trailer.emplace("X-Reflected",
  8950. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8951. // Attacker-controlled name carrying CR/LF.
  8952. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8953. sink.done_with_trailer(trailer);
  8954. }
  8955. (*i)++;
  8956. return true;
  8957. },
  8958. [i](bool /*success*/) { delete i; });
  8959. });
  8960. thread t = thread([&] { svr.listen(HOST, PORT); });
  8961. auto se = detail::scope_exit([&] {
  8962. svr.stop();
  8963. t.join();
  8964. ASSERT_FALSE(svr.is_running());
  8965. });
  8966. svr.wait_until_ready();
  8967. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8968. "Host: " + HOST +
  8969. "\r\n"
  8970. "Connection: close\r\n"
  8971. "\r\n";
  8972. std::string res;
  8973. ASSERT_TRUE(send_request(5, req, &res));
  8974. // The injected fields must not appear anywhere in the raw response.
  8975. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8976. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8977. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8978. // Invalid trailers are dropped entirely, matching set_header().
  8979. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8980. // The valid trailer still passes through.
  8981. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8982. }
  8983. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8984. Server svr;
  8985. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8986. // res.headers is a public field an application can populate directly,
  8987. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8988. // A valid header that must survive.
  8989. res.headers.emplace("X-Safe", "safe");
  8990. // Attacker-controlled value carrying CR/LF (response splitting).
  8991. res.headers.emplace("X-Reflected",
  8992. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8993. // Attacker-controlled name carrying CR/LF.
  8994. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8995. res.set_content("body", "text/plain");
  8996. });
  8997. thread t = thread([&] { svr.listen(HOST, PORT); });
  8998. auto se = detail::scope_exit([&] {
  8999. svr.stop();
  9000. t.join();
  9001. ASSERT_FALSE(svr.is_running());
  9002. });
  9003. svr.wait_until_ready();
  9004. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9005. "Host: " + HOST +
  9006. "\r\n"
  9007. "Connection: close\r\n"
  9008. "\r\n";
  9009. std::string res;
  9010. ASSERT_TRUE(send_request(5, req, &res));
  9011. // The injected fields must not appear anywhere in the raw response.
  9012. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9013. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9014. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9015. // Invalid headers are dropped entirely, matching set_header().
  9016. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9017. // The valid header still passes through.
  9018. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9019. }
  9020. // Forward declaration: in split builds split.py strips `inline` and moves the
  9021. // definition into httplib.cc, so detail::write_request_line is not visible from
  9022. // the public httplib.h. Re-declaring it here lets the tests link against the
  9023. // symbol in both header-only and split builds.
  9024. namespace httplib {
  9025. namespace detail {
  9026. ssize_t write_request_line(Stream &strm, const std::string &method,
  9027. const std::string &path);
  9028. } // namespace detail
  9029. } // namespace httplib
  9030. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9031. // A well-formed target is written verbatim.
  9032. {
  9033. detail::BufferStream strm;
  9034. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9035. EXPECT_GT(n, 0);
  9036. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9037. }
  9038. // A target carrying CR/LF, SP or other control octets must be rejected
  9039. // before anything reaches the wire, otherwise it splits the request line and
  9040. // injects a header or a whole request.
  9041. const std::string evil_targets[] = {
  9042. "/a\r\nInjected: pwned",
  9043. "/a\rInjected",
  9044. "/a\nInjected",
  9045. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9046. "/a b",
  9047. "/a\tb",
  9048. "/a\x7f",
  9049. };
  9050. for (const auto &evil : evil_targets) {
  9051. detail::BufferStream strm;
  9052. auto n = detail::write_request_line(strm, "GET", evil);
  9053. EXPECT_LT(n, 0);
  9054. EXPECT_TRUE(strm.get_buffer().empty());
  9055. }
  9056. }
  9057. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9058. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9059. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9060. // target reaches write_request. The client must fail cleanly with
  9061. // Error::Write instead of putting a request-line-less, header-injecting
  9062. // request on the wire.
  9063. Server svr;
  9064. svr.Get("/a", [](const Request &, Response &res) {
  9065. res.set_content("ok", "text/plain");
  9066. });
  9067. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9068. auto se = detail::scope_exit([&] {
  9069. svr.stop();
  9070. thread.join();
  9071. ASSERT_FALSE(svr.is_running());
  9072. });
  9073. svr.wait_until_ready();
  9074. {
  9075. Client cli(HOST, PORT);
  9076. cli.set_path_encode(false);
  9077. // The request is rejected before anything is written, so the connection
  9078. // stays silent and the subsequent response read would otherwise block for
  9079. // the full default read timeout. Shorten it -- the assertion is on the
  9080. // error, not the timeout.
  9081. cli.set_read_timeout(1, 0);
  9082. auto res = cli.Get("/a\r\nInjected: pwned");
  9083. EXPECT_FALSE(res);
  9084. EXPECT_EQ(Error::Write, res.error());
  9085. }
  9086. }
  9087. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9088. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9089. // including extension methods.
  9090. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9091. for (const auto &method : good_methods) {
  9092. detail::BufferStream strm;
  9093. auto n = detail::write_request_line(strm, method, "/");
  9094. EXPECT_GT(n, 0);
  9095. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9096. }
  9097. // A method carrying CR/LF would split the request line and smuggle a whole
  9098. // request ahead of the real one. A space or an empty method corrupts the
  9099. // request line. All must be rejected before anything reaches the wire.
  9100. const std::string evil_methods[] = {
  9101. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9102. "GET\r\nInjected: pwned",
  9103. "GET\r",
  9104. "GET\n",
  9105. "GE T",
  9106. "",
  9107. };
  9108. for (const auto &evil : evil_methods) {
  9109. detail::BufferStream strm;
  9110. auto n = detail::write_request_line(strm, evil, "/");
  9111. EXPECT_LT(n, 0);
  9112. EXPECT_TRUE(strm.get_buffer().empty());
  9113. }
  9114. }
  9115. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9116. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9117. // through Client::send must fail with Error::Write and no request, neither
  9118. // the smuggled one nor the real one, may reach the server.
  9119. Server svr;
  9120. std::atomic<int> request_count(0);
  9121. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9122. request_count++;
  9123. res.status = StatusCode::OK_200;
  9124. return Server::HandlerResponse::Handled;
  9125. });
  9126. auto port = svr.bind_to_any_port(HOST);
  9127. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9128. auto se = detail::scope_exit([&] {
  9129. svr.stop();
  9130. thread.join();
  9131. ASSERT_FALSE(svr.is_running());
  9132. });
  9133. svr.wait_until_ready();
  9134. {
  9135. Client cli(HOST, port);
  9136. const std::string evil_methods[] = {
  9137. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9138. "GE T",
  9139. "",
  9140. };
  9141. for (const auto &evil : evil_methods) {
  9142. Request req;
  9143. req.method = evil;
  9144. req.path = "/";
  9145. auto res = cli.send(req);
  9146. EXPECT_FALSE(res);
  9147. EXPECT_EQ(Error::Write, res.error());
  9148. }
  9149. auto handle =
  9150. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9151. EXPECT_FALSE(handle.is_valid());
  9152. EXPECT_EQ(Error::Write, handle.error);
  9153. // A valid request on the same client still goes through.
  9154. auto res = cli.Get("/");
  9155. ASSERT_TRUE(res);
  9156. EXPECT_EQ(StatusCode::OK_200, res->status);
  9157. }
  9158. EXPECT_EQ(1, request_count.load());
  9159. }
  9160. // Sends a raw request and verifies that there isn't a crash or exception.
  9161. static void test_raw_request(const std::string &req,
  9162. std::string *out = nullptr) {
  9163. Server svr;
  9164. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9165. res.set_content("ok", "text/plain");
  9166. });
  9167. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9168. res.set_content("ok", "text/plain");
  9169. });
  9170. svr.Get("/header_field_value_check",
  9171. [&](const Request & /*req*/, Response &res) {
  9172. res.set_content("ok", "text/plain");
  9173. });
  9174. svr.CustomRoute("PROPFIND", "/dav",
  9175. [&](const Request & /*req*/, Response &res) {
  9176. res.status = StatusCode::MultiStatus_207;
  9177. });
  9178. // Server read timeout must be longer than the client read timeout for the
  9179. // bug to reproduce, probably to force the server to process a request
  9180. // without a trailing blank line.
  9181. const time_t client_read_timeout_sec = 1;
  9182. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9183. bool listen_thread_ok = false;
  9184. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9185. auto se = detail::scope_exit([&] {
  9186. svr.stop();
  9187. t.join();
  9188. ASSERT_FALSE(svr.is_running());
  9189. EXPECT_TRUE(listen_thread_ok);
  9190. });
  9191. svr.wait_until_ready();
  9192. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9193. }
  9194. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9195. // A certain header line causes an exception if the header property is parsed
  9196. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9197. test_raw_request(
  9198. "GET /hi HTTP/1.1\r\n"
  9199. " : "
  9200. " "
  9201. " ");
  9202. }
  9203. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9204. // A certain header line causes an exception if the header property *name* is
  9205. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9206. // greedy matcher and requires backtracking when there are a lot of ":"
  9207. // characters.
  9208. // This occurs with libc++ but not libstdc++.
  9209. test_raw_request(
  9210. "GET /hi HTTP/1.1\r\n"
  9211. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9212. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9213. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9214. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9215. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9216. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9217. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9218. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9219. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9220. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9221. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9222. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9223. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9224. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9225. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9226. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9227. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9228. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9229. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9230. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9231. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9232. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9233. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9234. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9235. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9236. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9237. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9238. "&&&%%%");
  9239. }
  9240. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9241. // Make sure this doesn't crash the server.
  9242. // In a previous version of the header line regex, the "\r" rendered the line
  9243. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9244. // a new position where the leading white space ended and the field value
  9245. // began.
  9246. // The crash occurs with libc++ but not libstdc++.
  9247. test_raw_request("GET /hi HTTP/1.1\r\n"
  9248. "a:" +
  9249. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9250. "\r\n"
  9251. "\r\n");
  9252. }
  9253. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9254. const char *rejected[] = {
  9255. // RFC 9112 §3: one SP between the parts, and nothing else
  9256. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9257. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9258. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9259. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9260. // A request-target has no fragment
  9261. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9262. // An HTTP/1.1 request needs a Host
  9263. "GET /hi HTTP/1.1\r\n\r\n",
  9264. };
  9265. for (auto request : rejected) {
  9266. std::string out;
  9267. test_raw_request(request, &out);
  9268. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9269. }
  9270. std::string out;
  9271. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9272. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9273. }
  9274. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9275. // RFC 9112 §6.1
  9276. const char *requests[] = {
  9277. "PUT /put_hi HTTP/1.1\r\n"
  9278. "Host: localhost\r\n"
  9279. "Content-Length: 0\r\n"
  9280. "Transfer-Encoding: chunked\r\n"
  9281. "\r\n"
  9282. "0\r\n\r\n",
  9283. "PUT /put_hi HTTP/1.0\r\n"
  9284. "Connection: keep-alive\r\n"
  9285. "Transfer-Encoding: chunked\r\n"
  9286. "\r\n"
  9287. "0\r\n\r\n",
  9288. };
  9289. for (auto request : requests) {
  9290. std::string out;
  9291. test_raw_request(request, &out);
  9292. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9293. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9294. }
  9295. }
  9296. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9297. std::string out;
  9298. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9299. "Content-Type: text/plain\r\n"
  9300. "Transfer-Encoding: chunked\r\n"
  9301. "\r\n"
  9302. "nothex\r\n",
  9303. &out);
  9304. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9305. }
  9306. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9307. std::string out;
  9308. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9309. "Content-Type: text/plain\r\n"
  9310. "Transfer-Encoding: chunked\r\n"
  9311. "\r\n"
  9312. "3\r\n"
  9313. "xyz\r\n"
  9314. "NaN\r\n",
  9315. &out);
  9316. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9317. }
  9318. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9319. std::string out;
  9320. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9321. "Content-Type: text/plain\r\n"
  9322. "Transfer-Encoding: chunked\r\n"
  9323. "\r\n"
  9324. // Length is too large for 64 bits.
  9325. "1ffffffffffffffff\r\n"
  9326. "xyz\r\n",
  9327. &out);
  9328. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9329. }
  9330. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9331. test_raw_request("GET /hi HTTP/1.1\r\n"
  9332. "Content-Type: text/plain\r\n\r");
  9333. }
  9334. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9335. std::string out;
  9336. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9337. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9338. }
  9339. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9340. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9341. std::string out;
  9342. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9343. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9344. }
  9345. }
  9346. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9347. std::string out;
  9348. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9349. "Host: localhost\r\n"
  9350. "Connection: close\r\n\r\n",
  9351. &out);
  9352. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9353. }
  9354. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9355. Server svr;
  9356. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9357. EXPECT_TRUE(!req.remote_addr.empty());
  9358. });
  9359. thread t = thread([&] { svr.listen(HOST, PORT); });
  9360. auto se = detail::scope_exit([&] {
  9361. svr.stop();
  9362. t.join();
  9363. ASSERT_FALSE(svr.is_running());
  9364. });
  9365. svr.wait_until_ready();
  9366. // Send an invalid request line to trigger Bad Request
  9367. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9368. std::string out;
  9369. ASSERT_TRUE(send_request(5, bad_req, &out));
  9370. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9371. }
  9372. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9373. // answered right away rather than blocking on a read that waits for EOF.
  9374. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9375. std::string out;
  9376. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9377. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9378. }
  9379. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9380. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9381. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9382. for (const auto *method : methods) {
  9383. Server svr;
  9384. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9385. EXPECT_FALSE(svr.is_valid()) << method;
  9386. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9387. }
  9388. }
  9389. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9390. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9391. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9392. for (const auto *method : methods) {
  9393. Server svr;
  9394. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9395. EXPECT_FALSE(svr.is_valid()) << method;
  9396. }
  9397. }
  9398. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9399. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9400. "COPY", "MOVE", "LOCK",
  9401. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9402. Server svr;
  9403. for (const auto *method : methods) {
  9404. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9405. }
  9406. EXPECT_TRUE(svr.is_valid());
  9407. }
  9408. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9409. Server svr;
  9410. svr.CustomRoute("POST", "/x",
  9411. [](const Request &, Response &, const ContentReader &) {});
  9412. EXPECT_FALSE(svr.is_valid());
  9413. }
  9414. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9415. Server svr;
  9416. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9417. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9418. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9419. EXPECT_FALSE(svr.is_valid());
  9420. }
  9421. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9422. Server svr;
  9423. auto captured = Error::Success;
  9424. svr.set_error_logger(
  9425. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9426. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9427. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9428. }
  9429. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9430. std::string out;
  9431. std::string request(
  9432. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9433. test_raw_request(request, &out);
  9434. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9435. }
  9436. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9437. std::string out;
  9438. std::string request(
  9439. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9440. test_raw_request(request, &out);
  9441. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9442. }
  9443. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9444. std::string out;
  9445. std::string request(
  9446. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9447. test_raw_request(request, &out);
  9448. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9449. }
  9450. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9451. std::string out;
  9452. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9453. "Host: localhost\r\n"
  9454. "Test: \r\n\r\n",
  9455. &out);
  9456. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9457. }
  9458. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9459. Server svr;
  9460. std::string x_custom;
  9461. std::string cookie;
  9462. std::string xff;
  9463. std::string x_unicode;
  9464. std::string x_iis;
  9465. svr.Get("/check", [&](const Request &req, Response &res) {
  9466. x_custom = req.get_header_value("X-Custom");
  9467. cookie = req.get_header_value("Cookie");
  9468. xff = req.get_header_value("X-Forwarded-For");
  9469. x_unicode = req.get_header_value("X-Unicode");
  9470. x_iis = req.get_header_value("X-IIS");
  9471. res.set_content("ok", "text/plain");
  9472. });
  9473. thread t = thread([&] { svr.listen(HOST, PORT); });
  9474. auto se = detail::scope_exit([&] {
  9475. svr.stop();
  9476. t.join();
  9477. ASSERT_FALSE(svr.is_running());
  9478. });
  9479. svr.wait_until_ready();
  9480. const std::string req = "GET /check HTTP/1.1\r\n"
  9481. "Host: localhost\r\n"
  9482. "X-Custom: a%0D%0AInjected: b\r\n"
  9483. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9484. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9485. "X-Unicode: %E3%81%82\r\n"
  9486. "X-IIS: %u00E9\r\n"
  9487. "Connection: close\r\n"
  9488. "\r\n";
  9489. std::string res;
  9490. ASSERT_TRUE(send_request(5, req, &res));
  9491. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9492. // Every value must be returned verbatim (wire form), with no decoding.
  9493. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9494. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9495. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9496. EXPECT_EQ("%E3%81%82", x_unicode);
  9497. EXPECT_EQ("%u00E9", x_iis);
  9498. }
  9499. // Applications that previously relied on automatic percent-decoding can
  9500. // reproduce the old behavior by explicitly calling decode_path_component()
  9501. // or, for RFC 3986 conformance, decode_uri_component().
  9502. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9503. Server svr;
  9504. std::string decoded;
  9505. svr.Get("/check", [&](const Request &req, Response &res) {
  9506. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9507. res.set_content("ok", "text/plain");
  9508. });
  9509. thread t = thread([&] { svr.listen(HOST, PORT); });
  9510. auto se = detail::scope_exit([&] {
  9511. svr.stop();
  9512. t.join();
  9513. ASSERT_FALSE(svr.is_running());
  9514. });
  9515. svr.wait_until_ready();
  9516. const std::string req = "GET /check HTTP/1.1\r\n"
  9517. "Host: localhost\r\n"
  9518. "X-Custom: hello%20world\r\n"
  9519. "Connection: close\r\n"
  9520. "\r\n";
  9521. std::string res;
  9522. ASSERT_TRUE(send_request(5, req, &res));
  9523. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9524. EXPECT_EQ("hello world", decoded);
  9525. }
  9526. // Regression test for #2033. Browsers send Referer values that include
  9527. // percent-encoded characters such as %0A inside the URL. Decoding the
  9528. // header value would either trip the post-decode CR/LF/NUL guard (the
  9529. // original bug, returning 400) or, after that guard was relaxed, silently
  9530. // store a literal LF — both unacceptable. The wire form must round-trip.
  9531. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9532. Server svr;
  9533. std::string referer;
  9534. svr.Get("/check", [&](const Request &req, Response &res) {
  9535. referer = req.get_header_value("Referer");
  9536. res.set_content("ok", "text/plain");
  9537. });
  9538. thread t = thread([&] { svr.listen(HOST, PORT); });
  9539. auto se = detail::scope_exit([&] {
  9540. svr.stop();
  9541. t.join();
  9542. ASSERT_FALSE(svr.is_running());
  9543. });
  9544. svr.wait_until_ready();
  9545. const std::string req = "GET /check HTTP/1.1\r\n"
  9546. "Host: localhost\r\n"
  9547. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9548. "Connection: close\r\n"
  9549. "\r\n";
  9550. std::string res;
  9551. ASSERT_TRUE(send_request(5, req, &res));
  9552. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9553. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9554. }
  9555. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9556. Server svr;
  9557. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9558. res.set_header("Cache-Control", "no-cache");
  9559. res.set_chunked_content_provider(
  9560. "text/event-stream", [](size_t offset, DataSink &sink) {
  9561. std::string s = "data:";
  9562. s += std::to_string(offset);
  9563. s += "\n\n";
  9564. auto ret = sink.write(s.data(), s.size());
  9565. EXPECT_TRUE(ret);
  9566. std::this_thread::sleep_for(std::chrono::seconds(1));
  9567. return true;
  9568. });
  9569. });
  9570. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9571. svr.wait_until_ready();
  9572. Client client(HOST, PORT);
  9573. const Headers headers = {{"Accept", "text/event-stream"}};
  9574. auto get_thread = std::thread([&client, &headers]() {
  9575. auto res = client.Get(
  9576. "/events", headers,
  9577. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9578. });
  9579. auto se = detail::scope_exit([&] {
  9580. svr.stop();
  9581. get_thread.join();
  9582. listen_thread.join();
  9583. ASSERT_FALSE(svr.is_running());
  9584. });
  9585. // Give GET time to get a few messages.
  9586. std::this_thread::sleep_for(std::chrono::seconds(2));
  9587. }
  9588. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9589. httplib::Server svr;
  9590. svr.Post("/hi",
  9591. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9592. res.status = StatusCode::OK_200;
  9593. });
  9594. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9595. svr.wait_until_ready();
  9596. Client cli(HOST, PORT);
  9597. auto res = cli.Post("/hi", "data", "text/plain");
  9598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9599. EXPECT_EQ(StatusCode::OK_200, res->status);
  9600. svr.stop();
  9601. thread.join();
  9602. ASSERT_FALSE(svr.is_running());
  9603. res = cli.Post("/hi", "data", "text/plain");
  9604. ASSERT_FALSE(res);
  9605. }
  9606. TEST(ServerStopTest, ListenFailure) {
  9607. Server svr;
  9608. auto t = thread([&]() {
  9609. auto ret = svr.listen("????", PORT);
  9610. EXPECT_FALSE(ret);
  9611. });
  9612. svr.wait_until_ready();
  9613. svr.stop();
  9614. t.join();
  9615. }
  9616. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9617. TEST(ServerStopTest, Decommision) {
  9618. Server svr;
  9619. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9620. for (int i = 0; i < 4; i++) {
  9621. auto is_even = !(i % 2);
  9622. std::thread t{[&] {
  9623. try {
  9624. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9625. if (is_even) {
  9626. throw std::runtime_error("Some thing that happens to go wrong.");
  9627. }
  9628. svr.listen(HOST, PORT);
  9629. } catch (...) { svr.decommission(); }
  9630. }};
  9631. svr.wait_until_ready();
  9632. // Server is up
  9633. {
  9634. Client cli(HOST, PORT);
  9635. auto res = cli.Get("/hi");
  9636. if (is_even) {
  9637. EXPECT_FALSE(res);
  9638. } else {
  9639. EXPECT_TRUE(res);
  9640. EXPECT_EQ("hi...", res->body);
  9641. }
  9642. }
  9643. svr.stop();
  9644. t.join();
  9645. // Server is down...
  9646. {
  9647. Client cli(HOST, PORT);
  9648. auto res = cli.Get("/hi");
  9649. EXPECT_FALSE(res);
  9650. }
  9651. }
  9652. }
  9653. #endif
  9654. // Helper function for string body upload progress tests
  9655. template <typename SetupHandler, typename ClientCall>
  9656. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9657. ClientCall &&client_call,
  9658. const string &body) {
  9659. Server svr;
  9660. setup_handler(svr);
  9661. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9662. auto se = detail::scope_exit([&] {
  9663. svr.stop();
  9664. t.join();
  9665. });
  9666. svr.wait_until_ready();
  9667. Client cli(HOST, PORT);
  9668. vector<uint64_t> progress_values;
  9669. bool progress_called = false;
  9670. auto res =
  9671. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9672. progress_values.push_back(current);
  9673. progress_called = true;
  9674. return true;
  9675. });
  9676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9677. EXPECT_EQ(200, res->status);
  9678. EXPECT_TRUE(progress_called);
  9679. }
  9680. TEST(UploadProgressTest, PostStringBodyBasic) {
  9681. TestStringBodyUploadProgress(
  9682. [](Server &svr) {
  9683. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9684. res.set_content("received", "text/plain");
  9685. });
  9686. },
  9687. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9688. return cli.Post("/test", body, "text/plain", progress_callback);
  9689. },
  9690. "test data for upload progress");
  9691. }
  9692. TEST(UploadProgressTest, PutStringBodyBasic) {
  9693. TestStringBodyUploadProgress(
  9694. [](Server &svr) {
  9695. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9696. res.set_content("put received", "text/plain");
  9697. });
  9698. },
  9699. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9700. return cli.Put("/test", body, "text/plain", progress_callback);
  9701. },
  9702. "put test data for upload progress");
  9703. }
  9704. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9705. TestStringBodyUploadProgress(
  9706. [](Server &svr) {
  9707. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9708. res.set_content("patch received", "text/plain");
  9709. });
  9710. },
  9711. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9712. return cli.Patch("/test", body, "text/plain", progress_callback);
  9713. },
  9714. "patch test data for upload progress");
  9715. }
  9716. // Helper function for content provider upload progress tests
  9717. template <typename SetupHandler, typename ClientCall>
  9718. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9719. ClientCall &&client_call) {
  9720. Server svr;
  9721. setup_handler(svr);
  9722. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9723. auto se = detail::scope_exit([&] {
  9724. svr.stop();
  9725. t.join();
  9726. });
  9727. svr.wait_until_ready();
  9728. Client cli(HOST, PORT);
  9729. vector<uint64_t> progress_values;
  9730. auto res =
  9731. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9732. progress_values.push_back(current);
  9733. return true;
  9734. });
  9735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9736. EXPECT_EQ(200, res->status);
  9737. EXPECT_FALSE(progress_values.empty());
  9738. }
  9739. TEST(UploadProgressTest, PostContentProviderProgress) {
  9740. TestContentProviderUploadProgress(
  9741. [](Server &svr) {
  9742. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9743. res.set_content("provider received", "text/plain");
  9744. });
  9745. },
  9746. [](Client &cli, UploadProgress progress_callback) {
  9747. return cli.Post(
  9748. "/test", 10,
  9749. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9750. sink.os << "test data";
  9751. return true;
  9752. },
  9753. "text/plain", progress_callback);
  9754. });
  9755. }
  9756. // Helper function for multipart upload progress tests
  9757. template <typename SetupHandler, typename ClientCall>
  9758. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9759. ClientCall &&client_call,
  9760. const string &endpoint) {
  9761. Server svr;
  9762. setup_handler(svr);
  9763. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9764. auto se = detail::scope_exit([&] {
  9765. svr.stop();
  9766. t.join();
  9767. });
  9768. svr.wait_until_ready();
  9769. Client cli(HOST, PORT);
  9770. vector<uint64_t> progress_values;
  9771. UploadFormDataItems items = {
  9772. {"field1", "value1", "", ""},
  9773. {"field2", "longer value for progress tracking test", "", ""},
  9774. {"file1", "file content data for upload progress", "test.txt",
  9775. "text/plain"}};
  9776. auto res = client_call(cli, endpoint, items,
  9777. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9778. progress_values.push_back(current);
  9779. return true;
  9780. });
  9781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9782. EXPECT_EQ(200, res->status);
  9783. EXPECT_FALSE(progress_values.empty());
  9784. }
  9785. TEST(UploadProgressTest, PostMultipartProgress) {
  9786. TestMultipartUploadProgress(
  9787. [](Server &svr) {
  9788. svr.Post("/multipart", [](const Request &req, Response &res) {
  9789. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9790. res.set_content("multipart received", "text/plain");
  9791. });
  9792. },
  9793. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9794. UploadProgress progress_callback) {
  9795. return cli.Post(endpoint, items, progress_callback);
  9796. },
  9797. "/multipart");
  9798. }
  9799. // Helper function for basic download progress tests
  9800. template <typename SetupHandler, typename ClientCall>
  9801. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9802. ClientCall &&client_call, const string &endpoint,
  9803. size_t expected_content_size) {
  9804. Server svr;
  9805. setup_handler(svr);
  9806. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9807. auto se = detail::scope_exit([&] {
  9808. svr.stop();
  9809. t.join();
  9810. });
  9811. svr.wait_until_ready();
  9812. Client cli(HOST, PORT);
  9813. vector<uint64_t> progress_values;
  9814. auto res = client_call(cli, endpoint,
  9815. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9816. progress_values.push_back(current);
  9817. return true;
  9818. });
  9819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9820. EXPECT_EQ(200, res->status);
  9821. EXPECT_FALSE(progress_values.empty());
  9822. EXPECT_EQ(expected_content_size, res->body.size());
  9823. }
  9824. TEST(DownloadProgressTest, GetBasic) {
  9825. TestBasicDownloadProgress(
  9826. [](Server &svr) {
  9827. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9828. string content(1000, 'D');
  9829. res.set_content(content, "text/plain");
  9830. });
  9831. },
  9832. [](Client &cli, const string &endpoint,
  9833. DownloadProgress progress_callback) {
  9834. return cli.Get(endpoint, progress_callback);
  9835. },
  9836. "/download", 1000u);
  9837. }
  9838. // Helper function for content receiver download progress tests
  9839. template <typename SetupHandler, typename ClientCall>
  9840. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9841. ClientCall &&client_call,
  9842. const string &endpoint,
  9843. size_t expected_content_size) {
  9844. Server svr;
  9845. setup_handler(svr);
  9846. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9847. auto se = detail::scope_exit([&] {
  9848. svr.stop();
  9849. t.join();
  9850. });
  9851. svr.wait_until_ready();
  9852. Client cli(HOST, PORT);
  9853. vector<uint64_t> progress_values;
  9854. string received_body;
  9855. auto res = client_call(
  9856. cli, endpoint,
  9857. [&](const char *data, size_t data_length) -> bool {
  9858. received_body.append(data, data_length);
  9859. return true;
  9860. },
  9861. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9862. progress_values.push_back(current);
  9863. return true;
  9864. });
  9865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9866. EXPECT_EQ(200, res->status);
  9867. EXPECT_FALSE(progress_values.empty());
  9868. EXPECT_EQ(expected_content_size, received_body.size());
  9869. EXPECT_TRUE(res->body.empty());
  9870. }
  9871. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9872. TestContentReceiverDownloadProgress(
  9873. [](Server &svr) {
  9874. svr.Get("/download-receiver",
  9875. [](const Request & /*req*/, Response &res) {
  9876. string content(2000, 'R');
  9877. res.set_content(content, "text/plain");
  9878. });
  9879. },
  9880. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9881. DownloadProgress progress_callback) {
  9882. return cli.Get(endpoint, content_receiver, progress_callback);
  9883. },
  9884. "/download-receiver", 2000u);
  9885. }
  9886. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9887. // A provider reaching a pass with nothing to hand over - an empty buffer
  9888. // popped off a queue, say - must not be taken to mean the body is finished.
  9889. // It used to end the loop with the terminating chunk unwritten while the
  9890. // server still considered the response complete, so the peer waited for an
  9891. // end that never arrived.
  9892. Server svr;
  9893. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9894. auto step = std::make_shared<int>(0);
  9895. res.set_chunked_content_provider("text/plain",
  9896. [step](size_t /*offset*/, DataSink &sink) {
  9897. switch ((*step)++) {
  9898. case 0: sink.write("", 0); break;
  9899. case 1: sink.write("hello", 5); break;
  9900. default: sink.done(); break;
  9901. }
  9902. return true;
  9903. });
  9904. });
  9905. auto port = svr.bind_to_any_port(HOST);
  9906. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9907. auto listen_se = detail::scope_exit([&] {
  9908. svr.stop();
  9909. listen_thread.join();
  9910. ASSERT_FALSE(svr.is_running());
  9911. });
  9912. svr.wait_until_ready();
  9913. Client cli(HOST, port);
  9914. // Without the fix the body is never terminated, so bound the wait rather
  9915. // than letting the test hang on the default read timeout.
  9916. cli.set_read_timeout(5, 0);
  9917. auto res = cli.Get("/stream");
  9918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9919. EXPECT_EQ(StatusCode::OK_200, res->status);
  9920. EXPECT_EQ("hello", res->body);
  9921. }
  9922. TEST(StreamingTest, NoContentLengthStreaming) {
  9923. Server svr;
  9924. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9925. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9926. if (offset < 6) {
  9927. sink.os << (offset < 3 ? "a" : "b");
  9928. } else {
  9929. sink.done();
  9930. }
  9931. return true;
  9932. });
  9933. });
  9934. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9935. auto listen_se = detail::scope_exit([&] {
  9936. svr.stop();
  9937. listen_thread.join();
  9938. ASSERT_FALSE(svr.is_running());
  9939. });
  9940. svr.wait_until_ready();
  9941. Client client(HOST, PORT);
  9942. auto get_thread = std::thread([&client]() {
  9943. std::string s;
  9944. auto res =
  9945. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9946. s += std::string(data, len);
  9947. return true;
  9948. });
  9949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9950. EXPECT_EQ(StatusCode::OK_200, res->status);
  9951. EXPECT_EQ("aaabbb", s);
  9952. });
  9953. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9954. // Give GET time to get a few messages.
  9955. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9956. }
  9957. TEST(MountTest, Unmount) {
  9958. Server svr;
  9959. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9960. auto se = detail::scope_exit([&] {
  9961. svr.stop();
  9962. listen_thread.join();
  9963. ASSERT_FALSE(svr.is_running());
  9964. });
  9965. svr.wait_until_ready();
  9966. Client cli("localhost", PORT);
  9967. svr.set_mount_point("/mount2", "./www2");
  9968. auto res = cli.Get("/");
  9969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9970. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9971. res = cli.Get("/mount2/dir/test.html");
  9972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9973. EXPECT_EQ(StatusCode::OK_200, res->status);
  9974. svr.set_mount_point("/", "./www");
  9975. res = cli.Get("/dir/");
  9976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9977. EXPECT_EQ(StatusCode::OK_200, res->status);
  9978. svr.remove_mount_point("/");
  9979. res = cli.Get("/dir/");
  9980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9981. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9982. svr.remove_mount_point("/mount2");
  9983. res = cli.Get("/mount2/dir/test.html");
  9984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9985. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9986. }
  9987. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  9988. Server svr;
  9989. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  9990. svr.Get("/api/hello", [](const Request &, Response &res) {
  9991. res.set_content("api", "text/plain");
  9992. });
  9993. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9994. auto se = detail::scope_exit([&] {
  9995. svr.stop();
  9996. listen_thread.join();
  9997. ASSERT_FALSE(svr.is_running());
  9998. });
  9999. svr.wait_until_ready();
  10000. Client cli(HOST, PORT);
  10001. auto res = cli.Get("/dir/test.html");
  10002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10003. EXPECT_EQ(StatusCode::OK_200, res->status);
  10004. res = cli.Get("/api/hello");
  10005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10006. EXPECT_EQ(StatusCode::OK_200, res->status);
  10007. EXPECT_EQ("api", res->body);
  10008. }
  10009. TEST(MountTest, PathSegmentBoundary) {
  10010. Server svr;
  10011. svr.set_mount_point("/mount2", "./www2");
  10012. svr.set_mount_point("/", "./www");
  10013. auto port = svr.bind_to_any_port(HOST);
  10014. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10015. auto se = detail::scope_exit([&] {
  10016. svr.stop();
  10017. listen_thread.join();
  10018. ASSERT_FALSE(svr.is_running());
  10019. });
  10020. svr.wait_until_ready();
  10021. Client cli(HOST, port);
  10022. auto res = cli.Get("/mount2/dir/test.html");
  10023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10024. EXPECT_EQ(StatusCode::OK_200, res->status);
  10025. // "/mount2" must not match part-way through a path segment.
  10026. res = cli.Get("/mount2dir/test.html");
  10027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10028. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10029. // A mount point ending in '/' keeps matching every path below it.
  10030. res = cli.Get("/dir/test.html");
  10031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10032. EXPECT_EQ(StatusCode::OK_200, res->status);
  10033. }
  10034. TEST(MountTest, Redicect) {
  10035. Server svr;
  10036. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10037. auto se = detail::scope_exit([&] {
  10038. svr.stop();
  10039. listen_thread.join();
  10040. ASSERT_FALSE(svr.is_running());
  10041. });
  10042. svr.set_mount_point("/", "./www");
  10043. svr.wait_until_ready();
  10044. Client cli("localhost", PORT);
  10045. auto res = cli.Get("/dir/");
  10046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10047. EXPECT_EQ(StatusCode::OK_200, res->status);
  10048. res = cli.Get("/dir");
  10049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10050. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10051. res = cli.Get("/file");
  10052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10053. EXPECT_EQ(StatusCode::OK_200, res->status);
  10054. res = cli.Get("/file/");
  10055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10056. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10057. cli.set_follow_location(true);
  10058. res = cli.Get("/dir");
  10059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10060. EXPECT_EQ(StatusCode::OK_200, res->status);
  10061. }
  10062. TEST(MountTest, MultibytesPathName) {
  10063. Server svr;
  10064. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10065. auto se = detail::scope_exit([&] {
  10066. svr.stop();
  10067. listen_thread.join();
  10068. ASSERT_FALSE(svr.is_running());
  10069. });
  10070. svr.set_mount_point("/", "./www");
  10071. svr.wait_until_ready();
  10072. Client cli("localhost", PORT);
  10073. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10075. EXPECT_EQ(StatusCode::OK_200, res->status);
  10076. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10077. }
  10078. #ifdef _WIN32
  10079. // Issue #2435: mmap::open() must succeed even when another handle holds
  10080. // the file open for writing (e.g. an active log file).
  10081. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10082. const char *path = "mmap_concurrent_writer_test.txt";
  10083. const char *content = "hello";
  10084. {
  10085. std::ofstream f(path, std::ios::binary);
  10086. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10087. }
  10088. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10089. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10090. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10091. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10092. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10093. detail::mmap m(path);
  10094. ASSERT_TRUE(m.is_open());
  10095. EXPECT_EQ(strlen(content), m.size());
  10096. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  10097. }
  10098. #endif
  10099. #ifndef _WIN32
  10100. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  10101. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  10102. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  10103. TEST(MmapTest, FailedMappingIsNotOpen) {
  10104. const char *path = "./mmap_failed_mapping_test_dir";
  10105. ASSERT_EQ(0, ::mkdir(path, 0755));
  10106. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10107. detail::mmap m(path);
  10108. EXPECT_FALSE(m.is_open());
  10109. EXPECT_EQ(0U, m.size());
  10110. EXPECT_NE(static_cast<const void *>(m.data()),
  10111. static_cast<const void *>(MAP_FAILED));
  10112. }
  10113. #endif
  10114. TEST(KeepAliveTest, ReadTimeout) {
  10115. Server svr;
  10116. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10117. std::this_thread::sleep_for(std::chrono::seconds(2));
  10118. res.set_content("a", "text/plain");
  10119. });
  10120. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10121. res.set_content("b", "text/plain");
  10122. });
  10123. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10124. auto se = detail::scope_exit([&] {
  10125. svr.stop();
  10126. listen_thread.join();
  10127. ASSERT_FALSE(svr.is_running());
  10128. });
  10129. svr.wait_until_ready();
  10130. Client cli("localhost", PORT);
  10131. cli.set_keep_alive(true);
  10132. cli.set_read_timeout(std::chrono::seconds(1));
  10133. auto resa = cli.Get("/a");
  10134. ASSERT_FALSE(resa);
  10135. EXPECT_EQ(Error::Read, resa.error());
  10136. auto resb = cli.Get("/b");
  10137. ASSERT_TRUE(resb);
  10138. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10139. EXPECT_EQ("b", resb->body);
  10140. }
  10141. TEST(KeepAliveTest, MaxCount) {
  10142. size_t keep_alive_max_count = 3;
  10143. Server svr;
  10144. svr.set_keep_alive_max_count(keep_alive_max_count);
  10145. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10146. res.set_content("Hello World!", "text/plain");
  10147. });
  10148. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10149. auto se = detail::scope_exit([&] {
  10150. svr.stop();
  10151. listen_thread.join();
  10152. ASSERT_FALSE(svr.is_running());
  10153. });
  10154. svr.wait_until_ready();
  10155. Client cli(HOST, PORT);
  10156. cli.set_keep_alive(true);
  10157. for (size_t i = 0; i < 5; i++) {
  10158. auto result = cli.Get("/hi");
  10159. ASSERT_TRUE(result);
  10160. EXPECT_EQ(StatusCode::OK_200, result->status);
  10161. if (i == keep_alive_max_count - 1) {
  10162. EXPECT_EQ("close", result->get_header_value("Connection"));
  10163. } else {
  10164. EXPECT_FALSE(result->has_header("Connection"));
  10165. }
  10166. }
  10167. }
  10168. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10169. // can pull the next one into the server's buffer. The server must serve it
  10170. // without waiting for the socket to become readable again. The keep-alive
  10171. // timeout outlasts the client's read timeout, so a request left waiting for it
  10172. // shows up as a missing response.
  10173. static void serve_pipelining_routes(Server &svr,
  10174. const std::function<void(int)> &client) {
  10175. svr.set_keep_alive_timeout(5);
  10176. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10177. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10178. });
  10179. svr.Post("/echo", [](const Request &req, Response &res) {
  10180. res.set_content("echo " + req.body, "text/plain");
  10181. });
  10182. auto port = svr.bind_to_any_port(HOST);
  10183. thread t = thread([&] { svr.listen_after_bind(); });
  10184. auto se = detail::scope_exit([&] {
  10185. svr.stop();
  10186. t.join();
  10187. });
  10188. svr.wait_until_ready();
  10189. client(port);
  10190. }
  10191. static std::string
  10192. send_pipelined_requests(const std::vector<std::string> &parts) {
  10193. Server svr;
  10194. std::string res;
  10195. serve_pipelining_routes(svr, [&](int port) {
  10196. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10197. });
  10198. return res;
  10199. }
  10200. static void expect_in_order(const std::string &res,
  10201. const std::vector<std::string> &bodies) {
  10202. size_t pos = 0;
  10203. for (const auto &body : bodies) {
  10204. pos = res.find(body, pos);
  10205. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10206. pos += body.size();
  10207. }
  10208. }
  10209. TEST(KeepAliveTest, PipelinedRequests) {
  10210. auto res = send_pipelined_requests(
  10211. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10212. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10213. "Content-Length: 4\r\n\r\nbody"
  10214. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10215. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10216. }
  10217. // The second request starts in the server's buffer and ends on the socket.
  10218. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10219. auto res =
  10220. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10221. "GET /hi/2 HTTP/1.1\r\nHo",
  10222. "st: localhost\r\nConnection: close\r\n\r\n"});
  10223. expect_in_order(res, {"hi 1", "hi 2"});
  10224. }
  10225. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10226. // CRLF after a body does not turn into a 400 for the next request.
  10227. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10228. auto res = send_pipelined_requests(
  10229. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10230. "Content-Length: 4\r\n\r\nbody\r\n"
  10231. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10232. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10233. expect_in_order(res, {"echo body", "hi 2"});
  10234. }
  10235. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10236. // must not be served as the next request.
  10237. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10238. auto res = send_pipelined_requests(
  10239. {"INVALID REQUEST LINE\r\n\r\n"
  10240. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10241. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10242. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10243. }
  10244. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10245. // Over TLS, the next request is held by the TLS library as already decrypted
  10246. // data rather than on the socket.
  10247. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10248. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10249. std::string res;
  10250. serve_pipelining_routes(svr, [&](int port) {
  10251. auto error = Error::Success;
  10252. auto sock = detail::create_client_socket(
  10253. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  10254. /*connection_timeout_sec=*/5, 0,
  10255. /*read_timeout_sec=*/2, 0,
  10256. /*write_timeout_sec=*/5, 0, std::string(), error);
  10257. ASSERT_NE(INVALID_SOCKET, sock);
  10258. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  10259. auto ctx = SSL_CTX_new(TLS_client_method());
  10260. auto ssl = SSL_new(ctx);
  10261. auto ssl_se = detail::scope_exit([&] {
  10262. SSL_free(ssl);
  10263. SSL_CTX_free(ctx);
  10264. });
  10265. SSL_set_fd(ssl, static_cast<int>(sock));
  10266. ASSERT_EQ(1, SSL_connect(ssl));
  10267. // One write, so all three requests arrive in one TLS record
  10268. const std::string req =
  10269. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10270. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10271. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
  10272. ASSERT_EQ(static_cast<int>(req.size()),
  10273. SSL_write(ssl, req.data(), static_cast<int>(req.size())));
  10274. char buf[512];
  10275. int n;
  10276. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  10277. res.append(buf, static_cast<size_t>(n));
  10278. }
  10279. });
  10280. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10281. }
  10282. #endif
  10283. TEST(KeepAliveTest, Issue1041) {
  10284. Server svr;
  10285. svr.set_keep_alive_timeout(3);
  10286. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10287. res.set_content("Hello World!", "text/plain");
  10288. });
  10289. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10290. auto se = detail::scope_exit([&] {
  10291. svr.stop();
  10292. listen_thread.join();
  10293. ASSERT_FALSE(svr.is_running());
  10294. });
  10295. svr.wait_until_ready();
  10296. Client cli(HOST, PORT);
  10297. cli.set_keep_alive(true);
  10298. auto result = cli.Get("/hi");
  10299. ASSERT_TRUE(result);
  10300. EXPECT_EQ(StatusCode::OK_200, result->status);
  10301. std::this_thread::sleep_for(std::chrono::seconds(5));
  10302. result = cli.Get("/hi");
  10303. ASSERT_TRUE(result);
  10304. EXPECT_EQ(StatusCode::OK_200, result->status);
  10305. }
  10306. TEST(KeepAliveTest, Issue1959) {
  10307. Server svr;
  10308. svr.set_keep_alive_timeout(5);
  10309. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10310. res.set_content("a", "text/plain");
  10311. });
  10312. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10313. auto se = detail::scope_exit([&] {
  10314. if (!svr.is_running()) return;
  10315. svr.stop();
  10316. listen_thread.join();
  10317. ASSERT_FALSE(svr.is_running());
  10318. });
  10319. svr.wait_until_ready();
  10320. Client cli("localhost", PORT);
  10321. cli.set_keep_alive(true);
  10322. using namespace std::chrono;
  10323. auto start = steady_clock::now();
  10324. cli.Get("/a");
  10325. svr.stop();
  10326. listen_thread.join();
  10327. auto end = steady_clock::now();
  10328. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10329. EXPECT_LT(elapsed, 5000);
  10330. }
  10331. #ifdef CPPHTTPLIB_SSL_ENABLED
  10332. TEST(KeepAliveTest, SSLClientReconnection) {
  10333. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10334. ASSERT_TRUE(svr.is_valid());
  10335. svr.set_keep_alive_timeout(1);
  10336. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10337. res.set_content("Hello World!", "text/plain");
  10338. });
  10339. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10340. auto se = detail::scope_exit([&] {
  10341. svr.stop();
  10342. listen_thread.join();
  10343. ASSERT_FALSE(svr.is_running());
  10344. });
  10345. svr.wait_until_ready();
  10346. SSLClient cli(HOST, PORT);
  10347. cli.enable_server_certificate_verification(false);
  10348. cli.set_keep_alive(true);
  10349. auto result = cli.Get("/hi");
  10350. ASSERT_TRUE(result);
  10351. EXPECT_EQ(StatusCode::OK_200, result->status);
  10352. result = cli.Get("/hi");
  10353. ASSERT_TRUE(result);
  10354. EXPECT_EQ(StatusCode::OK_200, result->status);
  10355. std::this_thread::sleep_for(std::chrono::seconds(2));
  10356. // Recoonect
  10357. result = cli.Get("/hi");
  10358. ASSERT_TRUE(result);
  10359. EXPECT_EQ(StatusCode::OK_200, result->status);
  10360. result = cli.Get("/hi");
  10361. ASSERT_TRUE(result);
  10362. EXPECT_EQ(StatusCode::OK_200, result->status);
  10363. }
  10364. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10365. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10366. ASSERT_TRUE(svr.is_valid());
  10367. svr.set_keep_alive_timeout(1);
  10368. std::string content = "reconnect";
  10369. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10370. res.set_content("Hello World!", "text/plain");
  10371. });
  10372. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10373. auto se = detail::scope_exit([&] {
  10374. svr.stop();
  10375. listen_thread.join();
  10376. ASSERT_FALSE(svr.is_running());
  10377. });
  10378. svr.wait_until_ready();
  10379. SSLClient cli(HOST, PORT);
  10380. cli.enable_server_certificate_verification(false);
  10381. cli.set_keep_alive(true);
  10382. auto result = cli.Post(
  10383. "/hi", content.size(),
  10384. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10385. sink.write(content.c_str(), content.size());
  10386. return true;
  10387. },
  10388. "text/plain");
  10389. ASSERT_TRUE(result);
  10390. EXPECT_EQ(200, result->status);
  10391. std::this_thread::sleep_for(std::chrono::seconds(2));
  10392. // Recoonect
  10393. result = cli.Post(
  10394. "/hi", content.size(),
  10395. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10396. sink.write(content.c_str(), content.size());
  10397. return true;
  10398. },
  10399. "text/plain");
  10400. ASSERT_TRUE(result);
  10401. EXPECT_EQ(200, result->status);
  10402. result = cli.Post(
  10403. "/hi", content.size(),
  10404. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10405. sink.write(content.c_str(), content.size());
  10406. return true;
  10407. },
  10408. "text/plain");
  10409. ASSERT_TRUE(result);
  10410. EXPECT_EQ(200, result->status);
  10411. }
  10412. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10413. using namespace httplib::tls;
  10414. {
  10415. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10416. ASSERT_TRUE(svr.is_valid());
  10417. svr.Get("/sni", [&](const Request &req, Response &res) {
  10418. std::string expected = req.sni();
  10419. EXPECT_EQ(expected, req.get_param_value("expected"));
  10420. res.set_content("ok", "text/plain");
  10421. });
  10422. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10423. auto se = detail::scope_exit([&] {
  10424. svr.stop();
  10425. listen_thread.join();
  10426. ASSERT_FALSE(svr.is_running());
  10427. });
  10428. svr.wait_until_ready();
  10429. {
  10430. SSLClient cli("localhost", PORT);
  10431. cli.enable_server_certificate_verification(false);
  10432. auto res = cli.Get("/sni?expected=localhost");
  10433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10434. }
  10435. {
  10436. SSLClient cli("::1", PORT);
  10437. cli.enable_server_certificate_verification(false);
  10438. auto res = cli.Get("/sni?expected=");
  10439. // NOTE: This may fail if the server is listening on IPv4 only
  10440. // (e.g., when localhost resolves to 127.0.0.1 only)
  10441. if (res) {
  10442. EXPECT_EQ(StatusCode::OK_200, res->status);
  10443. } else {
  10444. EXPECT_EQ(Error::Connection, res.error());
  10445. }
  10446. }
  10447. }
  10448. }
  10449. #endif
  10450. TEST(ClientProblemDetectionTest, ContentProvider) {
  10451. Server svr;
  10452. size_t content_length = 1024 * 1024;
  10453. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10454. res.set_content_provider(
  10455. content_length, "text/plain",
  10456. [&](size_t offset, size_t length, DataSink &sink) {
  10457. auto out_len = std::min(length, static_cast<size_t>(1024));
  10458. std::string out(out_len, '@');
  10459. sink.write(out.data(), out_len);
  10460. return offset < 4096;
  10461. },
  10462. [](bool success) { ASSERT_FALSE(success); });
  10463. });
  10464. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10465. res.set_content_provider(
  10466. 0, "text/plain",
  10467. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10468. EXPECT_TRUE(false);
  10469. return true;
  10470. },
  10471. [](bool success) { ASSERT_FALSE(success); });
  10472. });
  10473. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10474. auto se = detail::scope_exit([&] {
  10475. svr.stop();
  10476. listen_thread.join();
  10477. ASSERT_FALSE(svr.is_running());
  10478. });
  10479. svr.wait_until_ready();
  10480. Client cli("localhost", PORT);
  10481. {
  10482. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10483. size_t /*data_length*/) { return false; });
  10484. ASSERT_FALSE(res);
  10485. }
  10486. {
  10487. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10488. size_t /*data_length*/) { return false; });
  10489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10490. }
  10491. }
  10492. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10493. // A provider that reports success without writing anything and without
  10494. // calling done() used to be handed the same offset and length again on every
  10495. // pass, so it spun for as long as the peer stayed connected.
  10496. Server svr;
  10497. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10498. res.set_content("ok", "text/plain");
  10499. });
  10500. auto port = svr.bind_to_any_port(HOST);
  10501. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10502. auto se = detail::scope_exit([&] {
  10503. svr.stop();
  10504. listen_thread.join();
  10505. ASSERT_FALSE(svr.is_running());
  10506. });
  10507. svr.wait_until_ready();
  10508. std::atomic<int> call_count{0};
  10509. Client cli(HOST, port);
  10510. auto res = cli.Post(
  10511. "/", 1024,
  10512. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10513. // Give up after enough passes to show the spin, so that losing the
  10514. // check below fails this test instead of hanging it.
  10515. return ++call_count < 100;
  10516. },
  10517. "text/plain");
  10518. ASSERT_FALSE(res);
  10519. EXPECT_EQ(Error::Write, res.error());
  10520. EXPECT_EQ(1, call_count.load());
  10521. }
  10522. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10523. // A writer only has to assign `write`. The other three used to be left as
  10524. // empty std::functions, so a provider calling one threw
  10525. // std::bad_function_call out of the thread running it and took the whole
  10526. // process down.
  10527. DataSink sink;
  10528. std::string written;
  10529. sink.write = [&](const char *data, size_t data_len) {
  10530. written.append(data, data_len);
  10531. return true;
  10532. };
  10533. EXPECT_TRUE(sink.is_writable());
  10534. sink.done();
  10535. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10536. EXPECT_TRUE(written.empty());
  10537. }
  10538. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10539. // A sink that cannot carry trailers still has to finish.
  10540. DataSink sink;
  10541. auto done_count = 0;
  10542. sink.done = [&]() { done_count++; };
  10543. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10544. EXPECT_EQ(1, done_count);
  10545. }
  10546. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10547. Server svr;
  10548. const std::string body(4096, 'x');
  10549. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10550. res.set_content_provider(body.size(), "text/plain",
  10551. [&](size_t offset, size_t length, DataSink &sink) {
  10552. sink.write(body.data() + offset, length);
  10553. sink.done();
  10554. return true;
  10555. });
  10556. });
  10557. auto port = svr.bind_to_any_port(HOST);
  10558. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10559. auto se = detail::scope_exit([&] {
  10560. svr.stop();
  10561. listen_thread.join();
  10562. ASSERT_FALSE(svr.is_running());
  10563. });
  10564. svr.wait_until_ready();
  10565. Client cli(HOST, port);
  10566. auto res = cli.Get("/");
  10567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10568. EXPECT_EQ(StatusCode::OK_200, res->status);
  10569. EXPECT_EQ(body, res->body);
  10570. }
  10571. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10572. Server svr;
  10573. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10574. res.set_content_provider(
  10575. 1024, "text/plain",
  10576. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10577. sink.write("hello", 5);
  10578. sink.done(); // short of the 1024 bytes the response promised
  10579. return true;
  10580. });
  10581. });
  10582. auto port = svr.bind_to_any_port(HOST);
  10583. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10584. auto se = detail::scope_exit([&] {
  10585. svr.stop();
  10586. listen_thread.join();
  10587. ASSERT_FALSE(svr.is_running());
  10588. });
  10589. svr.wait_until_ready();
  10590. Client cli(HOST, port);
  10591. cli.set_read_timeout(5, 0);
  10592. // The response is short of its Content-Length, so the client cannot read a
  10593. // complete body. What matters is that this returns at all: a no-op done()
  10594. // would leave the writer looping over a provider that never makes progress.
  10595. auto res = cli.Get("/");
  10596. EXPECT_FALSE(res);
  10597. }
  10598. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10599. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10600. // The compressed path builds the whole body before connecting, so this
  10601. // fails client-side and never reaches a server.
  10602. Client cli(HOST, PORT);
  10603. cli.set_compress(true);
  10604. auto res = cli.Post(
  10605. "/", 1024,
  10606. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10607. sink.write("hello", 5);
  10608. sink.done(); // short of the 1024 bytes the request announced
  10609. return true;
  10610. },
  10611. "text/plain");
  10612. ASSERT_FALSE(res);
  10613. EXPECT_EQ(Error::Write, res.error());
  10614. }
  10615. #endif
  10616. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  10617. Server svr;
  10618. svr.set_error_handler([](Request const &, Response &res) -> void {
  10619. res.set_chunked_content_provider(
  10620. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10621. sink.os << "hello";
  10622. sink.os << "world";
  10623. sink.done();
  10624. return true;
  10625. });
  10626. });
  10627. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10628. auto se = detail::scope_exit([&] {
  10629. svr.stop();
  10630. listen_thread.join();
  10631. ASSERT_FALSE(svr.is_running());
  10632. });
  10633. svr.wait_until_ready();
  10634. Client cli("localhost", PORT);
  10635. auto res = cli.Get("/");
  10636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10637. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10638. EXPECT_EQ("helloworld", res->body);
  10639. }
  10640. // A body set after a content provider must replace it, not be sent through it.
  10641. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  10642. Server svr;
  10643. svr.set_mount_point("/", "./www");
  10644. svr.set_file_request_handler([](const Request &req, Response &res) {
  10645. if (req.path == "/dir/test.html") {
  10646. res.status = StatusCode::Forbidden_403;
  10647. res.set_content(std::string(5000, 'D'), "text/plain");
  10648. } else if (req.path == "/file") {
  10649. res.status = StatusCode::Forbidden_403;
  10650. res.body = "Denied";
  10651. }
  10652. });
  10653. auto port = svr.bind_to_any_port(HOST);
  10654. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10655. auto se = detail::scope_exit([&] {
  10656. svr.stop();
  10657. t.join();
  10658. ASSERT_FALSE(svr.is_running());
  10659. });
  10660. svr.wait_until_ready();
  10661. Client cli(HOST, port);
  10662. {
  10663. auto res = cli.Get("/dir/test.html");
  10664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10665. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10666. EXPECT_EQ(std::string(5000, 'D'), res->body);
  10667. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  10668. }
  10669. {
  10670. auto res = cli.Get("/file");
  10671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10672. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10673. EXPECT_EQ("Denied", res->body);
  10674. }
  10675. {
  10676. auto res = cli.Get("/dir/index.html");
  10677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10678. EXPECT_EQ(StatusCode::OK_200, res->status);
  10679. EXPECT_EQ(0U, res->body.find("<html>"));
  10680. }
  10681. }
  10682. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  10683. Server svr;
  10684. std::vector<bool> released;
  10685. std::mutex released_mutex;
  10686. auto releaser = [&](bool success) {
  10687. std::lock_guard<std::mutex> guard(released_mutex);
  10688. released.push_back(success);
  10689. };
  10690. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  10691. return sink.write(&"hello"[offset], length);
  10692. };
  10693. svr.Get("/sized", [&](const Request &, Response &res) {
  10694. res.status = StatusCode::NotFound_404;
  10695. res.set_content_provider(5, "text/plain", provider, releaser);
  10696. });
  10697. svr.Get("/chunked", [&](const Request &, Response &res) {
  10698. res.status = StatusCode::ServiceUnavailable_503;
  10699. res.set_chunked_content_provider(
  10700. "text/plain",
  10701. [](size_t, DataSink &sink) {
  10702. sink.os << "chunk";
  10703. sink.done();
  10704. return true;
  10705. },
  10706. releaser);
  10707. });
  10708. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  10709. res.set_content_provider(5, "text/plain", provider, releaser);
  10710. throw std::runtime_error("after the provider");
  10711. });
  10712. svr.set_error_handler([](const Request &req, Response &res) {
  10713. // Leave the exception handler's content to it.
  10714. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  10715. res.set_content(std::string(1000, 'E'), "text/html");
  10716. return Server::HandlerResponse::Handled;
  10717. });
  10718. svr.set_exception_handler(
  10719. [](const Request &, Response &res, std::exception_ptr) {
  10720. res.status = StatusCode::InternalServerError_500;
  10721. res.set_content(std::string(1000, 'X'), "text/html");
  10722. });
  10723. auto port = svr.bind_to_any_port(HOST);
  10724. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10725. auto se = detail::scope_exit([&] {
  10726. svr.stop();
  10727. t.join();
  10728. ASSERT_FALSE(svr.is_running());
  10729. });
  10730. svr.wait_until_ready();
  10731. Client cli(HOST, port);
  10732. {
  10733. auto res = cli.Get("/sized");
  10734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10735. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10736. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10737. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  10738. }
  10739. {
  10740. auto res = cli.Get("/chunked");
  10741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10742. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  10743. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10744. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  10745. }
  10746. {
  10747. auto res = cli.Get("/throw");
  10748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10749. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  10750. EXPECT_EQ(std::string(1000, 'X'), res->body);
  10751. }
  10752. std::lock_guard<std::mutex> guard(released_mutex);
  10753. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  10754. }
  10755. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  10756. Server svr;
  10757. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  10758. return sink.write(&"abc"[offset], length);
  10759. };
  10760. svr.Get("/file-then-body", [](const Request &, Response &res) {
  10761. res.set_file_content("./www/dir/test.html");
  10762. res.set_content("body", "text/plain");
  10763. });
  10764. svr.Get("/body-then-file", [](const Request &, Response &res) {
  10765. res.set_content(std::string(100, 'B'), "text/plain");
  10766. res.set_file_content("./www/dir/test.html");
  10767. });
  10768. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  10769. res.set_content(std::string(100, 'B'), "text/plain");
  10770. res.set_content_provider(3, "text/plain", abc);
  10771. });
  10772. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  10773. res.set_content_provider(3, "text/plain", abc);
  10774. res.set_content(std::string(100, 'B'), "text/plain");
  10775. });
  10776. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  10777. res.set_content_provider(3, "text/plain", abc);
  10778. res.body = "direct";
  10779. });
  10780. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  10781. res.set_file_content("./www/dir/test.html");
  10782. res.body = "direct";
  10783. });
  10784. auto port = svr.bind_to_any_port(HOST);
  10785. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10786. auto se = detail::scope_exit([&] {
  10787. svr.stop();
  10788. t.join();
  10789. ASSERT_FALSE(svr.is_running());
  10790. });
  10791. svr.wait_until_ready();
  10792. Client cli(HOST, port);
  10793. auto expect_body = [&](const char *path, const std::string &body) {
  10794. // Uncompressed, so Content-Length can be compared with the body.
  10795. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  10796. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  10797. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10798. EXPECT_EQ(body, res->body) << path;
  10799. EXPECT_EQ(std::to_string(body.size()),
  10800. res->get_header_value("Content-Length"))
  10801. << path;
  10802. };
  10803. expect_body("/file-then-body", "body");
  10804. expect_body("/body-then-file", "test.html");
  10805. expect_body("/body-then-provider", "abc");
  10806. expect_body("/provider-then-body", std::string(100, 'B'));
  10807. expect_body("/provider-then-direct-body", "direct");
  10808. expect_body("/file-then-direct-body", "direct");
  10809. // Ranges are checked against the body, not the dropped provider.
  10810. {
  10811. auto res = cli.Get("/provider-then-direct-body",
  10812. Headers{{make_range_header({{1, 2}})}});
  10813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10814. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10815. EXPECT_EQ("ir", res->body);
  10816. }
  10817. {
  10818. auto res = cli.Get("/file-then-direct-body",
  10819. Headers{{make_range_header({{7, 8}})}});
  10820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10821. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  10822. }
  10823. }
  10824. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  10825. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  10826. const char *path = "./truncated_while_served.txt";
  10827. const size_t size = 32 * 1024 * 1024;
  10828. {
  10829. std::ofstream f(path, std::ios::binary);
  10830. f << std::string(size, 'x');
  10831. }
  10832. auto se_file = detail::scope_exit([&] { std::remove(path); });
  10833. // Over TLS, where the bytes are encrypted in this process rather than
  10834. // copied by send().
  10835. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10836. svr.Get("/file", [&](const Request &, Response &res) {
  10837. res.set_file_content(path, "text/plain");
  10838. });
  10839. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10840. auto se = detail::scope_exit([&] {
  10841. svr.stop();
  10842. thread.join();
  10843. ASSERT_FALSE(svr.is_running());
  10844. });
  10845. svr.wait_until_ready();
  10846. // The file shrinks once the first bytes are in, as a rewrite in place
  10847. // would, and reading the mapping past its new end used to raise SIGBUS.
  10848. SSLClient cli(HOST, PORT);
  10849. cli.enable_server_certificate_verification(false);
  10850. size_t received = 0;
  10851. auto res = cli.Get("/file", [&](const char *, size_t len) {
  10852. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  10853. received += len;
  10854. return true;
  10855. });
  10856. EXPECT_FALSE(res);
  10857. EXPECT_LT(received, size);
  10858. }
  10859. #endif
  10860. // Forward declaration (see the base64_encode note).
  10861. namespace httplib {
  10862. namespace detail {
  10863. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  10864. const std::string &content_type,
  10865. EncodingType encoding);
  10866. } // namespace detail
  10867. } // namespace httplib
  10868. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  10869. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  10870. ASSERT_TRUE(mm->is_open());
  10871. Response res;
  10872. detail::set_file_content_provider(res, mm, "text/html",
  10873. detail::EncodingType::None);
  10874. std::string out;
  10875. DataSink sink;
  10876. sink.write = [&](const char *d, size_t l) {
  10877. out.append(d, l);
  10878. return true;
  10879. };
  10880. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  10881. EXPECT_EQ("test.html", out);
  10882. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  10883. EXPECT_EQ("test.html", out);
  10884. }
  10885. TEST(LongPollingTest, ClientCloseDetection) {
  10886. Server svr;
  10887. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10888. res.set_chunked_content_provider(
  10889. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10890. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10891. sink.os << "hello";
  10892. auto count = 10;
  10893. while (count > 0 && sink.is_writable()) {
  10894. this_thread::sleep_for(chrono::milliseconds(10));
  10895. count--;
  10896. }
  10897. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  10898. return true;
  10899. });
  10900. });
  10901. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10902. auto se = detail::scope_exit([&] {
  10903. svr.stop();
  10904. listen_thread.join();
  10905. ASSERT_FALSE(svr.is_running());
  10906. });
  10907. svr.wait_until_ready();
  10908. Client cli("localhost", PORT);
  10909. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10910. EXPECT_EQ("hello", string(data, data_length));
  10911. return false; // close the socket immediately.
  10912. });
  10913. ASSERT_FALSE(res);
  10914. }
  10915. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  10916. Server svr;
  10917. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10918. res.set_chunked_content_provider(
  10919. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10920. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10921. sink.os << "hello";
  10922. EXPECT_TRUE(sink.os.good());
  10923. // Wait for the client to close the connection
  10924. auto count = 10;
  10925. while (count > 0 && sink.is_writable()) {
  10926. this_thread::sleep_for(chrono::milliseconds(10));
  10927. count--;
  10928. }
  10929. // After client disconnect, write repeatedly until the socket
  10930. // write actually fails (small writes may be absorbed by the
  10931. // kernel buffer)
  10932. std::string chunk(1024, 'x');
  10933. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  10934. sink.os << chunk;
  10935. }
  10936. EXPECT_TRUE(sink.os.fail());
  10937. return true;
  10938. });
  10939. });
  10940. auto port = svr.bind_to_any_port("localhost");
  10941. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10942. auto se = detail::scope_exit([&] {
  10943. svr.stop();
  10944. listen_thread.join();
  10945. ASSERT_FALSE(svr.is_running());
  10946. });
  10947. svr.wait_until_ready();
  10948. Client cli("localhost", port);
  10949. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10950. EXPECT_EQ("hello", string(data, data_length));
  10951. return false; // close the socket immediately.
  10952. });
  10953. ASSERT_FALSE(res);
  10954. }
  10955. TEST(GetWithParametersTest, GetWithParameters) {
  10956. Server svr;
  10957. svr.Get("/", [&](const Request &req, Response &) {
  10958. EXPECT_EQ("world", req.get_param_value("hello"));
  10959. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10960. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10961. });
  10962. svr.Get("/params", [&](const Request &req, Response &) {
  10963. EXPECT_EQ("world", req.get_param_value("hello"));
  10964. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10965. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10966. });
  10967. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10968. EXPECT_EQ("resource-id", req.matches[1]);
  10969. EXPECT_EQ("foo", req.get_param_value("param1"));
  10970. EXPECT_EQ("bar", req.get_param_value("param2"));
  10971. });
  10972. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10973. EXPECT_EQ("user-id", req.path_params.at("id"));
  10974. EXPECT_EQ("foo", req.get_param_value("param1"));
  10975. EXPECT_EQ("bar", req.get_param_value("param2"));
  10976. });
  10977. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10978. auto se = detail::scope_exit([&] {
  10979. svr.stop();
  10980. listen_thread.join();
  10981. ASSERT_FALSE(svr.is_running());
  10982. });
  10983. svr.wait_until_ready();
  10984. {
  10985. Client cli(HOST, PORT);
  10986. Params params;
  10987. params.emplace("hello", "world");
  10988. params.emplace("hello2", "world2");
  10989. params.emplace("hello3", "world3");
  10990. auto res = cli.Get("/", params, Headers{});
  10991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10992. EXPECT_EQ(StatusCode::OK_200, res->status);
  10993. }
  10994. {
  10995. Client cli(HOST, PORT);
  10996. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10998. EXPECT_EQ(StatusCode::OK_200, res->status);
  10999. }
  11000. {
  11001. Client cli(HOST, PORT);
  11002. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11004. EXPECT_EQ(StatusCode::OK_200, res->status);
  11005. }
  11006. {
  11007. Client cli(HOST, PORT);
  11008. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11010. EXPECT_EQ(StatusCode::OK_200, res->status);
  11011. }
  11012. }
  11013. TEST(GetWithParametersTest, GetWithParameters2) {
  11014. Server svr;
  11015. svr.Get("/", [&](const Request &req, Response &res) {
  11016. auto text = req.get_param_value("hello");
  11017. res.set_content(text, "text/plain");
  11018. });
  11019. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11020. auto se = detail::scope_exit([&] {
  11021. svr.stop();
  11022. listen_thread.join();
  11023. ASSERT_FALSE(svr.is_running());
  11024. });
  11025. svr.wait_until_ready();
  11026. Client cli("localhost", PORT);
  11027. Params params;
  11028. params.emplace("hello", "world");
  11029. std::string body;
  11030. auto res = cli.Get("/", params, Headers{},
  11031. [&](const char *data, size_t data_length) {
  11032. body.append(data, data_length);
  11033. return true;
  11034. });
  11035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11036. EXPECT_EQ(StatusCode::OK_200, res->status);
  11037. EXPECT_EQ("world", body);
  11038. }
  11039. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11040. Server svr;
  11041. svr.Get("/search", [&](const Request &req, Response &res) {
  11042. auto q = req.get_param_value("q");
  11043. res.set_content(q, "text/plain");
  11044. });
  11045. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11046. auto se = detail::scope_exit([&] {
  11047. svr.stop();
  11048. listen_thread.join();
  11049. ASSERT_FALSE(svr.is_running());
  11050. });
  11051. svr.wait_until_ready();
  11052. Client cli("localhost", PORT);
  11053. // Verify that Get(path, params) works without requiring Headers argument
  11054. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11056. EXPECT_EQ(StatusCode::OK_200, res->status);
  11057. EXPECT_EQ("cpp-httplib", res->body);
  11058. }
  11059. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11060. auto host = "httpbingo.org";
  11061. auto path = std::string{"/range/32"};
  11062. #ifdef CPPHTTPLIB_SSL_ENABLED
  11063. SSLClient cli(host);
  11064. #else
  11065. Client cli(host);
  11066. #endif
  11067. cli.set_default_headers({make_range_header({{1, 10}})});
  11068. cli.set_connection_timeout(5);
  11069. {
  11070. auto res = cli.Get(path);
  11071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11072. EXPECT_EQ("bcdefghijk", res->body);
  11073. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11074. }
  11075. {
  11076. auto res = cli.Get(path);
  11077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11078. EXPECT_EQ("bcdefghijk", res->body);
  11079. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11080. }
  11081. }
  11082. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11083. Server svr;
  11084. svr.set_default_headers({{"Hello", "World"}});
  11085. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11086. res.set_content("ok", "text/plain");
  11087. });
  11088. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11089. auto se = detail::scope_exit([&] {
  11090. svr.stop();
  11091. listen_thread.join();
  11092. ASSERT_FALSE(svr.is_running());
  11093. });
  11094. svr.wait_until_ready();
  11095. Client cli("localhost", PORT);
  11096. auto res = cli.Get("/");
  11097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11098. EXPECT_EQ(StatusCode::OK_200, res->status);
  11099. EXPECT_EQ("ok", res->body);
  11100. EXPECT_EQ("World", res->get_header_value("Hello"));
  11101. }
  11102. #ifdef CPPHTTPLIB_SSL_ENABLED
  11103. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11104. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11105. ASSERT_TRUE(svr.is_valid());
  11106. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11107. std::this_thread::sleep_for(std::chrono::seconds(2));
  11108. res.set_content("a", "text/plain");
  11109. });
  11110. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11111. res.set_content("b", "text/plain");
  11112. });
  11113. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11114. auto se = detail::scope_exit([&] {
  11115. svr.stop();
  11116. listen_thread.join();
  11117. ASSERT_FALSE(svr.is_running());
  11118. });
  11119. svr.wait_until_ready();
  11120. SSLClient cli("localhost", PORT);
  11121. cli.enable_server_certificate_verification(false);
  11122. cli.set_keep_alive(true);
  11123. cli.set_read_timeout(std::chrono::seconds(1));
  11124. auto resa = cli.Get("/a");
  11125. ASSERT_TRUE(!resa);
  11126. EXPECT_EQ(Error::Read, resa.error());
  11127. auto resb = cli.Get("/b");
  11128. ASSERT_TRUE(resb);
  11129. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11130. EXPECT_EQ("b", resb->body);
  11131. }
  11132. // Closing an idle keep-alive connection sends close_notify and returns. The
  11133. // server must not wait for the client's close_notify: an idle client never
  11134. // sends one, so the worker would be held until the read timeout expires, and
  11135. // stop() would wait for it.
  11136. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11137. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11138. ASSERT_TRUE(svr.is_valid());
  11139. svr.set_keep_alive_timeout(1);
  11140. svr.set_read_timeout(10, 0);
  11141. svr.Get("/", [](const Request &, Response &res) {
  11142. res.set_content("ok", "text/plain");
  11143. });
  11144. auto port = svr.bind_to_any_port(HOST);
  11145. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11146. auto se = detail::scope_exit([&] {
  11147. if (listen_thread.joinable()) {
  11148. svr.stop();
  11149. listen_thread.join();
  11150. }
  11151. });
  11152. svr.wait_until_ready();
  11153. SSLClient cli(HOST, port);
  11154. cli.enable_server_certificate_verification(false);
  11155. cli.set_keep_alive(true);
  11156. auto res = cli.Get("/");
  11157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11158. EXPECT_EQ(StatusCode::OK_200, res->status);
  11159. // Stay idle past the keep-alive timeout so the server closes the connection.
  11160. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11161. auto start = std::chrono::steady_clock::now();
  11162. svr.stop();
  11163. listen_thread.join();
  11164. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11165. std::chrono::steady_clock::now() - start)
  11166. .count();
  11167. EXPECT_LT(elapsed, 3000);
  11168. }
  11169. #endif
  11170. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11171. protected:
  11172. ServerTestWithAI_PASSIVE()
  11173. : cli_(HOST, PORT)
  11174. #ifdef CPPHTTPLIB_SSL_ENABLED
  11175. ,
  11176. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11177. #endif
  11178. {
  11179. #ifdef CPPHTTPLIB_SSL_ENABLED
  11180. cli_.enable_server_certificate_verification(false);
  11181. #endif
  11182. }
  11183. virtual void SetUp() {
  11184. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11185. res.set_content("Hello World!", "text/plain");
  11186. });
  11187. t_ = thread(
  11188. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11189. svr_.wait_until_ready();
  11190. }
  11191. virtual void TearDown() {
  11192. svr_.stop();
  11193. t_.join();
  11194. }
  11195. #ifdef CPPHTTPLIB_SSL_ENABLED
  11196. SSLClient cli_;
  11197. SSLServer svr_;
  11198. #else
  11199. Client cli_;
  11200. Server svr_;
  11201. #endif
  11202. thread t_;
  11203. };
  11204. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11205. auto res = cli_.Get("/hi");
  11206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11207. EXPECT_EQ(StatusCode::OK_200, res->status);
  11208. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11209. EXPECT_EQ("Hello World!", res->body);
  11210. }
  11211. class ServerUpDownTest : public ::testing::Test {
  11212. protected:
  11213. ServerUpDownTest() : cli_(HOST, PORT) {}
  11214. virtual void SetUp() {
  11215. t_ = thread([&]() {
  11216. svr_.bind_to_any_port(HOST);
  11217. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11218. ASSERT_TRUE(svr_.listen_after_bind());
  11219. });
  11220. svr_.wait_until_ready();
  11221. }
  11222. virtual void TearDown() {
  11223. svr_.stop();
  11224. t_.join();
  11225. }
  11226. Client cli_;
  11227. Server svr_;
  11228. thread t_;
  11229. };
  11230. TEST_F(ServerUpDownTest, QuickStartStop) {
  11231. // Should not crash, especially when run with
  11232. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11233. }
  11234. class PayloadMaxLengthTest : public ::testing::Test {
  11235. protected:
  11236. PayloadMaxLengthTest()
  11237. : cli_(HOST, PORT)
  11238. #ifdef CPPHTTPLIB_SSL_ENABLED
  11239. ,
  11240. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11241. #endif
  11242. {
  11243. #ifdef CPPHTTPLIB_SSL_ENABLED
  11244. cli_.enable_server_certificate_verification(false);
  11245. #endif
  11246. }
  11247. virtual void SetUp() {
  11248. svr_.set_payload_max_length(8);
  11249. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11250. res.set_content("test", "text/plain");
  11251. });
  11252. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11253. svr_.wait_until_ready();
  11254. }
  11255. virtual void TearDown() {
  11256. svr_.stop();
  11257. t_.join();
  11258. }
  11259. #ifdef CPPHTTPLIB_SSL_ENABLED
  11260. SSLClient cli_;
  11261. SSLServer svr_;
  11262. #else
  11263. Client cli_;
  11264. Server svr_;
  11265. #endif
  11266. thread t_;
  11267. };
  11268. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11269. auto res = cli_.Post("/test", "123456789", "text/plain");
  11270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11271. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11272. res = cli_.Post("/test", "12345678", "text/plain");
  11273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11274. EXPECT_EQ(StatusCode::OK_200, res->status);
  11275. }
  11276. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11277. // Test chunked encoding with payload exceeding the 8-byte limit
  11278. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11279. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11281. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11282. }
  11283. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11284. // Test chunked encoding with payload within the 8-byte limit
  11285. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11286. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11288. EXPECT_EQ(StatusCode::OK_200, res->status);
  11289. }
  11290. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11291. // Test using send_request to send chunked data exceeding payload limit
  11292. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11293. "Host: " +
  11294. std::string(HOST) + ":" + std::to_string(PORT) +
  11295. "\r\n"
  11296. "Transfer-Encoding: chunked\r\n"
  11297. "Connection: close\r\n"
  11298. "\r\n"
  11299. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  11300. "0123456789\r\n"
  11301. "0\r\n" // End chunk
  11302. "\r\n";
  11303. std::string response;
  11304. bool result = send_request(1, chunked_request, &response);
  11305. if (!result) {
  11306. // If send_request fails, it might be because the server closed the
  11307. // connection due to payload limit enforcement, which is acceptable
  11308. SUCCEED()
  11309. << "Server rejected oversized chunked request (connection closed)";
  11310. } else {
  11311. // If we got a response, check if it's an error response or connection was
  11312. // closed early Short response length indicates connection was closed due to
  11313. // payload limit
  11314. if (response.length() <= 10) {
  11315. SUCCEED() << "Server closed connection for oversized chunked request";
  11316. } else {
  11317. // Check for error status codes
  11318. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11319. response.find("Payload Too Large") != std::string::npos ||
  11320. response.find("400") != std::string::npos);
  11321. }
  11322. }
  11323. }
  11324. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  11325. // Test request without Content-Length header exceeding payload limit
  11326. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11327. "Host: " +
  11328. std::string(HOST) + ":" +
  11329. std::to_string(PORT) +
  11330. "\r\n"
  11331. "Connection: close\r\n"
  11332. "\r\n";
  11333. // Add payload exceeding the 8-byte limit
  11334. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  11335. request_without_content_length += large_payload;
  11336. std::string response;
  11337. bool result = send_request(1, request_without_content_length, &response);
  11338. if (!result) {
  11339. // If send_request fails, server likely closed connection due to payload
  11340. // limit
  11341. SUCCEED() << "Server rejected oversized request without Content-Length "
  11342. "(connection closed)";
  11343. } else {
  11344. // Check if server responded with error or closed connection early
  11345. if (response.length() <= 10) {
  11346. SUCCEED() << "Server closed connection for oversized request without "
  11347. "Content-Length";
  11348. } else {
  11349. // Check for error status codes
  11350. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11351. response.find("Payload Too Large") != std::string::npos ||
  11352. response.find("400") != std::string::npos);
  11353. }
  11354. }
  11355. }
  11356. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  11357. // Test request without Content-Length header within payload limit
  11358. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11359. "Host: " +
  11360. std::string(HOST) + ":" +
  11361. std::to_string(PORT) +
  11362. "\r\n"
  11363. "Connection: close\r\n"
  11364. "\r\n";
  11365. // Add payload within the 8-byte limit
  11366. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  11367. request_without_content_length += small_payload;
  11368. std::string response;
  11369. bool result = send_request(1, request_without_content_length, &response);
  11370. // For requests without Content-Length, the server may have different behavior
  11371. // The key is that it should not reject due to payload limit for small
  11372. // payloads
  11373. if (result) {
  11374. // Check for any HTTP response (success or error, but not connection closed)
  11375. if (response.length() > 10) {
  11376. SUCCEED()
  11377. << "Server processed request without Content-Length within limit";
  11378. } else {
  11379. // Short response might indicate connection closed, which is acceptable
  11380. SUCCEED() << "Server closed connection for request without "
  11381. "Content-Length (acceptable behavior)";
  11382. }
  11383. } else {
  11384. // Connection failure might be due to protocol requirements
  11385. SUCCEED() << "Connection issue with request without Content-Length "
  11386. "(environment-specific)";
  11387. }
  11388. }
  11389. class LargePayloadMaxLengthTest : public ::testing::Test {
  11390. protected:
  11391. LargePayloadMaxLengthTest()
  11392. : cli_(HOST, PORT)
  11393. #ifdef CPPHTTPLIB_SSL_ENABLED
  11394. ,
  11395. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11396. #endif
  11397. {
  11398. #ifdef CPPHTTPLIB_SSL_ENABLED
  11399. cli_.enable_server_certificate_verification(false);
  11400. #endif
  11401. }
  11402. virtual void SetUp() {
  11403. // Set 10MB payload limit
  11404. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  11405. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  11406. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11407. res.set_content("Large payload test", "text/plain");
  11408. });
  11409. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11410. svr_.wait_until_ready();
  11411. }
  11412. virtual void TearDown() {
  11413. svr_.stop();
  11414. t_.join();
  11415. }
  11416. #ifdef CPPHTTPLIB_SSL_ENABLED
  11417. SSLClient cli_;
  11418. SSLServer svr_;
  11419. #else
  11420. Client cli_;
  11421. Server svr_;
  11422. #endif
  11423. thread t_;
  11424. };
  11425. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  11426. // Test chunked encoding with payload within 10MB limit
  11427. std::string medium_payload(5 * 1024 * 1024,
  11428. 'A'); // 5MB payload, within 10MB limit
  11429. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  11430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11431. EXPECT_EQ(StatusCode::OK_200, res->status);
  11432. }
  11433. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  11434. // Test chunked encoding with payload exceeding 10MB limit
  11435. std::string large_payload(12 * 1024 * 1024,
  11436. 'B'); // 12MB payload, exceeds 10MB limit
  11437. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  11438. // Server may either return 413 or close the connection
  11439. if (res) {
  11440. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11441. } else {
  11442. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  11443. }
  11444. }
  11445. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  11446. // Test request without Content-Length header within 10MB limit
  11447. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11448. "Host: " +
  11449. std::string(HOST) + ":" +
  11450. std::to_string(PORT) +
  11451. "\r\n"
  11452. "Connection: close\r\n"
  11453. "\r\n";
  11454. // Add 1MB payload (within 10MB limit)
  11455. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  11456. request_without_content_length += medium_payload;
  11457. std::string response;
  11458. bool result = send_request(5, request_without_content_length, &response);
  11459. if (result) {
  11460. // Should get a proper HTTP response for payloads within limit
  11461. if (response.length() > 10) {
  11462. SUCCEED() << "Server processed 1MB request without Content-Length within "
  11463. "10MB limit";
  11464. } else {
  11465. SUCCEED() << "Server closed connection (acceptable behavior for no "
  11466. "Content-Length)";
  11467. }
  11468. } else {
  11469. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  11470. }
  11471. }
  11472. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  11473. // Test request without Content-Length header exceeding 10MB limit
  11474. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11475. "Host: " +
  11476. std::string(HOST) + ":" +
  11477. std::to_string(PORT) +
  11478. "\r\n"
  11479. "Connection: close\r\n"
  11480. "\r\n";
  11481. // Add 12MB payload (exceeds 10MB limit)
  11482. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  11483. request_without_content_length += large_payload;
  11484. std::string response;
  11485. bool result = send_request(10, request_without_content_length, &response);
  11486. if (!result) {
  11487. // Server should close connection due to payload limit
  11488. SUCCEED() << "Server rejected 12MB request without Content-Length "
  11489. "(connection closed)";
  11490. } else {
  11491. // Check for error response
  11492. if (response.length() <= 10) {
  11493. SUCCEED()
  11494. << "Server closed connection for 12MB request exceeding 10MB limit";
  11495. } else {
  11496. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11497. response.find("Payload Too Large") != std::string::npos ||
  11498. response.find("400") != std::string::npos);
  11499. }
  11500. }
  11501. }
  11502. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  11503. Server svr;
  11504. svr.Get("/", [](const Request &, Response &res) {
  11505. // Claims far more than it sends, then drops the connection.
  11506. res.set_content_provider(size_t(1) << 41, "text/plain",
  11507. [](size_t, size_t, DataSink &sink) {
  11508. sink.write("abc", 3);
  11509. return false;
  11510. });
  11511. });
  11512. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11513. auto se = detail::scope_exit([&] {
  11514. svr.stop();
  11515. thread.join();
  11516. ASSERT_FALSE(svr.is_running());
  11517. });
  11518. svr.wait_until_ready();
  11519. Client cli(HOST, PORT);
  11520. cli.set_payload_max_length(0);
  11521. EXPECT_FALSE(cli.Get("/"));
  11522. }
  11523. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11524. // `payload_max_length` is not enforced on decompressed body in ContentReader
  11525. // path.
  11526. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  11527. Server svr;
  11528. const size_t LIMIT = 64 * 1024; // 64KB
  11529. svr.set_payload_max_length(LIMIT);
  11530. size_t total = 0;
  11531. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11532. const ContentReader &content_reader) {
  11533. content_reader([&](const char * /*data*/, size_t len) {
  11534. total += len;
  11535. return true;
  11536. });
  11537. res.status = 200;
  11538. res.set_content("stream_ok", "text/plain");
  11539. });
  11540. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11541. auto se = detail::scope_exit([&] {
  11542. svr.stop();
  11543. thread.join();
  11544. ASSERT_FALSE(svr.is_running());
  11545. });
  11546. svr.wait_until_ready();
  11547. // Prepare 256KB raw data and gzip-compress it
  11548. std::string raw(256 * 1024, 'A');
  11549. std::string gz;
  11550. {
  11551. z_stream zs{};
  11552. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  11553. Z_DEFAULT_STRATEGY);
  11554. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  11555. zs.avail_in = static_cast<uInt>(raw.size());
  11556. char outbuf[4096];
  11557. int ret;
  11558. do {
  11559. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  11560. zs.avail_out = sizeof(outbuf);
  11561. ret = deflate(&zs, Z_FINISH);
  11562. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  11563. } while (ret != Z_STREAM_END);
  11564. deflateEnd(&zs);
  11565. }
  11566. Client cli(HOST, PORT);
  11567. cli.set_connection_timeout(std::chrono::seconds(5));
  11568. Headers headers = {{"Content-Encoding", "gzip"}};
  11569. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  11570. "application/octet-stream");
  11571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11572. // Server must reject oversized decompressed payloads with 413.
  11573. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11574. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11575. EXPECT_LE(total, LIMIT);
  11576. }
  11577. #ifndef CPPHTTPLIB_SSL_ENABLED
  11578. // For a request with neither Content-Length nor Transfer-Encoding, the
  11579. // non-SSL raw-socket fallback in read_content_core() used to hand the
  11580. // compressed wire bytes straight to the ContentReader without ever routing
  11581. // them through the decompressor, so payload_max_length_ only bounded the
  11582. // compressed size on the wire, not the decompressed size.
  11583. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  11584. Server svr;
  11585. const size_t LIMIT = 64 * 1024; // 64KB
  11586. svr.set_payload_max_length(LIMIT);
  11587. size_t total = 0;
  11588. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11589. const ContentReader &content_reader) {
  11590. content_reader([&](const char * /*data*/, size_t len) {
  11591. total += len;
  11592. return true;
  11593. });
  11594. res.status = 200;
  11595. res.set_content("stream_ok", "text/plain");
  11596. });
  11597. auto port = svr.bind_to_any_port(HOST);
  11598. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11599. auto se = detail::scope_exit([&] {
  11600. svr.stop();
  11601. thread.join();
  11602. ASSERT_FALSE(svr.is_running());
  11603. });
  11604. svr.wait_until_ready();
  11605. // Prepare 256KB raw data and gzip-compress it, same payload as the
  11606. // StreamingGzipDecompression test above.
  11607. std::string raw(256 * 1024, 'A');
  11608. std::string gz;
  11609. {
  11610. httplib::detail::gzip_compressor compressor;
  11611. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  11612. [&](const char *chunk, size_t len) {
  11613. gz.append(chunk, len);
  11614. return true;
  11615. });
  11616. ASSERT_TRUE(result);
  11617. }
  11618. // Send the gzip body over raw TCP with neither Content-Length nor
  11619. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  11620. // kicks in.
  11621. std::string req = "POST /stream HTTP/1.1\r\n"
  11622. "Host: " +
  11623. std::string(HOST) + ":" + std::to_string(port) +
  11624. "\r\n"
  11625. "Content-Encoding: gzip\r\n"
  11626. "Connection: close\r\n"
  11627. "\r\n" +
  11628. gz;
  11629. std::string response;
  11630. ASSERT_TRUE(send_request(5, req, &response, port));
  11631. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11632. EXPECT_LE(total, LIMIT);
  11633. }
  11634. #endif
  11635. #endif
  11636. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  11637. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  11638. // the payload must be passed through untouched instead of being rejected.
  11639. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  11640. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11641. Server svr;
  11642. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  11643. res.set_content(body, "image/jpeg");
  11644. res.set_header("Content-Encoding", "UTF-8");
  11645. });
  11646. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  11647. res.set_content(body, "image/jpeg");
  11648. res.set_header("Content-Encoding", "identity");
  11649. });
  11650. svr.Post("/echo", [](const Request &req, Response &res) {
  11651. res.set_content(req.body, "image/jpeg");
  11652. });
  11653. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11654. auto se = detail::scope_exit([&] {
  11655. svr.stop();
  11656. t.join();
  11657. ASSERT_FALSE(svr.is_running());
  11658. });
  11659. svr.wait_until_ready();
  11660. Client cli(HOST, PORT);
  11661. {
  11662. auto res = cli.Get("/image");
  11663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11664. EXPECT_EQ(StatusCode::OK_200, res->status);
  11665. EXPECT_EQ(body, res->body);
  11666. }
  11667. {
  11668. auto res = cli.Get("/identity");
  11669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11670. EXPECT_EQ(StatusCode::OK_200, res->status);
  11671. EXPECT_EQ(body, res->body);
  11672. }
  11673. {
  11674. // The same applies to a request body reaching the server.
  11675. Headers headers = {{"Content-Encoding", "UTF-8"}};
  11676. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  11677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11678. EXPECT_EQ(StatusCode::OK_200, res->status);
  11679. EXPECT_EQ(body, res->body);
  11680. }
  11681. }
  11682. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  11683. // gzip-encoded response even when the build has no zlib support.
  11684. static const char GZIPPED_HELLO_WORLD[] = {
  11685. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  11686. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  11687. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  11688. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  11689. // A content coding is a whole token, not something the field value merely
  11690. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  11691. // as "fibre" look like Brotli, and turned a multi-coding value like
  11692. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  11693. // it was never meant to see.
  11694. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  11695. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11696. Server svr;
  11697. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  11698. res.set_content(body, "image/jpeg");
  11699. res.set_header("Content-Encoding", "fibre");
  11700. });
  11701. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  11702. res.set_content(body, "image/jpeg");
  11703. res.set_header("Content-Encoding", "gzip, br");
  11704. });
  11705. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  11706. res.set_content(body, "image/jpeg");
  11707. res.set_header("Content-Encoding", "x-zstd-ish");
  11708. });
  11709. auto port = svr.bind_to_any_port(HOST);
  11710. thread t = thread([&]() { svr.listen_after_bind(); });
  11711. auto se = detail::scope_exit([&] {
  11712. svr.stop();
  11713. t.join();
  11714. ASSERT_FALSE(svr.is_running());
  11715. });
  11716. svr.wait_until_ready();
  11717. Client cli(HOST, port);
  11718. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  11719. auto res = cli.Get(path);
  11720. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11721. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11722. // Not a coding we recognize, so the payload comes back untouched
  11723. EXPECT_EQ(body, res->body) << path;
  11724. }
  11725. }
  11726. // A content coding cpp-httplib recognizes but was not built with must be
  11727. // reported as such. Handing the still-compressed payload back to the caller
  11728. // would silently corrupt it.
  11729. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  11730. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11731. Server svr;
  11732. // "image/jpeg" keeps the server from applying a content coding of its own,
  11733. // so the hand-crafted Content-Encoding below survives.
  11734. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  11735. res.set_content(gzipped, "image/jpeg");
  11736. res.set_header("Content-Encoding", "gzip");
  11737. });
  11738. // Content codings are case-insensitive (RFC 9110 8.4.1).
  11739. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  11740. res.set_content(gzipped, "image/jpeg");
  11741. res.set_header("Content-Encoding", "GZIP");
  11742. });
  11743. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11744. auto se = detail::scope_exit([&] {
  11745. svr.stop();
  11746. t.join();
  11747. ASSERT_FALSE(svr.is_running());
  11748. });
  11749. svr.wait_until_ready();
  11750. Client cli(HOST, PORT);
  11751. {
  11752. auto res = cli.Get("/gzipped");
  11753. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11755. EXPECT_EQ("Hello World!", res->body);
  11756. #else
  11757. ASSERT_FALSE(res);
  11758. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11759. #endif
  11760. }
  11761. {
  11762. // open_stream() must behave the same way.
  11763. auto handle = cli.open_stream("GET", "/gzipped");
  11764. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11765. ASSERT_TRUE(handle.is_valid());
  11766. std::string received;
  11767. char buf[256];
  11768. ssize_t n;
  11769. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11770. received.append(buf, static_cast<size_t>(n));
  11771. }
  11772. EXPECT_EQ("Hello World!", received);
  11773. #else
  11774. EXPECT_FALSE(handle.is_valid());
  11775. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  11776. #endif
  11777. }
  11778. {
  11779. // A differently-cased coding must not be mistaken for an unknown one, or
  11780. // the body would be handed back still compressed.
  11781. auto res = cli.Get("/gzipped-uppercase");
  11782. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11784. EXPECT_EQ("Hello World!", res->body);
  11785. #else
  11786. ASSERT_FALSE(res);
  11787. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11788. #endif
  11789. }
  11790. }
  11791. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11792. // A handler serving pre-compressed content (e.g. build-time gzipped static
  11793. // assets) sets Content-Encoding itself. The server used to pick a coding from
  11794. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  11795. // body a second time and appending a second Content-Encoding field line, so
  11796. // clients that decode one coding per listed value handed back raw gzip bytes.
  11797. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  11798. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11799. Server svr;
  11800. // text/plain is a compressible type, so only the pre-set Content-Encoding
  11801. // keeps the server from applying a coding of its own.
  11802. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11803. res.set_content(gzipped, "text/plain");
  11804. res.set_header("Content-Encoding", "gzip");
  11805. });
  11806. auto port = svr.bind_to_any_port(HOST);
  11807. thread t = thread([&]() { svr.listen_after_bind(); });
  11808. auto se = detail::scope_exit([&] {
  11809. svr.stop();
  11810. t.join();
  11811. ASSERT_FALSE(svr.is_running());
  11812. });
  11813. svr.wait_until_ready();
  11814. Client cli(HOST, port);
  11815. Headers headers = {{"Accept-Encoding", "gzip"}};
  11816. auto res = cli.Get("/pre-gzipped", headers);
  11817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11818. EXPECT_EQ(StatusCode::OK_200, res->status);
  11819. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11820. EXPECT_EQ("Hello World!", res->body);
  11821. }
  11822. // A chunked provider settles its coding where the headers are written and
  11823. // reuses it at write time. Both ends of that have to hold: a handler's own
  11824. // Content-Encoding suppresses the coding, and a response without one is still
  11825. // compressed as it always was.
  11826. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  11827. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11828. const std::string plain = "Hello World! Hello World! Hello World!";
  11829. Server svr;
  11830. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11831. res.set_header("Content-Encoding", "gzip");
  11832. res.set_chunked_content_provider(
  11833. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  11834. sink.write(gzipped.data(), gzipped.size());
  11835. sink.done();
  11836. return true;
  11837. });
  11838. });
  11839. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  11840. res.set_chunked_content_provider(
  11841. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  11842. sink.write(plain.data(), plain.size());
  11843. sink.done();
  11844. return true;
  11845. });
  11846. });
  11847. auto port = svr.bind_to_any_port(HOST);
  11848. thread t = thread([&]() { svr.listen_after_bind(); });
  11849. auto se = detail::scope_exit([&] {
  11850. svr.stop();
  11851. t.join();
  11852. ASSERT_FALSE(svr.is_running());
  11853. });
  11854. svr.wait_until_ready();
  11855. Client cli(HOST, port);
  11856. Headers headers = {{"Accept-Encoding", "gzip"}};
  11857. {
  11858. auto res = cli.Get("/pre-gzipped", headers);
  11859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11860. EXPECT_EQ(StatusCode::OK_200, res->status);
  11861. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11862. EXPECT_EQ("Hello World!", res->body);
  11863. }
  11864. {
  11865. auto res = cli.Get("/negotiated", headers);
  11866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11867. EXPECT_EQ(StatusCode::OK_200, res->status);
  11868. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  11869. EXPECT_EQ(plain, res->body);
  11870. }
  11871. }
  11872. #endif
  11873. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  11874. // the same message as the comma-joined one, so both have to be read the same
  11875. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  11876. // single gzip coding, and a body the sender says was encoded twice was handed
  11877. // back after one pass, still compressed but presented as decoded.
  11878. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  11879. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11880. Server svr;
  11881. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  11882. res.set_content(body, "image/jpeg");
  11883. res.headers.emplace("Content-Encoding", "gzip");
  11884. res.headers.emplace("Content-Encoding", "gzip");
  11885. });
  11886. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  11887. res.set_content(body, "image/jpeg");
  11888. res.set_header("Content-Encoding", "gzip, gzip");
  11889. });
  11890. auto port = svr.bind_to_any_port(HOST);
  11891. thread t = thread([&]() { svr.listen_after_bind(); });
  11892. auto se = detail::scope_exit([&] {
  11893. svr.stop();
  11894. t.join();
  11895. ASSERT_FALSE(svr.is_running());
  11896. });
  11897. svr.wait_until_ready();
  11898. Client cli(HOST, port);
  11899. // Two codings is not something cpp-httplib decodes, so both representations
  11900. // take the pass-through path rather than one of them being gunzipped once.
  11901. for (const char *path : {"/split", "/joined"}) {
  11902. auto res = cli.Get(path);
  11903. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11904. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11905. EXPECT_EQ(body, res->body) << path;
  11906. }
  11907. }
  11908. // Regression test for DoS vulnerability: a malicious server sending a response
  11909. // without Content-Length header must not cause unbounded memory consumption on
  11910. // the client side. The client should stop reading after a reasonable limit,
  11911. // similar to the server-side set_payload_max_length protection.
  11912. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  11913. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11914. #ifndef _WIN32
  11915. signal(SIGPIPE, SIG_IGN);
  11916. #endif
  11917. auto server_thread = std::thread([] {
  11918. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  11919. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11920. default_socket_options(srv);
  11921. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11922. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11923. sockaddr_in addr{};
  11924. addr.sin_family = AF_INET;
  11925. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11926. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11927. int opt = 1;
  11928. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11929. #ifdef _WIN32
  11930. reinterpret_cast<const char *>(&opt),
  11931. #else
  11932. &opt,
  11933. #endif
  11934. sizeof(opt));
  11935. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11936. ::listen(srv, 1);
  11937. sockaddr_in cli_addr{};
  11938. socklen_t cli_len = sizeof(cli_addr);
  11939. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11940. if (cli != INVALID_SOCKET) {
  11941. char buf[4096];
  11942. ::recv(cli, buf, sizeof(buf), 0);
  11943. // Malicious response: no Content-Length, no chunked encoding
  11944. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11945. "Connection: close\r\n"
  11946. "\r\n";
  11947. ::send(cli,
  11948. #ifdef _WIN32
  11949. static_cast<const char *>(response_header.c_str()),
  11950. static_cast<int>(response_header.size()),
  11951. #else
  11952. response_header.c_str(), response_header.size(),
  11953. #endif
  11954. 0);
  11955. // Send 10MB of data
  11956. std::string chunk(64 * 1024, 'A');
  11957. size_t total_sent = 0;
  11958. while (total_sent < MALICIOUS_DATA_SIZE) {
  11959. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  11960. auto sent = ::send(cli,
  11961. #ifdef _WIN32
  11962. static_cast<const char *>(chunk.c_str()),
  11963. static_cast<int>(to_send),
  11964. #else
  11965. chunk.c_str(), to_send,
  11966. #endif
  11967. 0);
  11968. if (sent <= 0) break;
  11969. total_sent += static_cast<size_t>(sent);
  11970. }
  11971. detail::close_socket(cli);
  11972. }
  11973. detail::close_socket(srv);
  11974. });
  11975. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11976. size_t total_read = 0;
  11977. {
  11978. Client cli("127.0.0.1", PORT + 2);
  11979. cli.set_read_timeout(5, 0);
  11980. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11981. auto stream = cli.open_stream("GET", "/malicious");
  11982. ASSERT_TRUE(stream.is_valid());
  11983. char buffer[64 * 1024];
  11984. ssize_t n;
  11985. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11986. total_read += static_cast<size_t>(n);
  11987. }
  11988. } // StreamHandle and Client destroyed here, closing the socket
  11989. server_thread.join();
  11990. // With set_payload_max_length, the client must stop reading before consuming
  11991. // all 10MB. The read loop should be cut off at or near the configured limit.
  11992. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  11993. << "Client read " << total_read << " bytes, exceeding the configured "
  11994. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  11995. }
  11996. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  11997. // the entire response body without truncation.
  11998. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  11999. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12000. #ifndef _WIN32
  12001. signal(SIGPIPE, SIG_IGN);
  12002. #endif
  12003. auto server_thread = std::thread([] {
  12004. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12005. default_socket_options(srv);
  12006. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12007. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12008. sockaddr_in addr{};
  12009. addr.sin_family = AF_INET;
  12010. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12011. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12012. int opt = 1;
  12013. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12014. #ifdef _WIN32
  12015. reinterpret_cast<const char *>(&opt),
  12016. #else
  12017. &opt,
  12018. #endif
  12019. sizeof(opt));
  12020. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12021. ::listen(srv, 1);
  12022. sockaddr_in cli_addr{};
  12023. socklen_t cli_len = sizeof(cli_addr);
  12024. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12025. if (cli != INVALID_SOCKET) {
  12026. char buf[4096];
  12027. ::recv(cli, buf, sizeof(buf), 0);
  12028. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12029. "Connection: close\r\n"
  12030. "\r\n";
  12031. ::send(cli,
  12032. #ifdef _WIN32
  12033. static_cast<const char *>(response_header.c_str()),
  12034. static_cast<int>(response_header.size()),
  12035. #else
  12036. response_header.c_str(), response_header.size(),
  12037. #endif
  12038. 0);
  12039. std::string chunk(64 * 1024, 'A');
  12040. size_t total_sent = 0;
  12041. while (total_sent < DATA_SIZE) {
  12042. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12043. auto sent = ::send(cli,
  12044. #ifdef _WIN32
  12045. static_cast<const char *>(chunk.c_str()),
  12046. static_cast<int>(to_send),
  12047. #else
  12048. chunk.c_str(), to_send,
  12049. #endif
  12050. 0);
  12051. if (sent <= 0) break;
  12052. total_sent += static_cast<size_t>(sent);
  12053. }
  12054. #ifdef _WIN32
  12055. ::shutdown(cli, SD_SEND);
  12056. #else
  12057. ::shutdown(cli, SHUT_WR);
  12058. #endif
  12059. // Drain until the client closes its end, ensuring all data is delivered
  12060. char drain[1024];
  12061. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12062. detail::close_socket(cli);
  12063. }
  12064. detail::close_socket(srv);
  12065. });
  12066. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12067. size_t total_read = 0;
  12068. {
  12069. Client cli("127.0.0.1", PORT + 2);
  12070. cli.set_read_timeout(5, 0);
  12071. cli.set_payload_max_length(0); // 0 means no limit
  12072. auto stream = cli.open_stream("GET", "/data");
  12073. ASSERT_TRUE(stream.is_valid());
  12074. char buffer[64 * 1024];
  12075. ssize_t n;
  12076. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12077. total_read += static_cast<size_t>(n);
  12078. }
  12079. }
  12080. server_thread.join();
  12081. EXPECT_EQ(total_read, DATA_SIZE)
  12082. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12083. << " bytes without truncation, but only read " << total_read << " bytes.";
  12084. }
  12085. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12086. // enormous Content-Length must not cause the client to pre-allocate a huge
  12087. // response body buffer. The reservation is capped at payload_max_length_, and
  12088. // the read itself fails when the body exceeds the limit.
  12089. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12090. #ifndef _WIN32
  12091. signal(SIGPIPE, SIG_IGN);
  12092. #endif
  12093. auto server_thread = std::thread([] {
  12094. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12095. default_socket_options(srv);
  12096. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12097. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12098. sockaddr_in addr{};
  12099. addr.sin_family = AF_INET;
  12100. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12101. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12102. int opt = 1;
  12103. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12104. #ifdef _WIN32
  12105. reinterpret_cast<const char *>(&opt),
  12106. #else
  12107. &opt,
  12108. #endif
  12109. sizeof(opt));
  12110. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12111. ::listen(srv, 1);
  12112. sockaddr_in cli_addr{};
  12113. socklen_t cli_len = sizeof(cli_addr);
  12114. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12115. if (cli != INVALID_SOCKET) {
  12116. char buf[4096];
  12117. ::recv(cli, buf, sizeof(buf), 0);
  12118. // Malicious response: claim a 20GB body but send only a tiny payload.
  12119. std::string response = "HTTP/1.1 200 OK\r\n"
  12120. "Content-Length: 20000000000\r\n"
  12121. "\r\n"
  12122. "abc";
  12123. ::send(cli,
  12124. #ifdef _WIN32
  12125. static_cast<const char *>(response.c_str()),
  12126. static_cast<int>(response.size()),
  12127. #else
  12128. response.c_str(), response.size(),
  12129. #endif
  12130. 0);
  12131. detail::close_socket(cli);
  12132. }
  12133. detail::close_socket(srv);
  12134. });
  12135. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12136. {
  12137. Client cli("127.0.0.1", PORT + 2);
  12138. cli.set_read_timeout(5, 0);
  12139. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12140. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12141. // (server claims more bytes than payload_max_length permits), but it must
  12142. // not exhaust memory before getting there.
  12143. auto res = cli.Get("/malicious");
  12144. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12145. }
  12146. server_thread.join();
  12147. }
  12148. // Verify that content_receiver bypasses the default payload_max_length,
  12149. // allowing streaming downloads larger than 100MB without requiring an explicit
  12150. // set_payload_max_length call.
  12151. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12152. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12153. #ifndef _WIN32
  12154. signal(SIGPIPE, SIG_IGN);
  12155. #endif
  12156. auto server_thread = std::thread([] {
  12157. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12158. default_socket_options(srv);
  12159. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12160. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12161. sockaddr_in addr{};
  12162. addr.sin_family = AF_INET;
  12163. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12164. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12165. int opt = 1;
  12166. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12167. #ifdef _WIN32
  12168. reinterpret_cast<const char *>(&opt),
  12169. #else
  12170. &opt,
  12171. #endif
  12172. sizeof(opt));
  12173. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12174. ::listen(srv, 1);
  12175. sockaddr_in cli_addr{};
  12176. socklen_t cli_len = sizeof(cli_addr);
  12177. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12178. if (cli != INVALID_SOCKET) {
  12179. char buf[4096];
  12180. ::recv(cli, buf, sizeof(buf), 0);
  12181. // Response with Content-Length larger than default 100MB limit
  12182. auto content_length = std::to_string(DATA_SIZE);
  12183. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12184. "Content-Length: " +
  12185. content_length +
  12186. "\r\n"
  12187. "Connection: close\r\n"
  12188. "\r\n";
  12189. ::send(cli,
  12190. #ifdef _WIN32
  12191. static_cast<const char *>(response_header.c_str()),
  12192. static_cast<int>(response_header.size()),
  12193. #else
  12194. response_header.c_str(), response_header.size(),
  12195. #endif
  12196. 0);
  12197. std::string chunk(64 * 1024, 'A');
  12198. size_t total_sent = 0;
  12199. while (total_sent < DATA_SIZE) {
  12200. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12201. auto sent = ::send(cli,
  12202. #ifdef _WIN32
  12203. static_cast<const char *>(chunk.c_str()),
  12204. static_cast<int>(to_send),
  12205. #else
  12206. chunk.c_str(), to_send,
  12207. #endif
  12208. 0);
  12209. if (sent <= 0) break;
  12210. total_sent += static_cast<size_t>(sent);
  12211. }
  12212. detail::close_socket(cli);
  12213. }
  12214. detail::close_socket(srv);
  12215. });
  12216. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12217. size_t total_received = 0;
  12218. {
  12219. Client cli("127.0.0.1", PORT + 2);
  12220. cli.set_read_timeout(10, 0);
  12221. // Do NOT call set_payload_max_length — use the default 100MB limit
  12222. auto res =
  12223. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12224. total_received += data_length;
  12225. return true;
  12226. });
  12227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12228. EXPECT_EQ(StatusCode::OK_200, res->status);
  12229. }
  12230. server_thread.join();
  12231. EXPECT_EQ(total_received, DATA_SIZE)
  12232. << "With content_receiver, the client should read all " << DATA_SIZE
  12233. << " bytes despite the default 100MB payload_max_length, but only read "
  12234. << total_received << " bytes.";
  12235. }
  12236. // Verify that an explicit set_payload_max_length smaller than the response is
  12237. // enforced even when a content_receiver is used.
  12238. TEST(ClientVulnerabilityTest,
  12239. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12240. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12241. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12242. #ifndef _WIN32
  12243. signal(SIGPIPE, SIG_IGN);
  12244. #endif
  12245. auto server_thread = std::thread([] {
  12246. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12247. default_socket_options(srv);
  12248. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12249. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12250. sockaddr_in addr{};
  12251. addr.sin_family = AF_INET;
  12252. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12253. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12254. int opt = 1;
  12255. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12256. #ifdef _WIN32
  12257. reinterpret_cast<const char *>(&opt),
  12258. #else
  12259. &opt,
  12260. #endif
  12261. sizeof(opt));
  12262. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12263. ::listen(srv, 1);
  12264. sockaddr_in cli_addr{};
  12265. socklen_t cli_len = sizeof(cli_addr);
  12266. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12267. if (cli != INVALID_SOCKET) {
  12268. char buf[4096];
  12269. ::recv(cli, buf, sizeof(buf), 0);
  12270. auto content_length = std::to_string(DATA_SIZE);
  12271. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12272. "Content-Length: " +
  12273. content_length +
  12274. "\r\n"
  12275. "Connection: close\r\n"
  12276. "\r\n";
  12277. ::send(cli,
  12278. #ifdef _WIN32
  12279. static_cast<const char *>(response_header.c_str()),
  12280. static_cast<int>(response_header.size()),
  12281. #else
  12282. response_header.c_str(), response_header.size(),
  12283. #endif
  12284. 0);
  12285. std::string chunk(64 * 1024, 'A');
  12286. size_t total_sent = 0;
  12287. while (total_sent < DATA_SIZE) {
  12288. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12289. auto sent = ::send(cli,
  12290. #ifdef _WIN32
  12291. static_cast<const char *>(chunk.c_str()),
  12292. static_cast<int>(to_send),
  12293. #else
  12294. chunk.c_str(), to_send,
  12295. #endif
  12296. 0);
  12297. if (sent <= 0) break;
  12298. total_sent += static_cast<size_t>(sent);
  12299. }
  12300. detail::close_socket(cli);
  12301. }
  12302. detail::close_socket(srv);
  12303. });
  12304. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12305. size_t total_received = 0;
  12306. {
  12307. Client cli("127.0.0.1", PORT + 2);
  12308. cli.set_read_timeout(10, 0);
  12309. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  12310. auto res =
  12311. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12312. total_received += data_length;
  12313. return true;
  12314. });
  12315. // Should fail because 200MB exceeds the explicit 150MB limit
  12316. EXPECT_FALSE(res);
  12317. }
  12318. server_thread.join();
  12319. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12320. << "Client with content_receiver should respect the explicit "
  12321. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12322. << total_received << " bytes.";
  12323. }
  12324. // Verify that an explicit set_payload_max_length larger than the response
  12325. // allows the content_receiver to read all data successfully.
  12326. TEST(ClientVulnerabilityTest,
  12327. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  12328. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12329. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  12330. #ifndef _WIN32
  12331. signal(SIGPIPE, SIG_IGN);
  12332. #endif
  12333. auto server_thread = std::thread([] {
  12334. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12335. default_socket_options(srv);
  12336. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12337. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12338. sockaddr_in addr{};
  12339. addr.sin_family = AF_INET;
  12340. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12341. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12342. int opt = 1;
  12343. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12344. #ifdef _WIN32
  12345. reinterpret_cast<const char *>(&opt),
  12346. #else
  12347. &opt,
  12348. #endif
  12349. sizeof(opt));
  12350. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12351. ::listen(srv, 1);
  12352. sockaddr_in cli_addr{};
  12353. socklen_t cli_len = sizeof(cli_addr);
  12354. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12355. if (cli != INVALID_SOCKET) {
  12356. char buf[4096];
  12357. ::recv(cli, buf, sizeof(buf), 0);
  12358. auto content_length = std::to_string(DATA_SIZE);
  12359. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12360. "Content-Length: " +
  12361. content_length +
  12362. "\r\n"
  12363. "Connection: close\r\n"
  12364. "\r\n";
  12365. ::send(cli,
  12366. #ifdef _WIN32
  12367. static_cast<const char *>(response_header.c_str()),
  12368. static_cast<int>(response_header.size()),
  12369. #else
  12370. response_header.c_str(), response_header.size(),
  12371. #endif
  12372. 0);
  12373. std::string chunk(64 * 1024, 'A');
  12374. size_t total_sent = 0;
  12375. while (total_sent < DATA_SIZE) {
  12376. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12377. auto sent = ::send(cli,
  12378. #ifdef _WIN32
  12379. static_cast<const char *>(chunk.c_str()),
  12380. static_cast<int>(to_send),
  12381. #else
  12382. chunk.c_str(), to_send,
  12383. #endif
  12384. 0);
  12385. if (sent <= 0) break;
  12386. total_sent += static_cast<size_t>(sent);
  12387. }
  12388. #ifdef _WIN32
  12389. ::shutdown(cli, SD_SEND);
  12390. #else
  12391. ::shutdown(cli, SHUT_WR);
  12392. #endif
  12393. char drain[1024];
  12394. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12395. detail::close_socket(cli);
  12396. }
  12397. detail::close_socket(srv);
  12398. });
  12399. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12400. size_t total_received = 0;
  12401. {
  12402. Client cli("127.0.0.1", PORT + 2);
  12403. cli.set_read_timeout(10, 0);
  12404. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  12405. auto res =
  12406. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12407. total_received += data_length;
  12408. return true;
  12409. });
  12410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12411. EXPECT_EQ(StatusCode::OK_200, res->status);
  12412. }
  12413. server_thread.join();
  12414. EXPECT_EQ(total_received, DATA_SIZE)
  12415. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  12416. << " bytes (larger than " << DATA_SIZE
  12417. << " bytes response), content_receiver should read all data, but only "
  12418. "read "
  12419. << total_received << " bytes.";
  12420. }
  12421. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  12422. // Regression test for "zip bomb" attack on the client side: a malicious server
  12423. // sends a small gzip-compressed response that decompresses to a huge payload.
  12424. // The client must enforce payload_max_length on the decompressed size.
  12425. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  12426. constexpr size_t DECOMPRESSED_SIZE =
  12427. 10 * 1024 * 1024; // 10MB after decompression
  12428. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12429. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  12430. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  12431. std::string compressed;
  12432. {
  12433. httplib::detail::gzip_compressor compressor;
  12434. bool ok =
  12435. compressor.compress(uncompressed.data(), uncompressed.size(),
  12436. /*last=*/true, [&](const char *buf, size_t len) {
  12437. compressed.append(buf, len);
  12438. return true;
  12439. });
  12440. ASSERT_TRUE(ok);
  12441. }
  12442. // Sanity: compressed data should be much smaller than the decompressed size
  12443. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  12444. #ifndef _WIN32
  12445. signal(SIGPIPE, SIG_IGN);
  12446. #endif
  12447. // Set up the listening socket in the main thread so the server is guaranteed
  12448. // to be ready before the client connects (eliminates race condition).
  12449. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12450. default_socket_options(srv);
  12451. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12452. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12453. sockaddr_in addr{};
  12454. addr.sin_family = AF_INET;
  12455. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  12456. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12457. int opt = 1;
  12458. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12459. #ifdef _WIN32
  12460. reinterpret_cast<const char *>(&opt),
  12461. #else
  12462. &opt,
  12463. #endif
  12464. sizeof(opt));
  12465. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12466. ASSERT_EQ(0, ::listen(srv, 1));
  12467. auto server_thread = std::thread([&compressed, srv] {
  12468. sockaddr_in cli_addr{};
  12469. socklen_t cli_len = sizeof(cli_addr);
  12470. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12471. if (cli != INVALID_SOCKET) {
  12472. // Read the full HTTP request (until \r\n\r\n)
  12473. char buf[4096];
  12474. size_t total = 0;
  12475. while (total < sizeof(buf)) {
  12476. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  12477. if (n <= 0) break;
  12478. total += static_cast<size_t>(n);
  12479. // Check for end of headers
  12480. if (total >= 4) {
  12481. std::string req(buf, total);
  12482. if (req.find("\r\n\r\n") != std::string::npos) break;
  12483. }
  12484. }
  12485. // Malicious response: gzip-compressed body, no Content-Length
  12486. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12487. "Content-Encoding: gzip\r\n"
  12488. "Connection: close\r\n"
  12489. "\r\n";
  12490. ::send(cli,
  12491. #ifdef _WIN32
  12492. static_cast<const char *>(response_header.c_str()),
  12493. static_cast<int>(response_header.size()),
  12494. #else
  12495. response_header.c_str(), response_header.size(),
  12496. #endif
  12497. 0);
  12498. // Send the compressed payload (small on the wire, huge when decompressed)
  12499. size_t total_sent = 0;
  12500. while (total_sent < compressed.size()) {
  12501. auto to_send = std::min(compressed.size() - total_sent,
  12502. static_cast<size_t>(64 * 1024));
  12503. auto sent =
  12504. ::send(cli,
  12505. #ifdef _WIN32
  12506. static_cast<const char *>(compressed.c_str() + total_sent),
  12507. static_cast<int>(to_send),
  12508. #else
  12509. compressed.c_str() + total_sent, to_send,
  12510. #endif
  12511. 0);
  12512. if (sent <= 0) break;
  12513. total_sent += static_cast<size_t>(sent);
  12514. }
  12515. detail::close_socket(cli);
  12516. }
  12517. });
  12518. auto se = detail::scope_exit([&] {
  12519. detail::close_socket(srv);
  12520. server_thread.join();
  12521. });
  12522. size_t total_decompressed = 0;
  12523. {
  12524. Client cli("127.0.0.1", PORT + 3);
  12525. cli.set_read_timeout(5, 0);
  12526. cli.set_decompress(true);
  12527. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12528. auto stream = cli.open_stream("GET", "/zipbomb");
  12529. ASSERT_TRUE(stream.is_valid());
  12530. char buffer[64 * 1024];
  12531. ssize_t n;
  12532. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12533. total_decompressed += static_cast<size_t>(n);
  12534. }
  12535. }
  12536. // The decompressed size must be capped by payload_max_length. Without
  12537. // protection, the client would decompress the full 10MB from a tiny
  12538. // compressed payload, enabling a zip bomb DoS attack.
  12539. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  12540. << "Client decompressed " << total_decompressed
  12541. << " bytes from a gzip response. The decompressed size should be "
  12542. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  12543. }
  12544. #endif
  12545. TEST(HostAndPortPropertiesTest, NoSSL) {
  12546. httplib::Client cli("www.google.com", 1234);
  12547. ASSERT_EQ("www.google.com", cli.host());
  12548. ASSERT_EQ(1234, cli.port());
  12549. }
  12550. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  12551. httplib::Client cli("www.google.com:1234");
  12552. ASSERT_EQ("www.google.com", cli.host());
  12553. ASSERT_EQ(1234, cli.port());
  12554. }
  12555. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  12556. // Port number that overflows int — should not crash, client becomes invalid
  12557. httplib::Client cli("http://www.google.com:99999999999999999999");
  12558. ASSERT_FALSE(cli.is_valid());
  12559. }
  12560. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  12561. // Port 99999 exceeds valid range (1-65535) — should not crash
  12562. httplib::Client cli("http://www.google.com:99999");
  12563. ASSERT_FALSE(cli.is_valid());
  12564. auto res = cli.Get("/");
  12565. EXPECT_FALSE(res);
  12566. EXPECT_EQ(Error::Connection, res.error());
  12567. }
  12568. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  12569. httplib::Client cli("http://user:pass@localhost:1234");
  12570. ASSERT_FALSE(cli.is_valid());
  12571. EXPECT_FALSE(cli.Get("/"));
  12572. }
  12573. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  12574. httplib::Client cli("http://www.google.com:80abc");
  12575. ASSERT_FALSE(cli.is_valid());
  12576. }
  12577. #ifdef CPPHTTPLIB_SSL_ENABLED
  12578. TEST(HostAndPortPropertiesTest, SSL) {
  12579. httplib::SSLClient cli("www.google.com");
  12580. ASSERT_EQ("www.google.com", cli.host());
  12581. ASSERT_EQ(443, cli.port());
  12582. }
  12583. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  12584. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  12585. std::string cert;
  12586. read_file(CA_CERT_FILE, cert);
  12587. httplib::SSLClient httplib_client("www.google.com");
  12588. // Load CA store first time
  12589. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12590. // Load CA store second time (update)
  12591. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12592. // Verify client is still valid and can make connections
  12593. httplib_client.enable_server_certificate_verification(true);
  12594. auto res = httplib_client.Get("/");
  12595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12596. // Google may return 200 or 301 depending on various factors
  12597. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  12598. res->status == StatusCode::MovedPermanently_301);
  12599. }
  12600. TEST(SSLClientTest, ServerNameIndication_Online) {
  12601. auto host = "httpbingo.org";
  12602. auto path = std::string{"/get"};
  12603. SSLClient cli(host, 443);
  12604. auto res = cli.Get(path);
  12605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12606. ASSERT_EQ(StatusCode::OK_200, res->status);
  12607. }
  12608. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  12609. // Use a site that will cause SSL verification failure due to self-signed cert
  12610. SSLClient cli("self-signed.badssl.com", 443);
  12611. cli.enable_server_certificate_verification(true);
  12612. auto res = cli.Get("/");
  12613. ASSERT_TRUE(!res);
  12614. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12615. // Verify backend error is captured for SSLServerVerification
  12616. // This occurs when certificate verification fails
  12617. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  12618. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  12619. EXPECT_NE(0UL, res.ssl_backend_error());
  12620. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12621. // For OpenSSL, ssl_error is 0 for verification errors
  12622. EXPECT_EQ(0, res.ssl_error());
  12623. #if !defined(_WIN32) || \
  12624. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12625. // On non-Windows or when Windows Schannel is disabled, the error comes
  12626. // from OpenSSL's verification
  12627. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  12628. res.ssl_backend_error());
  12629. #endif
  12630. #endif
  12631. }
  12632. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  12633. // Use a site where hostname doesn't match the certificate
  12634. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  12635. SSLClient cli("wrong.host.badssl.com", 443);
  12636. cli.enable_server_certificate_verification(true);
  12637. cli.enable_server_hostname_verification(true);
  12638. auto res = cli.Get("/");
  12639. ASSERT_TRUE(!res);
  12640. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  12641. // Verify backend error is captured for hostname verification failure
  12642. EXPECT_NE(0UL, res.ssl_backend_error());
  12643. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12644. // For OpenSSL, ssl_error is 0 for verification errors
  12645. EXPECT_EQ(0, res.ssl_error());
  12646. #if !defined(_WIN32) || \
  12647. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12648. // On non-Windows or when Windows Schannel is disabled, the error comes
  12649. // from OpenSSL's hostname verification
  12650. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  12651. res.ssl_backend_error());
  12652. #endif
  12653. #endif
  12654. }
  12655. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  12656. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12657. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  12658. SSLClient cli("www.google.com", 443);
  12659. cli.enable_server_certificate_verification(true);
  12660. auto res = cli.Get("/");
  12661. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12662. }
  12663. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  12664. SSLClient cli("www.google.com", 443);
  12665. cli.enable_server_certificate_verification(true);
  12666. cli.enable_windows_certificate_verification(false);
  12667. auto res = cli.Get("/");
  12668. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12669. }
  12670. // The server sends an intermediate cross-signed by a root Windows trusts,
  12671. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  12672. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  12673. SSLClient cli("accounts.spotify.com", 443);
  12674. auto res = cli.Get("/");
  12675. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  12676. << " ssl_backend_error=" << res.ssl_backend_error();
  12677. }
  12678. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  12679. // policy status, which no backend reports for a self-signed certificate.
  12680. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  12681. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12682. ASSERT_TRUE(svr.is_valid());
  12683. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12684. auto se = detail::scope_exit([&] {
  12685. svr.stop();
  12686. t.join();
  12687. ASSERT_FALSE(svr.is_running());
  12688. });
  12689. svr.wait_until_ready();
  12690. SSLClient cli("127.0.0.1", PORT);
  12691. cli.set_connection_timeout(30);
  12692. auto res = cli.Get("/");
  12693. ASSERT_FALSE(res);
  12694. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12695. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  12696. }
  12697. #endif
  12698. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  12699. Client cli("https://google.com");
  12700. auto res = cli.Get("/");
  12701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12702. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12703. }
  12704. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  12705. SSLClient cli("google.com");
  12706. cli.set_ca_cert_path(CA_CERT_FILE);
  12707. auto res = cli.Get("/");
  12708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12709. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12710. }
  12711. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  12712. SSLClient cli("google.com");
  12713. cli.enable_server_certificate_verification(true);
  12714. cli.set_ca_cert_path("hello");
  12715. auto res = cli.Get("/");
  12716. ASSERT_TRUE(!res);
  12717. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  12718. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  12719. // should be set
  12720. EXPECT_EQ(0, res.ssl_error());
  12721. // Verify backend error is captured for SSLLoadingCerts
  12722. // This error occurs when loading CA certificates fails
  12723. EXPECT_NE(0UL, res.ssl_backend_error());
  12724. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12725. // OpenSSL specific error codes:
  12726. // > openssl errstr 0x80000002
  12727. // error:80000002:system library::No such file or directory
  12728. // > openssl errstr 0xA000126
  12729. // error:0A000126:SSL routines::unexpected eof while reading
  12730. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  12731. res.ssl_backend_error() == 0xA000126);
  12732. #endif
  12733. }
  12734. TEST(SSLClientTest, ServerCertificateVerification4) {
  12735. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12736. ASSERT_TRUE(svr.is_valid());
  12737. svr.Get("/test", [&](const Request &, Response &res) {
  12738. res.set_content("test", "text/plain");
  12739. svr.stop();
  12740. ASSERT_TRUE(true);
  12741. });
  12742. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12743. auto se = detail::scope_exit([&] {
  12744. t.join();
  12745. ASSERT_FALSE(svr.is_running());
  12746. });
  12747. svr.wait_until_ready();
  12748. SSLClient cli("127.0.0.1", PORT);
  12749. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12750. cli.enable_server_certificate_verification(true);
  12751. cli.set_connection_timeout(30);
  12752. auto res = cli.Get("/test");
  12753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12754. ASSERT_EQ(StatusCode::OK_200, res->status);
  12755. }
  12756. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  12757. std::string cert;
  12758. read_file(CA_CERT_FILE, cert);
  12759. SSLClient cli("google.com");
  12760. cli.load_ca_cert_store(cert.data(), cert.size());
  12761. const auto res = cli.Get("/");
  12762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12763. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12764. }
  12765. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  12766. // clang-format off
  12767. static constexpr char cert[] =
  12768. "GlobalSign Root CA\n"
  12769. "==================\n"
  12770. "-----BEGIN CERTIFICATE-----\n"
  12771. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  12772. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  12773. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  12774. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  12775. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  12776. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  12777. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  12778. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  12779. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  12780. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  12781. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  12782. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  12783. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  12784. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  12785. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  12786. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  12787. "-----END CERTIFICATE-----\n";
  12788. // clang-format on
  12789. SSLClient cli("google.com");
  12790. cli.load_ca_cert_store(cert, sizeof(cert));
  12791. const auto res = cli.Get("/");
  12792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12793. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12794. }
  12795. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  12796. SSLClient cli("www.youtube.com");
  12797. cli.set_ca_cert_path(CA_CERT_FILE);
  12798. cli.enable_server_certificate_verification(true);
  12799. cli.set_follow_location(true);
  12800. auto res = cli.Get("/");
  12801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12802. ASSERT_EQ(StatusCode::OK_200, res->status);
  12803. }
  12804. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  12805. SSLClient cli("wWw.YouTube.Com");
  12806. cli.set_ca_cert_path(CA_CERT_FILE);
  12807. cli.enable_server_certificate_verification(true);
  12808. cli.enable_server_hostname_verification(true);
  12809. cli.set_follow_location(true);
  12810. auto res = cli.Get("/");
  12811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12812. ASSERT_EQ(StatusCode::OK_200, res->status);
  12813. }
  12814. TEST(SSLClientTest, HostNameMatchCase_Online) {
  12815. SSLClient cli("gOoGlE.COm");
  12816. cli.enable_server_certificate_verification(true);
  12817. cli.enable_server_hostname_verification(true);
  12818. cli.set_follow_location(true);
  12819. auto res = cli.Get("/");
  12820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12821. ASSERT_EQ(StatusCode::OK_200, res->status);
  12822. }
  12823. TEST(SSLClientTest, Issue2004_Online) {
  12824. Client client("https://google.com");
  12825. client.set_follow_location(true);
  12826. auto res = client.Get("/");
  12827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12828. ASSERT_EQ(StatusCode::OK_200, res->status);
  12829. auto body = res->body;
  12830. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  12831. }
  12832. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  12833. // Create SSLClient with invalid cert/key to make is_valid() return false
  12834. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  12835. "nonexistent_key.pem");
  12836. // is_valid() should be false due to cert loading failure
  12837. ASSERT_FALSE(cli.is_valid());
  12838. auto res = cli.Get("/");
  12839. ASSERT_FALSE(res);
  12840. EXPECT_EQ(Error::SSLConnection, res.error());
  12841. }
  12842. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  12843. // Test for Issue #2251: SSL error not properly reported when client cert
  12844. // and key paths are swapped or mismatched
  12845. // This simulates the scenario where user accidentally swaps the cert and key
  12846. // files
  12847. // Using client cert file as private key and vice versa (completely wrong)
  12848. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  12849. // Should fail validation due to cert/key mismatch
  12850. ASSERT_FALSE(cli.is_valid());
  12851. // Attempt to make a request should fail with proper error
  12852. auto res = cli.Get("/");
  12853. ASSERT_FALSE(res);
  12854. EXPECT_EQ(Error::SSLConnection, res.error());
  12855. // SSL error should be recorded in the Result object (this is the key fix for
  12856. // Issue #2251)
  12857. auto backend_error = res.ssl_backend_error();
  12858. EXPECT_NE(0u, backend_error);
  12859. }
  12860. // Tests cert/key mismatch detection at the TLS context level
  12861. TEST(TlsApiTest, ClientCertKeyMismatch) {
  12862. // Test that using mismatched cert/key causes connection failure.
  12863. // We verify this at the SSLClient level rather than through internal
  12864. // TLS API functions.
  12865. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  12866. cli.enable_server_certificate_verification(false);
  12867. cli.set_connection_timeout(2);
  12868. // The mismatch should cause a connection or handshake error
  12869. auto res = cli.Get("/test");
  12870. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  12871. // Either way, the request should fail
  12872. EXPECT_FALSE(res);
  12873. }
  12874. #endif
  12875. #if 0
  12876. TEST(SSLClientTest, SetInterfaceWithINET6) {
  12877. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  12878. ASSERT_TRUE(cli != nullptr);
  12879. cli->set_address_family(AF_INET6);
  12880. cli->set_interface("en0");
  12881. auto res = cli->Get("/get");
  12882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12883. ASSERT_EQ(StatusCode::OK_200, res->status);
  12884. }
  12885. #endif
  12886. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  12887. #ifdef CPPHTTPLIB_SSL_ENABLED
  12888. void ClientCertPresent(
  12889. const std::string &client_cert_file,
  12890. const std::string &client_private_key_file,
  12891. const std::string &client_encrypted_private_key_pass = std::string()) {
  12892. using namespace httplib::tls;
  12893. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12894. CLIENT_CA_CERT_DIR);
  12895. ASSERT_TRUE(svr.is_valid());
  12896. svr.Get("/test", [&](const Request &req, Response &res) {
  12897. res.set_content("test", "text/plain");
  12898. auto cert = req.peer_cert();
  12899. ASSERT_TRUE(static_cast<bool>(cert));
  12900. std::string common_name = cert.subject_cn();
  12901. EXPECT_EQ("Common Name", common_name);
  12902. });
  12903. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12904. auto se = detail::scope_exit([&] {
  12905. svr.stop();
  12906. t.join();
  12907. ASSERT_FALSE(svr.is_running());
  12908. });
  12909. svr.wait_until_ready();
  12910. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  12911. client_encrypted_private_key_pass);
  12912. cli.enable_server_certificate_verification(false);
  12913. cli.set_connection_timeout(30);
  12914. auto res = cli.Get("/test");
  12915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12916. ASSERT_EQ(StatusCode::OK_200, res->status);
  12917. }
  12918. TEST(SSLClientServerTest, ClientCertPresent) {
  12919. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12920. }
  12921. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  12922. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12923. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12924. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12925. }
  12926. // PEM memory-based constructor tests (works with all TLS backends)
  12927. void PemMemoryClientCertPresent(
  12928. const std::string &client_cert_file,
  12929. const std::string &client_private_key_file,
  12930. const std::string &client_encrypted_private_key_pass = std::string()) {
  12931. // Read PEM files into memory
  12932. std::string server_cert_pem, server_key_pem;
  12933. std::string client_ca_pem;
  12934. std::string client_cert_pem, client_key_pem;
  12935. read_file(SERVER_CERT_FILE, server_cert_pem);
  12936. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12937. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12938. read_file(client_cert_file, client_cert_pem);
  12939. read_file(client_private_key_file, client_key_pem);
  12940. // Create server with PEM memory
  12941. SSLServer::PemMemory server_pem = {
  12942. server_cert_pem.c_str(),
  12943. server_cert_pem.size(),
  12944. server_key_pem.c_str(),
  12945. server_key_pem.size(),
  12946. client_ca_pem.c_str(),
  12947. client_ca_pem.size(),
  12948. nullptr // no password for server key
  12949. };
  12950. SSLServer svr(server_pem);
  12951. ASSERT_TRUE(svr.is_valid());
  12952. svr.Get("/test", [&](const Request &, Response &res) {
  12953. res.set_content("test", "text/plain");
  12954. });
  12955. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12956. auto se = detail::scope_exit([&] {
  12957. svr.stop();
  12958. t.join();
  12959. ASSERT_FALSE(svr.is_running());
  12960. });
  12961. svr.wait_until_ready();
  12962. // Create client with PEM memory
  12963. const char *password = client_encrypted_private_key_pass.empty()
  12964. ? nullptr
  12965. : client_encrypted_private_key_pass.c_str();
  12966. SSLClient::PemMemory client_pem = {
  12967. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  12968. client_key_pem.size(), password};
  12969. SSLClient cli(HOST, PORT, client_pem);
  12970. cli.enable_server_certificate_verification(false);
  12971. cli.set_connection_timeout(30);
  12972. auto res = cli.Get("/test");
  12973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12974. ASSERT_EQ(StatusCode::OK_200, res->status);
  12975. }
  12976. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  12977. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12978. }
  12979. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  12980. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12981. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12982. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12983. }
  12984. TEST(SSLClientServerTest, ClientCertMissing) {
  12985. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12986. CLIENT_CA_CERT_DIR);
  12987. ASSERT_TRUE(svr.is_valid());
  12988. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  12989. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12990. auto se = detail::scope_exit([&] {
  12991. svr.stop();
  12992. t.join();
  12993. ASSERT_FALSE(svr.is_running());
  12994. });
  12995. svr.wait_until_ready();
  12996. SSLClient cli(HOST, PORT);
  12997. cli.set_connection_timeout(30);
  12998. // cert.pem does not match HOST. Skip the hostname check, which runs before
  12999. // the chain check on Windows, so the result does not depend on the order.
  13000. cli.enable_server_hostname_verification(false);
  13001. auto res = cli.Get("/test");
  13002. ASSERT_TRUE(!res);
  13003. // When client cert is missing and server requires it, connection fails
  13004. // Error type depends on backend implementation
  13005. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13006. res.error() == Error::SSLConnection);
  13007. // Verify backend error is captured
  13008. // Note: This test may have different error codes depending on the exact
  13009. // verification failure
  13010. EXPECT_NE(0UL, res.ssl_backend_error());
  13011. }
  13012. TEST(SSLClientServerTest, TrustDirOptional) {
  13013. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13014. ASSERT_TRUE(svr.is_valid());
  13015. svr.Get("/test", [&](const Request &, Response &res) {
  13016. res.set_content("test", "text/plain");
  13017. });
  13018. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13019. auto se = detail::scope_exit([&] {
  13020. svr.stop();
  13021. t.join();
  13022. ASSERT_FALSE(svr.is_running());
  13023. });
  13024. svr.wait_until_ready();
  13025. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13026. cli.enable_server_certificate_verification(false);
  13027. cli.set_connection_timeout(30);
  13028. auto res = cli.Get("/test");
  13029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13030. ASSERT_EQ(StatusCode::OK_200, res->status);
  13031. }
  13032. TEST(SSLClientServerTest, SSLConnectTimeout) {
  13033. class NoListenSSLServer : public SSLServer {
  13034. public:
  13035. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  13036. const char *client_ca_cert_file_path,
  13037. const char *client_ca_cert_dir_path = nullptr)
  13038. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  13039. client_ca_cert_dir_path),
  13040. stop_(false) {}
  13041. std::atomic_bool stop_;
  13042. private:
  13043. bool process_and_close_socket(socket_t /*sock*/) override {
  13044. // Don't create SSL context
  13045. while (!stop_.load()) {
  13046. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  13047. }
  13048. return true;
  13049. }
  13050. };
  13051. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13052. CLIENT_CA_CERT_FILE);
  13053. ASSERT_TRUE(svr.is_valid());
  13054. svr.Get("/test", [&](const Request &, Response &res) {
  13055. res.set_content("test", "text/plain");
  13056. });
  13057. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13058. auto se = detail::scope_exit([&] {
  13059. svr.stop_ = true;
  13060. svr.stop();
  13061. t.join();
  13062. ASSERT_FALSE(svr.is_running());
  13063. });
  13064. svr.wait_until_ready();
  13065. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13066. cli.enable_server_certificate_verification(false);
  13067. cli.set_connection_timeout(1);
  13068. auto res = cli.Get("/test");
  13069. ASSERT_TRUE(!res);
  13070. EXPECT_EQ(Error::SSLConnection, res.error());
  13071. // Timeout results in WantRead error code (maps to backend-specific value)
  13072. EXPECT_NE(0, res.ssl_error());
  13073. }
  13074. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  13075. // Test SSLServer with client certificate verification using the standard
  13076. // constructor (ContextSetupCallback is tested by backend-specific tests)
  13077. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13078. CLIENT_CA_CERT_DIR);
  13079. ASSERT_TRUE(svr.is_valid());
  13080. svr.Get("/test", [&](const Request &req, Response &res) {
  13081. res.set_content("test", "text/plain");
  13082. auto cert = req.peer_cert();
  13083. ASSERT_TRUE(static_cast<bool>(cert));
  13084. auto common_name = cert.subject_cn();
  13085. EXPECT_EQ("Common Name", common_name);
  13086. });
  13087. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13088. auto se = detail::scope_exit([&] {
  13089. svr.stop();
  13090. t.join();
  13091. ASSERT_FALSE(svr.is_running());
  13092. });
  13093. svr.wait_until_ready();
  13094. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13095. cli.enable_server_certificate_verification(false);
  13096. cli.set_connection_timeout(30);
  13097. auto res = cli.Get("/test");
  13098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13099. ASSERT_EQ(StatusCode::OK_200, res->status);
  13100. }
  13101. // Test verify_hostname for both OpenSSL and MbedTLS backends
  13102. // Verifies that wildcard matching and exact matching work consistently
  13103. TEST(SSLClientServerTest, TlsVerifyHostname) {
  13104. using namespace httplib::tls;
  13105. // We need a running server to test against
  13106. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13107. ASSERT_TRUE(svr.is_valid());
  13108. svr.Get("/test", [](const Request &, Response &res) {
  13109. res.set_content("ok", "text/plain");
  13110. });
  13111. thread t([&]() { svr.listen(HOST, PORT); });
  13112. auto se = detail::scope_exit([&] {
  13113. svr.stop();
  13114. t.join();
  13115. });
  13116. svr.wait_until_ready();
  13117. bool verify_callback_called = false;
  13118. bool verify_result_wrong = false;
  13119. SSLClient cli(HOST, PORT);
  13120. cli.enable_server_certificate_verification(true);
  13121. cli.set_ca_cert_path(CA_CERT_FILE);
  13122. cli.set_connection_timeout(5);
  13123. // Note: Test certificate has CN="Common Name", not "localhost"
  13124. bool verify_result_cn = false;
  13125. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13126. verify_callback_called = true;
  13127. if (!ctx.cert) return false;
  13128. // Test 1: "Common Name" should match (our test server cert CN)
  13129. verify_result_cn = ctx.check_hostname("Common Name");
  13130. // Test 2: wrong hostname should not match
  13131. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  13132. return true; // Accept for the purpose of this test
  13133. });
  13134. auto res = cli.Get("/test");
  13135. // The request may succeed or fail depending on cert configuration
  13136. // but the callback should have been called
  13137. ASSERT_TRUE(verify_callback_called)
  13138. << "Verify callback should have been called";
  13139. // CN="Common Name" should match our test certificate
  13140. //
  13141. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  13142. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  13143. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  13144. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  13145. // <openssl/base.h>, which is included transitively when
  13146. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  13147. #if defined(OPENSSL_IS_BORINGSSL)
  13148. EXPECT_FALSE(verify_result_cn)
  13149. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  13150. #else
  13151. EXPECT_TRUE(verify_result_cn)
  13152. << "verify_hostname should match 'Common Name' (certificate CN)";
  13153. #endif
  13154. // Wrong hostname should not match
  13155. EXPECT_FALSE(verify_result_wrong)
  13156. << "verify_hostname should not match 'wronghost.example.com'";
  13157. }
  13158. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  13159. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  13160. // X509_check_ip behavior and must hold for every backend.
  13161. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  13162. using namespace httplib::tls;
  13163. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  13164. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  13165. ASSERT_TRUE(svr.is_valid());
  13166. svr.Get("/test", [](const Request &, Response &res) {
  13167. res.set_content("ok", "text/plain");
  13168. });
  13169. thread t([&]() { svr.listen(HOST, PORT); });
  13170. auto se = detail::scope_exit([&] {
  13171. svr.stop();
  13172. t.join();
  13173. });
  13174. svr.wait_until_ready();
  13175. bool verify_callback_called = false;
  13176. bool ip_matched_via_cn = true;
  13177. SSLClient cli(HOST, PORT);
  13178. cli.enable_server_certificate_verification(true);
  13179. cli.set_ca_cert_path(CA_CERT_FILE);
  13180. cli.set_connection_timeout(5);
  13181. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13182. verify_callback_called = true;
  13183. if (!ctx.cert) return false;
  13184. // The IP appears only in the CN, so it must NOT be accepted.
  13185. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  13186. return true; // Accept for the purpose of this test
  13187. });
  13188. cli.Get("/test");
  13189. ASSERT_TRUE(verify_callback_called)
  13190. << "Verify callback should have been called";
  13191. EXPECT_FALSE(ip_matched_via_cn)
  13192. << "An IP host must not be authenticated via the certificate CN";
  13193. }
  13194. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  13195. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  13196. using namespace httplib::tls;
  13197. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  13198. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  13199. ASSERT_TRUE(svr.is_valid());
  13200. svr.Get("/test", [](const Request &, Response &res) {
  13201. res.set_content("ok", "text/plain");
  13202. });
  13203. thread t([&]() { svr.listen(HOST, PORT); });
  13204. auto se = detail::scope_exit([&] {
  13205. svr.stop();
  13206. t.join();
  13207. });
  13208. svr.wait_until_ready();
  13209. bool verify_callback_called = false;
  13210. bool san_matched = false;
  13211. bool wrong_ipv6_matched = true;
  13212. bool cn_ipv6_matched = true;
  13213. SSLClient cli(HOST, PORT);
  13214. cli.enable_server_certificate_verification(true);
  13215. cli.set_ca_cert_path(CA_CERT_FILE);
  13216. cli.set_connection_timeout(5);
  13217. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13218. verify_callback_called = true;
  13219. if (!ctx.cert) return false;
  13220. // Matches the IPv6 iPAddress SAN.
  13221. san_matched = ctx.check_hostname("2001:db8::1");
  13222. // A different IPv6 address must not match.
  13223. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  13224. // "::1" lives only in the CN, so it must not be accepted.
  13225. cn_ipv6_matched = ctx.check_hostname("::1");
  13226. return true; // Accept for the purpose of this test
  13227. });
  13228. cli.Get("/test");
  13229. ASSERT_TRUE(verify_callback_called)
  13230. << "Verify callback should have been called";
  13231. EXPECT_TRUE(san_matched)
  13232. << "verify_hostname should match an IPv6 iPAddress SAN";
  13233. EXPECT_FALSE(wrong_ipv6_matched)
  13234. << "verify_hostname should not match a non-matching IPv6 address";
  13235. EXPECT_FALSE(cn_ipv6_matched)
  13236. << "An IPv6 host must not be authenticated via the certificate CN";
  13237. }
  13238. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  13239. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  13240. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  13241. using namespace httplib::tls;
  13242. // SANs: DNS:a.zz, IP:42.46.122.122
  13243. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13244. ASSERT_TRUE(svr.is_valid());
  13245. svr.Get("/test", [](const Request &, Response &res) {
  13246. res.set_content("ok", "text/plain");
  13247. });
  13248. auto port = svr.bind_to_any_port(HOST);
  13249. thread t([&]() { svr.listen_after_bind(); });
  13250. auto se = detail::scope_exit([&] {
  13251. svr.stop();
  13252. t.join();
  13253. });
  13254. svr.wait_until_ready();
  13255. bool verify_callback_called = false;
  13256. bool dns_san_matched = false;
  13257. bool ip_san_matched = false;
  13258. bool ip_matched_via_dns_san = true;
  13259. bool dns_matched_via_ip_san = true;
  13260. SSLClient cli(HOST, port);
  13261. cli.enable_server_certificate_verification(true);
  13262. cli.set_ca_cert_path(CA_CERT_FILE);
  13263. cli.set_connection_timeout(5);
  13264. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13265. verify_callback_called = true;
  13266. if (!ctx.cert) return false;
  13267. dns_san_matched = ctx.check_hostname("a.zz");
  13268. ip_san_matched = ctx.check_hostname("42.46.122.122");
  13269. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  13270. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  13271. return true; // Accept for the purpose of this test
  13272. });
  13273. cli.Get("/test");
  13274. ASSERT_TRUE(verify_callback_called)
  13275. << "Verify callback should have been called";
  13276. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  13277. EXPECT_TRUE(ip_san_matched)
  13278. << "verify_hostname should match an iPAddress SAN";
  13279. EXPECT_FALSE(ip_matched_via_dns_san)
  13280. << "An IP host must not be authenticated via a dNSName SAN";
  13281. EXPECT_FALSE(dns_matched_via_ip_san)
  13282. << "A DNS host must not be authenticated via an iPAddress SAN";
  13283. }
  13284. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  13285. // "www.*.example.test" names one host and not every host under example.test.
  13286. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  13287. using namespace httplib::tls;
  13288. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  13289. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  13290. ASSERT_TRUE(svr.is_valid());
  13291. svr.Get("/test", [](const Request &, Response &res) {
  13292. res.set_content("ok", "text/plain");
  13293. });
  13294. auto port = svr.bind_to_any_port(HOST);
  13295. thread t([&]() { svr.listen_after_bind(); });
  13296. auto se = detail::scope_exit([&] {
  13297. svr.stop();
  13298. t.join();
  13299. });
  13300. svr.wait_until_ready();
  13301. bool verify_callback_called = false;
  13302. bool leftmost_wildcard_matched = false;
  13303. bool wildcard_spanned_labels = true;
  13304. bool inner_wildcard_matched = true;
  13305. SSLClient cli(HOST, port);
  13306. cli.enable_server_certificate_verification(true);
  13307. cli.set_ca_cert_path(CA_CERT_FILE);
  13308. cli.set_connection_timeout(5);
  13309. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13310. verify_callback_called = true;
  13311. if (!ctx.cert) return false;
  13312. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  13313. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  13314. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  13315. return true; // Accept for the purpose of this test
  13316. });
  13317. cli.Get("/test");
  13318. ASSERT_TRUE(verify_callback_called)
  13319. << "Verify callback should have been called";
  13320. EXPECT_TRUE(leftmost_wildcard_matched)
  13321. << "A leftmost wildcard should match a single label";
  13322. EXPECT_FALSE(wildcard_spanned_labels)
  13323. << "A wildcard label must not match more than one label";
  13324. EXPECT_FALSE(inner_wildcard_matched)
  13325. << "A wildcard outside the leftmost label must not be honoured";
  13326. }
  13327. // sans() must report each SAN entry under its own type.
  13328. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  13329. using namespace httplib::tls;
  13330. // SANs: DNS:a.zz, IP:42.46.122.122
  13331. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13332. ASSERT_TRUE(svr.is_valid());
  13333. svr.Get("/test", [](const Request &, Response &res) {
  13334. res.set_content("ok", "text/plain");
  13335. });
  13336. auto port = svr.bind_to_any_port(HOST);
  13337. thread t([&]() { svr.listen_after_bind(); });
  13338. auto se = detail::scope_exit([&] {
  13339. svr.stop();
  13340. t.join();
  13341. });
  13342. svr.wait_until_ready();
  13343. bool verify_callback_called = false;
  13344. std::vector<SanEntry> sans;
  13345. SSLClient cli(HOST, port);
  13346. cli.enable_server_certificate_verification(true);
  13347. cli.set_ca_cert_path(CA_CERT_FILE);
  13348. cli.set_connection_timeout(5);
  13349. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13350. verify_callback_called = true;
  13351. if (!ctx.cert) return false;
  13352. sans = ctx.sans();
  13353. return true; // Accept for the purpose of this test
  13354. });
  13355. cli.Get("/test");
  13356. ASSERT_TRUE(verify_callback_called)
  13357. << "Verify callback should have been called";
  13358. auto has_san = [&](SanType type, const std::string &value) {
  13359. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  13360. return san.type == type && san.value == value;
  13361. });
  13362. };
  13363. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  13364. << "sans() should report the dNSName SAN";
  13365. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  13366. << "sans() should report the iPAddress SAN";
  13367. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  13368. << "sans() must not report the dNSName SAN as an address";
  13369. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  13370. << "sans() must not report the iPAddress SAN as a DNS name";
  13371. }
  13372. #endif
  13373. // mbedTLS-specific callback constructor test
  13374. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  13375. #ifdef CPPHTTPLIB_SSL_ENABLED
  13376. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  13377. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13378. ASSERT_TRUE(svr.is_valid());
  13379. // Set up a handler to verify client certificate is present
  13380. bool client_cert_verified = false;
  13381. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13382. // Verify that client certificate was provided
  13383. client_cert_verified = true;
  13384. res.set_content("success", "text/plain");
  13385. });
  13386. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13387. auto se = detail::scope_exit([&] {
  13388. svr.stop();
  13389. t.join();
  13390. ASSERT_FALSE(svr.is_running());
  13391. });
  13392. svr.wait_until_ready();
  13393. // Client with certificate
  13394. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13395. cli.enable_server_certificate_verification(false);
  13396. cli.set_connection_timeout(30);
  13397. auto res = cli.Get("/test");
  13398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13399. ASSERT_EQ(StatusCode::OK_200, res->status);
  13400. ASSERT_TRUE(client_cert_verified);
  13401. EXPECT_EQ("success", res->body);
  13402. }
  13403. #endif
  13404. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  13405. // backends
  13406. #ifdef CPPHTTPLIB_SSL_ENABLED
  13407. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  13408. using namespace httplib::tls;
  13409. // Test that when client CA cert file is provided,
  13410. // the server properly requests and validates client certificates
  13411. // Create a server with client authentication
  13412. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13413. ASSERT_TRUE(svr.is_valid());
  13414. bool handler_called = false;
  13415. svr.Get("/test", [&](const Request &req, Response &res) {
  13416. handler_called = true;
  13417. // Verify that a client certificate was provided
  13418. auto cert = req.peer_cert();
  13419. ASSERT_TRUE(static_cast<bool>(cert));
  13420. // Get the issuer name
  13421. std::string issuer_str = cert.issuer_name();
  13422. ASSERT_FALSE(issuer_str.empty());
  13423. // The client certificate should be issued by our test CA
  13424. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  13425. res.set_content("authenticated", "text/plain");
  13426. });
  13427. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13428. auto se = detail::scope_exit([&] {
  13429. svr.stop();
  13430. t.join();
  13431. ASSERT_FALSE(svr.is_running());
  13432. });
  13433. svr.wait_until_ready();
  13434. // Connect with a client certificate issued by the CA
  13435. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13436. cli.enable_server_certificate_verification(false);
  13437. cli.set_connection_timeout(30);
  13438. auto res = cli.Get("/test");
  13439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13440. ASSERT_EQ(StatusCode::OK_200, res->status);
  13441. ASSERT_TRUE(handler_called);
  13442. EXPECT_EQ("authenticated", res->body);
  13443. }
  13444. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  13445. using namespace httplib::tls;
  13446. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13447. ASSERT_TRUE(svr.is_valid());
  13448. svr.Get("/test", [](const Request &, Response &res) {
  13449. res.set_content("ok", "text/plain");
  13450. });
  13451. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13452. auto se = detail::scope_exit([&] {
  13453. svr.stop();
  13454. t.join();
  13455. });
  13456. svr.wait_until_ready();
  13457. SSLClient cli(HOST, PORT);
  13458. cli.enable_server_certificate_verification(false);
  13459. cli.set_connection_timeout(30);
  13460. bool cert_checked = false;
  13461. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13462. if (ctx.cert) {
  13463. auto sans = ctx.sans();
  13464. // Test certificate may or may not have SANs - just verify the API
  13465. // works If SANs exist, verify the types are valid
  13466. for (const auto &san : sans) {
  13467. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  13468. san.type == SanType::EMAIL || san.type == SanType::URI ||
  13469. san.type == SanType::OTHER);
  13470. EXPECT_FALSE(san.value.empty());
  13471. }
  13472. cert_checked = true;
  13473. }
  13474. return true;
  13475. });
  13476. auto res = cli.Get("/test");
  13477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13478. EXPECT_TRUE(cert_checked);
  13479. }
  13480. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  13481. using namespace httplib::tls;
  13482. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13483. ASSERT_TRUE(svr.is_valid());
  13484. svr.Get("/test", [](const Request &, Response &res) {
  13485. res.set_content("ok", "text/plain");
  13486. });
  13487. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13488. auto se = detail::scope_exit([&] {
  13489. svr.stop();
  13490. t.join();
  13491. });
  13492. svr.wait_until_ready();
  13493. SSLClient cli(HOST, PORT);
  13494. cli.enable_server_certificate_verification(false);
  13495. cli.set_connection_timeout(30);
  13496. bool validity_checked = false;
  13497. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13498. if (ctx.cert) {
  13499. time_t not_before = 0, not_after = 0;
  13500. bool result = ctx.validity(not_before, not_after);
  13501. EXPECT_TRUE(result);
  13502. // Verify that not_before < now < not_after for a valid cert
  13503. time_t now = time(nullptr);
  13504. EXPECT_LT(not_before, now);
  13505. EXPECT_GT(not_after, now);
  13506. validity_checked = true;
  13507. }
  13508. return true;
  13509. });
  13510. auto res = cli.Get("/test");
  13511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13512. EXPECT_TRUE(validity_checked);
  13513. }
  13514. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  13515. using namespace httplib::tls;
  13516. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13517. ASSERT_TRUE(svr.is_valid());
  13518. svr.Get("/test", [](const Request &, Response &res) {
  13519. res.set_content("ok", "text/plain");
  13520. });
  13521. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13522. auto se = detail::scope_exit([&] {
  13523. svr.stop();
  13524. t.join();
  13525. });
  13526. svr.wait_until_ready();
  13527. SSLClient cli(HOST, PORT);
  13528. cli.enable_server_certificate_verification(false);
  13529. cli.set_connection_timeout(30);
  13530. bool serial_checked = false;
  13531. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13532. if (ctx.cert) {
  13533. std::string serial = ctx.serial();
  13534. EXPECT_FALSE(serial.empty());
  13535. // Serial should be a hex string
  13536. for (char c : serial) {
  13537. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  13538. (c >= 'a' && c <= 'f'));
  13539. }
  13540. serial_checked = true;
  13541. }
  13542. return true;
  13543. });
  13544. auto res = cli.Get("/test");
  13545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13546. EXPECT_TRUE(serial_checked);
  13547. }
  13548. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  13549. // Test 1: Valid CA file - no error should be recorded
  13550. {
  13551. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13552. CLIENT_CA_CERT_FILE);
  13553. ASSERT_TRUE(svr.is_valid());
  13554. // With valid setup, last_ssl_error should be 0
  13555. EXPECT_EQ(0, svr.ssl_last_error());
  13556. }
  13557. // Test 2: Invalid CA file content
  13558. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  13559. {
  13560. // Create a temporary file with completely invalid content
  13561. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  13562. {
  13563. std::ofstream ofs(temp_invalid_ca);
  13564. ofs << "This is not a certificate file at all\n";
  13565. ofs << "Just plain text content\n";
  13566. }
  13567. // Create server with invalid CA file
  13568. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  13569. // Clean up temporary file
  13570. std::remove(temp_invalid_ca);
  13571. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  13572. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  13573. // Note: SSL_CTX_load_verify_locations typically fails first,
  13574. // but our error handling code path is still exercised
  13575. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  13576. }
  13577. }
  13578. TEST(VerifyCallbackTest, VerifyContextFields) {
  13579. using namespace httplib::tls;
  13580. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13581. ASSERT_TRUE(svr.is_valid());
  13582. svr.Get("/test", [](const Request &, Response &res) {
  13583. res.set_content("ok", "text/plain");
  13584. });
  13585. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13586. auto se = detail::scope_exit([&] {
  13587. svr.stop();
  13588. t.join();
  13589. });
  13590. svr.wait_until_ready();
  13591. SSLClient cli(HOST, PORT);
  13592. cli.enable_server_certificate_verification(false);
  13593. cli.set_connection_timeout(30);
  13594. int callback_count = 0;
  13595. bool saw_leaf_cert = false;
  13596. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13597. if (ctx.cert) {
  13598. callback_count++;
  13599. // We should see at least one certificate (the leaf)
  13600. std::string cn = ctx.subject_cn();
  13601. if (!cn.empty()) { saw_leaf_cert = true; }
  13602. // Verify context fields are populated
  13603. EXPECT_NE(ctx.session, nullptr);
  13604. EXPECT_GE(ctx.depth, 0);
  13605. }
  13606. return true;
  13607. });
  13608. auto res = cli.Get("/test");
  13609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13610. EXPECT_GT(callback_count, 0);
  13611. EXPECT_TRUE(saw_leaf_cert);
  13612. }
  13613. // A verifier belongs to the client that set it, not to the thread that set it.
  13614. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  13615. using namespace httplib::tls;
  13616. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13617. ASSERT_TRUE(svr.is_valid());
  13618. svr.Get("/test", [](const Request &, Response &res) {
  13619. res.set_content("ok", "text/plain");
  13620. });
  13621. auto port = svr.bind_to_any_port(HOST);
  13622. thread t([&]() { svr.listen_after_bind(); });
  13623. auto se = detail::scope_exit([&] {
  13624. svr.stop();
  13625. t.join();
  13626. });
  13627. svr.wait_until_ready();
  13628. auto rejecting_calls = 0;
  13629. SSLClient rejecting(HOST, port);
  13630. rejecting.enable_server_certificate_verification(false);
  13631. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  13632. rejecting_calls++;
  13633. return false;
  13634. });
  13635. auto accepting_calls = 0;
  13636. SSLClient accepting(HOST, port);
  13637. accepting.enable_server_certificate_verification(false);
  13638. // Set on another thread than the requests below.
  13639. thread([&]() {
  13640. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  13641. accepting_calls++;
  13642. return true;
  13643. });
  13644. }).join();
  13645. // Requested on another thread than the verifier was set on.
  13646. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  13647. EXPECT_GT(rejecting_calls, 0);
  13648. auto res = accepting.Get("/test");
  13649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13650. EXPECT_GT(accepting_calls, 0);
  13651. }
  13652. // VerifyContext::session is the same handle the other tls:: functions take.
  13653. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  13654. using namespace httplib::tls;
  13655. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13656. ASSERT_TRUE(svr.is_valid());
  13657. svr.Get("/test", [](const Request &, Response &res) {
  13658. res.set_content("ok", "text/plain");
  13659. });
  13660. auto port = svr.bind_to_any_port(HOST);
  13661. thread t([&]() { svr.listen_after_bind(); });
  13662. auto se = detail::scope_exit([&] {
  13663. svr.stop();
  13664. t.join();
  13665. });
  13666. svr.wait_until_ready();
  13667. SSLClient cli(HOST, port);
  13668. cli.enable_server_certificate_verification(false);
  13669. session_t verifier_session = nullptr;
  13670. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  13671. verifier_session = ctx.session;
  13672. return true;
  13673. });
  13674. session_t session_verifier_session = nullptr;
  13675. cli.set_session_verifier([&](session_t session) {
  13676. session_verifier_session = session;
  13677. return SSLVerifierResponse::NoDecisionMade;
  13678. });
  13679. auto res = cli.Get("/test");
  13680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13681. EXPECT_NE(nullptr, verifier_session);
  13682. EXPECT_EQ(session_verifier_session, verifier_session);
  13683. }
  13684. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  13685. using httplib::tls::TlsError;
  13686. // Test that verify_error_to_string returns empty for success
  13687. std::string success_str = TlsError::verify_error_to_string(0);
  13688. EXPECT_TRUE(success_str.empty());
  13689. // Test that verify_error_to_string returns non-empty for error codes
  13690. // Using a common error code (certificate expired)
  13691. std::string error_str =
  13692. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  13693. EXPECT_FALSE(error_str.empty());
  13694. }
  13695. TEST(SessionVerifierTest, CertificateAccepted) {
  13696. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13697. ASSERT_TRUE(svr.is_valid());
  13698. svr.Get("/test", [](const Request &, Response &res) {
  13699. res.set_content("ok", "text/plain");
  13700. });
  13701. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13702. auto se = detail::scope_exit([&] {
  13703. svr.stop();
  13704. t.join();
  13705. });
  13706. svr.wait_until_ready();
  13707. SSLClient cli(HOST, PORT);
  13708. cli.enable_server_certificate_verification(false);
  13709. cli.set_connection_timeout(30);
  13710. bool callback_called = false;
  13711. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13712. EXPECT_NE(session, nullptr);
  13713. callback_called = true;
  13714. return SSLVerifierResponse::CertificateAccepted;
  13715. });
  13716. auto res = cli.Get("/test");
  13717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13718. EXPECT_EQ(200, res->status);
  13719. EXPECT_TRUE(callback_called);
  13720. }
  13721. TEST(SessionVerifierTest, CertificateRejected) {
  13722. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13723. ASSERT_TRUE(svr.is_valid());
  13724. svr.Get("/test", [](const Request &, Response &res) {
  13725. res.set_content("ok", "text/plain");
  13726. });
  13727. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13728. auto se = detail::scope_exit([&] {
  13729. svr.stop();
  13730. t.join();
  13731. });
  13732. svr.wait_until_ready();
  13733. SSLClient cli(HOST, PORT);
  13734. cli.enable_server_certificate_verification(false);
  13735. cli.set_connection_timeout(30);
  13736. bool callback_called = false;
  13737. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13738. EXPECT_NE(session, nullptr);
  13739. callback_called = true;
  13740. return SSLVerifierResponse::CertificateRejected;
  13741. });
  13742. auto res = cli.Get("/test");
  13743. EXPECT_FALSE(res);
  13744. EXPECT_TRUE(callback_called);
  13745. }
  13746. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  13747. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13748. ASSERT_TRUE(svr.is_valid());
  13749. svr.Get("/test", [](const Request &, Response &res) {
  13750. res.set_content("ok", "text/plain");
  13751. });
  13752. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13753. auto se = detail::scope_exit([&] {
  13754. svr.stop();
  13755. t.join();
  13756. });
  13757. svr.wait_until_ready();
  13758. // NoDecisionMade with verification disabled should succeed (no default check)
  13759. SSLClient cli(HOST, PORT);
  13760. cli.enable_server_certificate_verification(false);
  13761. cli.set_connection_timeout(30);
  13762. bool callback_called = false;
  13763. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13764. EXPECT_NE(session, nullptr);
  13765. callback_called = true;
  13766. return SSLVerifierResponse::NoDecisionMade;
  13767. });
  13768. auto res = cli.Get("/test");
  13769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13770. EXPECT_EQ(200, res->status);
  13771. EXPECT_TRUE(callback_called);
  13772. }
  13773. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  13774. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13775. ASSERT_TRUE(svr.is_valid());
  13776. svr.Get("/test", [](const Request &, Response &res) {
  13777. res.set_content("ok", "text/plain");
  13778. });
  13779. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13780. auto se = detail::scope_exit([&] {
  13781. svr.stop();
  13782. t.join();
  13783. });
  13784. svr.wait_until_ready();
  13785. // NoDecisionMade with verification enabled should fail (self-signed cert).
  13786. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  13787. // so we only check that the request fails, not whether the callback was
  13788. // called.
  13789. SSLClient cli(HOST, PORT);
  13790. cli.enable_server_certificate_verification(true);
  13791. cli.set_connection_timeout(30);
  13792. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13793. EXPECT_NE(session, nullptr);
  13794. return SSLVerifierResponse::NoDecisionMade;
  13795. });
  13796. auto res = cli.Get("/test");
  13797. EXPECT_FALSE(res);
  13798. }
  13799. TEST(SSLClientServerTest, ClientCAListFromPem) {
  13800. // Test SSL server using PemMemory constructor with client CA certificates
  13801. // Read PEM files
  13802. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13803. read_file(SERVER_CERT_FILE, server_cert_pem);
  13804. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13805. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13806. // Create SSLServer with PemMemory constructor including client CA
  13807. SSLServer::PemMemory server_pem = {
  13808. server_cert_pem.c_str(),
  13809. server_cert_pem.size(),
  13810. server_key_pem.c_str(),
  13811. server_key_pem.size(),
  13812. client_ca_pem.c_str(),
  13813. client_ca_pem.size(),
  13814. nullptr // no password for server key
  13815. };
  13816. SSLServer svr(server_pem);
  13817. ASSERT_TRUE(svr.is_valid());
  13818. // No SSL error should be recorded for valid setup
  13819. EXPECT_EQ(0, svr.ssl_last_error());
  13820. // Set up server endpoints
  13821. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  13822. res.set_content("ok", "text/plain");
  13823. });
  13824. // Start server in a thread
  13825. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  13826. svr.wait_until_ready();
  13827. // Connect with client certificate (using constructor with paths)
  13828. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13829. cli.enable_server_certificate_verification(false);
  13830. auto res = cli.Get("/test-pem-ca");
  13831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13832. EXPECT_EQ(200, res->status);
  13833. EXPECT_EQ("ok", res->body);
  13834. svr.stop();
  13835. server_thread.join();
  13836. }
  13837. #endif
  13838. #ifdef _WIN32
  13839. TEST(CleanupTest, WSACleanup) {
  13840. int ret = WSACleanup();
  13841. ASSERT_EQ(0, ret);
  13842. }
  13843. #endif
  13844. #ifndef CPPHTTPLIB_SSL_ENABLED
  13845. TEST(NoSSLSupport, SimpleInterface) {
  13846. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  13847. }
  13848. #endif
  13849. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  13850. TEST(InvalidScheme, SimpleInterface) {
  13851. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  13852. }
  13853. #endif
  13854. TEST(NoScheme, SimpleInterface) {
  13855. Client cli("yahoo.com:80");
  13856. ASSERT_TRUE(cli.is_valid());
  13857. }
  13858. TEST(SendAPI, SimpleInterface_Online) {
  13859. Client cli("http://yahoo.com");
  13860. Request req;
  13861. req.method = "GET";
  13862. req.path = "/";
  13863. auto res = cli.send(req);
  13864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13865. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13866. }
  13867. TEST(SendAPI, WithParamsInRequest) {
  13868. Server svr;
  13869. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  13870. EXPECT_TRUE(req.has_param("test"));
  13871. EXPECT_EQ("test_value", req.get_param_value("test"));
  13872. });
  13873. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13874. auto se = detail::scope_exit([&] {
  13875. svr.stop();
  13876. t.join();
  13877. ASSERT_FALSE(svr.is_running());
  13878. });
  13879. svr.wait_until_ready();
  13880. Client cli(HOST, PORT);
  13881. {
  13882. Request req;
  13883. req.method = "GET";
  13884. req.path = "/";
  13885. req.params.emplace("test", "test_value");
  13886. auto res = cli.send(req);
  13887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13888. }
  13889. {
  13890. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  13891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13892. }
  13893. }
  13894. TEST(ClientImplMethods, GetSocketTest) {
  13895. httplib::Server svr;
  13896. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  13897. res.status = StatusCode::OK_200;
  13898. });
  13899. auto port = svr.bind_to_any_port("127.0.0.1");
  13900. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13901. auto se = detail::scope_exit([&] {
  13902. svr.stop();
  13903. thread.join();
  13904. ASSERT_FALSE(svr.is_running());
  13905. });
  13906. svr.wait_until_ready();
  13907. {
  13908. httplib::Client cli("127.0.0.1", port);
  13909. cli.set_keep_alive(true);
  13910. // Use the behavior of cpp-httplib of opening the connection
  13911. // only when the first request happens. If that changes,
  13912. // this test would be obsolete.
  13913. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  13914. // This also implicitly tests the server. But other tests would fail much
  13915. // earlier than this one to be considered.
  13916. auto res = cli.Get("/");
  13917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13918. EXPECT_EQ(StatusCode::OK_200, res->status);
  13919. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  13920. }
  13921. }
  13922. #ifdef CPPHTTPLIB_SSL_ENABLED
  13923. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  13924. Client cli("http://yahoo.com");
  13925. auto res = cli.Get("/");
  13926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13927. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13928. cli.set_follow_location(true);
  13929. res = cli.Get("/");
  13930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13931. EXPECT_EQ(StatusCode::OK_200, res->status);
  13932. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13933. }
  13934. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  13935. Client cli("https://yahoo.com");
  13936. auto res = cli.Get("/");
  13937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13938. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13939. cli.set_follow_location(true);
  13940. res = cli.Get("/");
  13941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13942. EXPECT_EQ(StatusCode::OK_200, res->status);
  13943. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13944. }
  13945. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  13946. Client cli("https://yahoo.com");
  13947. auto res = cli.Get("/");
  13948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13949. ASSERT_FALSE(!res);
  13950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13951. ASSERT_FALSE(res == nullptr);
  13952. ASSERT_TRUE(res != nullptr);
  13953. EXPECT_EQ(Error::Success, res.error());
  13954. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  13955. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  13956. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13957. cli.set_follow_location(true);
  13958. res = cli.Get("/");
  13959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13960. EXPECT_EQ(Error::Success, res.error());
  13961. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  13962. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  13963. EXPECT_EQ(StatusCode::OK_200, res->status);
  13964. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13965. }
  13966. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13967. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  13968. Client cli("https://cdnjs.cloudflare.com");
  13969. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  13970. Headers{{"Accept-Encoding", "br"}});
  13971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13972. EXPECT_EQ(StatusCode::OK_200, res->status);
  13973. EXPECT_EQ(287630U, res->body.size());
  13974. EXPECT_EQ("application/javascript; charset=utf-8",
  13975. res->get_header_value("Content-Type"));
  13976. }
  13977. #endif
  13978. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  13979. #undef REDIR_HOST // Silence compiler warning
  13980. #define REDIR_HOST "https://httpbingo.org"
  13981. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  13982. Client cli(REDIR_HOST);
  13983. cli.set_follow_location(true);
  13984. auto res =
  13985. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  13986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13987. EXPECT_EQ(StatusCode::OK_200, res->status);
  13988. }
  13989. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  13990. Client cli(REDIR_HOST);
  13991. cli.set_follow_location(true);
  13992. Params params;
  13993. params.emplace("url", "http://example.com");
  13994. params.emplace("status_code", "302");
  13995. auto res = cli.Get(REDIR_PATH, params, Headers{});
  13996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13997. EXPECT_EQ(StatusCode::OK_200, res->status);
  13998. }
  13999. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  14000. Client cli(REDIR_HOST);
  14001. cli.set_follow_location(true);
  14002. Params params;
  14003. params.emplace("url", "http://example.com");
  14004. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  14005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14006. EXPECT_EQ(StatusCode::OK_200, res->status);
  14007. }
  14008. TEST(HttpToHttpsRedirectTest, CertFile) {
  14009. auto ssl_port = PORT + 1;
  14010. Server svr;
  14011. ASSERT_TRUE(svr.is_valid());
  14012. svr.Get("/index", [&](const Request &, Response &res) {
  14013. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14014. "/index");
  14015. svr.stop();
  14016. });
  14017. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14018. ASSERT_TRUE(ssl_svr.is_valid());
  14019. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  14020. res.set_content("test", "text/plain");
  14021. ssl_svr.stop();
  14022. });
  14023. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14024. thread t2 =
  14025. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  14026. auto se = detail::scope_exit([&] {
  14027. t2.join();
  14028. t.join();
  14029. ASSERT_FALSE(svr.is_running());
  14030. });
  14031. svr.wait_until_ready();
  14032. ssl_svr.wait_until_ready();
  14033. Client cli("127.0.0.1", PORT);
  14034. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14035. cli.enable_server_certificate_verification(true);
  14036. cli.set_follow_location(true);
  14037. cli.set_connection_timeout(30);
  14038. auto res = cli.Get("/index");
  14039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14040. ASSERT_EQ(StatusCode::OK_200, res->status);
  14041. }
  14042. TEST(SSLClientRedirectTest, CertFile) {
  14043. auto ssl_port = PORT + 1;
  14044. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14045. ASSERT_TRUE(ssl_svr1.is_valid());
  14046. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14047. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14048. "/index");
  14049. ssl_svr1.stop();
  14050. });
  14051. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14052. ASSERT_TRUE(ssl_svr2.is_valid());
  14053. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14054. res.set_content("test", "text/plain");
  14055. ssl_svr2.stop();
  14056. });
  14057. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14058. thread t2 =
  14059. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14060. auto se = detail::scope_exit([&] {
  14061. t2.join();
  14062. t.join();
  14063. ASSERT_FALSE(ssl_svr1.is_running());
  14064. });
  14065. ssl_svr1.wait_until_ready();
  14066. ssl_svr2.wait_until_ready();
  14067. SSLClient cli("127.0.0.1", PORT);
  14068. std::string cert;
  14069. read_file(SERVER_CERT2_FILE, cert);
  14070. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14071. cli.enable_server_certificate_verification(true);
  14072. cli.set_follow_location(true);
  14073. cli.set_connection_timeout(30);
  14074. auto res = cli.Get("/index");
  14075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14076. ASSERT_EQ(StatusCode::OK_200, res->status);
  14077. }
  14078. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  14079. // another port, so the client follows it with a new client.
  14080. static Result GetThroughTlsRedirectToDifferentPort(
  14081. const std::function<void(SSLClient &)> &setup,
  14082. const char *target_cert = SERVER_CERT2_FILE) {
  14083. auto ssl_port = PORT + 1;
  14084. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14085. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14086. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14087. "/index");
  14088. });
  14089. SSLServer ssl_svr2(target_cert, SERVER_PRIVATE_KEY_FILE);
  14090. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14091. res.set_content("test", "text/plain");
  14092. });
  14093. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  14094. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  14095. auto se = detail::scope_exit([&] {
  14096. ssl_svr2.stop();
  14097. ssl_svr1.stop();
  14098. t2.join();
  14099. t.join();
  14100. });
  14101. ssl_svr1.wait_until_ready();
  14102. ssl_svr2.wait_until_ready();
  14103. SSLClient cli("127.0.0.1", PORT);
  14104. cli.set_follow_location(true);
  14105. cli.set_connection_timeout(30);
  14106. setup(cli);
  14107. return cli.Get("/index");
  14108. }
  14109. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  14110. auto calls = 0;
  14111. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  14112. cli.enable_server_certificate_verification(false);
  14113. // Accept the first server only.
  14114. cli.set_session_verifier([&](tls::session_t) {
  14115. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  14116. : SSLVerifierResponse::CertificateRejected;
  14117. });
  14118. });
  14119. EXPECT_FALSE(res);
  14120. EXPECT_EQ(2, calls);
  14121. }
  14122. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  14123. std::string pinned;
  14124. auto res = GetThroughTlsRedirectToDifferentPort(
  14125. [&](SSLClient &cli) {
  14126. cli.enable_server_certificate_verification(false);
  14127. // Pin the first certificate seen.
  14128. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  14129. if (pinned.empty()) { pinned = ctx.serial(); }
  14130. return ctx.serial() == pinned;
  14131. });
  14132. },
  14133. // A certificate other than the first server's.
  14134. SERVER_CERT_FILE);
  14135. EXPECT_FALSE(res);
  14136. EXPECT_FALSE(pinned.empty());
  14137. }
  14138. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  14139. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  14140. std::string cert;
  14141. read_file(SERVER_CERT2_FILE, cert);
  14142. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14143. });
  14144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14145. EXPECT_EQ(StatusCode::OK_200, res->status);
  14146. }
  14147. #endif
  14148. #ifdef CPPHTTPLIB_SSL_ENABLED
  14149. // Test that set_ca_cert_store() skips system certs (consistent with
  14150. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  14151. // should be trusted - system certs should NOT be loaded.
  14152. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  14153. // Load a specific cert that is NOT a system CA cert
  14154. std::string cert;
  14155. read_file(SERVER_CERT2_FILE, cert);
  14156. SSLClient cli("google.com");
  14157. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14158. cli.enable_server_certificate_verification(true);
  14159. // This should FAIL because:
  14160. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  14161. // 2. System certs should NOT be loaded when custom store is set
  14162. // If system certs WERE loaded, this would succeed
  14163. auto res = cli.Get("/");
  14164. ASSERT_FALSE(res);
  14165. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14166. }
  14167. // Same as above, but through the native store handle path. Regression test:
  14168. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  14169. // merged system certs into the user-provided store.
  14170. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  14171. std::string cert;
  14172. read_file(SERVER_CERT2_FILE, cert);
  14173. SSLClient cli("google.com");
  14174. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14175. cli.enable_server_certificate_verification(true);
  14176. auto res = cli.Get("/");
  14177. ASSERT_FALSE(res);
  14178. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14179. }
  14180. // A custom store set via the native handle must still verify a server whose
  14181. // cert it does contain.
  14182. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  14183. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14184. ASSERT_TRUE(svr.is_valid());
  14185. svr.Get("/test", [&](const Request &, Response &res) {
  14186. res.set_content("test", "text/plain");
  14187. });
  14188. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14189. auto se = detail::scope_exit([&] {
  14190. svr.stop();
  14191. t.join();
  14192. ASSERT_FALSE(svr.is_running());
  14193. });
  14194. svr.wait_until_ready();
  14195. SSLClient cli("127.0.0.1", PORT);
  14196. std::string cert;
  14197. read_file(SERVER_CERT2_FILE, cert);
  14198. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14199. cli.enable_server_certificate_verification(true);
  14200. cli.set_connection_timeout(30);
  14201. auto res = cli.Get("/test");
  14202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14203. ASSERT_EQ(StatusCode::OK_200, res->status);
  14204. }
  14205. // CA certs loaded through the universal Client must be transferred to the
  14206. // client created internally for following an HTTPS redirect. Regression test:
  14207. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  14208. // the CA data for redirect transfer.
  14209. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  14210. auto ssl_port = PORT + 1;
  14211. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14212. ASSERT_TRUE(ssl_svr1.is_valid());
  14213. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14214. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14215. "/index");
  14216. });
  14217. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14218. ASSERT_TRUE(ssl_svr2.is_valid());
  14219. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14220. res.set_content("test", "text/plain");
  14221. });
  14222. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14223. thread t2 =
  14224. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14225. auto se = detail::scope_exit([&] {
  14226. ssl_svr2.stop();
  14227. ssl_svr1.stop();
  14228. t2.join();
  14229. t.join();
  14230. ASSERT_FALSE(ssl_svr1.is_running());
  14231. });
  14232. ssl_svr1.wait_until_ready();
  14233. ssl_svr2.wait_until_ready();
  14234. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14235. std::string cert;
  14236. read_file(SERVER_CERT2_FILE, cert);
  14237. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14238. cli.enable_server_certificate_verification(true);
  14239. cli.set_follow_location(true);
  14240. cli.set_connection_timeout(30);
  14241. auto res = cli.Get("/index");
  14242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14243. ASSERT_EQ(StatusCode::OK_200, res->status);
  14244. }
  14245. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  14246. // so a host signed by a system CA verifies even though a custom CA is set
  14247. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  14248. std::string cert;
  14249. read_file(SERVER_CERT2_FILE, cert);
  14250. SSLClient cli("google.com");
  14251. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14252. cli.enable_system_ca(true);
  14253. cli.enable_server_certificate_verification(true);
  14254. auto res = cli.Get("/");
  14255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14256. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14257. }
  14258. // The custom CA remains effective when combined with the system CA
  14259. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  14260. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14261. ASSERT_TRUE(svr.is_valid());
  14262. svr.Get("/test", [&](const Request &, Response &res) {
  14263. res.set_content("test", "text/plain");
  14264. });
  14265. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14266. auto se = detail::scope_exit([&] {
  14267. svr.stop();
  14268. t.join();
  14269. ASSERT_FALSE(svr.is_running());
  14270. });
  14271. svr.wait_until_ready();
  14272. SSLClient cli("127.0.0.1", PORT);
  14273. std::string cert;
  14274. read_file(SERVER_CERT2_FILE, cert);
  14275. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14276. cli.enable_system_ca(true);
  14277. cli.enable_server_certificate_verification(true);
  14278. cli.set_connection_timeout(30);
  14279. auto res = cli.Get("/test");
  14280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14281. ASSERT_EQ(StatusCode::OK_200, res->status);
  14282. }
  14283. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  14284. // skip chain verification entirely (only the certificate identity was
  14285. // checked), so a server presenting an untrusted certificate with a matching
  14286. // IP SAN was accepted. The chain must be validated for IP hosts too.
  14287. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  14288. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14289. ASSERT_TRUE(svr.is_valid());
  14290. svr.Get("/test", [&](const Request &, Response &res) {
  14291. res.set_content("test", "text/plain");
  14292. });
  14293. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14294. auto se = detail::scope_exit([&] {
  14295. svr.stop();
  14296. t.join();
  14297. ASSERT_FALSE(svr.is_running());
  14298. });
  14299. svr.wait_until_ready();
  14300. SSLClient cli("127.0.0.1", PORT);
  14301. std::string cert;
  14302. // A trusted CA that did not sign the server certificate. The server cert
  14303. // (cert2) carries the matching IP SAN, so only chain validation can reject
  14304. // this connection.
  14305. read_file(CLIENT_CA_CERT_FILE, cert);
  14306. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14307. cli.enable_server_certificate_verification(true);
  14308. cli.set_connection_timeout(30);
  14309. auto res = cli.Get("/test");
  14310. ASSERT_FALSE(res);
  14311. }
  14312. // enable_system_ca(false) prevents system CA loading entirely
  14313. TEST(SSLClientTest, DisableSystemCa_Online) {
  14314. SSLClient cli("google.com");
  14315. cli.enable_system_ca(false);
  14316. cli.enable_server_certificate_verification(true);
  14317. auto res = cli.Get("/");
  14318. ASSERT_FALSE(res);
  14319. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  14320. // itself when the CA chain is empty
  14321. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  14322. res.error() == Error::SSLConnection);
  14323. }
  14324. // The universal Client forwards enable_system_ca()
  14325. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  14326. std::string cert;
  14327. read_file(SERVER_CERT2_FILE, cert);
  14328. Client cli("https://google.com");
  14329. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14330. cli.enable_system_ca(true);
  14331. cli.enable_server_certificate_verification(true);
  14332. auto res = cli.Get("/");
  14333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14334. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14335. }
  14336. // The system CA policy must carry over to the client created internally for
  14337. // following a cross-host HTTPS redirect
  14338. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  14339. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14340. ASSERT_TRUE(svr.is_valid());
  14341. svr.Get("/index", [&](const Request &, Response &res) {
  14342. res.set_redirect("https://www.google.com/");
  14343. });
  14344. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14345. auto se = detail::scope_exit([&] {
  14346. svr.stop();
  14347. t.join();
  14348. ASSERT_FALSE(svr.is_running());
  14349. });
  14350. svr.wait_until_ready();
  14351. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14352. std::string cert;
  14353. read_file(SERVER_CERT2_FILE, cert);
  14354. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14355. cli.enable_system_ca(true);
  14356. cli.enable_server_certificate_verification(true);
  14357. cli.set_follow_location(true);
  14358. cli.set_connection_timeout(30);
  14359. // Receiving any response proves the redirect client completed the TLS
  14360. // handshake with a system-CA-signed host
  14361. auto res = cli.Get("/index");
  14362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14363. }
  14364. TEST(MultipartFormDataTest, LargeData) {
  14365. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14366. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  14367. const ContentReader &content_reader) {
  14368. if (req.is_multipart_form_data()) {
  14369. std::vector<FormData> items;
  14370. content_reader(
  14371. [&](const FormData &file) {
  14372. items.push_back(file);
  14373. return true;
  14374. },
  14375. [&](const char *data, size_t data_length) {
  14376. items.back().content.append(data, data_length);
  14377. return true;
  14378. });
  14379. EXPECT_TRUE(std::string(items[0].name) == "document");
  14380. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14381. EXPECT_TRUE(items[0].filename == "2MB_data");
  14382. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14383. EXPECT_TRUE(items[1].name == "hello");
  14384. EXPECT_TRUE(items[1].content == "world");
  14385. EXPECT_TRUE(items[1].filename == "");
  14386. EXPECT_TRUE(items[1].content_type == "");
  14387. } else {
  14388. std::string body;
  14389. content_reader([&](const char *data, size_t data_length) {
  14390. body.append(data, data_length);
  14391. return true;
  14392. });
  14393. }
  14394. });
  14395. auto port = svr.bind_to_any_port(HOST);
  14396. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14397. auto se = detail::scope_exit([&] {
  14398. svr.stop();
  14399. t.join();
  14400. ASSERT_FALSE(svr.is_running());
  14401. });
  14402. svr.wait_until_ready();
  14403. {
  14404. std::string data(1024 * 1024 * 2, '.');
  14405. std::stringstream buffer;
  14406. buffer << data;
  14407. SSLClient cli(HOST, port);
  14408. cli.enable_server_certificate_verification(false);
  14409. UploadFormDataItems items{
  14410. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14411. {"hello", "world", "", ""},
  14412. };
  14413. auto res = cli.Post("/post", items);
  14414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14415. ASSERT_EQ(StatusCode::OK_200, res->status);
  14416. }
  14417. }
  14418. TEST(MultipartFormDataTest, DataProviderItems) {
  14419. std::random_device seed_gen;
  14420. std::mt19937 random(seed_gen());
  14421. std::string rand1;
  14422. rand1.resize(1000);
  14423. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  14424. std::string rand2;
  14425. rand2.resize(3000);
  14426. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  14427. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14428. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  14429. const ContentReader &content_reader) {
  14430. ASSERT_FALSE(req.is_multipart_form_data());
  14431. std::string body;
  14432. content_reader([&](const char *data, size_t data_length) {
  14433. body.append(data, data_length);
  14434. return true;
  14435. });
  14436. EXPECT_EQ(body, "");
  14437. });
  14438. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  14439. const ContentReader &content_reader) {
  14440. ASSERT_TRUE(req.is_multipart_form_data());
  14441. std::vector<FormData> items;
  14442. content_reader(
  14443. [&](const FormData &file) {
  14444. items.push_back(file);
  14445. return true;
  14446. },
  14447. [&](const char *data, size_t data_length) {
  14448. items.back().content.append(data, data_length);
  14449. return true;
  14450. });
  14451. ASSERT_TRUE(items.size() == 2);
  14452. EXPECT_EQ(std::string(items[0].name), "name1");
  14453. EXPECT_EQ(items[0].content, "Testing123");
  14454. EXPECT_EQ(items[0].filename, "filename1");
  14455. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14456. EXPECT_EQ(items[1].name, "name2");
  14457. EXPECT_EQ(items[1].content, "Testing456");
  14458. EXPECT_EQ(items[1].filename, "");
  14459. EXPECT_EQ(items[1].content_type, "");
  14460. });
  14461. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  14462. const ContentReader &content_reader) {
  14463. ASSERT_TRUE(req.is_multipart_form_data());
  14464. std::vector<FormData> items;
  14465. content_reader(
  14466. [&](const FormData &file) {
  14467. items.push_back(file);
  14468. return true;
  14469. },
  14470. [&](const char *data, size_t data_length) {
  14471. items.back().content.append(data, data_length);
  14472. return true;
  14473. });
  14474. ASSERT_TRUE(items.size() == 2);
  14475. EXPECT_EQ(items[0].name, "name3");
  14476. EXPECT_EQ(items[0].content, rand1);
  14477. EXPECT_EQ(items[0].filename, "filename3");
  14478. EXPECT_EQ(items[0].content_type, "");
  14479. EXPECT_EQ(items[1].name, "name4");
  14480. EXPECT_EQ(items[1].content, rand2);
  14481. EXPECT_EQ(items[1].filename, "filename4");
  14482. EXPECT_EQ(items[1].content_type, "");
  14483. });
  14484. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  14485. const ContentReader &content_reader) {
  14486. ASSERT_TRUE(req.is_multipart_form_data());
  14487. std::vector<FormData> items;
  14488. content_reader(
  14489. [&](const FormData &file) {
  14490. items.push_back(file);
  14491. return true;
  14492. },
  14493. [&](const char *data, size_t data_length) {
  14494. items.back().content.append(data, data_length);
  14495. return true;
  14496. });
  14497. ASSERT_TRUE(items.size() == 4);
  14498. EXPECT_EQ(std::string(items[0].name), "name1");
  14499. EXPECT_EQ(items[0].content, "Testing123");
  14500. EXPECT_EQ(items[0].filename, "filename1");
  14501. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14502. EXPECT_EQ(items[1].name, "name2");
  14503. EXPECT_EQ(items[1].content, "Testing456");
  14504. EXPECT_EQ(items[1].filename, "");
  14505. EXPECT_EQ(items[1].content_type, "");
  14506. EXPECT_EQ(items[2].name, "name3");
  14507. EXPECT_EQ(items[2].content, rand1);
  14508. EXPECT_EQ(items[2].filename, "filename3");
  14509. EXPECT_EQ(items[2].content_type, "");
  14510. EXPECT_EQ(items[3].name, "name4");
  14511. EXPECT_EQ(items[3].content, rand2);
  14512. EXPECT_EQ(items[3].filename, "filename4");
  14513. EXPECT_EQ(items[3].content_type, "");
  14514. });
  14515. auto port = svr.bind_to_any_port("localhost");
  14516. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14517. auto se = detail::scope_exit([&] {
  14518. svr.stop();
  14519. t.join();
  14520. ASSERT_FALSE(svr.is_running());
  14521. });
  14522. svr.wait_until_ready();
  14523. {
  14524. SSLClient cli("localhost", port);
  14525. cli.enable_server_certificate_verification(false);
  14526. UploadFormDataItems items{
  14527. {"name1", "Testing123", "filename1", "application/octet-stream"},
  14528. {"name2", "Testing456", "", ""}, // not a file
  14529. };
  14530. {
  14531. auto res = cli.Post("/post-none", {}, {}, {});
  14532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14533. ASSERT_EQ(StatusCode::OK_200, res->status);
  14534. }
  14535. FormDataProviderItems providers;
  14536. {
  14537. auto res =
  14538. cli.Post("/post-items", {}, items, providers); // empty providers
  14539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14540. ASSERT_EQ(StatusCode::OK_200, res->status);
  14541. }
  14542. providers.push_back({"name3",
  14543. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14544. // test the offset is given correctly at each step
  14545. if (!offset)
  14546. sink.os.write(rand1.data(), 30);
  14547. else if (offset == 30)
  14548. sink.os.write(rand1.data() + 30, 300);
  14549. else if (offset == 330)
  14550. sink.os.write(rand1.data() + 330, 670);
  14551. else if (offset == rand1.size())
  14552. sink.done();
  14553. return true;
  14554. },
  14555. "filename3",
  14556. {}});
  14557. providers.push_back({"name4",
  14558. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14559. // test the offset is given correctly at each step
  14560. if (!offset)
  14561. sink.os.write(rand2.data(), 2000);
  14562. else if (offset == 2000)
  14563. sink.os.write(rand2.data() + 2000, 1);
  14564. else if (offset == 2001)
  14565. sink.os.write(rand2.data() + 2001, 999);
  14566. else if (offset == rand2.size())
  14567. sink.done();
  14568. return true;
  14569. },
  14570. "filename4",
  14571. {}});
  14572. {
  14573. auto res = cli.Post("/post-providers", {}, {}, providers);
  14574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14575. ASSERT_EQ(StatusCode::OK_200, res->status);
  14576. }
  14577. {
  14578. auto res = cli.Post("/post-both", {}, items, providers);
  14579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14580. ASSERT_EQ(StatusCode::OK_200, res->status);
  14581. }
  14582. }
  14583. }
  14584. TEST(MultipartFormDataTest, BadHeader) {
  14585. Server svr;
  14586. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14587. res.set_content("ok", "text/plain");
  14588. });
  14589. thread t = thread([&] { svr.listen(HOST, PORT); });
  14590. auto se = detail::scope_exit([&] {
  14591. svr.stop();
  14592. t.join();
  14593. ASSERT_FALSE(svr.is_running());
  14594. });
  14595. svr.wait_until_ready();
  14596. const std::string body =
  14597. "This is the preamble. It is to be ignored, though it\r\n"
  14598. "is a handy place for composition agents to include an\r\n"
  14599. "explanatory note to non-MIME conformant readers.\r\n"
  14600. "\r\n"
  14601. "\r\n"
  14602. "--simple boundary\r\n"
  14603. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14604. ": BAD...\r\n"
  14605. "\r\n"
  14606. "value1\r\n"
  14607. "--simple boundary\r\n"
  14608. "Content-Disposition: form-data; name=\"field2\"; "
  14609. "filename=\"example.txt\"\r\n"
  14610. "\r\n"
  14611. "value2\r\n"
  14612. "--simple boundary--\r\n"
  14613. "This is the epilogue. It is also to be ignored.\r\n";
  14614. std::string content_type =
  14615. R"(multipart/form-data; boundary="simple boundary")";
  14616. Client cli(HOST, PORT);
  14617. auto res = cli.Post("/post", body, content_type.c_str());
  14618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14619. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14620. }
  14621. TEST(MultipartFormDataTest, WithPreamble) {
  14622. Server svr;
  14623. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14624. res.set_content("ok", "text/plain");
  14625. });
  14626. thread t = thread([&] { svr.listen(HOST, PORT); });
  14627. auto se = detail::scope_exit([&] {
  14628. svr.stop();
  14629. t.join();
  14630. ASSERT_FALSE(svr.is_running());
  14631. });
  14632. svr.wait_until_ready();
  14633. const std::string body =
  14634. "This is the preamble. It is to be ignored, though it\r\n"
  14635. "is a handy place for composition agents to include an\r\n"
  14636. "explanatory note to non-MIME conformant readers.\r\n"
  14637. "\r\n"
  14638. "\r\n"
  14639. "--simple boundary\r\n"
  14640. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14641. "\r\n"
  14642. "value1\r\n"
  14643. "--simple boundary\r\n"
  14644. "Content-Disposition: form-data; name=\"field2\"; "
  14645. "filename=\"example.txt\"\r\n"
  14646. "\r\n"
  14647. "value2\r\n"
  14648. "--simple boundary--\r\n"
  14649. "This is the epilogue. It is also to be ignored.\r\n";
  14650. std::string content_type =
  14651. R"(multipart/form-data; boundary="simple boundary")";
  14652. Client cli(HOST, PORT);
  14653. auto res = cli.Post("/post", body, content_type.c_str());
  14654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14655. EXPECT_EQ(StatusCode::OK_200, res->status);
  14656. }
  14657. TEST(MultipartFormDataTest, PostCustomBoundary) {
  14658. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14659. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  14660. const ContentReader &content_reader) {
  14661. if (req.is_multipart_form_data()) {
  14662. std::vector<FormData> items;
  14663. content_reader(
  14664. [&](const FormData &file) {
  14665. items.push_back(file);
  14666. return true;
  14667. },
  14668. [&](const char *data, size_t data_length) {
  14669. items.back().content.append(data, data_length);
  14670. return true;
  14671. });
  14672. EXPECT_TRUE(std::string(items[0].name) == "document");
  14673. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14674. EXPECT_TRUE(items[0].filename == "2MB_data");
  14675. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14676. EXPECT_TRUE(items[1].name == "hello");
  14677. EXPECT_TRUE(items[1].content == "world");
  14678. EXPECT_TRUE(items[1].filename == "");
  14679. EXPECT_TRUE(items[1].content_type == "");
  14680. } else {
  14681. std::string body;
  14682. content_reader([&](const char *data, size_t data_length) {
  14683. body.append(data, data_length);
  14684. return true;
  14685. });
  14686. }
  14687. });
  14688. auto port = svr.bind_to_any_port("localhost");
  14689. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14690. auto se = detail::scope_exit([&] {
  14691. svr.stop();
  14692. t.join();
  14693. ASSERT_FALSE(svr.is_running());
  14694. });
  14695. svr.wait_until_ready();
  14696. {
  14697. std::string data(1024 * 1024 * 2, '.');
  14698. std::stringstream buffer;
  14699. buffer << data;
  14700. SSLClient cli("localhost", port);
  14701. cli.enable_server_certificate_verification(false);
  14702. UploadFormDataItems items{
  14703. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14704. {"hello", "world", "", ""},
  14705. };
  14706. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  14707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14708. ASSERT_EQ(StatusCode::OK_200, res->status);
  14709. }
  14710. }
  14711. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  14712. std::string data(1024 * 1024 * 2, '&');
  14713. std::stringstream buffer;
  14714. buffer << data;
  14715. Client cli("https://localhost:8080");
  14716. UploadFormDataItems items{
  14717. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14718. {"hello", "world", "", ""},
  14719. };
  14720. for (const char &c : " \t\r\n") {
  14721. auto res =
  14722. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  14723. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14724. ASSERT_FALSE(res);
  14725. }
  14726. }
  14727. TEST(MultipartFormDataTest, PutFormData) {
  14728. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14729. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  14730. const ContentReader &content_reader) {
  14731. if (req.is_multipart_form_data()) {
  14732. std::vector<FormData> items;
  14733. content_reader(
  14734. [&](const FormData &file) {
  14735. items.push_back(file);
  14736. return true;
  14737. },
  14738. [&](const char *data, size_t data_length) {
  14739. items.back().content.append(data, data_length);
  14740. return true;
  14741. });
  14742. EXPECT_TRUE(std::string(items[0].name) == "document");
  14743. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14744. EXPECT_TRUE(items[0].filename == "2MB_data");
  14745. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14746. EXPECT_TRUE(items[1].name == "hello");
  14747. EXPECT_TRUE(items[1].content == "world");
  14748. EXPECT_TRUE(items[1].filename == "");
  14749. EXPECT_TRUE(items[1].content_type == "");
  14750. } else {
  14751. std::string body;
  14752. content_reader([&](const char *data, size_t data_length) {
  14753. body.append(data, data_length);
  14754. return true;
  14755. });
  14756. }
  14757. });
  14758. auto port = svr.bind_to_any_port("localhost");
  14759. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14760. auto se = detail::scope_exit([&] {
  14761. svr.stop();
  14762. t.join();
  14763. ASSERT_FALSE(svr.is_running());
  14764. });
  14765. svr.wait_until_ready();
  14766. {
  14767. std::string data(1024 * 1024 * 2, '&');
  14768. std::stringstream buffer;
  14769. buffer << data;
  14770. SSLClient cli("localhost", port);
  14771. cli.enable_server_certificate_verification(false);
  14772. UploadFormDataItems items{
  14773. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14774. {"hello", "world", "", ""},
  14775. };
  14776. auto res = cli.Put("/put", items);
  14777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14778. ASSERT_EQ(StatusCode::OK_200, res->status);
  14779. }
  14780. }
  14781. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  14782. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14783. svr.Put("/put_customboundary",
  14784. [&](const Request &req, const Response & /*res*/,
  14785. const ContentReader &content_reader) {
  14786. if (req.is_multipart_form_data()) {
  14787. std::vector<FormData> items;
  14788. content_reader(
  14789. [&](const FormData &file) {
  14790. items.push_back(file);
  14791. return true;
  14792. },
  14793. [&](const char *data, size_t data_length) {
  14794. items.back().content.append(data, data_length);
  14795. return true;
  14796. });
  14797. EXPECT_TRUE(std::string(items[0].name) == "document");
  14798. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14799. EXPECT_TRUE(items[0].filename == "2MB_data");
  14800. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14801. EXPECT_TRUE(items[1].name == "hello");
  14802. EXPECT_TRUE(items[1].content == "world");
  14803. EXPECT_TRUE(items[1].filename == "");
  14804. EXPECT_TRUE(items[1].content_type == "");
  14805. } else {
  14806. std::string body;
  14807. content_reader([&](const char *data, size_t data_length) {
  14808. body.append(data, data_length);
  14809. return true;
  14810. });
  14811. }
  14812. });
  14813. auto port = svr.bind_to_any_port("localhost");
  14814. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14815. auto se = detail::scope_exit([&] {
  14816. svr.stop();
  14817. t.join();
  14818. ASSERT_FALSE(svr.is_running());
  14819. });
  14820. svr.wait_until_ready();
  14821. {
  14822. std::string data(1024 * 1024 * 2, '&');
  14823. std::stringstream buffer;
  14824. buffer << data;
  14825. SSLClient cli("localhost", port);
  14826. cli.enable_server_certificate_verification(false);
  14827. UploadFormDataItems items{
  14828. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14829. {"hello", "world", "", ""},
  14830. };
  14831. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  14832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14833. ASSERT_EQ(StatusCode::OK_200, res->status);
  14834. }
  14835. }
  14836. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  14837. std::string data(1024 * 1024 * 2, '&');
  14838. std::stringstream buffer;
  14839. buffer << data;
  14840. Client cli("https://localhost:8080");
  14841. cli.enable_server_certificate_verification(false);
  14842. UploadFormDataItems items{
  14843. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14844. {"hello", "world", "", ""},
  14845. };
  14846. for (const char &c : " \t\r\n") {
  14847. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  14848. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14849. ASSERT_FALSE(res);
  14850. }
  14851. }
  14852. TEST(MultipartFormDataTest, AlternateFilename) {
  14853. auto handled = false;
  14854. Server svr;
  14855. svr.Post("/test", [&](const Request &req, Response &res) {
  14856. ASSERT_EQ(2u, req.form.files.size());
  14857. ASSERT_EQ(1u, req.form.fields.size());
  14858. // Test files
  14859. const auto &file1 = req.form.get_file("file1");
  14860. ASSERT_EQ("file1", file1.name);
  14861. ASSERT_EQ("A.txt", file1.filename);
  14862. ASSERT_EQ("text/plain", file1.content_type);
  14863. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  14864. const auto &file2 = req.form.get_file("file2");
  14865. ASSERT_EQ("file2", file2.name);
  14866. ASSERT_EQ("a.html", file2.filename);
  14867. ASSERT_EQ("text/html", file2.content_type);
  14868. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  14869. file2.content);
  14870. // Test text field
  14871. const auto &text = req.form.get_field("text");
  14872. ASSERT_EQ("text default", text);
  14873. res.set_content("ok", "text/plain");
  14874. handled = true;
  14875. });
  14876. thread t = thread([&] { svr.listen(HOST, PORT); });
  14877. auto se = detail::scope_exit([&] {
  14878. svr.stop();
  14879. t.join();
  14880. ASSERT_FALSE(svr.is_running());
  14881. ASSERT_TRUE(handled);
  14882. });
  14883. svr.wait_until_ready();
  14884. auto req = "POST /test HTTP/1.1\r\n"
  14885. "Host: localhost\r\n"
  14886. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14887. "Content-Length: 399\r\n"
  14888. "\r\n"
  14889. "----------\r\n"
  14890. "Content-Disposition: form-data; name=\"text\"\r\n"
  14891. "\r\n"
  14892. "text default\r\n"
  14893. "----------\r\n"
  14894. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  14895. "filename=\"a.txt\"; name=\"file1\"\r\n"
  14896. "Content-Type: text/plain\r\n"
  14897. "\r\n"
  14898. "Content of a.txt.\r\n"
  14899. "\r\n"
  14900. "----------\r\n"
  14901. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  14902. "\"a.html\"\r\n"
  14903. "Content-Type: text/html\r\n"
  14904. "\r\n"
  14905. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  14906. "\r\n"
  14907. "------------\r\n";
  14908. ASSERT_TRUE(send_request(1, req));
  14909. }
  14910. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  14911. auto handled = false;
  14912. Server svr;
  14913. svr.Post("/test", [&](const Request &req, Response &res) {
  14914. // Case-insensitive "utf-8''" prefix with a long value
  14915. const auto &file = req.form.get_file("file1");
  14916. ASSERT_EQ("file1", file.name);
  14917. // 8000 chars exercises both the Content-Disposition parser and the
  14918. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  14919. // Prior to the fix, std::regex_match on this header would cause O(N)
  14920. // stack recursion in libstdc++, leading to SIGSEGV.
  14921. std::string expected_filename(8000, 'A');
  14922. ASSERT_EQ(expected_filename, file.filename);
  14923. res.set_content("ok", "text/plain");
  14924. handled = true;
  14925. });
  14926. thread t = thread([&] { svr.listen(HOST, PORT); });
  14927. auto se = detail::scope_exit([&] {
  14928. svr.stop();
  14929. t.join();
  14930. ASSERT_FALSE(svr.is_running());
  14931. ASSERT_TRUE(handled);
  14932. });
  14933. svr.wait_until_ready();
  14934. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  14935. // Regression test for GHSA-qq6v-r583-3h69
  14936. std::string long_filename(8000, 'A');
  14937. std::string body = "----------\r\n"
  14938. "Content-Disposition: form-data; name=\"file1\"; "
  14939. "filename*=\"Utf-8''" +
  14940. long_filename +
  14941. "\"\r\n"
  14942. "\r\n"
  14943. "hello\r\n"
  14944. "------------\r\n";
  14945. auto req = "POST /test HTTP/1.1\r\n"
  14946. "Host: localhost\r\n"
  14947. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14948. "Content-Length: " +
  14949. std::to_string(body.size()) + "\r\n\r\n" + body;
  14950. ASSERT_TRUE(send_request(1, req));
  14951. }
  14952. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  14953. auto handled = false;
  14954. Server svr;
  14955. svr.Post("/test", [&](const Request &req, Response &) {
  14956. ASSERT_EQ(2u, req.form.fields.size());
  14957. const auto &text1 = req.form.get_field("text1");
  14958. ASSERT_EQ("text1", text1);
  14959. const auto &text2 = req.form.get_field("text2");
  14960. ASSERT_EQ("text2", text2);
  14961. handled = true;
  14962. });
  14963. thread t = thread([&] { svr.listen(HOST, PORT); });
  14964. auto se = detail::scope_exit([&] {
  14965. svr.stop();
  14966. t.join();
  14967. ASSERT_FALSE(svr.is_running());
  14968. ASSERT_TRUE(handled);
  14969. });
  14970. svr.wait_until_ready();
  14971. auto req = "POST /test HTTP/1.1\r\n"
  14972. "Host: localhost\r\n"
  14973. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14974. "Content-Length: 146\r\n"
  14975. "\r\n----------\r\n"
  14976. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14977. "\r\n"
  14978. "text1"
  14979. "\r\n----------\r\n"
  14980. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14981. "\r\n"
  14982. "text2"
  14983. "\r\n------------";
  14984. std::string response;
  14985. ASSERT_TRUE(send_request(1, req, &response));
  14986. ASSERT_EQ("200", response.substr(9, 3));
  14987. }
  14988. TEST(MultipartFormDataTest, ContentLength) {
  14989. auto handled = false;
  14990. Server svr;
  14991. svr.Post("/test", [&](const Request &req, Response &) {
  14992. ASSERT_EQ(2u, req.form.fields.size());
  14993. const auto &text1 = req.form.get_field("text1");
  14994. ASSERT_EQ("text1", text1);
  14995. const auto &text2 = req.form.get_field("text2");
  14996. ASSERT_EQ("text2", text2);
  14997. handled = true;
  14998. });
  14999. thread t = thread([&] { svr.listen(HOST, PORT); });
  15000. auto se = detail::scope_exit([&] {
  15001. svr.stop();
  15002. t.join();
  15003. ASSERT_FALSE(svr.is_running());
  15004. ASSERT_TRUE(handled);
  15005. });
  15006. svr.wait_until_ready();
  15007. auto req = "POST /test HTTP/1.1\r\n"
  15008. "Host: localhost\r\n"
  15009. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15010. "Content-Length: 167\r\n"
  15011. "\r\n----------\r\n"
  15012. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15013. "Content-Length: 5\r\n"
  15014. "\r\n"
  15015. "text1"
  15016. "\r\n----------\r\n"
  15017. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15018. "\r\n"
  15019. "text2"
  15020. "\r\n------------\r\n";
  15021. std::string response;
  15022. ASSERT_TRUE(send_request(1, req, &response));
  15023. ASSERT_EQ("200", response.substr(9, 3));
  15024. }
  15025. TEST(MultipartFormDataTest, AccessPartHeaders) {
  15026. auto handled = false;
  15027. Server svr;
  15028. svr.Post("/test", [&](const Request &req, Response &) {
  15029. ASSERT_EQ(2u, req.form.fields.size());
  15030. const auto &text1 = req.form.get_field("text1");
  15031. ASSERT_EQ("text1", text1);
  15032. // TODO: Add header access for text fields if needed
  15033. const auto &text2 = req.form.get_field("text2");
  15034. ASSERT_EQ("text2", text2);
  15035. // TODO: Header access for text fields needs to be implemented
  15036. // auto &headers = it->second.headers;
  15037. // ASSERT_EQ(3U, headers.size());
  15038. // auto custom_header = headers.find("x-whatever");
  15039. // ASSERT_TRUE(custom_header != headers.end());
  15040. // ASSERT_NE("customvalue", custom_header->second);
  15041. // ASSERT_EQ("CustomValue", custom_header->second);
  15042. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  15043. handled = true;
  15044. });
  15045. thread t = thread([&] { svr.listen(HOST, PORT); });
  15046. auto se = detail::scope_exit([&] {
  15047. svr.stop();
  15048. t.join();
  15049. ASSERT_FALSE(svr.is_running());
  15050. ASSERT_TRUE(handled);
  15051. });
  15052. svr.wait_until_ready();
  15053. auto req = "POST /test HTTP/1.1\r\n"
  15054. "Host: localhost\r\n"
  15055. "Content-Type: multipart/form-data;boundary=--------\r\n"
  15056. "Content-Length: 232\r\n"
  15057. "\r\n----------\r\n"
  15058. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15059. "Content-Length: 5\r\n"
  15060. "X-Test: 1\r\n"
  15061. "\r\n"
  15062. "text1"
  15063. "\r\n----------\r\n"
  15064. "Content-Disposition: form-data; name=\"text2\"\r\n"
  15065. "Content-Type: text/plain\r\n"
  15066. "X-Whatever: CustomValue\r\n"
  15067. "\r\n"
  15068. "text2"
  15069. "\r\n------------\r\n"
  15070. "That should be disregarded. Not even read";
  15071. std::string response;
  15072. ASSERT_TRUE(send_request(1, req, &response));
  15073. ASSERT_EQ("200", response.substr(9, 3));
  15074. }
  15075. TEST(MultipartFormDataTest, LargeHeader) {
  15076. auto handled = false;
  15077. Server svr;
  15078. svr.Post("/test", [&](const Request &req, Response &) {
  15079. ASSERT_EQ(1u, req.form.fields.size());
  15080. const auto &text = req.form.get_field("name1");
  15081. ASSERT_EQ("text1", text);
  15082. handled = true;
  15083. });
  15084. thread t = thread([&] { svr.listen(HOST, PORT); });
  15085. auto se = detail::scope_exit([&] {
  15086. svr.stop();
  15087. t.join();
  15088. ASSERT_FALSE(svr.is_running());
  15089. ASSERT_TRUE(handled);
  15090. });
  15091. svr.wait_until_ready();
  15092. auto boundary = std::string("cpp-httplib-multipart-data");
  15093. std::string content = "--" + boundary +
  15094. "\r\n"
  15095. "Content-Disposition: form-data; name=\"name1\"\r\n"
  15096. "\r\n"
  15097. "text1\r\n"
  15098. "--" +
  15099. boundary + "--\r\n";
  15100. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  15101. "Host: localhost\r\n"
  15102. "Content-Type: multipart/form-data;boundary=" +
  15103. boundary +
  15104. "\r\n"
  15105. "Content-Length: " +
  15106. std::to_string(content.size()) +
  15107. "\r\n"
  15108. "Dummy-Header: ";
  15109. std::string header_suffix = "\r\n"
  15110. "\r\n";
  15111. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  15112. size_t header_dummy_size =
  15113. read_buff_size -
  15114. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  15115. auto header_dummy = std::string(header_dummy_size, '@');
  15116. auto req = header_prefix + header_dummy + header_suffix + content;
  15117. std::string response;
  15118. ASSERT_TRUE(send_request(1, req, &response));
  15119. ASSERT_EQ("200", response.substr(9, 3));
  15120. }
  15121. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  15122. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  15123. // (not chunked Transfer-Encoding) after the streaming refactor.
  15124. auto handled = false;
  15125. Server svr;
  15126. svr.Post("/upload", [&](const Request &req, Response &res) {
  15127. auto cl_it = req.headers.find("Content-Length");
  15128. EXPECT_TRUE(cl_it != req.headers.end());
  15129. auto te_it = req.headers.find("Transfer-Encoding");
  15130. EXPECT_TRUE(te_it == req.headers.end());
  15131. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  15132. res.set_content("ok", "text/plain");
  15133. handled = true;
  15134. });
  15135. auto port = svr.bind_to_any_port(HOST);
  15136. auto t = thread([&] { svr.listen_after_bind(); });
  15137. auto se = detail::scope_exit([&] {
  15138. svr.stop();
  15139. t.join();
  15140. ASSERT_FALSE(svr.is_running());
  15141. ASSERT_TRUE(handled);
  15142. });
  15143. svr.wait_until_ready();
  15144. UploadFormDataItems items = {
  15145. {"field1", "hello", "", "text/plain"},
  15146. {"file1", "world", "test.txt", "application/octet-stream"},
  15147. };
  15148. Client cli(HOST, port);
  15149. auto res = cli.Post("/upload", {}, items);
  15150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15151. EXPECT_EQ(StatusCode::OK_200, res->status);
  15152. }
  15153. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  15154. // Verify that make_multipart_content_provider coalesces many small segments
  15155. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  15156. constexpr size_t kItemCount = 1000;
  15157. UploadFormDataItems items;
  15158. items.reserve(kItemCount);
  15159. for (size_t i = 0; i < kItemCount; i++) {
  15160. items.push_back(
  15161. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15162. }
  15163. const std::string boundary = "----test-boundary";
  15164. auto content_length = detail::get_multipart_content_length(items, boundary);
  15165. auto provider = detail::make_multipart_content_provider(items, boundary);
  15166. // Drive the provider the same way write_content_with_progress does
  15167. size_t write_count = 0;
  15168. size_t total_bytes = 0;
  15169. DataSink sink;
  15170. size_t offset = 0;
  15171. sink.write = [&](const char *d, size_t l) -> bool {
  15172. (void)d;
  15173. write_count++;
  15174. total_bytes += l;
  15175. offset += l;
  15176. return true;
  15177. };
  15178. sink.is_writable = []() -> bool { return true; };
  15179. while (offset < content_length) {
  15180. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  15181. }
  15182. EXPECT_EQ(content_length, total_bytes);
  15183. // The total number of segments is 3 * kItemCount + 1 = 3001.
  15184. // With buffering into 64KB blocks, write_count should be much smaller.
  15185. auto segment_count = 3 * kItemCount + 1;
  15186. EXPECT_LT(write_count, segment_count / 10);
  15187. }
  15188. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  15189. // Integration test: send many UploadFormDataItems and verify the server
  15190. // receives all of them correctly (#2410).
  15191. constexpr size_t kItemCount = 500;
  15192. auto handled = false;
  15193. Server svr;
  15194. svr.Post("/upload", [&](const Request &req, Response &res) {
  15195. EXPECT_EQ(kItemCount, req.form.fields.size());
  15196. for (size_t i = 0; i < kItemCount; i++) {
  15197. auto key = "field" + std::to_string(i);
  15198. auto val = "value" + std::to_string(i);
  15199. auto it = req.form.fields.find(key);
  15200. if (it != req.form.fields.end()) {
  15201. EXPECT_EQ(val, it->second.content);
  15202. } else {
  15203. ADD_FAILURE() << "Missing field: " << key;
  15204. }
  15205. }
  15206. res.set_content("ok", "text/plain");
  15207. handled = true;
  15208. });
  15209. auto port = svr.bind_to_any_port(HOST);
  15210. auto t = thread([&] { svr.listen_after_bind(); });
  15211. auto se = detail::scope_exit([&] {
  15212. svr.stop();
  15213. t.join();
  15214. ASSERT_FALSE(svr.is_running());
  15215. ASSERT_TRUE(handled);
  15216. });
  15217. svr.wait_until_ready();
  15218. UploadFormDataItems items;
  15219. items.reserve(kItemCount);
  15220. for (size_t i = 0; i < kItemCount; i++) {
  15221. items.push_back(
  15222. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15223. }
  15224. Client cli(HOST, port);
  15225. auto res = cli.Post("/upload", items);
  15226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15227. EXPECT_EQ(StatusCode::OK_200, res->status);
  15228. }
  15229. TEST(MultipartFormDataTest, MakeFileProvider) {
  15230. // Verify make_file_provider sends a file's contents correctly.
  15231. const std::string file_content(4096, 'Z');
  15232. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  15233. {
  15234. std::ofstream ofs(tmp_path, std::ios::binary);
  15235. ofs.write(file_content.data(),
  15236. static_cast<std::streamsize>(file_content.size()));
  15237. }
  15238. auto handled = false;
  15239. Server svr;
  15240. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  15241. const ContentReader &content_reader) {
  15242. ASSERT_TRUE(req.is_multipart_form_data());
  15243. std::vector<FormData> items;
  15244. content_reader(
  15245. [&](const FormData &file) {
  15246. items.push_back(file);
  15247. return true;
  15248. },
  15249. [&](const char *data, size_t data_length) {
  15250. items.back().content.append(data, data_length);
  15251. return true;
  15252. });
  15253. ASSERT_EQ(1u, items.size());
  15254. EXPECT_EQ("myfile", items[0].name);
  15255. EXPECT_EQ("data.bin", items[0].filename);
  15256. EXPECT_EQ("application/octet-stream", items[0].content_type);
  15257. EXPECT_EQ(file_content, items[0].content);
  15258. handled = true;
  15259. });
  15260. auto port = svr.bind_to_any_port(HOST);
  15261. auto t = thread([&] { svr.listen_after_bind(); });
  15262. auto se = detail::scope_exit([&] {
  15263. svr.stop();
  15264. t.join();
  15265. ASSERT_FALSE(svr.is_running());
  15266. ASSERT_TRUE(handled);
  15267. std::remove(tmp_path.c_str());
  15268. });
  15269. svr.wait_until_ready();
  15270. FormDataProviderItems providers;
  15271. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  15272. "application/octet-stream"));
  15273. Client cli(HOST, port);
  15274. auto res = cli.Post("/upload", {}, {}, providers);
  15275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15276. EXPECT_EQ(StatusCode::OK_200, res->status);
  15277. }
  15278. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  15279. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  15280. // (100) headers is rejected with a 400 Bad Request response.
  15281. Server svr;
  15282. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15283. res.set_content("ok", "text/plain");
  15284. });
  15285. thread t = thread([&] { svr.listen(HOST, PORT); });
  15286. auto se = detail::scope_exit([&] {
  15287. svr.stop();
  15288. t.join();
  15289. ASSERT_FALSE(svr.is_running());
  15290. });
  15291. svr.wait_until_ready();
  15292. // Build a multipart part with 101 custom headers (exceeding
  15293. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  15294. std::stringstream body;
  15295. body << "--simpleboundary\r\n"
  15296. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  15297. for (int i = 0; i < 101; i++) {
  15298. body << "X-Custom-Header-" << i << ": value\r\n";
  15299. }
  15300. body << "\r\n"
  15301. << "value1\r\n"
  15302. << "--simpleboundary--\r\n";
  15303. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  15304. Client cli(HOST, PORT);
  15305. auto res = cli.Post("/post", body.str(), content_type.c_str());
  15306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15307. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15308. }
  15309. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  15310. // A body that never contains the declared boundary must not be accumulated
  15311. // while the parser waits for it. Buffering it would also make every read
  15312. // rescan everything seen so far, which is quadratic in the body size.
  15313. Server svr;
  15314. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15315. res.set_content("ok", "text/plain");
  15316. });
  15317. auto port = svr.bind_to_any_port(HOST);
  15318. thread t = thread([&] { svr.listen_after_bind(); });
  15319. auto se = detail::scope_exit([&] {
  15320. svr.stop();
  15321. t.join();
  15322. ASSERT_FALSE(svr.is_running());
  15323. });
  15324. svr.wait_until_ready();
  15325. Client cli(HOST, port);
  15326. cli.set_read_timeout(60, 0);
  15327. cli.set_write_timeout(60, 0);
  15328. // '-' is the worst case: it matches the first character of the boundary, so
  15329. // every position has to be checked against it.
  15330. auto post_dashes = [&](size_t size) {
  15331. const std::string body(size, '-');
  15332. auto start = std::chrono::steady_clock::now();
  15333. auto res =
  15334. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  15335. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  15336. std::chrono::steady_clock::now() - start)
  15337. .count();
  15338. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15339. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  15340. return ms;
  15341. };
  15342. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  15343. // Windows.
  15344. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  15345. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  15346. // Comparing the two sizes rather than checking an absolute duration keeps
  15347. // this meaningful across build types and CI load, both of which move the
  15348. // absolute numbers by more than an order of magnitude. Four times the bytes
  15349. // costs about four times the time when parsing is linear, and about sixteen
  15350. // times when the body is buffered and rescanned.
  15351. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  15352. EXPECT_LT(ms_16mb, ms_4mb * 10)
  15353. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  15354. << "ms, which suggests the body is being buffered and rescanned";
  15355. }
  15356. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  15357. // A boundary can only be followed by CRLF or by "--", so anything else is
  15358. // malformed no matter what comes next. The parser must say so right away
  15359. // instead of buffering the rest of the declared body.
  15360. Server svr;
  15361. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15362. res.set_content("ok", "text/plain");
  15363. });
  15364. auto port = svr.bind_to_any_port(HOST);
  15365. thread t = thread([&] { svr.listen_after_bind(); });
  15366. auto se = detail::scope_exit([&] {
  15367. svr.stop();
  15368. t.join();
  15369. ASSERT_FALSE(svr.is_running());
  15370. });
  15371. svr.wait_until_ready();
  15372. // Announce a 1 MB body but send only the malformed prefix. A parser that
  15373. // buffers instead of failing would still be waiting for the remaining bytes.
  15374. const std::string body = "--zzzz\r\n"
  15375. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15376. "\r\n"
  15377. "text1"
  15378. "\r\n--zzzzXX";
  15379. const std::string req = "POST /post HTTP/1.1\r\n"
  15380. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15381. "Content-Length: 1048576\r\n"
  15382. "\r\n" +
  15383. body;
  15384. std::string response;
  15385. ASSERT_TRUE(send_request(3, req, &response, port));
  15386. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  15387. EXPECT_EQ("400", response.substr(9, 3));
  15388. }
  15389. // Posts a multipart body split into two writes, so that the server sees the
  15390. // split at whatever offset the caller chose, and expects the single "text1"
  15391. // field to come through.
  15392. static void expect_split_multipart_ok(const std::string &body1,
  15393. const std::string &body2) {
  15394. auto handled = false;
  15395. Server svr;
  15396. svr.Post("/post", [&](const Request &req, Response &) {
  15397. EXPECT_EQ(1u, req.form.fields.size());
  15398. EXPECT_EQ("text1", req.form.get_field("text1"));
  15399. handled = true;
  15400. });
  15401. auto port = svr.bind_to_any_port(HOST);
  15402. thread t = thread([&] { svr.listen_after_bind(); });
  15403. auto se = detail::scope_exit([&] {
  15404. svr.stop();
  15405. t.join();
  15406. ASSERT_FALSE(svr.is_running());
  15407. ASSERT_TRUE(handled);
  15408. });
  15409. svr.wait_until_ready();
  15410. // "Connection: close" makes the server close once it has answered, so the
  15411. // response drain ends immediately instead of idling until the read timeout.
  15412. const std::string head =
  15413. "POST /post HTTP/1.1\r\n"
  15414. "Host: localhost\r\n"
  15415. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15416. "Connection: close\r\n"
  15417. "Content-Length: " +
  15418. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  15419. std::string response;
  15420. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  15421. ASSERT_GE(response.size(), 12u) << "no response";
  15422. EXPECT_EQ("200", response.substr(9, 3));
  15423. }
  15424. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  15425. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  15426. // ignored, including when it does not arrive in the same read as the
  15427. // close-delimiter itself.
  15428. expect_split_multipart_ok("--zzzz\r\n"
  15429. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15430. "\r\n"
  15431. "text1"
  15432. "\r\n--zzzz--",
  15433. "\r\nthis epilogue must be ignored\r\n");
  15434. }
  15435. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  15436. // The initial boundary may be preceded by a preamble of any length and may
  15437. // straddle a read boundary. Discarding data while waiting for it must not
  15438. // throw away a partial boundary sitting at the end of the buffer.
  15439. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  15440. "zz\r\n"
  15441. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15442. "\r\n"
  15443. "text1"
  15444. "\r\n--zzzz--\r\n");
  15445. }
  15446. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  15447. // The received boundary was only checked for being non-empty, so it could be
  15448. // as long as a header is allowed to be. The parser scans the body for
  15449. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  15450. // costs a nearly full comparison at nearly every position, making the
  15451. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  15452. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  15453. Server svr;
  15454. svr.Post("/post", [](const Request &req, Response &res) {
  15455. EXPECT_EQ(1u, req.form.fields.size());
  15456. EXPECT_EQ("text1", req.form.get_field("text1"));
  15457. res.set_content("ok", "text/plain");
  15458. });
  15459. auto port = svr.bind_to_any_port(HOST);
  15460. thread t = thread([&] { svr.listen_after_bind(); });
  15461. auto se = detail::scope_exit([&] {
  15462. svr.stop();
  15463. t.join();
  15464. ASSERT_FALSE(svr.is_running());
  15465. });
  15466. svr.wait_until_ready();
  15467. Client cli(HOST, port);
  15468. auto post_with_boundary_of_length = [&](size_t len) {
  15469. const std::string boundary(len, 'a');
  15470. const std::string body =
  15471. "--" + boundary +
  15472. "\r\n"
  15473. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15474. "\r\n"
  15475. "text1"
  15476. "\r\n--" +
  15477. boundary + "--\r\n";
  15478. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  15479. };
  15480. auto res = post_with_boundary_of_length(70);
  15481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15482. EXPECT_EQ(StatusCode::OK_200, res->status);
  15483. res = post_with_boundary_of_length(71);
  15484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15485. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15486. }
  15487. TEST(MakeFileBodyTest, Basic) {
  15488. const std::string file_content(4096, 'Z');
  15489. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  15490. {
  15491. std::ofstream ofs(tmp_path, std::ios::binary);
  15492. ofs.write(file_content.data(),
  15493. static_cast<std::streamsize>(file_content.size()));
  15494. }
  15495. auto handled = false;
  15496. Server svr;
  15497. svr.Post("/upload", [&](const Request &req, Response &res) {
  15498. EXPECT_EQ(file_content, req.body);
  15499. handled = true;
  15500. res.status = StatusCode::OK_200;
  15501. });
  15502. auto port = svr.bind_to_any_port(HOST);
  15503. auto t = thread([&] { svr.listen_after_bind(); });
  15504. auto se = detail::scope_exit([&] {
  15505. svr.stop();
  15506. t.join();
  15507. ASSERT_FALSE(svr.is_running());
  15508. ASSERT_TRUE(handled);
  15509. std::remove(tmp_path.c_str());
  15510. });
  15511. svr.wait_until_ready();
  15512. auto fb = make_file_body(tmp_path);
  15513. ASSERT_GT(fb.first, 0u);
  15514. Client cli(HOST, port);
  15515. auto res =
  15516. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  15517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15518. EXPECT_EQ(StatusCode::OK_200, res->status);
  15519. }
  15520. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  15521. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  15522. {
  15523. std::ofstream ofs(path, std::ios::binary);
  15524. const std::string content(100, 'A');
  15525. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15526. }
  15527. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15528. auto body = make_file_body(path);
  15529. ASSERT_EQ(100u, body.first);
  15530. ASSERT_TRUE(static_cast<bool>(body.second));
  15531. // Rewritten shorter after its length was measured - and, on a server, after
  15532. // that length has already gone out as Content-Length.
  15533. {
  15534. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  15535. const std::string content(10, 'A');
  15536. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15537. }
  15538. std::string written;
  15539. DataSink sink;
  15540. sink.write = [&](const char *d, size_t l) {
  15541. written.append(d, l);
  15542. return true;
  15543. };
  15544. // The provider has to report failure. write_content_with_progress() advances
  15545. // its offset only by what was written, so a provider that returns true
  15546. // without completing the length it promised is called again straight away,
  15547. // and again.
  15548. EXPECT_FALSE(body.second(0, body.first, sink));
  15549. EXPECT_EQ(std::string(10, 'A'), written);
  15550. }
  15551. TEST(MakeFileBodyTest, WholeFileIsSent) {
  15552. const std::string path = "./httplib_test_make_file_body_whole.bin";
  15553. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  15554. {
  15555. std::ofstream ofs(path, std::ios::binary);
  15556. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15557. }
  15558. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15559. auto body = make_file_body(path);
  15560. ASSERT_EQ(content.size(), body.first);
  15561. ASSERT_TRUE(static_cast<bool>(body.second));
  15562. std::string written;
  15563. DataSink sink;
  15564. sink.write = [&](const char *d, size_t l) {
  15565. written.append(d, l);
  15566. return true;
  15567. };
  15568. EXPECT_TRUE(body.second(0, body.first, sink));
  15569. EXPECT_EQ(content, written);
  15570. }
  15571. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  15572. static constexpr unsigned int number_of_tasks{1000000};
  15573. std::atomic_uint count{0};
  15574. std::unique_ptr<TaskQueue> task_queue{
  15575. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  15576. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15577. auto queued = task_queue->enqueue(
  15578. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  15579. EXPECT_TRUE(queued);
  15580. }
  15581. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15582. task_queue->shutdown();
  15583. #else
  15584. EXPECT_NO_THROW(task_queue->shutdown());
  15585. #endif
  15586. EXPECT_EQ(number_of_tasks, count.load());
  15587. }
  15588. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  15589. static constexpr unsigned int number_of_tasks{1000000};
  15590. static constexpr unsigned int qlimit{2};
  15591. unsigned int queued_count{0};
  15592. std::atomic_uint count{0};
  15593. std::unique_ptr<TaskQueue> task_queue{
  15594. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  15595. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15596. if (task_queue->enqueue(
  15597. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  15598. queued_count++;
  15599. }
  15600. }
  15601. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15602. task_queue->shutdown();
  15603. #else
  15604. EXPECT_NO_THROW(task_queue->shutdown());
  15605. #endif
  15606. EXPECT_EQ(queued_count, count.load());
  15607. EXPECT_TRUE(queued_count <= number_of_tasks);
  15608. EXPECT_TRUE(queued_count >= qlimit);
  15609. }
  15610. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  15611. // Use a short idle timeout so a dynamic thread spawns, times out and
  15612. // exits during the test, and the pool keeps working afterwards.
  15613. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  15614. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  15615. /*idle_timeout_sec=*/1}};
  15616. std::atomic_uint count{0};
  15617. std::condition_variable cv;
  15618. std::mutex mtx;
  15619. bool release = false;
  15620. // Block the base thread so the second task spawns a dynamic thread.
  15621. EXPECT_TRUE(task_queue->enqueue([&] {
  15622. std::unique_lock<std::mutex> lock(mtx);
  15623. while (!release) {
  15624. cv.wait(lock);
  15625. }
  15626. count++;
  15627. }));
  15628. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15629. // Let the dynamic thread finish its task and exceed the idle timeout.
  15630. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  15631. {
  15632. std::unique_lock<std::mutex> lock(mtx);
  15633. release = true;
  15634. }
  15635. cv.notify_all();
  15636. // The pool must still accept and run tasks after the dynamic thread exited.
  15637. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15638. task_queue->shutdown();
  15639. EXPECT_EQ(3u, count.load());
  15640. }
  15641. TEST(TaskQueueTest, MaxQueuedRequests) {
  15642. static constexpr unsigned int qlimit{3};
  15643. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  15644. std::condition_variable sem_cv;
  15645. std::mutex sem_mtx;
  15646. int credits = 0;
  15647. bool queued;
  15648. /* Fill up the queue with tasks that will block until we give them credits to
  15649. * complete. */
  15650. for (unsigned int n = 0; n <= qlimit;) {
  15651. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  15652. std::unique_lock<std::mutex> lock(sem_mtx);
  15653. while (credits <= 0) {
  15654. sem_cv.wait(lock);
  15655. }
  15656. /* Consume the credit and signal the test code if they are all gone. */
  15657. if (--credits == 0) { sem_cv.notify_one(); }
  15658. });
  15659. if (n < qlimit) {
  15660. /* The first qlimit enqueues must succeed. */
  15661. EXPECT_TRUE(queued);
  15662. } else {
  15663. /* The last one will succeed only when the worker thread
  15664. * starts and dequeues the first blocking task. Although
  15665. * not necessary for the correctness of this test, we sleep for
  15666. * a short while to avoid busy waiting. */
  15667. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15668. }
  15669. if (queued) { n++; }
  15670. }
  15671. /* Further enqueues must fail since the queue is full. */
  15672. for (auto i = 0; i < 4; i++) {
  15673. queued = task_queue->enqueue([] {});
  15674. EXPECT_FALSE(queued);
  15675. }
  15676. /* Give the credits to allow the previous tasks to complete. */
  15677. {
  15678. std::unique_lock<std::mutex> lock(sem_mtx);
  15679. credits += qlimit + 1;
  15680. }
  15681. sem_cv.notify_all();
  15682. /* Wait for all the credits to be consumed. */
  15683. {
  15684. std::unique_lock<std::mutex> lock(sem_mtx);
  15685. while (credits > 0) {
  15686. sem_cv.wait(lock);
  15687. }
  15688. }
  15689. /* Check that we are able again to enqueue at least qlimit tasks. */
  15690. for (unsigned int i = 0; i < qlimit; i++) {
  15691. queued = task_queue->enqueue([] {});
  15692. EXPECT_TRUE(queued);
  15693. }
  15694. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15695. task_queue->shutdown();
  15696. #else
  15697. EXPECT_NO_THROW(task_queue->shutdown());
  15698. #endif
  15699. }
  15700. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  15701. Server svr;
  15702. std::string method;
  15703. std::string body;
  15704. auto has_content_length = false;
  15705. auto has_transfer_encoding = false;
  15706. std::atomic<int> bad_requests{0};
  15707. // Leftover body bytes get parsed as a malformed request and answered with
  15708. // 400
  15709. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  15710. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  15711. });
  15712. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  15713. res.set_redirect("/down", StatusCode::SeeOther_303);
  15714. });
  15715. svr.Get("/down", [&](const Request &req, Response &res) {
  15716. method = req.method;
  15717. body = req.body;
  15718. has_content_length = req.has_header("Content-Length");
  15719. has_transfer_encoding = req.has_header("Transfer-Encoding");
  15720. res.set_content("ok", "text/plain");
  15721. });
  15722. auto port = svr.bind_to_any_port(HOST);
  15723. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15724. auto se = detail::scope_exit([&] {
  15725. svr.stop();
  15726. thread.join();
  15727. ASSERT_FALSE(svr.is_running());
  15728. });
  15729. svr.wait_until_ready();
  15730. const std::string payload = "SECRET-BODY";
  15731. auto check = [&](Client &cli, const Result &res) {
  15732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15733. EXPECT_EQ(StatusCode::OK_200, res->status);
  15734. EXPECT_EQ("ok", res->body);
  15735. EXPECT_EQ("GET", method);
  15736. EXPECT_TRUE(body.empty());
  15737. EXPECT_FALSE(has_content_length);
  15738. EXPECT_FALSE(has_transfer_encoding);
  15739. // Nothing of the original body may be left on the connection
  15740. auto res2 = cli.Get("/down");
  15741. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  15742. EXPECT_EQ(StatusCode::OK_200, res2->status);
  15743. EXPECT_EQ("ok", res2->body);
  15744. EXPECT_EQ(0, bad_requests);
  15745. };
  15746. // With content length
  15747. {
  15748. Client cli(HOST, port);
  15749. cli.set_keep_alive(true);
  15750. cli.set_follow_location(true);
  15751. auto res = cli.Post(
  15752. "/up", payload.size(),
  15753. [&](size_t offset, size_t length, DataSink &sink) {
  15754. return sink.write(payload.data() + offset, length);
  15755. },
  15756. "text/plain");
  15757. check(cli, res);
  15758. }
  15759. // Without content length (chunked)
  15760. {
  15761. Client cli(HOST, port);
  15762. cli.set_keep_alive(true);
  15763. cli.set_follow_location(true);
  15764. auto res = cli.Post(
  15765. "/up",
  15766. [&](size_t /*offset*/, DataSink &sink) {
  15767. sink.write(payload.data(), payload.size());
  15768. sink.done();
  15769. return true;
  15770. },
  15771. "text/plain");
  15772. check(cli, res);
  15773. }
  15774. }
  15775. TEST(RedirectTest, LocationPathIsNotDecoded) {
  15776. Server svr;
  15777. std::string target;
  15778. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  15779. // Echo the still-encoded name back in the Location
  15780. const std::string prefix = "/start/";
  15781. res.status = StatusCode::Found_302;
  15782. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  15783. });
  15784. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  15785. target = req.target;
  15786. res.set_content("ok", "text/plain");
  15787. });
  15788. auto port = svr.bind_to_any_port(HOST);
  15789. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15790. auto se = detail::scope_exit([&] {
  15791. svr.stop();
  15792. thread.join();
  15793. ASSERT_FALSE(svr.is_running());
  15794. });
  15795. svr.wait_until_ready();
  15796. // Decoding the Location path would turn the first four into a path
  15797. // separator, a query delimiter, a fragment delimiter and a different
  15798. // percent-encoded octet. The rest must keep reaching the server as they are.
  15799. const std::vector<std::string> names = {
  15800. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  15801. };
  15802. for (auto path_encode : {true, false}) {
  15803. Client cli(HOST, port);
  15804. cli.set_follow_location(true);
  15805. cli.set_path_encode(path_encode);
  15806. for (const auto &name : names) {
  15807. target.clear();
  15808. auto res = cli.Get("/start/" + name);
  15809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15810. EXPECT_EQ(StatusCode::OK_200, res->status);
  15811. EXPECT_EQ("/dest/" + name, target);
  15812. }
  15813. }
  15814. }
  15815. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  15816. Server svr;
  15817. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15818. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  15819. });
  15820. svr.Get("/hello", [](const Request &req, Response &res) {
  15821. res.set_content(req.get_param_value("key"), "text/plain");
  15822. });
  15823. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15824. auto se = detail::scope_exit([&] {
  15825. svr.stop();
  15826. thread.join();
  15827. ASSERT_FALSE(svr.is_running());
  15828. });
  15829. svr.wait_until_ready();
  15830. {
  15831. Client cli(HOST, PORT);
  15832. cli.set_follow_location(true);
  15833. auto res = cli.Get("/");
  15834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15835. EXPECT_EQ(StatusCode::OK_200, res->status);
  15836. EXPECT_EQ("val&key2=val2", res->body);
  15837. }
  15838. }
  15839. #endif
  15840. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  15841. Server svr;
  15842. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15843. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  15844. });
  15845. svr.Get("/hello", [](const Request &req, Response &res) {
  15846. res.set_content(req.get_param_value("key"), "text/plain");
  15847. });
  15848. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15849. auto se = detail::scope_exit([&] {
  15850. svr.stop();
  15851. thread.join();
  15852. ASSERT_FALSE(svr.is_running());
  15853. });
  15854. svr.wait_until_ready();
  15855. {
  15856. Client cli(HOST, PORT);
  15857. cli.set_follow_location(true);
  15858. auto res = cli.Get("/");
  15859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15860. EXPECT_EQ(StatusCode::OK_200, res->status);
  15861. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  15862. }
  15863. }
  15864. TEST(RedirectTest, RedirectWithPlusInPath) {
  15865. Server svr;
  15866. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15867. res.set_redirect("/a+b");
  15868. });
  15869. // Route pattern uses regex; escape + as \\+
  15870. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  15871. res.set_content(req.path, "text/plain");
  15872. });
  15873. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15874. auto se = detail::scope_exit([&] {
  15875. svr.stop();
  15876. thread.join();
  15877. ASSERT_FALSE(svr.is_running());
  15878. });
  15879. svr.wait_until_ready();
  15880. {
  15881. Client cli(HOST, PORT);
  15882. cli.set_follow_location(true);
  15883. auto res = cli.Get("/");
  15884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15885. EXPECT_EQ(StatusCode::OK_200, res->status);
  15886. EXPECT_EQ("/a+b", res->body);
  15887. }
  15888. }
  15889. TEST(RedirectTest, ResolveRelativeLocation) {
  15890. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  15891. const std::vector<std::pair<std::string, std::string>> cases = {
  15892. {"g", "/b/c/g"},
  15893. {"./g", "/b/c/g"},
  15894. {"g/", "/b/c/g/"},
  15895. {"?y", "/b/c/d;p?y"},
  15896. {"g?y", "/b/c/g?y"},
  15897. {"#s", "/b/c/d;p?q#s"},
  15898. {"g#s", "/b/c/g#s"},
  15899. {"g?y#s", "/b/c/g?y#s"},
  15900. {";x", "/b/c/;x"},
  15901. {"g;x", "/b/c/g;x"},
  15902. {".", "/b/c/"},
  15903. {"./", "/b/c/"},
  15904. {"..", "/b/"},
  15905. {"../", "/b/"},
  15906. {"../g", "/b/g"},
  15907. {"../..", "/"},
  15908. {"../../", "/"},
  15909. {"../../g", "/g"},
  15910. {"../../../g", "/g"},
  15911. {"g.", "/b/c/g."},
  15912. {".g", "/b/c/.g"},
  15913. {"g..", "/b/c/g.."},
  15914. {"..g", "/b/c/..g"},
  15915. {"./../g", "/b/g"},
  15916. {"./g/.", "/b/c/g/"},
  15917. {"g/./h", "/b/c/g/h"},
  15918. {"g/../h", "/b/c/h"},
  15919. {"g;x=1/./y", "/b/c/g;x=1/y"},
  15920. {"g;x=1/../y", "/b/c/y"},
  15921. {"g?y/./x", "/b/c/g?y/./x"},
  15922. {"g#s/../x", "/b/c/g#s/../x"},
  15923. // Not relative-path references, so left for parse_url.
  15924. {"/g", "/g"},
  15925. {"//g", "//g"},
  15926. {"http://g/x", "http://g/x"},
  15927. {"g:h", "g:h"},
  15928. };
  15929. for (const auto &c : cases) {
  15930. EXPECT_EQ(c.second,
  15931. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  15932. << c.first;
  15933. }
  15934. }
  15935. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  15936. Server svr;
  15937. svr.Get("/dir/page", [](const Request &req, Response &res) {
  15938. res.set_redirect(req.get_param_value("to"));
  15939. });
  15940. svr.Get("/dir/next", [](const Request &req, Response &res) {
  15941. res.set_content(req.target, "text/plain");
  15942. });
  15943. svr.Get("/other", [](const Request &req, Response &res) {
  15944. res.set_content(req.target, "text/plain");
  15945. });
  15946. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15947. auto se = detail::scope_exit([&] {
  15948. svr.stop();
  15949. thread.join();
  15950. ASSERT_FALSE(svr.is_running());
  15951. });
  15952. svr.wait_until_ready();
  15953. const std::vector<std::pair<std::string, std::string>> cases = {
  15954. {"next", "/dir/next"},
  15955. {"./next?x=1", "/dir/next?x=1"},
  15956. {"../other", "/other"},
  15957. };
  15958. for (const auto &c : cases) {
  15959. Client cli(HOST, PORT);
  15960. cli.set_follow_location(true);
  15961. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  15962. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  15963. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  15964. EXPECT_EQ(c.second, res->body) << c.first;
  15965. }
  15966. }
  15967. #ifdef CPPHTTPLIB_SSL_ENABLED
  15968. TEST(RedirectTest, Issue2185_Online) {
  15969. SSLClient client("github.com");
  15970. client.set_follow_location(true);
  15971. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  15972. "Coollab-Windows.zip");
  15973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15974. EXPECT_EQ(StatusCode::OK_200, res->status);
  15975. EXPECT_EQ(9920427U, res->body.size());
  15976. }
  15977. #endif
  15978. TEST(VulnerabilityTest, CRLFInjection) {
  15979. Server svr;
  15980. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  15981. res.set_content("Hello 1", "text/plain");
  15982. });
  15983. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  15984. res.set_content("Hello 2", "text/plain");
  15985. });
  15986. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  15987. res.set_content("Hello 3", "text/plain");
  15988. });
  15989. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  15990. res.set_content("Hello 4", "text/plain");
  15991. });
  15992. svr.set_logger([](const Request &req, const Response & /*res*/) {
  15993. for (const auto &x : req.headers) {
  15994. auto key = x.first;
  15995. EXPECT_STRNE("evil", key.c_str());
  15996. }
  15997. });
  15998. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15999. auto se = detail::scope_exit([&] {
  16000. svr.stop();
  16001. thread.join();
  16002. ASSERT_FALSE(svr.is_running());
  16003. });
  16004. svr.wait_until_ready();
  16005. {
  16006. Client cli(HOST, PORT);
  16007. cli.Post("/test1", "A=B",
  16008. "application/x-www-form-urlencoded\r\nevil: hello1");
  16009. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  16010. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  16011. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  16012. }
  16013. }
  16014. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  16015. auto server_thread = std::thread([] {
  16016. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16017. default_socket_options(srv);
  16018. sockaddr_in addr{};
  16019. addr.sin_family = AF_INET;
  16020. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16021. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16022. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  16023. ::listen(srv, 1);
  16024. sockaddr_in cli_addr{};
  16025. socklen_t cli_len = sizeof(cli_addr);
  16026. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16027. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  16028. std::string buf_all;
  16029. char buf[2048];
  16030. ssize_t n;
  16031. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  16032. buf_all.append(buf, static_cast<size_t>(n));
  16033. size_t pos;
  16034. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  16035. auto request_block = buf_all.substr(0, pos + 4); // include separator
  16036. auto e = request_block.find("\r\n");
  16037. if (e != std::string::npos) {
  16038. auto request_line = request_block.substr(0, e);
  16039. std::string msg =
  16040. "CRLF injection detected in request line: '" + request_line + "'";
  16041. EXPECT_FALSE(true) << msg;
  16042. }
  16043. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  16044. ::send(cli,
  16045. #ifdef _WIN32
  16046. static_cast<const char *>(resp.c_str()),
  16047. static_cast<int>(resp.size()),
  16048. #else
  16049. resp.c_str(), resp.size(),
  16050. #endif
  16051. 0);
  16052. buf_all.erase(0, pos + 4);
  16053. }
  16054. }
  16055. detail::close_socket(cli);
  16056. detail::close_socket(srv);
  16057. });
  16058. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  16059. auto cli = Client("127.0.0.1", PORT + 1);
  16060. auto headers = Headers{
  16061. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  16062. {"Connection", "keep-alive"}};
  16063. auto res = cli.Get("/hi", headers);
  16064. EXPECT_FALSE(res);
  16065. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16066. server_thread.join();
  16067. }
  16068. // A request rejected before any byte reaches the socket must fail right away
  16069. // instead of waiting for a response the server will never send.
  16070. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  16071. // The kernel completes the TCP handshake from the listen backlog, so the
  16072. // client connects, but nothing ever reads, responds or closes.
  16073. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16074. default_socket_options(srv);
  16075. sockaddr_in addr{};
  16076. addr.sin_family = AF_INET;
  16077. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16078. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16079. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16080. ASSERT_EQ(0, ::listen(srv, 8));
  16081. auto cli = Client("127.0.0.1", PORT + 1);
  16082. cli.set_read_timeout(10, 0);
  16083. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  16084. return std::chrono::duration_cast<std::chrono::milliseconds>(
  16085. std::chrono::steady_clock::now() - start)
  16086. .count();
  16087. };
  16088. {
  16089. Request req;
  16090. req.method = "GE T";
  16091. req.path = "/";
  16092. auto start = std::chrono::steady_clock::now();
  16093. auto res = cli.send(req);
  16094. EXPECT_FALSE(res);
  16095. EXPECT_EQ(Error::Write, res.error());
  16096. EXPECT_LT(elapsed_ms(start), 1000);
  16097. }
  16098. {
  16099. auto start = std::chrono::steady_clock::now();
  16100. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  16101. EXPECT_FALSE(res);
  16102. EXPECT_EQ(Error::InvalidHeaders, res.error());
  16103. EXPECT_LT(elapsed_ms(start), 1000);
  16104. }
  16105. EXPECT_FALSE(cli.is_socket_open());
  16106. detail::close_socket(srv);
  16107. }
  16108. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  16109. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16110. default_socket_options(srv);
  16111. sockaddr_in addr{};
  16112. addr.sin_family = AF_INET;
  16113. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  16114. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16115. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16116. ASSERT_EQ(0, ::listen(srv, 1));
  16117. std::string received;
  16118. auto server_thread = std::thread([&] {
  16119. auto sock = ::accept(srv, nullptr, nullptr);
  16120. if (sock == INVALID_SOCKET) { return; }
  16121. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  16122. char buf[2048];
  16123. ssize_t n;
  16124. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  16125. received.append(buf, static_cast<size_t>(n));
  16126. }
  16127. detail::close_socket(sock);
  16128. });
  16129. {
  16130. auto cli = Client("127.0.0.1", PORT + 1);
  16131. // "Z" sorts after the default headers, so writing straight to the socket
  16132. // would have sent the request line and those headers before the rejection.
  16133. auto handle =
  16134. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  16135. EXPECT_FALSE(handle.is_valid());
  16136. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  16137. }
  16138. server_thread.join();
  16139. detail::close_socket(srv);
  16140. EXPECT_TRUE(received.empty()) << received;
  16141. }
  16142. TEST(PathParamsTest, StaticMatch) {
  16143. const auto pattern = "/users/all";
  16144. detail::PathParamsMatcher matcher(pattern);
  16145. Request request;
  16146. request.path = "/users/all";
  16147. ASSERT_TRUE(matcher.match(request));
  16148. std::unordered_map<std::string, std::string> expected_params = {};
  16149. EXPECT_EQ(request.path_params, expected_params);
  16150. }
  16151. TEST(PathParamsTest, StaticMismatch) {
  16152. const auto pattern = "/users/all";
  16153. detail::PathParamsMatcher matcher(pattern);
  16154. Request request;
  16155. request.path = "/users/1";
  16156. ASSERT_FALSE(matcher.match(request));
  16157. }
  16158. TEST(PathParamsTest, SingleParamInTheMiddle) {
  16159. const auto pattern = "/users/:id/subscriptions";
  16160. detail::PathParamsMatcher matcher(pattern);
  16161. Request request;
  16162. request.path = "/users/42/subscriptions";
  16163. ASSERT_TRUE(matcher.match(request));
  16164. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16165. EXPECT_EQ(request.path_params, expected_params);
  16166. }
  16167. TEST(PathParamsTest, SingleParamInTheEnd) {
  16168. const auto pattern = "/users/:id";
  16169. detail::PathParamsMatcher matcher(pattern);
  16170. Request request;
  16171. request.path = "/users/24";
  16172. ASSERT_TRUE(matcher.match(request));
  16173. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  16174. EXPECT_EQ(request.path_params, expected_params);
  16175. }
  16176. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  16177. const auto pattern = "/users/:id/";
  16178. detail::PathParamsMatcher matcher(pattern);
  16179. Request request;
  16180. request.path = "/users/42/";
  16181. ASSERT_TRUE(matcher.match(request));
  16182. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16183. EXPECT_EQ(request.path_params, expected_params);
  16184. }
  16185. TEST(PathParamsTest, EmptyParam) {
  16186. const auto pattern = "/users/:id/";
  16187. detail::PathParamsMatcher matcher(pattern);
  16188. Request request;
  16189. request.path = "/users//";
  16190. ASSERT_TRUE(matcher.match(request));
  16191. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  16192. EXPECT_EQ(request.path_params, expected_params);
  16193. }
  16194. TEST(PathParamsTest, FragmentMismatch) {
  16195. const auto pattern = "/users/:id/";
  16196. detail::PathParamsMatcher matcher(pattern);
  16197. Request request;
  16198. request.path = "/admins/24/";
  16199. ASSERT_FALSE(matcher.match(request));
  16200. }
  16201. TEST(PathParamsTest, ExtraFragments) {
  16202. const auto pattern = "/users/:id";
  16203. detail::PathParamsMatcher matcher(pattern);
  16204. Request request;
  16205. request.path = "/users/42/subscriptions";
  16206. ASSERT_FALSE(matcher.match(request));
  16207. }
  16208. TEST(PathParamsTest, MissingTrailingParam) {
  16209. const auto pattern = "/users/:id";
  16210. detail::PathParamsMatcher matcher(pattern);
  16211. Request request;
  16212. request.path = "/users";
  16213. ASSERT_FALSE(matcher.match(request));
  16214. }
  16215. TEST(PathParamsTest, MissingParamInTheMiddle) {
  16216. const auto pattern = "/users/:id/subscriptions";
  16217. detail::PathParamsMatcher matcher(pattern);
  16218. Request request;
  16219. request.path = "/users/subscriptions";
  16220. ASSERT_FALSE(matcher.match(request));
  16221. }
  16222. TEST(PathParamsTest, MultipleParams) {
  16223. const auto pattern = "/users/:userid/subscriptions/:subid";
  16224. detail::PathParamsMatcher matcher(pattern);
  16225. Request request;
  16226. request.path = "/users/42/subscriptions/2";
  16227. ASSERT_TRUE(matcher.match(request));
  16228. std::unordered_map<std::string, std::string> expected_params = {
  16229. {"userid", "42"}, {"subid", "2"}};
  16230. EXPECT_EQ(request.path_params, expected_params);
  16231. }
  16232. TEST(PathParamsTest, SequenceOfParams) {
  16233. const auto pattern = "/values/:x/:y/:z";
  16234. detail::PathParamsMatcher matcher(pattern);
  16235. Request request;
  16236. request.path = "/values/1/2/3";
  16237. ASSERT_TRUE(matcher.match(request));
  16238. std::unordered_map<std::string, std::string> expected_params = {
  16239. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  16240. EXPECT_EQ(request.path_params, expected_params);
  16241. }
  16242. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  16243. const auto pattern = "/prefix:suffix";
  16244. detail::PathParamsMatcher matcher(pattern);
  16245. Request request;
  16246. request.path = "/prefix:suffix";
  16247. ASSERT_TRUE(matcher.match(request));
  16248. const std::unordered_map<std::string, std::string> expected_params = {};
  16249. EXPECT_EQ(request.path_params, expected_params);
  16250. }
  16251. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  16252. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  16253. // calling thread's stack on a long enough path for a quantified pattern;
  16254. // RegexMatcher must refuse to run regex matching on paths beyond
  16255. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  16256. detail::RegexMatcher matcher("/files/(.*)");
  16257. Request within_limit;
  16258. within_limit.path = "/files/" + std::string(10, 'A');
  16259. EXPECT_TRUE(matcher.match(within_limit));
  16260. Request over_limit;
  16261. over_limit.path =
  16262. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  16263. EXPECT_FALSE(matcher.match(over_limit));
  16264. }
  16265. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  16266. Server svr;
  16267. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  16268. res.set_content("ok", "text/plain");
  16269. });
  16270. auto port = svr.bind_to_any_port(HOST);
  16271. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16272. auto se = detail::scope_exit([&] {
  16273. svr.stop();
  16274. thread.join();
  16275. ASSERT_FALSE(svr.is_running());
  16276. });
  16277. svr.wait_until_ready();
  16278. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  16279. // request URI limit; this used to be able to crash the process.
  16280. std::string path =
  16281. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  16282. std::string req = "GET " + path +
  16283. " HTTP/1.1\r\n"
  16284. "Host: " +
  16285. std::string(HOST) + ":" + std::to_string(port) +
  16286. "\r\n"
  16287. "Connection: close\r\n"
  16288. "\r\n";
  16289. std::string response;
  16290. ASSERT_TRUE(send_request(5, req, &response, port));
  16291. EXPECT_NE(std::string::npos, response.find("404"));
  16292. }
  16293. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  16294. Server svr;
  16295. auto handler = [](const Request & /*req*/, Response &res) {
  16296. res.set_content("hit", "text/plain");
  16297. };
  16298. // No regex metacharacter, so this one is compared literally
  16299. svr.Get("/literal/route", handler);
  16300. // '.' is a regex metacharacter, so this one must keep regex semantics
  16301. svr.Get("/a.c", handler);
  16302. auto port = svr.bind_to_any_port(HOST);
  16303. std::thread t([&]() { svr.listen_after_bind(); });
  16304. auto se = detail::scope_exit([&] {
  16305. svr.stop();
  16306. t.join();
  16307. ASSERT_FALSE(svr.is_running());
  16308. });
  16309. svr.wait_until_ready();
  16310. Client cli(HOST, port);
  16311. struct {
  16312. const char *path;
  16313. int status;
  16314. } cases[] = {
  16315. {"/literal/route", StatusCode::OK_200},
  16316. {"/literal/routes", StatusCode::NotFound_404},
  16317. {"/literal/rout", StatusCode::NotFound_404},
  16318. {"/abc", StatusCode::OK_200},
  16319. {"/a.c", StatusCode::OK_200},
  16320. };
  16321. for (const auto &x : cases) {
  16322. auto res = cli.Get(x.path);
  16323. ASSERT_TRUE(res) << x.path;
  16324. EXPECT_EQ(x.status, res->status) << x.path;
  16325. }
  16326. }
  16327. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  16328. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  16329. // from exhausting the stack, so it must only constrain routes that actually
  16330. // run a regular expression. A literal route is matched by comparison and
  16331. // stays usable at any length.
  16332. Server svr;
  16333. const std::string pattern =
  16334. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  16335. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  16336. res.set_content("hit", "text/plain");
  16337. });
  16338. auto port = svr.bind_to_any_port(HOST);
  16339. std::thread t([&]() { svr.listen_after_bind(); });
  16340. auto se = detail::scope_exit([&] {
  16341. svr.stop();
  16342. t.join();
  16343. ASSERT_FALSE(svr.is_running());
  16344. });
  16345. svr.wait_until_ready();
  16346. Client cli(HOST, port);
  16347. auto res = cli.Get(pattern);
  16348. ASSERT_TRUE(res);
  16349. EXPECT_EQ(StatusCode::OK_200, res->status);
  16350. }
  16351. TEST(ParseUrlTest, VariousPatterns) {
  16352. {
  16353. detail::UrlComponents uc;
  16354. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  16355. EXPECT_EQ("http", uc.scheme);
  16356. EXPECT_EQ("example.com", uc.host);
  16357. EXPECT_EQ("8080", uc.port);
  16358. EXPECT_EQ("/path", uc.path);
  16359. EXPECT_EQ("?q=1", uc.query);
  16360. }
  16361. {
  16362. detail::UrlComponents uc;
  16363. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  16364. EXPECT_EQ("https", uc.scheme);
  16365. EXPECT_EQ("example.com", uc.host);
  16366. EXPECT_TRUE(uc.port.empty());
  16367. EXPECT_EQ("/path", uc.path);
  16368. }
  16369. {
  16370. detail::UrlComponents uc;
  16371. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  16372. EXPECT_EQ("::1", uc.host);
  16373. EXPECT_EQ("8080", uc.port);
  16374. EXPECT_EQ("/path", uc.path);
  16375. }
  16376. {
  16377. detail::UrlComponents uc;
  16378. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  16379. }
  16380. {
  16381. // Bytes after the IPv6 literal must be a delimiter, not folded into
  16382. // the path while the connection still targets the bracketed host.
  16383. detail::UrlComponents uc;
  16384. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  16385. }
  16386. {
  16387. detail::UrlComponents uc;
  16388. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  16389. }
  16390. {
  16391. detail::UrlComponents uc;
  16392. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  16393. EXPECT_EQ("::1", uc.host);
  16394. EXPECT_TRUE(uc.port.empty());
  16395. EXPECT_EQ("/path", uc.path);
  16396. }
  16397. {
  16398. detail::UrlComponents uc;
  16399. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  16400. EXPECT_TRUE(uc.scheme.empty());
  16401. EXPECT_EQ("example.com", uc.host);
  16402. EXPECT_EQ("/path", uc.path);
  16403. EXPECT_EQ("?q=1", uc.query);
  16404. }
  16405. {
  16406. detail::UrlComponents uc;
  16407. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  16408. EXPECT_TRUE(uc.host.empty());
  16409. EXPECT_EQ("/path", uc.path);
  16410. EXPECT_EQ("?q=1", uc.query);
  16411. }
  16412. {
  16413. detail::UrlComponents uc;
  16414. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  16415. EXPECT_EQ("example.com", uc.host);
  16416. EXPECT_EQ("8080", uc.port);
  16417. }
  16418. {
  16419. // Unix socket path — must not be parsed as host
  16420. detail::UrlComponents uc;
  16421. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  16422. EXPECT_TRUE(uc.host.empty());
  16423. }
  16424. {
  16425. detail::UrlComponents uc;
  16426. ASSERT_TRUE(detail::parse_url("", uc));
  16427. EXPECT_TRUE(uc.host.empty());
  16428. EXPECT_TRUE(uc.path.empty());
  16429. }
  16430. {
  16431. detail::UrlComponents uc;
  16432. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  16433. }
  16434. {
  16435. detail::UrlComponents uc;
  16436. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  16437. }
  16438. {
  16439. // Accepted by parse_url; callers restrict to http/https
  16440. detail::UrlComponents uc;
  16441. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  16442. EXPECT_EQ("ftp", uc.scheme);
  16443. }
  16444. {
  16445. detail::UrlComponents uc;
  16446. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  16447. }
  16448. {
  16449. detail::UrlComponents uc;
  16450. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  16451. }
  16452. }
  16453. TEST(ParseUrlTest, FragmentHandling) {
  16454. {
  16455. detail::UrlComponents uc;
  16456. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  16457. EXPECT_EQ("/path", uc.path);
  16458. EXPECT_TRUE(uc.query.empty());
  16459. }
  16460. {
  16461. detail::UrlComponents uc;
  16462. ASSERT_TRUE(detail::parse_url("#frag", uc));
  16463. EXPECT_TRUE(uc.path.empty());
  16464. EXPECT_TRUE(uc.query.empty());
  16465. }
  16466. }
  16467. TEST(ParseUrlTest, UserinfoHandling) {
  16468. // userinfo, and a backslash some parsers take for '/', are rejected: such
  16469. // parsers would see evil.com as the host.
  16470. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  16471. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  16472. for (auto url : urls) {
  16473. detail::UrlComponents uc;
  16474. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  16475. }
  16476. }
  16477. TEST(ParseUrlTest, IPv6EdgeCases) {
  16478. {
  16479. detail::UrlComponents uc;
  16480. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  16481. EXPECT_TRUE(uc.scheme.empty());
  16482. EXPECT_EQ("::1", uc.host);
  16483. EXPECT_EQ("8080", uc.port);
  16484. }
  16485. {
  16486. // Zone ID '%25' is not in [a-fA-F0-9:]
  16487. detail::UrlComponents uc;
  16488. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  16489. }
  16490. }
  16491. TEST(ParseUrlTest, SchemeEdgeCases) {
  16492. {
  16493. detail::UrlComponents uc;
  16494. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  16495. }
  16496. {
  16497. detail::UrlComponents uc;
  16498. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  16499. }
  16500. {
  16501. detail::UrlComponents uc;
  16502. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  16503. }
  16504. }
  16505. TEST(ParseUrlTest, PortEdgeCases) {
  16506. {
  16507. detail::UrlComponents uc;
  16508. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  16509. EXPECT_TRUE(uc.port.empty());
  16510. EXPECT_EQ("/path", uc.path);
  16511. }
  16512. {
  16513. // parse_url accepts any port string; validation is done by parse_port
  16514. detail::UrlComponents uc;
  16515. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  16516. EXPECT_EQ("abc", uc.port);
  16517. }
  16518. }
  16519. TEST(ParseUrlTest, WebSocketPatterns) {
  16520. {
  16521. detail::UrlComponents uc;
  16522. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  16523. EXPECT_EQ("ws", uc.scheme);
  16524. EXPECT_EQ("echo.example.com", uc.host);
  16525. EXPECT_EQ("8080", uc.port);
  16526. EXPECT_EQ("/ws", uc.path);
  16527. }
  16528. {
  16529. detail::UrlComponents uc;
  16530. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  16531. EXPECT_EQ("wss", uc.scheme);
  16532. EXPECT_EQ("echo.example.com", uc.host);
  16533. EXPECT_TRUE(uc.port.empty());
  16534. EXPECT_EQ("/ws", uc.path);
  16535. }
  16536. }
  16537. TEST(ParseUrlTest, QueryOnly) {
  16538. detail::UrlComponents uc;
  16539. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  16540. EXPECT_TRUE(uc.host.empty());
  16541. EXPECT_TRUE(uc.path.empty());
  16542. EXPECT_EQ("?q=1&r=2", uc.query);
  16543. }
  16544. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  16545. detail::UrlComponents uc;
  16546. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  16547. EXPECT_TRUE(uc.scheme.empty());
  16548. EXPECT_EQ("example.com", uc.host);
  16549. EXPECT_EQ("443", uc.port);
  16550. EXPECT_EQ("/path", uc.path);
  16551. }
  16552. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  16553. // If ipv6 regex working, regex match codepath is taken.
  16554. // else port will default to 80 in Client impl
  16555. int clientImplMagicPort = 80;
  16556. int port = 4321;
  16557. // above ports must be different to avoid false negative
  16558. EXPECT_NE(clientImplMagicPort, port);
  16559. std::string ipV6TestURL = "http://[ff06::c3]";
  16560. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  16561. CLIENT_PRIVATE_KEY_FILE);
  16562. EXPECT_EQ(cli.port(), port);
  16563. }
  16564. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  16565. auto file_path = "./www/dir/index.html";
  16566. auto dir_path = "./www/dir";
  16567. detail::FileStat stat_file(file_path);
  16568. EXPECT_TRUE(stat_file.is_file());
  16569. EXPECT_FALSE(stat_file.is_dir());
  16570. detail::FileStat stat_dir(dir_path);
  16571. EXPECT_FALSE(stat_dir.is_file());
  16572. EXPECT_TRUE(stat_dir.is_dir());
  16573. }
  16574. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  16575. // IPv4 with default HTTP port (80)
  16576. EXPECT_EQ("example.com",
  16577. detail::make_host_and_port_string("example.com", 80, false));
  16578. // IPv4 with default HTTPS port (443)
  16579. EXPECT_EQ("example.com",
  16580. detail::make_host_and_port_string("example.com", 443, true));
  16581. // IPv4 with non-default HTTP port
  16582. EXPECT_EQ("example.com:8080",
  16583. detail::make_host_and_port_string("example.com", 8080, false));
  16584. // IPv4 with non-default HTTPS port
  16585. EXPECT_EQ("example.com:8443",
  16586. detail::make_host_and_port_string("example.com", 8443, true));
  16587. // IPv6 with default HTTP port (80)
  16588. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  16589. // IPv6 with default HTTPS port (443)
  16590. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  16591. // IPv6 with non-default HTTP port
  16592. EXPECT_EQ("[::1]:8080",
  16593. detail::make_host_and_port_string("::1", 8080, false));
  16594. // IPv6 with non-default HTTPS port
  16595. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  16596. // IPv6 full address with default port
  16597. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  16598. detail::make_host_and_port_string(
  16599. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  16600. // IPv6 full address with non-default port
  16601. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  16602. detail::make_host_and_port_string(
  16603. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  16604. // IPv6 localhost with non-default port
  16605. EXPECT_EQ("[::1]:3000",
  16606. detail::make_host_and_port_string("::1", 3000, false));
  16607. // IPv6 with zone ID (link-local address) with default port
  16608. EXPECT_EQ("[fe80::1%eth0]",
  16609. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  16610. // IPv6 with zone ID (link-local address) with non-default port
  16611. EXPECT_EQ("[fe80::1%eth0]:8080",
  16612. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  16613. // Edge case: Port 443 with is_ssl=false (should add port)
  16614. EXPECT_EQ("example.com:443",
  16615. detail::make_host_and_port_string("example.com", 443, false));
  16616. // Edge case: Port 80 with is_ssl=true (should add port)
  16617. EXPECT_EQ("example.com:80",
  16618. detail::make_host_and_port_string("example.com", 80, true));
  16619. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  16620. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  16621. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  16622. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  16623. // Security fix: Already bracketed IPv6 should not get double brackets
  16624. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  16625. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  16626. EXPECT_EQ("[::1]:8080",
  16627. detail::make_host_and_port_string("[::1]", 8080, false));
  16628. EXPECT_EQ("[2001:db8::1]:8080",
  16629. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  16630. EXPECT_EQ("[fe80::1%eth0]",
  16631. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  16632. EXPECT_EQ("[fe80::1%eth0]:8080",
  16633. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  16634. // Edge case: Empty host (should return as-is)
  16635. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  16636. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  16637. // This is a known limitation but shouldn't crash
  16638. EXPECT_EQ("[host:name]",
  16639. detail::make_host_and_port_string("host:name", 80, false));
  16640. // Port number edge cases (no validation, but should not crash)
  16641. EXPECT_EQ("example.com:0",
  16642. detail::make_host_and_port_string("example.com", 0, false));
  16643. EXPECT_EQ("example.com:-1",
  16644. detail::make_host_and_port_string("example.com", -1, false));
  16645. EXPECT_EQ("example.com:65535",
  16646. detail::make_host_and_port_string("example.com", 65535, false));
  16647. EXPECT_EQ("example.com:65536",
  16648. detail::make_host_and_port_string("example.com", 65536, false));
  16649. }
  16650. #ifdef CPPHTTPLIB_SSL_ENABLED
  16651. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  16652. httplib::SSLClient cli("roblox.com", 443);
  16653. cli.set_follow_location(true);
  16654. auto res = cli.Get("/");
  16655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16656. EXPECT_EQ(StatusCode::OK_200, res->status);
  16657. }
  16658. #endif
  16659. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  16660. Server svr;
  16661. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16662. EXPECT_EQ(res.status, 400);
  16663. });
  16664. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16665. auto se = detail::scope_exit([&] {
  16666. svr.stop();
  16667. thread.join();
  16668. ASSERT_FALSE(svr.is_running());
  16669. });
  16670. svr.wait_until_ready();
  16671. Client cli(HOST, PORT);
  16672. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  16673. }
  16674. TEST(InvalidHeaderCharsTest, is_field_name) {
  16675. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  16676. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  16677. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  16678. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  16679. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  16680. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  16681. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  16682. EXPECT_FALSE(detail::fields::is_field_name(""));
  16683. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  16684. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  16685. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  16686. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  16687. }
  16688. TEST(InvalidHeaderCharsTest, is_field_value) {
  16689. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  16690. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  16691. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  16692. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  16693. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  16694. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  16695. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  16696. EXPECT_TRUE(detail::fields::is_field_value(""));
  16697. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  16698. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  16699. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  16700. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  16701. EXPECT_TRUE(detail::fields::is_field_value("0"));
  16702. }
  16703. TEST(InvalidHeaderCharsTest, OnServer) {
  16704. Server svr;
  16705. svr.Get("/test_name", [&](const Request &req, Response &res) {
  16706. std::string header = "Not Set";
  16707. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16708. res.set_header(header, "value");
  16709. res.set_content("Page Content Page Content", "text/plain");
  16710. });
  16711. svr.Get("/test_value", [&](const Request &req, Response &res) {
  16712. std::string header = "Not Set";
  16713. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16714. res.set_header("X-Test", header);
  16715. res.set_content("Page Content Page Content", "text/plain");
  16716. });
  16717. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16718. auto se = detail::scope_exit([&] {
  16719. svr.stop();
  16720. thread.join();
  16721. ASSERT_FALSE(svr.is_running());
  16722. });
  16723. svr.wait_until_ready();
  16724. Client cli(HOST, PORT);
  16725. {
  16726. auto res = cli.Get(
  16727. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16729. EXPECT_EQ("Page Content Page Content", res->body);
  16730. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16731. }
  16732. {
  16733. auto res = cli.Get(
  16734. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16736. EXPECT_EQ("Page Content Page Content", res->body);
  16737. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16738. }
  16739. }
  16740. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  16741. auto handled = false;
  16742. Server svr;
  16743. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16744. thread t = thread([&] { svr.listen(HOST, PORT); });
  16745. auto se = detail::scope_exit([&] {
  16746. svr.stop();
  16747. t.join();
  16748. ASSERT_FALSE(svr.is_running());
  16749. ASSERT_FALSE(handled);
  16750. });
  16751. svr.wait_until_ready();
  16752. auto req = "POST /test HTTP/1.1\r\n"
  16753. "Content-Length: x\r\n"
  16754. "\r\n";
  16755. std::string response;
  16756. ASSERT_TRUE(send_request(1, req, &response));
  16757. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16758. response.substr(0, response.find("\r\n")));
  16759. }
  16760. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  16761. // case-insensitive, and a server that receives a 100-continue expectation in
  16762. // an HTTP/1.0 request MUST ignore it.
  16763. static void probe_expect(int port, const std::string &req, bool *got_100) {
  16764. std::string response;
  16765. ASSERT_TRUE(send_request(1, req, &response, port));
  16766. *got_100 = response.find("100 Continue") != std::string::npos;
  16767. }
  16768. class ExpectTokenTest : public ::testing::Test {
  16769. protected:
  16770. void SetUp() override {
  16771. svr_.Post("/p", [](const Request &, Response &res) {
  16772. res.set_content("ok", "text/plain");
  16773. });
  16774. port_ = svr_.bind_to_any_port(HOST);
  16775. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16776. svr_.wait_until_ready();
  16777. }
  16778. void TearDown() override {
  16779. svr_.stop();
  16780. if (thread_.joinable()) { thread_.join(); }
  16781. }
  16782. std::string request(const char *version, const char *expect_value) const {
  16783. return std::string("POST /p ") + version +
  16784. "\r\n"
  16785. "Host: localhost\r\n"
  16786. "Content-Length: 2\r\n"
  16787. "Connection: close\r\n"
  16788. "Expect: " +
  16789. expect_value +
  16790. "\r\n"
  16791. "\r\n"
  16792. "hi";
  16793. }
  16794. Server svr_;
  16795. int port_ = 0;
  16796. thread thread_;
  16797. };
  16798. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  16799. bool got_100 = false;
  16800. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  16801. EXPECT_TRUE(got_100);
  16802. }
  16803. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  16804. bool got_100 = true;
  16805. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  16806. EXPECT_FALSE(got_100);
  16807. }
  16808. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  16809. bool got_100 = false;
  16810. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  16811. EXPECT_TRUE(got_100);
  16812. }
  16813. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  16814. bool got_100 = false;
  16815. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  16816. EXPECT_TRUE(got_100);
  16817. }
  16818. // `100 Continue` is sent only when the server starts reading the body, so a
  16819. // request rejected before that never invites the client to send it. The
  16820. // requests below carry the expectation but withhold the body, as a client
  16821. // waiting for `100 Continue` would.
  16822. // A POST that expects `100 Continue` and withholds its two-byte body.
  16823. static std::string expect_headers_only(const std::string &path) {
  16824. return "POST " + path +
  16825. " HTTP/1.1\r\n"
  16826. "Host: localhost\r\n"
  16827. "Content-Length: 2\r\n"
  16828. "Expect: 100-continue\r\n"
  16829. "\r\n";
  16830. }
  16831. class ExpectLazyContinueTest : public ::testing::Test {
  16832. protected:
  16833. void SetUp() override {
  16834. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  16835. if (req.path == "/pre-routing") {
  16836. res.status = StatusCode::Unauthorized_401;
  16837. return Server::HandlerResponse::Handled;
  16838. }
  16839. return Server::HandlerResponse::Unhandled;
  16840. });
  16841. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  16842. if (req.matched_route == "/pre-request") {
  16843. res.status = StatusCode::Forbidden_403;
  16844. return Server::HandlerResponse::Handled;
  16845. }
  16846. return Server::HandlerResponse::Unhandled;
  16847. });
  16848. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  16849. res.set_content("ok", "text/plain");
  16850. });
  16851. svr_.Post("/pre-request", [](const Request &, Response &res) {
  16852. res.set_content("ok", "text/plain");
  16853. });
  16854. svr_.Post("/reader-used", [](const Request &, Response &res,
  16855. const ContentReader &content_reader) {
  16856. std::string body;
  16857. content_reader([&](const char *data, size_t len) {
  16858. body.append(data, len);
  16859. return true;
  16860. });
  16861. res.set_content(body, "text/plain");
  16862. });
  16863. svr_.Post("/reader-unused",
  16864. [](const Request &, Response &res, const ContentReader &) {
  16865. res.set_content("ignored", "text/plain");
  16866. });
  16867. port_ = svr_.bind_to_any_port(HOST);
  16868. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16869. svr_.wait_until_ready();
  16870. }
  16871. void TearDown() override {
  16872. svr_.stop();
  16873. if (thread_.joinable()) { thread_.join(); }
  16874. }
  16875. // Sends `req` and reads until the server closes the connection. Returns
  16876. // false if the read had to wait for the client-side timeout instead.
  16877. bool send_until_closed(const std::string &req, std::string *resp) const {
  16878. auto start = std::chrono::steady_clock::now();
  16879. if (!send_request(3, req, resp, port_)) { return false; }
  16880. auto elapsed = std::chrono::steady_clock::now() - start;
  16881. return elapsed < std::chrono::seconds(2);
  16882. }
  16883. // The final response comes without `100 Continue`, and the server closes
  16884. // the connection since the body may or may not follow.
  16885. void expect_final_without_interim(const std::string &path,
  16886. const char *status_line) const {
  16887. std::string resp;
  16888. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  16889. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  16890. EXPECT_EQ(0u, resp.find(status_line));
  16891. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16892. }
  16893. Server svr_;
  16894. int port_ = 0;
  16895. thread thread_;
  16896. };
  16897. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  16898. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  16899. }
  16900. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  16901. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  16902. }
  16903. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  16904. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  16905. }
  16906. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  16907. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  16908. }
  16909. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  16910. // The body follows once `100 Continue` has had time to arrive.
  16911. auto req = expect_headers_only("/reader-used");
  16912. req.insert(req.size() - 2, "Connection: close\r\n");
  16913. std::string resp;
  16914. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  16915. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  16916. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  16917. EXPECT_NE(std::string::npos, resp.find("hi"));
  16918. }
  16919. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  16920. // Large enough for the client to add `Expect: 100-continue` itself.
  16921. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  16922. std::atomic<bool> body_sent{false};
  16923. Client cli(HOST, port_);
  16924. auto res = cli.Post(
  16925. "/pre-request", length,
  16926. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  16927. body_sent = true;
  16928. std::string chunk(len, 'x');
  16929. sink.write(chunk.data(), chunk.size());
  16930. return true;
  16931. },
  16932. "application/octet-stream");
  16933. ASSERT_TRUE(res);
  16934. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16935. EXPECT_FALSE(body_sent);
  16936. }
  16937. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  16938. Server svr;
  16939. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  16940. return StatusCode::ExpectationFailed_417;
  16941. });
  16942. svr.Post("/p", [](const Request &, Response &res) {
  16943. res.set_content("ok", "text/plain");
  16944. });
  16945. auto port = svr.bind_to_any_port(HOST);
  16946. thread t = thread([&] { svr.listen_after_bind(); });
  16947. auto se = detail::scope_exit([&] {
  16948. svr.stop();
  16949. t.join();
  16950. });
  16951. svr.wait_until_ready();
  16952. std::string resp;
  16953. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  16954. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  16955. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16956. // Exactly one response: the route handler must not run after the 417.
  16957. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  16958. }
  16959. #ifndef _WIN32
  16960. TEST(Expect100ContinueTest, ServerClosesConnection) {
  16961. static constexpr char reject[] = "Unauthorized";
  16962. static constexpr char accept[] = "Upload accepted";
  16963. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  16964. Server svr;
  16965. svr.set_expect_100_continue_handler(
  16966. [](const Request & /*req*/, Response &res) {
  16967. res.status = StatusCode::Unauthorized_401;
  16968. res.set_content(reject, "text/plain");
  16969. return res.status;
  16970. });
  16971. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  16972. res.set_content(accept, "text/plain");
  16973. });
  16974. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16975. auto se = detail::scope_exit([&] {
  16976. svr.stop();
  16977. thread.join();
  16978. ASSERT_FALSE(svr.is_running());
  16979. });
  16980. svr.wait_until_ready();
  16981. {
  16982. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  16983. curl_easy_init(), &curl_easy_cleanup};
  16984. ASSERT_NE(curl, nullptr);
  16985. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  16986. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  16987. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  16988. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  16989. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  16990. &curl_slist_free_all};
  16991. ASSERT_NE(list, nullptr);
  16992. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  16993. struct read_data {
  16994. size_t read_size;
  16995. size_t total_size;
  16996. } data = {0, total_size};
  16997. using read_callback_t =
  16998. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16999. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  17000. void *userdata) -> size_t {
  17001. read_data *d = (read_data *)userdata;
  17002. if (!userdata || d->read_size >= d->total_size) { return 0; }
  17003. std::fill_n(ptr, size * nmemb, 'A');
  17004. d->read_size += size * nmemb;
  17005. return size * nmemb;
  17006. };
  17007. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  17008. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  17009. std::vector<char> buffer;
  17010. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  17011. using write_callback_t =
  17012. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  17013. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  17014. void *userdata) -> size_t {
  17015. std::vector<char> *buf = (std::vector<char> *)userdata;
  17016. buf->reserve(buf->size() + size * nmemb + 1);
  17017. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  17018. return size * nmemb;
  17019. };
  17020. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  17021. {
  17022. const auto res = curl_easy_perform(curl.get());
  17023. ASSERT_EQ(res, CURLE_OK);
  17024. }
  17025. {
  17026. auto response_code = long{};
  17027. const auto res =
  17028. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  17029. ASSERT_EQ(res, CURLE_OK);
  17030. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  17031. }
  17032. {
  17033. auto dl = curl_off_t{};
  17034. const auto res =
  17035. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  17036. ASSERT_EQ(res, CURLE_OK);
  17037. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  17038. }
  17039. {
  17040. buffer.push_back('\0');
  17041. ASSERT_STRCASEEQ(buffer.data(), reject);
  17042. }
  17043. }
  17044. }
  17045. #endif
  17046. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  17047. // Regression test for #2458.
  17048. //
  17049. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  17050. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  17051. // ticket can make the client socket spuriously readable during the
  17052. // 100-continue wait. If the readiness is mistaken for an incoming response,
  17053. // the client withholds the body and then blocks reading a response that never
  17054. // comes, failing with `Failed to read connection`.
  17055. //
  17056. // A correct client (like curl) sends the body once no `100 Continue` arrives
  17057. // within the timeout. This raw OpenSSL server deliberately never sends
  17058. // `100 Continue`; the client must still deliver the body and receive 200.
  17059. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  17060. signal(SIGPIPE, SIG_IGN);
  17061. const auto port = PORT + 4;
  17062. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17063. ASSERT_NE(srv, INVALID_SOCKET);
  17064. int opt = 1;
  17065. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  17066. sockaddr_in addr{};
  17067. addr.sin_family = AF_INET;
  17068. addr.sin_port = htons(static_cast<uint16_t>(port));
  17069. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17070. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17071. ASSERT_EQ(0, ::listen(srv, 1));
  17072. std::atomic<size_t> server_body_bytes{0};
  17073. auto server_thread = std::thread([&] {
  17074. sockaddr_in cli_addr{};
  17075. socklen_t cli_len = sizeof(cli_addr);
  17076. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17077. if (cli == INVALID_SOCKET) { return; }
  17078. // Bound the lifetime of the server side so a buggy client (which never
  17079. // sends the body) cannot make this thread block forever on join.
  17080. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  17081. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  17082. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  17083. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  17084. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  17085. SSL *ssl = SSL_new(ctx);
  17086. SSL_set_fd(ssl, static_cast<int>(cli));
  17087. if (SSL_accept(ssl) > 0) {
  17088. // Read the request headers. Reading here also flushes the TLS 1.3
  17089. // session tickets to the client. Deliberately do NOT send
  17090. // `100 Continue`.
  17091. std::string buf;
  17092. char tmp[1024];
  17093. while (buf.find("\r\n\r\n") == std::string::npos) {
  17094. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17095. if (n <= 0) { break; }
  17096. buf.append(tmp, static_cast<size_t>(n));
  17097. }
  17098. // A correct client sends the body now; count what arrives.
  17099. auto pos = buf.find("\r\n\r\n");
  17100. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  17101. while (body < 4096) {
  17102. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  17103. if (n <= 0) { break; }
  17104. body += static_cast<size_t>(n);
  17105. }
  17106. server_body_bytes = body;
  17107. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  17108. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  17109. SSL_shutdown(ssl);
  17110. }
  17111. SSL_free(ssl);
  17112. detail::close_socket(cli);
  17113. SSL_CTX_free(ctx);
  17114. });
  17115. auto se = detail::scope_exit([&] {
  17116. server_thread.join();
  17117. detail::close_socket(srv);
  17118. });
  17119. SSLClient cli("127.0.0.1", port);
  17120. cli.enable_server_certificate_verification(false);
  17121. cli.set_connection_timeout(5, 0);
  17122. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  17123. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  17124. std::string body(4096, 'A');
  17125. auto res = cli.Put("/api/test", body, "application/json");
  17126. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  17127. EXPECT_EQ(StatusCode::OK_200, res->status);
  17128. EXPECT_EQ(body.size(), server_body_bytes.load());
  17129. }
  17130. #endif
  17131. template <typename S, typename C>
  17132. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  17133. svr.Get("/stream", [&](const Request &, Response &res) {
  17134. auto data = new std::string("01234567890123456789");
  17135. res.set_content_provider(
  17136. data->size(), "text/plain",
  17137. [&, data](size_t offset, size_t length, DataSink &sink) {
  17138. const size_t DATA_CHUNK_SIZE = 4;
  17139. const auto &d = *data;
  17140. std::this_thread::sleep_for(std::chrono::seconds(1));
  17141. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  17142. return true;
  17143. },
  17144. [data](bool success) {
  17145. EXPECT_FALSE(success);
  17146. delete data;
  17147. });
  17148. });
  17149. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  17150. auto i = new size_t(0);
  17151. res.set_content_provider(
  17152. "text/plain",
  17153. [i](size_t, DataSink &sink) {
  17154. if (*i < 5) {
  17155. std::this_thread::sleep_for(std::chrono::seconds(1));
  17156. sink.write("abcd", 4);
  17157. (*i)++;
  17158. } else {
  17159. sink.done();
  17160. }
  17161. return true;
  17162. },
  17163. [i](bool success) {
  17164. EXPECT_FALSE(success);
  17165. delete i;
  17166. });
  17167. });
  17168. svr.Get("/chunked", [&](const Request &, Response &res) {
  17169. auto i = new size_t(0);
  17170. res.set_chunked_content_provider(
  17171. "text/plain",
  17172. [i](size_t, DataSink &sink) {
  17173. if (*i < 5) {
  17174. std::this_thread::sleep_for(std::chrono::seconds(1));
  17175. sink.os << "abcd";
  17176. (*i)++;
  17177. } else {
  17178. sink.done();
  17179. }
  17180. return true;
  17181. },
  17182. [i](bool success) {
  17183. EXPECT_FALSE(success);
  17184. delete i;
  17185. });
  17186. });
  17187. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  17188. auto se = detail::scope_exit([&] {
  17189. svr.stop();
  17190. listen_thread.join();
  17191. ASSERT_FALSE(svr.is_running());
  17192. });
  17193. svr.wait_until_ready();
  17194. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  17195. {
  17196. auto start = std::chrono::steady_clock::now();
  17197. auto res = cli.Get("/stream");
  17198. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17199. std::chrono::steady_clock::now() - start)
  17200. .count();
  17201. ASSERT_FALSE(res);
  17202. EXPECT_EQ(Error::Read, res.error());
  17203. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17204. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17205. }
  17206. {
  17207. auto start = std::chrono::steady_clock::now();
  17208. auto res = cli.Get("/stream_without_length");
  17209. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17210. std::chrono::steady_clock::now() - start)
  17211. .count();
  17212. ASSERT_FALSE(res);
  17213. EXPECT_EQ(Error::Read, res.error());
  17214. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17215. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17216. }
  17217. {
  17218. auto start = std::chrono::steady_clock::now();
  17219. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  17220. EXPECT_EQ("abcd", string(data, data_length));
  17221. return true;
  17222. });
  17223. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17224. std::chrono::steady_clock::now() - start)
  17225. .count();
  17226. ASSERT_FALSE(res);
  17227. EXPECT_EQ(Error::Read, res.error());
  17228. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17229. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17230. }
  17231. }
  17232. TEST(MaxTimeoutTest, ContentStream) {
  17233. time_t timeout = 2000;
  17234. time_t threshold = 200;
  17235. Server svr;
  17236. Client cli("localhost", PORT);
  17237. max_timeout_test(svr, cli, timeout, threshold);
  17238. }
  17239. #ifdef CPPHTTPLIB_SSL_ENABLED
  17240. TEST(MaxTimeoutTest, ContentStreamSSL) {
  17241. time_t timeout = 2000;
  17242. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  17243. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17244. SSLClient cli("localhost", PORT);
  17245. cli.enable_server_certificate_verification(false);
  17246. max_timeout_test(svr, cli, timeout, threshold);
  17247. }
  17248. #endif
  17249. class EventDispatcher {
  17250. public:
  17251. EventDispatcher() {}
  17252. bool wait_event(DataSink *sink) {
  17253. unique_lock<mutex> lk(m_);
  17254. int id = id_;
  17255. // Wait with timeout to prevent hanging if client disconnects
  17256. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  17257. [&] { return cid_ == id; })) {
  17258. return false; // Timeout occurred
  17259. }
  17260. sink->write(message_.data(), message_.size());
  17261. return true;
  17262. }
  17263. void send_event(const string &message) {
  17264. lock_guard<mutex> lk(m_);
  17265. cid_ = id_++;
  17266. message_ = message;
  17267. cv_.notify_all();
  17268. }
  17269. private:
  17270. mutex m_;
  17271. condition_variable cv_;
  17272. atomic_int id_{0};
  17273. atomic_int cid_{-1};
  17274. string message_;
  17275. };
  17276. TEST(ClientInThreadTest, Issue2068) {
  17277. EventDispatcher ed;
  17278. Server svr;
  17279. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  17280. res.set_chunked_content_provider("text/event-stream",
  17281. [&](size_t /*offset*/, DataSink &sink) {
  17282. return ed.wait_event(&sink);
  17283. });
  17284. });
  17285. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  17286. svr.wait_until_ready();
  17287. thread event_thread([&] {
  17288. int id = 0;
  17289. while (svr.is_running()) {
  17290. this_thread::sleep_for(chrono::milliseconds(500));
  17291. std::stringstream ss;
  17292. ss << "data: " << id << "\n\n";
  17293. ed.send_event(ss.str());
  17294. id++;
  17295. }
  17296. });
  17297. auto se = detail::scope_exit([&] {
  17298. svr.stop();
  17299. listen_thread.join();
  17300. event_thread.join();
  17301. ASSERT_FALSE(svr.is_running());
  17302. });
  17303. {
  17304. auto client = detail::make_unique<Client>(HOST, PORT);
  17305. client->set_read_timeout(std::chrono::minutes(10));
  17306. std::atomic<bool> stop{false};
  17307. std::thread t([&] {
  17308. client->Get("/event1",
  17309. [&](const char *, size_t) -> bool { return !stop; });
  17310. });
  17311. std::this_thread::sleep_for(std::chrono::seconds(2));
  17312. stop = true;
  17313. client->stop();
  17314. t.join();
  17315. // Reset client after thread has finished
  17316. client.reset();
  17317. }
  17318. }
  17319. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  17320. auto handled = false;
  17321. Server svr;
  17322. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17323. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17324. auto se = detail::scope_exit([&] {
  17325. svr.stop();
  17326. t.join();
  17327. ASSERT_FALSE(svr.is_running());
  17328. ASSERT_FALSE(handled);
  17329. });
  17330. svr.wait_until_ready();
  17331. // Two Content-Length headers with different values — must be rejected
  17332. auto req = "POST /test HTTP/1.1\r\n"
  17333. "Content-Length: 5\r\n"
  17334. "Content-Length: 10\r\n"
  17335. "\r\n"
  17336. "hello";
  17337. std::string response;
  17338. ASSERT_TRUE(send_request(1, req, &response));
  17339. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17340. response.substr(0, response.find("\r\n")));
  17341. }
  17342. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  17343. auto handled = false;
  17344. Server svr;
  17345. svr.Post("/test", [&](const Request &, Response &res) {
  17346. handled = true;
  17347. res.set_content("ok", "text/plain");
  17348. });
  17349. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17350. auto se = detail::scope_exit([&] {
  17351. svr.stop();
  17352. t.join();
  17353. ASSERT_FALSE(svr.is_running());
  17354. ASSERT_TRUE(handled);
  17355. });
  17356. svr.wait_until_ready();
  17357. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  17358. auto req = "POST /test HTTP/1.1\r\n"
  17359. "Host: localhost\r\n"
  17360. "Content-Length: 5\r\n"
  17361. "Content-Length: 5\r\n"
  17362. "\r\n"
  17363. "hello";
  17364. std::string response;
  17365. ASSERT_TRUE(send_request(1, req, &response));
  17366. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  17367. }
  17368. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  17369. Server svr;
  17370. svr.Get("/test", [](const Request &, Response &res) {
  17371. res.set_content("ok", "text/plain");
  17372. });
  17373. auto port = svr.bind_to_any_port(HOST);
  17374. thread t = thread([&] { svr.listen_after_bind(); });
  17375. auto se = detail::scope_exit([&] {
  17376. svr.stop();
  17377. t.join();
  17378. ASSERT_FALSE(svr.is_running());
  17379. });
  17380. svr.wait_until_ready();
  17381. auto status_line = [&](const std::string &host_lines) {
  17382. std::string res;
  17383. send_request(
  17384. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  17385. &res, port);
  17386. return res.substr(0, res.find("\r\n"));
  17387. };
  17388. const char *accepted[] = {
  17389. "Host: localhost\r\n",
  17390. "Host: a.example:8080\r\n",
  17391. "Host: my_service\r\n",
  17392. "Host: [::1]:8080\r\n",
  17393. "Host: [fe80::1%25eth0]\r\n",
  17394. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  17395. };
  17396. for (auto host_lines : accepted) {
  17397. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  17398. }
  17399. const char *rejected[] = {
  17400. "Host: a.example\r\nHost: b.example\r\n",
  17401. "Host: a.example\r\nHost: a.example\r\n",
  17402. "Host: a@b.example\r\n",
  17403. "Host: a.example/b\r\n",
  17404. "Host: a.example\\b\r\n",
  17405. "Host: a.example?b\r\n",
  17406. "Host: a.example#b\r\n",
  17407. "Host: a.example b.example\r\n",
  17408. };
  17409. for (auto host_lines : rejected) {
  17410. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  17411. << host_lines;
  17412. }
  17413. }
  17414. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  17415. Server svr;
  17416. svr.Get("/", [](const Request &req, Response &res) {
  17417. EXPECT_EQ(2U, req.trailers.size());
  17418. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  17419. // Denied
  17420. EXPECT_FALSE(req.has_trailer("Content-Length"));
  17421. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  17422. // Accepted
  17423. EXPECT_TRUE(req.has_trailer("X-Hello"));
  17424. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  17425. EXPECT_TRUE(req.has_trailer("X-World"));
  17426. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  17427. res.set_content("ok", "text/plain");
  17428. });
  17429. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17430. auto se = detail::scope_exit([&] {
  17431. svr.stop();
  17432. t.join();
  17433. ASSERT_FALSE(svr.is_running());
  17434. });
  17435. svr.wait_until_ready();
  17436. const std::string req = "GET / HTTP/1.1\r\n"
  17437. "Transfer-Encoding: chunked\r\n"
  17438. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  17439. "\r\n"
  17440. "0\r\n"
  17441. "Content-Length: 10\r\n"
  17442. "Host: internal.local\r\n"
  17443. "Content-Type: malicious/content\r\n"
  17444. "Cookie: any\r\n"
  17445. "Set-Cookie: any\r\n"
  17446. "X-Forwarded-For: attacker.com\r\n"
  17447. "X-Real-Ip: 1.1.1.1\r\n"
  17448. "X-Hello: hello\r\n"
  17449. "X-World: world\r\n"
  17450. "\r\n";
  17451. std::string res;
  17452. ASSERT_TRUE(send_request(1, req, &res));
  17453. }
  17454. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  17455. // several field lines, and the combined value is what has to be parsed. A
  17456. // Trailer field split across lines therefore declares every name it lists;
  17457. // reading only the first line silently drops the trailers the later lines
  17458. // declare. The prohibited-trailer filter still applies to every line.
  17459. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  17460. Server svr;
  17461. size_t observed_trailer_count = 0;
  17462. std::string observed_hello;
  17463. std::string observed_world;
  17464. bool observed_content_length = true;
  17465. svr.Get("/", [&](const Request &req, Response &res) {
  17466. observed_trailer_count = req.trailers.size();
  17467. observed_hello = req.get_trailer_value("X-Hello");
  17468. observed_world = req.get_trailer_value("X-World");
  17469. observed_content_length = req.has_trailer("Content-Length");
  17470. res.set_content("ok", "text/plain");
  17471. });
  17472. auto port = svr.bind_to_any_port(HOST);
  17473. thread t = thread([&]() { svr.listen_after_bind(); });
  17474. auto se = detail::scope_exit([&] {
  17475. svr.stop();
  17476. t.join();
  17477. ASSERT_FALSE(svr.is_running());
  17478. });
  17479. svr.wait_until_ready();
  17480. const std::string req = "GET / HTTP/1.1\r\n"
  17481. "Host: localhost\r\n"
  17482. "Transfer-Encoding: chunked\r\n"
  17483. "Trailer: X-Hello\r\n"
  17484. "Trailer: X-World, Content-Length\r\n"
  17485. "\r\n"
  17486. "0\r\n"
  17487. "X-Hello: hello\r\n"
  17488. "X-World: world\r\n"
  17489. "Content-Length: 10\r\n"
  17490. "\r\n";
  17491. std::string res;
  17492. ASSERT_TRUE(send_request(1, req, &res, port));
  17493. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  17494. // Accepted: both field lines contribute to the declared set
  17495. EXPECT_EQ(2U, observed_trailer_count);
  17496. EXPECT_EQ(observed_hello, "hello");
  17497. EXPECT_EQ(observed_world, "world");
  17498. // Denied: a prohibited name stays prohibited on a later field line
  17499. EXPECT_FALSE(observed_content_length);
  17500. }
  17501. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  17502. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  17503. // unbounded run of fields that are never declared, because the counter would
  17504. // only advance for declared fields.
  17505. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  17506. Server svr;
  17507. bool handler_called = false;
  17508. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  17509. handler_called = true;
  17510. res.set_content("ok", "text/plain");
  17511. });
  17512. auto port = svr.bind_to_any_port(HOST);
  17513. thread t = thread([&]() { svr.listen_after_bind(); });
  17514. auto se = detail::scope_exit([&] {
  17515. svr.stop();
  17516. t.join();
  17517. ASSERT_FALSE(svr.is_running());
  17518. });
  17519. svr.wait_until_ready();
  17520. // Declare nothing, then send far more undeclared trailer fields than the
  17521. // header-count limit. Parsing must stop and reject the request rather than
  17522. // read every line.
  17523. std::string req = "GET / HTTP/1.1\r\n"
  17524. "Transfer-Encoding: chunked\r\n"
  17525. "\r\n"
  17526. "0\r\n";
  17527. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  17528. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  17529. }
  17530. req += "\r\n";
  17531. std::string res;
  17532. ASSERT_TRUE(send_request(1, req, &res, port));
  17533. // The request is rejected before the handler runs.
  17534. EXPECT_FALSE(handler_called);
  17535. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  17536. }
  17537. // The set of declared trailer names is capped so a peer cannot grow it without
  17538. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  17539. // declared past the cap is not honored, even if the field is actually sent.
  17540. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  17541. Server svr;
  17542. // One name inside the cap and one past it, so the test tracks the cap rather
  17543. // than a fixed count.
  17544. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  17545. const std::string within_cap_name = "X-T-0";
  17546. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  17547. bool observed_within_cap = false;
  17548. bool observed_past_cap = false;
  17549. svr.Get("/", [&](const Request &req, Response &res) {
  17550. observed_within_cap = req.has_trailer(within_cap_name);
  17551. observed_past_cap = req.has_trailer(past_cap_name);
  17552. res.set_content("ok", "text/plain");
  17553. });
  17554. auto port = svr.bind_to_any_port(HOST);
  17555. thread t = thread([&]() { svr.listen_after_bind(); });
  17556. auto se = detail::scope_exit([&] {
  17557. svr.stop();
  17558. t.join();
  17559. ASSERT_FALSE(svr.is_running());
  17560. });
  17561. svr.wait_until_ready();
  17562. // Declare more trailer names than the cap in a single Trailer field, then
  17563. // actually send the first (within the cap) and the last (past it).
  17564. std::string trailer_decl = "Trailer: ";
  17565. for (int i = 0; i < declared_count; i++) {
  17566. if (i != 0) { trailer_decl += ", "; }
  17567. trailer_decl += "X-T-" + std::to_string(i);
  17568. }
  17569. trailer_decl += "\r\n";
  17570. const std::string req = "GET / HTTP/1.1\r\n"
  17571. "Host: localhost\r\n"
  17572. "Transfer-Encoding: chunked\r\n" +
  17573. trailer_decl +
  17574. "\r\n"
  17575. "0\r\n" +
  17576. within_cap_name + ": a\r\n" + past_cap_name +
  17577. ": b\r\n"
  17578. "\r\n";
  17579. std::string res;
  17580. ASSERT_TRUE(send_request(1, req, &res, port));
  17581. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  17582. // A name within the cap is honored; one declared past the cap is dropped.
  17583. EXPECT_TRUE(observed_within_cap);
  17584. EXPECT_FALSE(observed_past_cap);
  17585. }
  17586. // A direct client that is not listed in trusted_proxies must not be able to
  17587. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  17588. // the peer address on the actual TCP connection determines whether the
  17589. // header is honored.
  17590. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  17591. Server svr;
  17592. // Deliberately does NOT include the loopback address the test client
  17593. // actually connects from, so the direct connection is not a trusted proxy.
  17594. svr.set_trusted_proxies({"203.0.113.66"});
  17595. std::string observed_remote_addr;
  17596. svr.Get("/ip", [&](const Request &req, Response &res) {
  17597. observed_remote_addr = req.remote_addr;
  17598. res.set_content("ok", "text/plain");
  17599. });
  17600. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17601. auto se = detail::scope_exit([&] {
  17602. svr.stop();
  17603. t.join();
  17604. ASSERT_FALSE(svr.is_running());
  17605. });
  17606. svr.wait_until_ready();
  17607. Client cli(HOST, PORT);
  17608. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  17609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17610. EXPECT_EQ(StatusCode::OK_200, res->status);
  17611. // The connecting peer is not a trusted proxy, so the spoofed header must be
  17612. // ignored entirely and the real connection-level address retained.
  17613. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17614. observed_remote_addr == "127.0.0.1");
  17615. }
  17616. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  17617. Server svr;
  17618. std::string observed_remote_addr;
  17619. std::string observed_xff;
  17620. svr.Get("/ip", [&](const Request &req, Response &res) {
  17621. observed_remote_addr = req.remote_addr;
  17622. observed_xff = req.get_header_value("X-Forwarded-For");
  17623. res.set_content("ok", "text/plain");
  17624. });
  17625. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17626. auto se = detail::scope_exit([&] {
  17627. svr.stop();
  17628. t.join();
  17629. ASSERT_FALSE(svr.is_running());
  17630. });
  17631. svr.wait_until_ready();
  17632. Client cli(HOST, PORT);
  17633. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  17634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17635. EXPECT_EQ(StatusCode::OK_200, res->status);
  17636. EXPECT_EQ(observed_xff, "203.0.113.66");
  17637. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17638. observed_remote_addr == "127.0.0.1");
  17639. }
  17640. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  17641. Server svr;
  17642. svr.set_trusted_proxies({"203.0.113.66"});
  17643. std::string observed_remote_addr;
  17644. std::string observed_xff;
  17645. svr.Get("/ip", [&](const Request &req, Response &res) {
  17646. observed_remote_addr = req.remote_addr;
  17647. observed_xff = req.get_header_value("X-Forwarded-For");
  17648. res.set_content("ok", "text/plain");
  17649. });
  17650. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17651. auto se = detail::scope_exit([&] {
  17652. svr.stop();
  17653. t.join();
  17654. ASSERT_FALSE(svr.is_running());
  17655. });
  17656. svr.wait_until_ready();
  17657. Client cli(HOST, PORT);
  17658. auto res = cli.Get("/ip");
  17659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17660. EXPECT_EQ(StatusCode::OK_200, res->status);
  17661. EXPECT_EQ(observed_xff, "");
  17662. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17663. observed_remote_addr == "127.0.0.1");
  17664. }
  17665. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  17666. Server svr;
  17667. // Include the loopback address the test client actually connects from, so
  17668. // the direct connection itself is recognized as the trusted proxy hop.
  17669. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  17670. std::string observed_remote_addr;
  17671. std::string observed_xff;
  17672. svr.Get("/ip", [&](const Request &req, Response &res) {
  17673. observed_remote_addr = req.remote_addr;
  17674. observed_xff = req.get_header_value("X-Forwarded-For");
  17675. res.set_content("ok", "text/plain");
  17676. });
  17677. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17678. auto se = detail::scope_exit([&] {
  17679. svr.stop();
  17680. t.join();
  17681. ASSERT_FALSE(svr.is_running());
  17682. });
  17683. svr.wait_until_ready();
  17684. Client cli(HOST, PORT);
  17685. auto res = cli.Get(
  17686. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  17687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17688. EXPECT_EQ(StatusCode::OK_200, res->status);
  17689. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  17690. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17691. }
  17692. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  17693. Server svr;
  17694. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  17695. std::string observed_remote_addr;
  17696. std::string observed_xff;
  17697. svr.Get("/ip", [&](const Request &req, Response &res) {
  17698. observed_remote_addr = req.remote_addr;
  17699. observed_xff = req.get_header_value("X-Forwarded-For");
  17700. res.set_content("ok", "text/plain");
  17701. });
  17702. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17703. auto se = detail::scope_exit([&] {
  17704. svr.stop();
  17705. t.join();
  17706. ASSERT_FALSE(svr.is_running());
  17707. });
  17708. svr.wait_until_ready();
  17709. Client cli(HOST, PORT);
  17710. auto res = cli.Get(
  17711. "/ip",
  17712. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17714. EXPECT_EQ(StatusCode::OK_200, res->status);
  17715. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17716. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17717. }
  17718. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  17719. Server svr;
  17720. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17721. std::string observed_remote_addr;
  17722. std::string observed_xff;
  17723. svr.Get("/ip", [&](const Request &req, Response &res) {
  17724. observed_remote_addr = req.remote_addr;
  17725. observed_xff = req.get_header_value("X-Forwarded-For");
  17726. res.set_content("ok", "text/plain");
  17727. });
  17728. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17729. auto se = detail::scope_exit([&] {
  17730. svr.stop();
  17731. t.join();
  17732. ASSERT_FALSE(svr.is_running());
  17733. });
  17734. svr.wait_until_ready();
  17735. Client cli(HOST, PORT);
  17736. auto res = cli.Get(
  17737. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  17738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17739. EXPECT_EQ(StatusCode::OK_200, res->status);
  17740. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  17741. // by the closest hop) is used. The leftmost entry is fully client-controlled
  17742. // and must not be selected.
  17743. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  17744. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  17745. }
  17746. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  17747. Server svr;
  17748. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  17749. std::string observed_remote_addr;
  17750. svr.Get("/ip", [&](const Request &req, Response &res) {
  17751. observed_remote_addr = req.remote_addr;
  17752. res.set_content("ok", "text/plain");
  17753. });
  17754. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17755. auto se = detail::scope_exit([&] {
  17756. svr.stop();
  17757. t.join();
  17758. ASSERT_FALSE(svr.is_running());
  17759. });
  17760. svr.wait_until_ready();
  17761. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  17762. // a forged address and the trusted proxy's own address; the forged value must
  17763. // not win over the address the trusted proxy actually recorded.
  17764. Client cli(HOST, PORT);
  17765. auto res = cli.Get(
  17766. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  17767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17768. EXPECT_EQ(StatusCode::OK_200, res->status);
  17769. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  17770. }
  17771. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  17772. Server svr;
  17773. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17774. std::string observed_remote_addr;
  17775. std::string observed_xff;
  17776. svr.Get("/ip", [&](const Request &req, Response &res) {
  17777. observed_remote_addr = req.remote_addr;
  17778. observed_xff = req.get_header_value("X-Forwarded-For");
  17779. res.set_content("ok", "text/plain");
  17780. });
  17781. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17782. auto se = detail::scope_exit([&] {
  17783. svr.stop();
  17784. t.join();
  17785. ASSERT_FALSE(svr.is_running());
  17786. });
  17787. svr.wait_until_ready();
  17788. Client cli(HOST, PORT);
  17789. auto res = cli.Get(
  17790. "/ip",
  17791. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17793. EXPECT_EQ(StatusCode::OK_200, res->status);
  17794. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17795. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17796. }
  17797. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  17798. Server svr;
  17799. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17800. std::string observed_remote_addr;
  17801. std::string observed_xff;
  17802. svr.Get("/ip", [&](const Request &req, Response &res) {
  17803. observed_remote_addr = req.remote_addr;
  17804. observed_xff = req.get_header_value("X-Forwarded-For");
  17805. res.set_content("ok", "text/plain");
  17806. });
  17807. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17808. auto se = detail::scope_exit([&] {
  17809. svr.stop();
  17810. t.join();
  17811. ASSERT_FALSE(svr.is_running());
  17812. });
  17813. svr.wait_until_ready();
  17814. std::string raw_req =
  17815. "GET /ip HTTP/1.1\r\n"
  17816. "Host: localhost\r\n"
  17817. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  17818. "Connection: close\r\n"
  17819. "\r\n";
  17820. std::string out;
  17821. ASSERT_TRUE(send_request(5, raw_req, &out));
  17822. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17823. // Header parser trims surrounding whitespace of the header value
  17824. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  17825. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17826. }
  17827. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  17828. // one comma-joined value, in the order received. Proxies such as HAProxy append
  17829. // their own X-Forwarded-For as a separate field line rather than extending the
  17830. // one the client sent, so every occurrence has to be taken into account.
  17831. // Reading only the first one hands back the address the client chose.
  17832. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  17833. Server svr;
  17834. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17835. std::string observed_remote_addr;
  17836. size_t observed_xff_count = 0;
  17837. svr.Get("/ip", [&](const Request &req, Response &res) {
  17838. observed_remote_addr = req.remote_addr;
  17839. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  17840. res.set_content("ok", "text/plain");
  17841. });
  17842. auto port = svr.bind_to_any_port(HOST);
  17843. thread t = thread([&]() { svr.listen_after_bind(); });
  17844. auto se = detail::scope_exit([&] {
  17845. svr.stop();
  17846. t.join();
  17847. ASSERT_FALSE(svr.is_running());
  17848. });
  17849. svr.wait_until_ready();
  17850. // The client supplies the first field line; the trusted proxy appends the
  17851. // address it observed as a second one.
  17852. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  17853. "Host: localhost\r\n"
  17854. "X-Forwarded-For: 1.2.3.4\r\n"
  17855. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  17856. "Connection: close\r\n"
  17857. "\r\n";
  17858. std::string out;
  17859. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17860. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17861. EXPECT_EQ(observed_xff_count, 2U);
  17862. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17863. // The same chain spread over one field line per hop derives the same client
  17864. // address, i.e. the split and the comma-joined representations agree.
  17865. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  17866. "Host: localhost\r\n"
  17867. "X-Forwarded-For: 1.2.3.4\r\n"
  17868. "X-Forwarded-For: 198.51.100.23\r\n"
  17869. "X-Forwarded-For: 192.0.2.45\r\n"
  17870. "Connection: close\r\n"
  17871. "\r\n";
  17872. out.clear();
  17873. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  17874. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17875. EXPECT_EQ(observed_xff_count, 3U);
  17876. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17877. }
  17878. // An X-Forwarded-For header whose value parses to zero IP segments must not
  17879. // crash the server (it used to call front() on an empty vector inside
  17880. // get_client_ip). The connection-level remote address must be retained instead.
  17881. static void run_malformed_xff_test(const std::string &xff_value) {
  17882. Server svr;
  17883. svr.set_trusted_proxies({"192.0.2.45"});
  17884. std::string observed_remote_addr;
  17885. svr.Get("/ip", [&](const Request &req, Response &res) {
  17886. observed_remote_addr = req.remote_addr;
  17887. res.set_content("ok", "text/plain");
  17888. });
  17889. int port = 0;
  17890. thread t = thread([&]() {
  17891. port = svr.bind_to_any_port(HOST);
  17892. svr.listen_after_bind();
  17893. });
  17894. auto se = detail::scope_exit([&] {
  17895. svr.stop();
  17896. t.join();
  17897. ASSERT_FALSE(svr.is_running());
  17898. });
  17899. svr.wait_until_ready();
  17900. Client cli(HOST, port);
  17901. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  17902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17903. EXPECT_EQ(StatusCode::OK_200, res->status);
  17904. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17905. observed_remote_addr == "127.0.0.1");
  17906. }
  17907. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  17908. run_malformed_xff_test("");
  17909. }
  17910. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  17911. run_malformed_xff_test(",");
  17912. }
  17913. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  17914. run_malformed_xff_test(", , ,");
  17915. }
  17916. // The same rule applies to Accept: a request whose acceptable types are spread
  17917. // over several field lines must be negotiated against all of them.
  17918. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  17919. // case-insensitive connection options. Comparing the whole field value against
  17920. // one option misses a client that sends several of them, and misses every
  17921. // casing but the one written in the comparison.
  17922. //
  17923. // Sends req, reads the response, then reuses the same socket for a second
  17924. // request to find out whether the server kept the connection.
  17925. static void probe_connection_reuse(int port, const std::string &req,
  17926. bool *announced_close, bool *reusable) {
  17927. auto error = Error::Success;
  17928. auto sock = detail::create_client_socket(
  17929. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17930. /*connection_timeout_sec=*/5, 0,
  17931. /*read_timeout_sec=*/1, 0,
  17932. /*write_timeout_sec=*/5, 0, std::string(), error);
  17933. ASSERT_NE(sock, INVALID_SOCKET);
  17934. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  17935. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  17936. "Host: localhost\r\n"
  17937. "Connection: close\r\n"
  17938. "\r\n";
  17939. std::string first_response;
  17940. std::string second_response;
  17941. detail::process_client_socket(
  17942. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  17943. [&](Stream &strm) {
  17944. if (strm.write(req.data(), req.size()) !=
  17945. static_cast<ssize_t>(req.size())) {
  17946. return false;
  17947. }
  17948. char buf[512];
  17949. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  17950. // Headers plus the two-byte body of the handler below
  17951. while (reader.getline()) {
  17952. first_response += reader.ptr();
  17953. if (first_response.find("ok") != std::string::npos) { break; }
  17954. }
  17955. if (strm.write(second.data(), second.size()) !=
  17956. static_cast<ssize_t>(second.size())) {
  17957. return true;
  17958. }
  17959. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  17960. while (reader2.getline()) {
  17961. second_response += reader2.ptr();
  17962. if (second_response.find("ok") != std::string::npos) { break; }
  17963. }
  17964. return true;
  17965. });
  17966. *announced_close =
  17967. first_response.find("Connection: close") != std::string::npos;
  17968. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  17969. }
  17970. class ConnectionTokenTest : public ::testing::Test {
  17971. protected:
  17972. void SetUp() override {
  17973. svr_.Get("/keepalive", [](const Request &, Response &res) {
  17974. res.set_content("ok", "text/plain");
  17975. });
  17976. port_ = svr_.bind_to_any_port(HOST);
  17977. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17978. svr_.wait_until_ready();
  17979. }
  17980. void TearDown() override {
  17981. svr_.stop();
  17982. if (thread_.joinable()) { thread_.join(); }
  17983. }
  17984. Server svr_;
  17985. int port_ = 0;
  17986. thread thread_;
  17987. };
  17988. // "close" alongside another option still closes the connection, and the
  17989. // response says so rather than leaving the peer to discover it.
  17990. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  17991. bool announced_close = false;
  17992. bool reusable = true;
  17993. probe_connection_reuse(port_,
  17994. "GET /keepalive HTTP/1.1\r\n"
  17995. "Host: localhost\r\n"
  17996. "Connection: keep-alive, close\r\n"
  17997. "\r\n",
  17998. &announced_close, &reusable);
  17999. EXPECT_TRUE(announced_close);
  18000. EXPECT_FALSE(reusable);
  18001. }
  18002. // "close" split over two field lines is the same list, so it is honored too.
  18003. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  18004. bool announced_close = false;
  18005. bool reusable = true;
  18006. probe_connection_reuse(port_,
  18007. "GET /keepalive HTTP/1.1\r\n"
  18008. "Host: localhost\r\n"
  18009. "Connection: keep-alive\r\n"
  18010. "Connection: close\r\n"
  18011. "\r\n",
  18012. &announced_close, &reusable);
  18013. EXPECT_TRUE(announced_close);
  18014. EXPECT_FALSE(reusable);
  18015. }
  18016. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  18017. // keep-alive in the spelling everyone actually sends keeps its connection.
  18018. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  18019. bool announced_close = false;
  18020. bool reusable = false;
  18021. probe_connection_reuse(port_,
  18022. "GET /keepalive HTTP/1.0\r\n"
  18023. "Host: localhost\r\n"
  18024. "Connection: keep-alive\r\n"
  18025. "\r\n",
  18026. &announced_close, &reusable);
  18027. EXPECT_FALSE(announced_close);
  18028. EXPECT_TRUE(reusable);
  18029. }
  18030. // A token the value merely contains is not the token itself.
  18031. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  18032. bool announced_close = false;
  18033. bool reusable = false;
  18034. probe_connection_reuse(port_,
  18035. "GET /keepalive HTTP/1.1\r\n"
  18036. "Host: localhost\r\n"
  18037. "Connection: notclose\r\n"
  18038. "\r\n",
  18039. &announced_close, &reusable);
  18040. EXPECT_FALSE(announced_close);
  18041. EXPECT_TRUE(reusable);
  18042. }
  18043. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  18044. Server svr;
  18045. std::vector<std::string> observed_types;
  18046. svr.Get("/", [&](const Request &req, Response &res) {
  18047. observed_types = req.accept_content_types;
  18048. res.set_content("ok", "text/plain");
  18049. });
  18050. auto port = svr.bind_to_any_port(HOST);
  18051. thread t = thread([&]() { svr.listen_after_bind(); });
  18052. auto se = detail::scope_exit([&] {
  18053. svr.stop();
  18054. t.join();
  18055. ASSERT_FALSE(svr.is_running());
  18056. });
  18057. svr.wait_until_ready();
  18058. Client cli(HOST, port);
  18059. Headers headers;
  18060. headers.emplace("Accept", "text/plain;q=0.5");
  18061. headers.emplace("Accept", "application/json");
  18062. auto res = cli.Get("/", headers);
  18063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18064. EXPECT_EQ(StatusCode::OK_200, res->status);
  18065. // Sorted by q-value, so the second field line's type comes first
  18066. ASSERT_EQ(2U, observed_types.size());
  18067. EXPECT_EQ("application/json", observed_types[0]);
  18068. EXPECT_EQ("text/plain", observed_types[1]);
  18069. }
  18070. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  18071. // empty field line must not contribute a bare comma to the combined value.
  18072. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  18073. Server svr;
  18074. std::vector<std::string> observed_types;
  18075. svr.Get("/", [&](const Request &req, Response &res) {
  18076. observed_types = req.accept_content_types;
  18077. res.set_content("ok", "text/plain");
  18078. });
  18079. auto port = svr.bind_to_any_port(HOST);
  18080. thread t = thread([&]() { svr.listen_after_bind(); });
  18081. auto se = detail::scope_exit([&] {
  18082. svr.stop();
  18083. t.join();
  18084. ASSERT_FALSE(svr.is_running());
  18085. });
  18086. svr.wait_until_ready();
  18087. // Empty first field line, then a real one
  18088. std::string raw_req = "GET / HTTP/1.1\r\n"
  18089. "Host: localhost\r\n"
  18090. "Accept:\r\n"
  18091. "Accept: application/json\r\n"
  18092. "Connection: close\r\n"
  18093. "\r\n";
  18094. std::string out;
  18095. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  18096. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18097. ASSERT_EQ(1U, observed_types.size());
  18098. EXPECT_EQ("application/json", observed_types[0]);
  18099. }
  18100. // The skip in get_combined_header_value() is what keeps an empty field line
  18101. // from contributing a bare comma. Only a trailing empty field line exercises
  18102. // it: a leading one is already covered by the "combined is still empty" check,
  18103. // and parse_accept_header() now ignores the empty element either way, so the
  18104. // request-level test above can no longer tell the two apart.
  18105. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  18106. Headers headers;
  18107. headers.emplace("Accept", "text/html");
  18108. headers.emplace("Accept", "");
  18109. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  18110. headers.clear();
  18111. headers.emplace("Accept", "");
  18112. headers.emplace("Accept", "application/json");
  18113. EXPECT_EQ("application/json",
  18114. detail::get_combined_header_value(headers, "Accept"));
  18115. }
  18116. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18117. // An encoding offered on a later Accept-Encoding field line is still offered.
  18118. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  18119. Server svr;
  18120. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18121. res.set_content(std::string(1024, 'x'), "text/plain");
  18122. });
  18123. auto port = svr.bind_to_any_port(HOST);
  18124. thread t = thread([&]() { svr.listen_after_bind(); });
  18125. auto se = detail::scope_exit([&] {
  18126. svr.stop();
  18127. t.join();
  18128. ASSERT_FALSE(svr.is_running());
  18129. });
  18130. svr.wait_until_ready();
  18131. Client cli(HOST, port);
  18132. cli.set_decompress(false);
  18133. Headers headers;
  18134. headers.emplace("Accept-Encoding", "identity");
  18135. headers.emplace("Accept-Encoding", "gzip");
  18136. auto res = cli.Get("/", headers);
  18137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18138. EXPECT_EQ(StatusCode::OK_200, res->status);
  18139. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  18140. }
  18141. #endif
  18142. #ifndef _WIN32
  18143. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  18144. Server svr;
  18145. svr.Post("/post", [&](const Request &req, Response &res) {
  18146. res.set_content(req.body, "text/plain");
  18147. });
  18148. svr.Put("/put", [&](const Request &req, Response &res) {
  18149. res.set_content(req.body, "text/plain");
  18150. });
  18151. svr.Patch("/patch", [&](const Request &req, Response &res) {
  18152. res.set_content(req.body, "text/plain");
  18153. });
  18154. svr.Delete("/delete", [&](const Request &req, Response &res) {
  18155. res.set_content(req.body, "text/plain");
  18156. });
  18157. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18158. auto se = detail::scope_exit([&] {
  18159. svr.stop();
  18160. t.join();
  18161. ASSERT_FALSE(svr.is_running());
  18162. });
  18163. svr.wait_until_ready();
  18164. std::string resp;
  18165. // POST without Content-Length
  18166. ASSERT_TRUE(send_request(5,
  18167. "POST /post HTTP/1.1\r\n"
  18168. "Host: localhost\r\n"
  18169. "Connection: close\r\n"
  18170. "\r\n",
  18171. &resp));
  18172. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18173. // PUT without Content-Length
  18174. resp.clear();
  18175. ASSERT_TRUE(send_request(5,
  18176. "PUT /put HTTP/1.1\r\n"
  18177. "Host: localhost\r\n"
  18178. "Connection: close\r\n"
  18179. "\r\n",
  18180. &resp));
  18181. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18182. // PATCH without Content-Length
  18183. resp.clear();
  18184. ASSERT_TRUE(send_request(5,
  18185. "PATCH /patch HTTP/1.1\r\n"
  18186. "Host: localhost\r\n"
  18187. "Connection: close\r\n"
  18188. "\r\n",
  18189. &resp));
  18190. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18191. // DELETE without Content-Length
  18192. resp.clear();
  18193. ASSERT_TRUE(send_request(5,
  18194. "DELETE /delete HTTP/1.1\r\n"
  18195. "Host: localhost\r\n"
  18196. "Connection: close\r\n"
  18197. "\r\n",
  18198. &resp));
  18199. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18200. }
  18201. #endif
  18202. //==============================================================================
  18203. // open_stream() Tests
  18204. //==============================================================================
  18205. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  18206. std::string result;
  18207. char buf[8192];
  18208. ssize_t n;
  18209. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18210. result.append(buf, static_cast<size_t>(n));
  18211. }
  18212. return result;
  18213. }
  18214. // Mock stream for unit tests
  18215. class MockStream : public Stream {
  18216. public:
  18217. std::string data;
  18218. size_t pos = 0;
  18219. ssize_t error_after = -1; // -1 = no error
  18220. explicit MockStream(const std::string &d, ssize_t err = -1)
  18221. : data(d), error_after(err) {}
  18222. bool is_readable() const override { return true; }
  18223. bool wait_readable() const override { return true; }
  18224. bool wait_writable() const override { return true; }
  18225. ssize_t read(char *ptr, size_t size) override {
  18226. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  18227. if (pos >= data.size()) return 0;
  18228. size_t limit =
  18229. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  18230. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  18231. std::memcpy(ptr, data.data() + pos, to_read);
  18232. pos += to_read;
  18233. return static_cast<ssize_t>(to_read);
  18234. }
  18235. ssize_t write(const char *, size_t) override { return -1; }
  18236. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  18237. ip = "127.0.0.1";
  18238. port = 0;
  18239. }
  18240. void get_local_ip_and_port(std::string &ip, int &port) const override {
  18241. ip = "127.0.0.1";
  18242. port = 0;
  18243. }
  18244. socket_t socket() const override { return INVALID_SOCKET; }
  18245. time_t duration() const override { return 0; }
  18246. };
  18247. TEST(StreamHandleTest, Basic) {
  18248. ClientImpl::StreamHandle handle;
  18249. EXPECT_FALSE(handle.is_valid());
  18250. handle.response = detail::make_unique<Response>();
  18251. handle.error = Error::Connection;
  18252. EXPECT_FALSE(handle.is_valid());
  18253. handle.error = Error::Success;
  18254. EXPECT_TRUE(handle.is_valid());
  18255. }
  18256. TEST(BodyReaderTest, Basic) {
  18257. MockStream stream("Hello, World!");
  18258. detail::BodyReader reader;
  18259. reader.stream = &stream;
  18260. reader.content_length = 13;
  18261. char buf[32];
  18262. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  18263. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  18264. EXPECT_TRUE(reader.eof);
  18265. }
  18266. TEST(BodyReaderTest, NoStream) {
  18267. detail::BodyReader reader;
  18268. char buf[32];
  18269. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18270. EXPECT_EQ(Error::Connection, reader.last_error);
  18271. }
  18272. TEST(BodyReaderTest, Error) {
  18273. MockStream stream("Hello, World!", 5);
  18274. detail::BodyReader reader;
  18275. reader.stream = &stream;
  18276. reader.content_length = 13;
  18277. char buf[32];
  18278. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  18279. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18280. EXPECT_EQ(Error::Read, reader.last_error);
  18281. }
  18282. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  18283. // Mock-based StreamHandle tests relying on private internals are removed.
  18284. class OpenStreamTest : public ::testing::Test {
  18285. protected:
  18286. void SetUp() override {
  18287. svr_.Get("/hello", [](const Request &, Response &res) {
  18288. res.set_content("Hello World!", "text/plain");
  18289. });
  18290. svr_.Get("/large", [](const Request &, Response &res) {
  18291. res.set_content(std::string(10000, 'X'), "text/plain");
  18292. });
  18293. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  18294. res.set_content("Hello World!", "image/jpeg");
  18295. res.set_header("Content-Encoding", "UTF-8");
  18296. });
  18297. svr_.Get("/chunked", [](const Request &, Response &res) {
  18298. res.set_chunked_content_provider("text/plain",
  18299. [](size_t offset, DataSink &sink) {
  18300. if (offset < 15) {
  18301. sink.write("chunk", 5);
  18302. return true;
  18303. }
  18304. sink.done();
  18305. return true;
  18306. });
  18307. });
  18308. svr_.Get("/compressible", [](const Request &, Response &res) {
  18309. res.set_chunked_content_provider("text/plain", [](size_t offset,
  18310. DataSink &sink) {
  18311. if (offset < 100 * 1024) {
  18312. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  18313. sink.write(chunk.data(), chunk.size());
  18314. return true;
  18315. }
  18316. sink.done();
  18317. return true;
  18318. });
  18319. });
  18320. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  18321. [](const Request & /*req*/, Response &res) {
  18322. auto i = new int(0);
  18323. res.set_header("Trailer", "Content-Length, X-Allowed");
  18324. res.set_chunked_content_provider(
  18325. "text/plain",
  18326. [i](size_t /*offset*/, DataSink &sink) {
  18327. switch (*i) {
  18328. case 0: sink.os << "123"; break;
  18329. case 1: sink.os << "456"; break;
  18330. case 2: sink.os << "789"; break;
  18331. case 3: {
  18332. sink.done_with_trailer(
  18333. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  18334. } break;
  18335. }
  18336. (*i)++;
  18337. return true;
  18338. },
  18339. [i](bool success) {
  18340. EXPECT_TRUE(success);
  18341. delete i;
  18342. });
  18343. });
  18344. // Echo headers endpoint for header-related tests
  18345. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  18346. std::string body;
  18347. for (const auto &h : req.headers) {
  18348. body.append(h.first);
  18349. body.push_back(':');
  18350. body.append(h.second);
  18351. body.push_back('\n');
  18352. }
  18353. res.set_content(body, "text/plain");
  18354. });
  18355. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  18356. std::string body;
  18357. for (const auto &h : req.headers) {
  18358. body.append(h.first);
  18359. body.push_back(':');
  18360. body.append(h.second);
  18361. body.push_back('\n');
  18362. }
  18363. res.set_content(body, "text/plain");
  18364. });
  18365. port_ = svr_.bind_to_any_port("127.0.0.1");
  18366. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18367. svr_.wait_until_ready();
  18368. }
  18369. void TearDown() override {
  18370. svr_.stop();
  18371. if (thread_.joinable()) thread_.join();
  18372. }
  18373. Server svr_;
  18374. std::thread thread_;
  18375. int port_ = 0;
  18376. };
  18377. TEST_F(OpenStreamTest, Basic) {
  18378. Client cli("127.0.0.1", port_);
  18379. auto handle = cli.open_stream("GET", "/hello");
  18380. EXPECT_TRUE(handle.is_valid());
  18381. EXPECT_EQ("Hello World!", read_all(handle));
  18382. }
  18383. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  18384. Client cli("127.0.0.1", port_);
  18385. auto handle = cli.open_stream("GET", "/unknown-encoding");
  18386. ASSERT_TRUE(handle.is_valid());
  18387. EXPECT_EQ("Hello World!", read_all(handle));
  18388. }
  18389. TEST_F(OpenStreamTest, SmallBuffer) {
  18390. Client cli("127.0.0.1", port_);
  18391. auto handle = cli.open_stream("GET", "/hello");
  18392. std::string result;
  18393. char buf[4];
  18394. ssize_t n;
  18395. while ((n = handle.read(buf, sizeof(buf))) > 0)
  18396. result.append(buf, static_cast<size_t>(n));
  18397. EXPECT_EQ("Hello World!", result);
  18398. }
  18399. TEST_F(OpenStreamTest, DefaultHeaders) {
  18400. Client cli("127.0.0.1", port_);
  18401. // open_stream GET should include Host, User-Agent and Accept-Encoding
  18402. {
  18403. auto handle = cli.open_stream("GET", "/echo-headers");
  18404. ASSERT_TRUE(handle.is_valid());
  18405. auto body = read_all(handle);
  18406. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  18407. std::string::npos);
  18408. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  18409. std::string::npos);
  18410. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  18411. }
  18412. // open_stream POST with body and no explicit content_type should NOT add
  18413. // text/plain Content-Type (behavior differs from non-streaming path), but
  18414. // should include Content-Length
  18415. {
  18416. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  18417. ASSERT_TRUE(handle.is_valid());
  18418. auto body = read_all(handle);
  18419. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  18420. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  18421. }
  18422. // open_stream POST with explicit Content-Type should preserve it
  18423. {
  18424. auto handle = cli.open_stream("POST", "/echo-headers", {},
  18425. {{"Content-Type", "application/custom"}},
  18426. "{}", "application/custom");
  18427. ASSERT_TRUE(handle.is_valid());
  18428. auto body = read_all(handle);
  18429. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  18430. }
  18431. // User-specified User-Agent must not be overwritten for stream API
  18432. {
  18433. auto handle = cli.open_stream("GET", "/echo-headers", {},
  18434. {{"User-Agent", "MyAgent/1.2"}});
  18435. ASSERT_TRUE(handle.is_valid());
  18436. auto body = read_all(handle);
  18437. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  18438. }
  18439. }
  18440. TEST_F(OpenStreamTest, Large) {
  18441. Client cli("127.0.0.1", port_);
  18442. auto handle = cli.open_stream("GET", "/large");
  18443. EXPECT_EQ(10000u, read_all(handle).size());
  18444. }
  18445. TEST_F(OpenStreamTest, ConnectionError) {
  18446. Client cli("127.0.0.1", 9999);
  18447. auto handle = cli.open_stream("GET", "/hello");
  18448. EXPECT_FALSE(handle.is_valid());
  18449. }
  18450. TEST_F(OpenStreamTest, Chunked) {
  18451. Client cli("127.0.0.1", port_);
  18452. auto handle = cli.open_stream("GET", "/chunked");
  18453. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18454. "Transfer-Encoding") == "chunked");
  18455. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  18456. }
  18457. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  18458. Client cli("127.0.0.1", port_);
  18459. auto handle =
  18460. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  18461. ASSERT_TRUE(handle.is_valid());
  18462. // Consume body to allow trailers to be received/parsed
  18463. auto body = read_all(handle);
  18464. // Explicitly parse trailers (ensure trailers are available for assertion)
  18465. handle.parse_trailers_if_needed();
  18466. EXPECT_EQ(std::string("123456789"), body);
  18467. // The response should include a Trailer header declaring both names
  18468. ASSERT_TRUE(handle.response);
  18469. EXPECT_TRUE(handle.response->has_header("Trailer"));
  18470. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  18471. handle.response->get_header_value("Trailer"));
  18472. // Prohibited trailer must not be present
  18473. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  18474. // Allowed trailer should be present
  18475. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  18476. EXPECT_EQ(std::string("yes"),
  18477. handle.response->get_trailer_value("X-Allowed"));
  18478. // Verify trailers are NOT present as regular headers
  18479. EXPECT_EQ(std::string(""),
  18480. handle.response->get_header_value("Content-Length"));
  18481. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  18482. }
  18483. // Accepts one connection on an OS-assigned port, which it hands over through
  18484. // port_promise, reads the request head and sends back response. after_send,
  18485. // if given, runs on the connection before it is closed.
  18486. static std::thread
  18487. serve_single_response(std::promise<int> &port_promise,
  18488. const std::string &response,
  18489. std::function<void(socket_t)> after_send = nullptr) {
  18490. return std::thread([&port_promise, response, after_send] {
  18491. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18492. default_socket_options(srv);
  18493. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18494. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  18495. sockaddr_in addr{};
  18496. addr.sin_family = AF_INET;
  18497. addr.sin_port = htons(0); // Let OS assign a free port
  18498. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18499. int opt = 1;
  18500. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  18501. #ifdef _WIN32
  18502. reinterpret_cast<const char *>(&opt),
  18503. #else
  18504. &opt,
  18505. #endif
  18506. sizeof(opt));
  18507. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  18508. ::listen(srv, 1) != 0) {
  18509. port_promise.set_value(-1);
  18510. detail::close_socket(srv);
  18511. return;
  18512. }
  18513. socklen_t addr_len = sizeof(addr);
  18514. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  18515. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  18516. sockaddr_in cli_addr{};
  18517. socklen_t cli_len = sizeof(cli_addr);
  18518. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18519. if (cli != INVALID_SOCKET) {
  18520. // Read the complete HTTP request (until the blank line that terminates
  18521. // headers) before sending the response. If the server closes the socket
  18522. // while the client's request data is still unread in the kernel receive
  18523. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  18524. // connection on both sides: it discards the client's receive buffer
  18525. // (which already holds our response) and causes any in-progress write on
  18526. // the client to fail with ECONNRESET. Reading all request data first
  18527. // ensures close() emits a graceful FIN.
  18528. {
  18529. char rbuf[256];
  18530. std::string req;
  18531. while (req.find("\r\n\r\n") == std::string::npos) {
  18532. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  18533. if (n <= 0) { break; }
  18534. req.append(rbuf, static_cast<size_t>(n));
  18535. }
  18536. }
  18537. ::send(cli,
  18538. #ifdef _WIN32
  18539. static_cast<const char *>(response.c_str()),
  18540. static_cast<int>(response.size()),
  18541. #else
  18542. response.c_str(), response.size(),
  18543. #endif
  18544. 0);
  18545. if (after_send) { after_send(cli); }
  18546. detail::close_socket(cli);
  18547. }
  18548. detail::close_socket(srv);
  18549. });
  18550. }
  18551. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  18552. #ifndef _WIN32
  18553. signal(SIGPIPE, SIG_IGN);
  18554. #endif
  18555. std::promise<int> port_promise;
  18556. auto port_future = port_promise.get_future();
  18557. auto server_thread =
  18558. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  18559. "Content-Type: text/plain\r\n"
  18560. "Content-Length: not-a-number\r\n"
  18561. "Connection: close\r\n"
  18562. "\r\n"
  18563. "hello");
  18564. auto port = port_future.get();
  18565. ASSERT_GT(port, 0);
  18566. Client cli("127.0.0.1", port);
  18567. auto handle = cli.open_stream("GET", "/");
  18568. EXPECT_FALSE(handle.is_valid());
  18569. server_thread.join();
  18570. }
  18571. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  18572. #ifndef _WIN32
  18573. signal(SIGPIPE, SIG_IGN);
  18574. #endif
  18575. std::promise<int> port_promise;
  18576. auto port_future = port_promise.get_future();
  18577. auto server_thread = serve_single_response(
  18578. port_promise, "HTTP/1.1 200 OK\r\n"
  18579. "Content-Type: text/plain\r\n"
  18580. "Content-Length: 99999999999999999999999999\r\n"
  18581. "Connection: close\r\n"
  18582. "\r\n"
  18583. "hello");
  18584. auto port = port_future.get();
  18585. ASSERT_GT(port, 0);
  18586. // Historically std::stoull would throw std::out_of_range here and crash
  18587. // the process, then parsing silently clamped to a bogus framing length and
  18588. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  18589. // so the stream fails to open, matching the not-a-number case above. The
  18590. // process still must NOT terminate.
  18591. Client cli("127.0.0.1", port);
  18592. auto handle = cli.open_stream("GET", "/");
  18593. EXPECT_FALSE(handle.is_valid());
  18594. server_thread.join();
  18595. }
  18596. // Serves `response` to the single request `fn` makes with a fresh client.
  18597. template <typename Fn>
  18598. static void with_single_response(const std::string &response, Fn fn) {
  18599. #ifndef _WIN32
  18600. signal(SIGPIPE, SIG_IGN);
  18601. #endif
  18602. std::promise<int> port_promise;
  18603. auto port_future = port_promise.get_future();
  18604. auto server_thread = serve_single_response(port_promise, response);
  18605. auto se = detail::scope_exit([&] { server_thread.join(); });
  18606. auto port = port_future.get();
  18607. ASSERT_GT(port, 0);
  18608. Client cli("127.0.0.1", port);
  18609. fn(cli);
  18610. }
  18611. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  18612. const char *responses[] = {
  18613. "HTTP/1.1 103 Early Hints\r\n"
  18614. "Link: </style.css>; rel=preload\r\n"
  18615. "\r\n"
  18616. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  18617. "HTTP/1.1 100 Continue\r\n"
  18618. "X-Note: interim\r\n"
  18619. "\r\n"
  18620. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  18621. };
  18622. for (auto response : responses) {
  18623. with_single_response(response, [](Client &cli) {
  18624. auto res = cli.Get("/");
  18625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18626. EXPECT_EQ(StatusCode::OK_200, res->status);
  18627. EXPECT_EQ("ok", res->body);
  18628. });
  18629. }
  18630. }
  18631. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  18632. #ifndef _WIN32
  18633. signal(SIGPIPE, SIG_IGN);
  18634. #endif
  18635. // The server answers the head without asking for the body. Bytes it then
  18636. // reads on the connection would be taken for the body the request declared.
  18637. auto closed_by_client = false;
  18638. std::promise<int> port_promise;
  18639. auto server_thread = serve_single_response(
  18640. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  18641. [&](socket_t sock) {
  18642. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  18643. char buf[256];
  18644. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  18645. });
  18646. Client cli("127.0.0.1", port_promise.get_future().get());
  18647. cli.set_keep_alive(true);
  18648. cli.set_read_timeout(1, 0);
  18649. // Long enough for the client to send Expect: 100-continue.
  18650. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  18651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18652. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  18653. cli.Get("/second");
  18654. server_thread.join();
  18655. EXPECT_TRUE(closed_by_client);
  18656. }
  18657. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  18658. // Long enough for the client to send Expect: 100-continue
  18659. with_single_response(
  18660. "HTTP/1.1 103 Early Hints\r\n"
  18661. "Link: </style.css>; rel=preload\r\n"
  18662. "\r\n"
  18663. "HTTP/1.1 401 Unauthorized\r\n"
  18664. "Content-Length: 0\r\n\r\n",
  18665. [](Client &cli) {
  18666. cli.set_read_timeout(2, 0);
  18667. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  18668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18669. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  18670. });
  18671. }
  18672. #ifdef CPPHTTPLIB_SSL_ENABLED
  18673. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  18674. #ifndef _WIN32
  18675. signal(SIGPIPE, SIG_IGN);
  18676. #endif
  18677. auto reused = false;
  18678. std::promise<int> port_promise;
  18679. auto server_thread = serve_single_response(
  18680. port_promise,
  18681. "HTTP/1.1 401 Unauthorized\r\n"
  18682. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  18683. "Content-Length: 0\r\n\r\n",
  18684. [&](socket_t sock) {
  18685. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  18686. char buf[256];
  18687. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  18688. });
  18689. Client cli("127.0.0.1", port_promise.get_future().get());
  18690. cli.set_keep_alive(true);
  18691. cli.set_digest_auth("user", "pass");
  18692. cli.set_read_timeout(1, 0);
  18693. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  18694. server_thread.join();
  18695. EXPECT_FALSE(reused);
  18696. }
  18697. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  18698. // Any other answer to CONNECT would read as the origin's response.
  18699. struct {
  18700. const char *response;
  18701. bool passed_on;
  18702. } cases[] = {
  18703. {"HTTP/1.1 201 Created\r\n"
  18704. "Set-Cookie: session=from-proxy\r\n"
  18705. "Content-Length: 0\r\n\r\n",
  18706. false},
  18707. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  18708. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  18709. "Content-Length: 0\r\n\r\n",
  18710. true},
  18711. };
  18712. for (const auto &c : cases) {
  18713. std::promise<int> port_promise;
  18714. auto server_thread = serve_single_response(port_promise, c.response);
  18715. SSLClient cli("example.com", 443);
  18716. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  18717. auto res = cli.Get("/");
  18718. server_thread.join();
  18719. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  18720. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  18721. if (res) {
  18722. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  18723. }
  18724. }
  18725. }
  18726. #endif
  18727. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  18728. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  18729. // the chunked coding and drop Content-Length, so a front-end that trusts
  18730. // Content-Length would disagree about where the body ends (response
  18731. // smuggling). The client must reject such a response.
  18732. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  18733. for (const char *te : {"chunked", "gzip, chunked"}) {
  18734. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  18735. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  18736. "\r\n" + "Connection: close\r\n" + "\r\n" +
  18737. "5\r\nhello\r\n0\r\n\r\n";
  18738. with_single_response(response, [&](Client &cli) {
  18739. auto res = cli.Get("/");
  18740. EXPECT_FALSE(static_cast<bool>(res)) << te;
  18741. EXPECT_EQ(Error::Read, res.error()) << te;
  18742. });
  18743. with_single_response(response, [&](Client &cli) {
  18744. auto handle = cli.open_stream("GET", "/");
  18745. EXPECT_FALSE(handle.is_valid()) << te;
  18746. EXPECT_EQ(Error::Read, handle.error) << te;
  18747. });
  18748. }
  18749. }
  18750. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  18751. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  18752. // closing the connection (unlike a request, which must be rejected).
  18753. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  18754. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18755. "Transfer-Encoding: chunked\r\n"
  18756. "Connection: close\r\n"
  18757. "\r\n"
  18758. "5\r\nhello\r\n0\r\n\r\n",
  18759. "HTTP/1.1 200 OK\r\n"
  18760. "Transfer-Encoding: gzip\r\n"
  18761. "Connection: close\r\n"
  18762. "\r\n"
  18763. "hello"}) {
  18764. with_single_response(response, [&](Client &cli) {
  18765. auto res = cli.Get("/");
  18766. ASSERT_TRUE(static_cast<bool>(res)) << response;
  18767. EXPECT_EQ("hello", res->body);
  18768. });
  18769. with_single_response(response, [&](Client &cli) {
  18770. auto handle = cli.open_stream("GET", "/");
  18771. ASSERT_TRUE(handle.is_valid()) << response;
  18772. EXPECT_EQ("hello", read_all(handle));
  18773. });
  18774. }
  18775. }
  18776. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  18777. // framing headers describe nothing to read and must not be rejected.
  18778. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  18779. const std::string framing = "Content-Length: 5\r\n"
  18780. "Transfer-Encoding: chunked\r\n"
  18781. "Connection: close\r\n"
  18782. "\r\n";
  18783. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18784. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  18785. });
  18786. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18787. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  18788. });
  18789. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  18790. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  18791. with_single_response(response, [&](Client &cli) {
  18792. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  18793. });
  18794. with_single_response(response, [&](Client &cli) {
  18795. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  18796. });
  18797. }
  18798. }
  18799. // A payload max length of 0 means no limit, however the body is framed.
  18800. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  18801. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18802. "Transfer-Encoding: chunked\r\n"
  18803. "\r\n"
  18804. "5\r\nhello\r\n0\r\n\r\n",
  18805. "HTTP/1.1 200 OK\r\n"
  18806. "Connection: close\r\n"
  18807. "\r\n"
  18808. "hello"}) {
  18809. with_single_response(response, [&](Client &cli) {
  18810. cli.set_payload_max_length(0);
  18811. auto res = cli.Get("/");
  18812. ASSERT_TRUE(res) << response;
  18813. EXPECT_EQ("hello", res->body) << response;
  18814. });
  18815. }
  18816. }
  18817. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  18818. Server svr;
  18819. svr.set_payload_max_length(0);
  18820. svr.Post("/echo", [](const Request &req, Response &res) {
  18821. res.set_content(req.body, "text/plain");
  18822. });
  18823. auto port = svr.bind_to_any_port(HOST);
  18824. thread t = thread([&] { svr.listen_after_bind(); });
  18825. auto se = detail::scope_exit([&] {
  18826. svr.stop();
  18827. t.join();
  18828. ASSERT_FALSE(svr.is_running());
  18829. });
  18830. svr.wait_until_ready();
  18831. Client cli(HOST, port);
  18832. auto res = cli.Post(
  18833. "/echo",
  18834. [](size_t /*offset*/, DataSink &sink) {
  18835. sink.write("hello", 5);
  18836. sink.done();
  18837. return true;
  18838. },
  18839. "text/plain");
  18840. ASSERT_TRUE(res);
  18841. EXPECT_EQ(StatusCode::OK_200, res->status);
  18842. EXPECT_EQ("hello", res->body);
  18843. }
  18844. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18845. TEST_F(OpenStreamTest, Gzip) {
  18846. Client cli("127.0.0.1", port_);
  18847. auto handle = cli.open_stream("GET", "/compressible", {},
  18848. {{"Accept-Encoding", "gzip"}});
  18849. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  18850. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18851. }
  18852. #endif
  18853. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18854. TEST_F(OpenStreamTest, Brotli) {
  18855. Client cli("127.0.0.1", port_);
  18856. auto handle =
  18857. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  18858. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  18859. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18860. }
  18861. #endif
  18862. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18863. TEST_F(OpenStreamTest, Zstd) {
  18864. Client cli("127.0.0.1", port_);
  18865. auto handle = cli.open_stream("GET", "/compressible", {},
  18866. {{"Accept-Encoding", "zstd"}});
  18867. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  18868. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18869. }
  18870. #endif
  18871. #ifdef CPPHTTPLIB_SSL_ENABLED
  18872. class SSLOpenStreamTest : public ::testing::Test {
  18873. protected:
  18874. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  18875. void SetUp() override {
  18876. svr_.Get("/hello", [](const Request &, Response &res) {
  18877. res.set_content("Hello SSL World!", "text/plain");
  18878. });
  18879. svr_.Get("/chunked", [](const Request &, Response &res) {
  18880. res.set_chunked_content_provider("text/plain",
  18881. [](size_t offset, DataSink &sink) {
  18882. if (offset < 15) {
  18883. sink.write("chunk", 5);
  18884. return true;
  18885. }
  18886. sink.done();
  18887. return true;
  18888. });
  18889. });
  18890. svr_.Post("/echo", [](const Request &req, Response &res) {
  18891. res.set_content(req.body, req.get_header_value("Content-Type"));
  18892. });
  18893. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  18894. std::string body = req.body;
  18895. res.set_chunked_content_provider(
  18896. "text/plain", [body](size_t offset, DataSink &sink) {
  18897. if (offset < body.size()) {
  18898. sink.write(body.data() + offset, body.size() - offset);
  18899. }
  18900. sink.done();
  18901. return true;
  18902. });
  18903. });
  18904. port_ = svr_.bind_to_any_port("127.0.0.1");
  18905. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18906. svr_.wait_until_ready();
  18907. }
  18908. void TearDown() override {
  18909. svr_.stop();
  18910. if (thread_.joinable()) thread_.join();
  18911. }
  18912. SSLServer svr_;
  18913. std::thread thread_;
  18914. int port_ = 0;
  18915. };
  18916. TEST_F(SSLOpenStreamTest, Basic) {
  18917. SSLClient cli("127.0.0.1", port_);
  18918. cli.enable_server_certificate_verification(false);
  18919. auto handle = cli.open_stream("GET", "/hello");
  18920. ASSERT_TRUE(handle.is_valid());
  18921. EXPECT_EQ("Hello SSL World!", read_all(handle));
  18922. }
  18923. TEST_F(SSLOpenStreamTest, Chunked) {
  18924. SSLClient cli("127.0.0.1", port_);
  18925. cli.enable_server_certificate_verification(false);
  18926. auto handle = cli.open_stream("GET", "/chunked");
  18927. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18928. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18929. "Transfer-Encoding") == "chunked");
  18930. auto body = read_all(handle);
  18931. EXPECT_EQ("chunkchunkchunk", body);
  18932. }
  18933. TEST_F(SSLOpenStreamTest, Post) {
  18934. SSLClient cli("127.0.0.1", port_);
  18935. cli.enable_server_certificate_verification(false);
  18936. auto handle =
  18937. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  18938. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18939. EXPECT_EQ(200, handle.response->status);
  18940. auto body = read_all(handle);
  18941. EXPECT_EQ("Hello SSL POST", body);
  18942. }
  18943. TEST_F(SSLOpenStreamTest, PostChunked) {
  18944. SSLClient cli("127.0.0.1", port_);
  18945. cli.enable_server_certificate_verification(false);
  18946. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  18947. "Chunked SSL Data", "text/plain");
  18948. ASSERT_TRUE(handle.is_valid());
  18949. EXPECT_EQ(200, handle.response->status);
  18950. auto body = read_all(handle);
  18951. EXPECT_EQ("Chunked SSL Data", body);
  18952. }
  18953. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  18954. // Content-Length is terminated by the server closing the connection. When the
  18955. // SSL peer sends a close_notify after the body, the client must treat it as a
  18956. // clean EOF and return a successful response rather than an error.
  18957. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  18958. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18959. ASSERT_TRUE(svr.is_valid());
  18960. svr.set_keep_alive_max_count(1);
  18961. const std::string expected_body = "Hello from connection-close response!";
  18962. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  18963. res.set_content_provider("text/plain",
  18964. [&](size_t offset, DataSink &sink) -> bool {
  18965. if (offset < expected_body.size()) {
  18966. sink.write(expected_body.data() + offset,
  18967. expected_body.size() - offset);
  18968. }
  18969. sink.done();
  18970. return true;
  18971. });
  18972. });
  18973. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  18974. auto se = detail::scope_exit([&] {
  18975. svr.stop();
  18976. listen_thread.join();
  18977. ASSERT_FALSE(svr.is_running());
  18978. });
  18979. svr.wait_until_ready();
  18980. SSLClient cli(HOST, PORT);
  18981. cli.enable_server_certificate_verification(false);
  18982. auto res = cli.Get("/no-content-length");
  18983. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  18984. EXPECT_EQ(StatusCode::OK_200, res->status);
  18985. EXPECT_EQ(expected_body, res->body);
  18986. }
  18987. #endif // CPPHTTPLIB_SSL_ENABLED
  18988. //==============================================================================
  18989. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  18990. // results for various scenarios.
  18991. //==============================================================================
  18992. TEST(ParityTest, GetVsOpenStream) {
  18993. Server svr;
  18994. const std::string path = "/parity";
  18995. const std::string content = "Parity test content: hello world";
  18996. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18997. res.set_content(content, "text/plain");
  18998. });
  18999. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19000. auto se = detail::scope_exit([&] {
  19001. svr.stop();
  19002. t.join();
  19003. ASSERT_FALSE(svr.is_running());
  19004. });
  19005. svr.wait_until_ready();
  19006. Client cli(HOST, PORT);
  19007. // Non-stream path
  19008. auto r1 = cli.Get(path);
  19009. ASSERT_TRUE(r1);
  19010. EXPECT_EQ(StatusCode::OK_200, r1->status);
  19011. // Stream path
  19012. auto h = cli.open_stream("GET", path);
  19013. ASSERT_TRUE(h.is_valid());
  19014. EXPECT_EQ(r1->body, read_all(h));
  19015. }
  19016. // Helper to compress data with provided compressor type T
  19017. template <typename Compressor>
  19018. static std::string compress_payload_for_parity(const std::string &in) {
  19019. std::string out;
  19020. Compressor compressor;
  19021. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  19022. [&](const char *data, size_t n) {
  19023. out.append(data, n);
  19024. return true;
  19025. });
  19026. EXPECT_TRUE(ok);
  19027. return out;
  19028. }
  19029. // Helper function for compression parity tests
  19030. template <typename Compressor>
  19031. static void test_compression_parity(const std::string &original,
  19032. const std::string &path,
  19033. const std::string &encoding) {
  19034. const std::string compressed =
  19035. compress_payload_for_parity<Compressor>(original);
  19036. Server svr;
  19037. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  19038. res.set_content(compressed, "application/octet-stream");
  19039. res.set_header("Content-Encoding", encoding);
  19040. });
  19041. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  19042. auto se = detail::scope_exit([&] {
  19043. svr.stop();
  19044. t.join();
  19045. ASSERT_FALSE(svr.is_running());
  19046. });
  19047. svr.wait_until_ready();
  19048. Client cli(HOST, PORT);
  19049. // Non-streaming
  19050. {
  19051. auto res = cli.Get(path);
  19052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19053. EXPECT_EQ(StatusCode::OK_200, res->status);
  19054. EXPECT_EQ(original, res->body);
  19055. }
  19056. // Streaming
  19057. {
  19058. auto h = cli.open_stream("GET", path);
  19059. ASSERT_TRUE(h.is_valid());
  19060. EXPECT_EQ(original, read_all(h));
  19061. }
  19062. }
  19063. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19064. TEST(ParityTest, Gzip) {
  19065. test_compression_parity<detail::gzip_compressor>(
  19066. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  19067. }
  19068. #endif
  19069. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  19070. TEST(ParityTest, Brotli) {
  19071. test_compression_parity<detail::brotli_compressor>(
  19072. "Hello, brotli parity test payload", "/parity-br", "br");
  19073. }
  19074. #endif
  19075. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  19076. TEST(ParityTest, Zstd) {
  19077. test_compression_parity<detail::zstd_compressor>(
  19078. "Zstandard parity test payload", "/parity-zstd", "zstd");
  19079. }
  19080. #endif
  19081. //==============================================================================
  19082. // New Stream API Tests
  19083. //==============================================================================
  19084. inline std::string read_body(httplib::stream::Result &result) {
  19085. std::string body;
  19086. while (result.next()) {
  19087. body.append(result.data(), result.size());
  19088. }
  19089. return body;
  19090. }
  19091. TEST(ClientConnectionTest, Basic) {
  19092. httplib::ClientConnection conn;
  19093. EXPECT_FALSE(conn.is_open());
  19094. conn.sock = 1;
  19095. EXPECT_TRUE(conn.is_open());
  19096. httplib::ClientConnection conn2(std::move(conn));
  19097. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  19098. conn2.sock = INVALID_SOCKET;
  19099. }
  19100. // Unified test server for all stream::* tests
  19101. class StreamApiTest : public ::testing::Test {
  19102. protected:
  19103. void SetUp() override {
  19104. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19105. res.set_content("Hello World!", "text/plain");
  19106. });
  19107. svr_.Get("/echo-params",
  19108. [](const httplib::Request &req, httplib::Response &res) {
  19109. std::string r;
  19110. for (const auto &p : req.params) {
  19111. if (!r.empty()) r += "&";
  19112. r += p.first + "=" + p.second;
  19113. }
  19114. res.set_content(r, "text/plain");
  19115. });
  19116. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19117. res.set_content(req.body, req.get_header_value("Content-Type"));
  19118. });
  19119. svr_.Post("/echo-headers",
  19120. [](const httplib::Request &req, httplib::Response &res) {
  19121. std::string r;
  19122. for (const auto &h : req.headers)
  19123. r += h.first + ": " + h.second + "\n";
  19124. res.set_content(r, "text/plain");
  19125. });
  19126. svr_.Post("/echo-params",
  19127. [](const httplib::Request &req, httplib::Response &res) {
  19128. std::string r = "params:";
  19129. for (const auto &p : req.params)
  19130. r += p.first + "=" + p.second + ";";
  19131. res.set_content(r + " body:" + req.body, "text/plain");
  19132. });
  19133. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  19134. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  19135. });
  19136. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19137. res.set_content("PUT:" + req.body, "text/plain");
  19138. });
  19139. svr_.Patch("/echo",
  19140. [](const httplib::Request &req, httplib::Response &res) {
  19141. res.set_content("PATCH:" + req.body, "text/plain");
  19142. });
  19143. svr_.Delete(
  19144. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  19145. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  19146. "text/plain");
  19147. });
  19148. svr_.Get("/head-test",
  19149. [](const httplib::Request &, httplib::Response &res) {
  19150. res.set_content("body for HEAD", "text/plain");
  19151. });
  19152. svr_.Options("/options",
  19153. [](const httplib::Request &, httplib::Response &res) {
  19154. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  19155. });
  19156. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  19157. svr_.wait_until_ready();
  19158. }
  19159. void TearDown() override {
  19160. svr_.stop();
  19161. if (thread_.joinable()) thread_.join();
  19162. }
  19163. httplib::Server svr_;
  19164. std::thread thread_;
  19165. };
  19166. // stream::Get tests
  19167. TEST_F(StreamApiTest, GetBasic) {
  19168. httplib::Client cli(HOST, PORT);
  19169. auto result = httplib::stream::Get(cli, "/hello");
  19170. ASSERT_TRUE(result.is_valid());
  19171. EXPECT_EQ(200, result.status());
  19172. EXPECT_EQ("Hello World!", read_body(result));
  19173. }
  19174. TEST_F(StreamApiTest, GetWithParams) {
  19175. httplib::Client cli(HOST, PORT);
  19176. httplib::Params params{{"foo", "bar"}};
  19177. auto result = httplib::stream::Get(cli, "/echo-params", params);
  19178. ASSERT_TRUE(result.is_valid());
  19179. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  19180. }
  19181. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19182. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  19183. httplib::Client cli(HOST, PORT);
  19184. cli.set_payload_max_length(0);
  19185. auto result = httplib::stream::Get(cli, "/hello");
  19186. ASSERT_TRUE(result.is_valid());
  19187. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  19188. EXPECT_EQ("Hello World!", read_body(result));
  19189. }
  19190. #endif
  19191. TEST_F(StreamApiTest, GetConnectionError) {
  19192. httplib::Client cli(HOST, 9999);
  19193. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  19194. }
  19195. TEST_F(StreamApiTest, Get404) {
  19196. httplib::Client cli(HOST, PORT);
  19197. auto result = httplib::stream::Get(cli, "/nonexistent");
  19198. EXPECT_TRUE(result.is_valid());
  19199. EXPECT_EQ(404, result.status());
  19200. }
  19201. // stream::Post tests
  19202. TEST_F(StreamApiTest, PostBasic) {
  19203. httplib::Client cli(HOST, PORT);
  19204. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  19205. "application/json");
  19206. ASSERT_TRUE(result.is_valid());
  19207. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  19208. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  19209. }
  19210. TEST_F(StreamApiTest, PostWithHeaders) {
  19211. httplib::Client cli(HOST, PORT);
  19212. httplib::Headers headers{{"X-Custom", "value"}};
  19213. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  19214. "text/plain");
  19215. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  19216. }
  19217. TEST_F(StreamApiTest, PostWithParams) {
  19218. httplib::Client cli(HOST, PORT);
  19219. httplib::Params params{{"k", "v"}};
  19220. auto result =
  19221. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  19222. auto body = read_body(result);
  19223. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  19224. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  19225. }
  19226. TEST_F(StreamApiTest, PostLarge) {
  19227. httplib::Client cli(HOST, PORT);
  19228. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  19229. size_t total = 0;
  19230. while (result.next()) {
  19231. total += result.size();
  19232. }
  19233. EXPECT_EQ(100u * 1024u, total);
  19234. }
  19235. // stream::Put/Patch tests
  19236. TEST_F(StreamApiTest, PutAndPatch) {
  19237. httplib::Client cli(HOST, PORT);
  19238. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  19239. EXPECT_EQ("PUT:test", read_body(put));
  19240. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  19241. EXPECT_EQ("PATCH:test", read_body(patch));
  19242. }
  19243. // stream::Delete tests
  19244. TEST_F(StreamApiTest, Delete) {
  19245. httplib::Client cli(HOST, PORT);
  19246. auto del1 = httplib::stream::Delete(cli, "/resource");
  19247. EXPECT_EQ("Deleted", read_body(del1));
  19248. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  19249. EXPECT_EQ("Deleted:data", read_body(del2));
  19250. }
  19251. // stream::Head/Options tests
  19252. TEST_F(StreamApiTest, HeadAndOptions) {
  19253. httplib::Client cli(HOST, PORT);
  19254. auto head = httplib::stream::Head(cli, "/head-test");
  19255. EXPECT_TRUE(head.is_valid());
  19256. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  19257. auto opts = httplib::stream::Options(cli, "/options");
  19258. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  19259. }
  19260. // SSL stream::* tests
  19261. #ifdef CPPHTTPLIB_SSL_ENABLED
  19262. class SSLStreamApiTest : public ::testing::Test {
  19263. protected:
  19264. void SetUp() override {
  19265. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19266. res.set_content("Hello SSL!", "text/plain");
  19267. });
  19268. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19269. res.set_content(req.body, "text/plain");
  19270. });
  19271. port_ = svr_.bind_to_any_port("127.0.0.1");
  19272. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19273. svr_.wait_until_ready();
  19274. }
  19275. void TearDown() override {
  19276. svr_.stop();
  19277. if (thread_.joinable()) thread_.join();
  19278. }
  19279. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  19280. std::thread thread_;
  19281. int port_ = 0;
  19282. };
  19283. TEST_F(SSLStreamApiTest, GetAndPost) {
  19284. httplib::SSLClient cli("127.0.0.1", port_);
  19285. cli.enable_server_certificate_verification(false);
  19286. auto get = httplib::stream::Get(cli, "/hello");
  19287. EXPECT_EQ("Hello SSL!", read_body(get));
  19288. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  19289. EXPECT_EQ("test", read_body(post));
  19290. }
  19291. #endif
  19292. // Tests for Error::Timeout and Error::ConnectionClosed error types
  19293. // These errors are set in SocketStream/SSLSocketStream and propagated through
  19294. // BodyReader
  19295. TEST(ErrorHandlingTest, StreamReadTimeout) {
  19296. // Test that read timeout during streaming is detected
  19297. // Use a large content-length response where server delays mid-stream
  19298. Server svr;
  19299. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19300. // Send a large response with delay in the middle
  19301. res.set_content_provider(
  19302. 1000, // content_length
  19303. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  19304. if (offset < 100) {
  19305. // Send first 100 bytes immediately
  19306. std::string data(100, 'A');
  19307. sink.write(data.c_str(), data.size());
  19308. return true;
  19309. }
  19310. // Then delay longer than client timeout
  19311. std::this_thread::sleep_for(std::chrono::seconds(3));
  19312. std::string data(900, 'B');
  19313. sink.write(data.c_str(), data.size());
  19314. return true;
  19315. });
  19316. });
  19317. auto port = 8091;
  19318. std::thread t([&]() { svr.listen("localhost", port); });
  19319. svr.wait_until_ready();
  19320. Client cli("localhost", port);
  19321. cli.set_read_timeout(1, 0); // 1 second timeout
  19322. auto handle = cli.open_stream("GET", "/slow-stream");
  19323. ASSERT_TRUE(handle.is_valid());
  19324. char buf[256];
  19325. ssize_t total = 0;
  19326. ssize_t n;
  19327. bool got_error = false;
  19328. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19329. total += n;
  19330. }
  19331. if (n < 0) {
  19332. got_error = true;
  19333. // Should be timeout or read error
  19334. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19335. handle.get_read_error() == Error::Read)
  19336. << "Actual error: " << to_string(handle.get_read_error());
  19337. }
  19338. // Either we got an error, or we got less data than expected
  19339. EXPECT_TRUE(got_error || total < 1000)
  19340. << "Expected timeout but got all " << total << " bytes";
  19341. svr.stop();
  19342. t.join();
  19343. }
  19344. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  19345. // Test connection closed detection via BodyReader
  19346. Server svr;
  19347. std::atomic<bool> close_now{false};
  19348. svr.Get("/will-close", [&](const Request &, Response &res) {
  19349. res.set_content_provider(
  19350. 10000, // Large content_length that we won't fully send
  19351. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19352. if (offset < 100) {
  19353. std::string data(100, 'X');
  19354. sink.write(data.c_str(), data.size());
  19355. return true;
  19356. }
  19357. // Wait for signal then abort
  19358. while (!close_now) {
  19359. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19360. }
  19361. return false; // Abort - server will close connection
  19362. });
  19363. });
  19364. auto port = 8092;
  19365. std::thread t([&]() { svr.listen("localhost", port); });
  19366. svr.wait_until_ready();
  19367. Client cli("localhost", port);
  19368. auto handle = cli.open_stream("GET", "/will-close");
  19369. ASSERT_TRUE(handle.is_valid());
  19370. char buf[256];
  19371. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19372. EXPECT_GT(n, 0) << "First read should succeed";
  19373. // Signal server to close
  19374. close_now = true;
  19375. // Keep reading until error or EOF
  19376. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19377. // Keep reading
  19378. }
  19379. // Should get an error since content_length wasn't satisfied
  19380. if (n < 0) {
  19381. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19382. handle.get_read_error() == Error::Read)
  19383. << "Actual error: " << to_string(handle.get_read_error());
  19384. }
  19385. svr.stop();
  19386. t.join();
  19387. }
  19388. #ifdef CPPHTTPLIB_SSL_ENABLED
  19389. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  19390. // Test that read timeout during SSL streaming is detected
  19391. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19392. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19393. res.set_content_provider(
  19394. 1000, "text/plain",
  19395. [](size_t offset, size_t /*length*/, DataSink &sink) {
  19396. if (offset < 100) {
  19397. std::string data(100, 'A');
  19398. sink.write(data.c_str(), data.size());
  19399. return true;
  19400. }
  19401. std::this_thread::sleep_for(std::chrono::seconds(3));
  19402. std::string data(900, 'B');
  19403. sink.write(data.c_str(), data.size());
  19404. return true;
  19405. });
  19406. });
  19407. auto port = 8093;
  19408. std::thread t([&]() { svr.listen("localhost", port); });
  19409. svr.wait_until_ready();
  19410. SSLClient cli("localhost", port);
  19411. cli.enable_server_certificate_verification(false);
  19412. cli.set_read_timeout(1, 0); // 1 second timeout
  19413. auto handle = cli.open_stream("GET", "/slow-stream");
  19414. ASSERT_TRUE(handle.is_valid());
  19415. char buf[256];
  19416. ssize_t total = 0;
  19417. ssize_t n;
  19418. bool got_error = false;
  19419. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19420. total += n;
  19421. }
  19422. if (n < 0) {
  19423. got_error = true;
  19424. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19425. handle.get_read_error() == Error::Read)
  19426. << "Actual error: " << to_string(handle.get_read_error());
  19427. }
  19428. EXPECT_TRUE(got_error || total < 1000)
  19429. << "Expected timeout but got all " << total << " bytes";
  19430. svr.stop();
  19431. t.join();
  19432. }
  19433. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  19434. // Test SSL connection closed detection
  19435. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19436. std::atomic<bool> close_now{false};
  19437. svr.Get("/will-close", [&](const Request &, Response &res) {
  19438. res.set_content_provider(
  19439. 10000, "text/plain",
  19440. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19441. if (offset < 100) {
  19442. std::string data(100, 'X');
  19443. sink.write(data.c_str(), data.size());
  19444. return true;
  19445. }
  19446. while (!close_now) {
  19447. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19448. }
  19449. return false;
  19450. });
  19451. });
  19452. auto port = 8094;
  19453. std::thread t([&]() { svr.listen("localhost", port); });
  19454. svr.wait_until_ready();
  19455. SSLClient cli("localhost", port);
  19456. cli.enable_server_certificate_verification(false);
  19457. auto handle = cli.open_stream("GET", "/will-close");
  19458. ASSERT_TRUE(handle.is_valid());
  19459. char buf[256];
  19460. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19461. EXPECT_GT(n, 0);
  19462. // Signal server to close
  19463. close_now = true;
  19464. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19465. // Keep reading
  19466. }
  19467. if (n < 0) {
  19468. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19469. handle.get_read_error() == Error::Read)
  19470. << "Actual error: " << to_string(handle.get_read_error());
  19471. }
  19472. svr.stop();
  19473. t.join();
  19474. }
  19475. #endif
  19476. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  19477. using namespace httplib;
  19478. // Create a test file
  19479. const char *fname = "etag_testfile.txt";
  19480. const char *content = "etag-content";
  19481. {
  19482. std::ofstream ofs(fname);
  19483. ofs << content;
  19484. ASSERT_TRUE(ofs.good());
  19485. }
  19486. Server svr;
  19487. svr.set_mount_point("/static", ".");
  19488. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19489. svr.wait_until_ready();
  19490. Client cli(HOST, PORT);
  19491. // First request: should get 200 with ETag header
  19492. auto res1 = cli.Get("/static/etag_testfile.txt");
  19493. ASSERT_TRUE(res1);
  19494. ASSERT_EQ(200, res1->status);
  19495. ASSERT_TRUE(res1->has_header("ETag"));
  19496. std::string etag = res1->get_header_value("ETag");
  19497. EXPECT_FALSE(etag.empty());
  19498. // Verify ETag format: W/"hex-hex"
  19499. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  19500. EXPECT_EQ('W', etag[0]);
  19501. EXPECT_EQ('/', etag[1]);
  19502. EXPECT_EQ('"', etag[2]);
  19503. EXPECT_EQ('"', etag.back());
  19504. // Exact match: expect 304 Not Modified
  19505. Headers h2 = {{"If-None-Match", etag}};
  19506. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  19507. ASSERT_TRUE(res2);
  19508. EXPECT_EQ(304, res2->status);
  19509. // Wildcard match: expect 304 Not Modified
  19510. Headers h3 = {{"If-None-Match", "*"}};
  19511. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  19512. ASSERT_TRUE(res3);
  19513. EXPECT_EQ(304, res3->status);
  19514. // Non-matching ETag: expect 200
  19515. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  19516. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  19517. ASSERT_TRUE(res4);
  19518. EXPECT_EQ(200, res4->status);
  19519. // Multiple ETags with one matching: expect 304
  19520. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  19521. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  19522. ASSERT_TRUE(res5);
  19523. EXPECT_EQ(304, res5->status);
  19524. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  19525. // that equivalent to the single comma-separated list above, so the match on
  19526. // the second line must still be found.
  19527. Headers h6;
  19528. h6.emplace("If-None-Match", "W/\"other\"");
  19529. h6.emplace("If-None-Match", etag);
  19530. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  19531. ASSERT_TRUE(res6);
  19532. EXPECT_EQ(304, res6->status);
  19533. svr.stop();
  19534. t.join();
  19535. std::remove(fname);
  19536. }
  19537. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  19538. using namespace httplib;
  19539. Server svr;
  19540. svr.set_mount_point("/static", ".");
  19541. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19542. svr.wait_until_ready();
  19543. Client cli(HOST, PORT);
  19544. // Send If-None-Match: * to a non-existent file
  19545. Headers h = {{"If-None-Match", "*"}};
  19546. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  19547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19548. EXPECT_EQ(404, res->status);
  19549. svr.stop();
  19550. t.join();
  19551. }
  19552. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  19553. using namespace httplib;
  19554. // Create a test file
  19555. const char *fname = "etag_boundary_testfile.txt";
  19556. const char *content = "boundary-test";
  19557. {
  19558. std::ofstream ofs(fname);
  19559. ofs << content;
  19560. ASSERT_TRUE(ofs.good());
  19561. }
  19562. Server svr;
  19563. svr.set_mount_point("/static", ".");
  19564. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19565. svr.wait_until_ready();
  19566. Client cli(HOST, PORT);
  19567. // Get the actual ETag
  19568. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  19569. ASSERT_TRUE(res1);
  19570. ASSERT_EQ(200, res1->status);
  19571. ASSERT_TRUE(res1->has_header("ETag"));
  19572. std::string etag = res1->get_header_value("ETag");
  19573. // Test 1: Very long ETag value (longer than actual ETag)
  19574. // Should NOT match and return 200 (not trigger out-of-bounds read)
  19575. Headers h1 = {{"If-None-Match", "W/"
  19576. "\"very-long-etag-value-that-is-much-longer-"
  19577. "than-the-actual-etag-value\""}};
  19578. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  19579. ASSERT_TRUE(res2);
  19580. EXPECT_EQ(200, res2->status); // Should not match
  19581. // Test 2: Long string followed by wildcard
  19582. // Should match on "*" and return 304 (without out-of-bounds read on the long
  19583. // string)
  19584. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  19585. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  19586. ASSERT_TRUE(res3);
  19587. EXPECT_EQ(304, res3->status); // Should match on "*"
  19588. // Test 3: Wildcard followed by long string
  19589. // Should match on "*" immediately and return 304
  19590. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  19591. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  19592. ASSERT_TRUE(res4);
  19593. EXPECT_EQ(304, res4->status); // Should match on "*"
  19594. // Test 4: Multiple long non-matching values
  19595. // Should NOT match and return 200 (test that all comparisons are safe)
  19596. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  19597. "W/\"second-long-non-matching-value\", "
  19598. "W/\"third-long-non-matching-value\""}};
  19599. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  19600. ASSERT_TRUE(res5);
  19601. EXPECT_EQ(200, res5->status); // Should not match
  19602. // Test 5: Single character that is not "*" (edge case)
  19603. Headers h5 = {{"If-None-Match", "X"}};
  19604. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  19605. ASSERT_TRUE(res6);
  19606. EXPECT_EQ(200, res6->status); // Should not match
  19607. svr.stop();
  19608. t.join();
  19609. std::remove(fname);
  19610. }
  19611. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  19612. using namespace httplib;
  19613. // Create a test file
  19614. const char *fname = "ims_testfile.txt";
  19615. const char *content = "if-modified-since-test";
  19616. {
  19617. std::ofstream ofs(fname);
  19618. ofs << content;
  19619. ASSERT_TRUE(ofs.good());
  19620. }
  19621. Server svr;
  19622. svr.set_mount_point("/static", ".");
  19623. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19624. svr.wait_until_ready();
  19625. Client cli(HOST, PORT);
  19626. // First request: should get 200 with Last-Modified header
  19627. auto res1 = cli.Get("/static/ims_testfile.txt");
  19628. ASSERT_TRUE(res1);
  19629. ASSERT_EQ(200, res1->status);
  19630. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19631. std::string last_modified = res1->get_header_value("Last-Modified");
  19632. EXPECT_FALSE(last_modified.empty());
  19633. // If-Modified-Since with same time: expect 304
  19634. Headers h2 = {{"If-Modified-Since", last_modified}};
  19635. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  19636. ASSERT_TRUE(res2);
  19637. EXPECT_EQ(304, res2->status);
  19638. // If-Modified-Since with future time: expect 304
  19639. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19640. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  19641. ASSERT_TRUE(res3);
  19642. EXPECT_EQ(304, res3->status);
  19643. // If-Modified-Since with past time: expect 200
  19644. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19645. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  19646. ASSERT_TRUE(res4);
  19647. EXPECT_EQ(200, res4->status);
  19648. // If-None-Match takes precedence over If-Modified-Since
  19649. // (send matching ETag with old If-Modified-Since -> should still be 304)
  19650. ASSERT_TRUE(res1->has_header("ETag"));
  19651. std::string etag = res1->get_header_value("ETag");
  19652. Headers h5 = {{"If-None-Match", etag},
  19653. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19654. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  19655. ASSERT_TRUE(res5);
  19656. EXPECT_EQ(304, res5->status);
  19657. svr.stop();
  19658. t.join();
  19659. std::remove(fname);
  19660. }
  19661. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  19662. using namespace httplib;
  19663. Server svr;
  19664. // Endpoint that returns compressible content
  19665. svr.Get("/compressible", [](const Request &, Response &res) {
  19666. // Return a large enough body to trigger compression
  19667. std::string body(1000, 'a');
  19668. res.set_content(body, "text/plain");
  19669. });
  19670. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19671. svr.wait_until_ready();
  19672. Client cli(HOST, PORT);
  19673. // Request with gzip support: should get Vary header when compressed
  19674. cli.set_compress(true);
  19675. auto res1 = cli.Get("/compressible");
  19676. ASSERT_TRUE(res1);
  19677. EXPECT_EQ(200, res1->status);
  19678. // If Content-Encoding is set, Vary should also be set
  19679. if (res1->has_header("Content-Encoding")) {
  19680. EXPECT_TRUE(res1->has_header("Vary"));
  19681. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  19682. }
  19683. // Request without Accept-Encoding header: should not have compression
  19684. Headers h_no_compress;
  19685. auto res2 = cli.Get("/compressible", h_no_compress);
  19686. ASSERT_TRUE(res2);
  19687. EXPECT_EQ(200, res2->status);
  19688. // Verify Vary header is present when compression is applied
  19689. // (the exact behavior depends on server configuration)
  19690. svr.stop();
  19691. t.join();
  19692. }
  19693. TEST(ETagTest, IfRangeWithETag) {
  19694. using namespace httplib;
  19695. // Create a test file with known content
  19696. const char *fname = "if_range_testfile.txt";
  19697. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  19698. {
  19699. std::ofstream ofs(fname);
  19700. ofs << content;
  19701. ASSERT_TRUE(ofs.good());
  19702. }
  19703. Server svr;
  19704. svr.set_mount_point("/static", ".");
  19705. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19706. svr.wait_until_ready();
  19707. Client cli(HOST, PORT);
  19708. // First request: get ETag
  19709. auto res1 = cli.Get("/static/if_range_testfile.txt");
  19710. ASSERT_TRUE(res1);
  19711. ASSERT_EQ(200, res1->status);
  19712. ASSERT_TRUE(res1->has_header("ETag"));
  19713. std::string etag = res1->get_header_value("ETag");
  19714. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  19715. // Since our server generates weak ETags (W/"..."), If-Range with our
  19716. // ETag should NOT result in partial content - it should return full content.
  19717. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  19718. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  19719. ASSERT_TRUE(res2);
  19720. // Weak ETag in If-Range -> full content (200), not partial (206)
  19721. EXPECT_EQ(200, res2->status);
  19722. EXPECT_EQ(content, res2->body);
  19723. EXPECT_FALSE(res2->has_header("Content-Range"));
  19724. // Range request with non-matching If-Range (ETag): should get 200 (full
  19725. // content)
  19726. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  19727. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  19728. ASSERT_TRUE(res3);
  19729. EXPECT_EQ(200, res3->status);
  19730. EXPECT_EQ(content, res3->body);
  19731. EXPECT_FALSE(res3->has_header("Content-Range"));
  19732. // Range request with strong ETag (hypothetical - our server doesn't generate
  19733. // strong ETags, but if client sends a strong ETag that doesn't match, it
  19734. // should return full content)
  19735. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  19736. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  19737. ASSERT_TRUE(res4);
  19738. EXPECT_EQ(200, res4->status);
  19739. EXPECT_EQ(content, res4->body);
  19740. EXPECT_FALSE(res4->has_header("Content-Range"));
  19741. svr.stop();
  19742. t.join();
  19743. std::remove(fname);
  19744. }
  19745. TEST(ETagTest, IfRangeWithDate) {
  19746. using namespace httplib;
  19747. // Create a test file
  19748. const char *fname = "if_range_date_testfile.txt";
  19749. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  19750. {
  19751. std::ofstream ofs(fname);
  19752. ofs << content;
  19753. ASSERT_TRUE(ofs.good());
  19754. }
  19755. Server svr;
  19756. svr.set_mount_point("/static", ".");
  19757. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19758. svr.wait_until_ready();
  19759. Client cli(HOST, PORT);
  19760. // First request: get Last-Modified
  19761. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  19762. ASSERT_TRUE(res1);
  19763. ASSERT_EQ(200, res1->status);
  19764. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19765. std::string last_modified = res1->get_header_value("Last-Modified");
  19766. // Range request with matching If-Range (date): should get 206
  19767. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  19768. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  19769. ASSERT_TRUE(res2);
  19770. EXPECT_EQ(206, res2->status);
  19771. EXPECT_EQ("FGHIJ", res2->body);
  19772. // Range request with old If-Range date: should get 200 (full content)
  19773. Headers h3 = {{"Range", "bytes=5-9"},
  19774. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19775. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  19776. ASSERT_TRUE(res3);
  19777. EXPECT_EQ(200, res3->status);
  19778. EXPECT_EQ(content, res3->body);
  19779. // Range request with future If-Range date: should get 206
  19780. Headers h4 = {{"Range", "bytes=0-4"},
  19781. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19782. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  19783. ASSERT_TRUE(res4);
  19784. EXPECT_EQ(206, res4->status);
  19785. EXPECT_EQ("ABCDE", res4->body);
  19786. svr.stop();
  19787. t.join();
  19788. std::remove(fname);
  19789. }
  19790. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  19791. using namespace httplib;
  19792. const char *fname = "etag_malformed.txt";
  19793. const char *content = "malformed-etag";
  19794. {
  19795. std::ofstream ofs(fname);
  19796. ofs << content;
  19797. ASSERT_TRUE(ofs.good());
  19798. }
  19799. Server svr;
  19800. svr.set_mount_point("/static", ".");
  19801. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19802. svr.wait_until_ready();
  19803. Client cli(HOST, PORT);
  19804. // baseline: should get 200 and an ETag
  19805. auto res1 = cli.Get("/static/etag_malformed.txt");
  19806. ASSERT_TRUE(res1);
  19807. ASSERT_EQ(200, res1->status);
  19808. ASSERT_TRUE(res1->has_header("ETag"));
  19809. // Malformed ETag value (missing quotes) should be treated as non-matching
  19810. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  19811. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  19812. ASSERT_TRUE(res_bad);
  19813. EXPECT_EQ(200, res_bad->status);
  19814. // Whitespace-only header value should be considered invalid / non-matching
  19815. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  19816. "Host: localhost\r\n"
  19817. "If-None-Match: \r\n"
  19818. "Connection: close\r\n"
  19819. "\r\n";
  19820. std::string out;
  19821. ASSERT_TRUE(send_request(5, raw_req, &out));
  19822. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19823. svr.stop();
  19824. t.join();
  19825. std::remove(fname);
  19826. }
  19827. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  19828. using namespace httplib;
  19829. const char *fname = "ims_invalid_format.txt";
  19830. const char *content = "ims-bad-format";
  19831. {
  19832. std::ofstream ofs(fname);
  19833. ofs << content;
  19834. ASSERT_TRUE(ofs.good());
  19835. }
  19836. Server svr;
  19837. svr.set_mount_point("/static", ".");
  19838. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19839. svr.wait_until_ready();
  19840. Client cli(HOST, PORT);
  19841. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  19842. ASSERT_TRUE(res1);
  19843. ASSERT_EQ(200, res1->status);
  19844. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19845. // If-Modified-Since with invalid format should not result in 304
  19846. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  19847. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  19848. ASSERT_TRUE(res_bad);
  19849. EXPECT_EQ(200, res_bad->status);
  19850. // If-Range with invalid date format should be treated as mismatch -> full
  19851. // content (200)
  19852. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  19853. {"If-Range", "invalid-date"}};
  19854. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  19855. ASSERT_TRUE(res_ifrange);
  19856. EXPECT_EQ(200, res_ifrange->status);
  19857. svr.stop();
  19858. t.join();
  19859. std::remove(fname);
  19860. }
  19861. TEST(ETagTest, IfRangeWithMalformedETag) {
  19862. using namespace httplib;
  19863. const char *fname = "ifrange_malformed.txt";
  19864. const std::string content = "0123456789";
  19865. {
  19866. std::ofstream ofs(fname);
  19867. ofs << content;
  19868. ASSERT_TRUE(ofs.good());
  19869. }
  19870. Server svr;
  19871. svr.set_mount_point("/static", ".");
  19872. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19873. svr.wait_until_ready();
  19874. Client cli(HOST, PORT);
  19875. // First request: get ETag
  19876. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  19877. ASSERT_TRUE(res1);
  19878. ASSERT_EQ(200, res1->status);
  19879. ASSERT_TRUE(res1->has_header("ETag"));
  19880. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  19881. // full content (200)
  19882. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  19883. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  19884. ASSERT_TRUE(res2);
  19885. EXPECT_EQ(200, res2->status);
  19886. EXPECT_EQ(content, res2->body);
  19887. svr.stop();
  19888. t.join();
  19889. std::remove(fname);
  19890. }
  19891. TEST(ETagTest, ExtremeLargeDateValues) {
  19892. using namespace httplib;
  19893. const char *fname = "ims_extreme_date.txt";
  19894. const char *content = "ims-extreme-date";
  19895. {
  19896. std::ofstream ofs(fname);
  19897. ofs << content;
  19898. ASSERT_TRUE(ofs.good());
  19899. }
  19900. Server svr;
  19901. svr.set_mount_point("/static", ".");
  19902. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19903. svr.wait_until_ready();
  19904. Client cli(HOST, PORT);
  19905. auto res1 = cli.Get(std::string("/static/") + fname);
  19906. ASSERT_TRUE(res1);
  19907. ASSERT_EQ(200, res1->status);
  19908. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19909. // Extremely large year that may overflow date parsing routines.
  19910. Headers h_large_date = {
  19911. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19912. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  19913. ASSERT_TRUE(res_bad);
  19914. // Expect server to treat this as invalid/mismatch and return full content
  19915. EXPECT_EQ(200, res_bad->status);
  19916. // If-Range with extremely large date should be treated as mismatch -> full
  19917. // content (200)
  19918. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  19919. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19920. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  19921. ASSERT_TRUE(res_ifrange);
  19922. EXPECT_EQ(200, res_ifrange->status);
  19923. svr.stop();
  19924. t.join();
  19925. std::remove(fname);
  19926. }
  19927. TEST(ETagTest, NegativeFileModificationTime) {
  19928. using namespace httplib;
  19929. const char *fname = "ims_negative_mtime.txt";
  19930. const std::string content = "negative-mtime";
  19931. {
  19932. std::ofstream ofs(fname);
  19933. ofs << content;
  19934. ASSERT_TRUE(ofs.good());
  19935. }
  19936. // Try to set file mtime to a negative value. This may fail on some
  19937. // platforms/filesystems; if it fails, the test will still verify server
  19938. // behaves safely by performing a regular conditional request.
  19939. #if defined(__APPLE__) || defined(__linux__)
  19940. bool set_negative = false;
  19941. do {
  19942. struct timeval times[2];
  19943. // access time: now
  19944. times[0].tv_sec = time(nullptr);
  19945. times[0].tv_usec = 0;
  19946. // modification time: negative (e.g., -1)
  19947. times[1].tv_sec = -1;
  19948. times[1].tv_usec = 0;
  19949. if (utimes(fname, times) == 0) { set_negative = true; }
  19950. } while (0);
  19951. #else
  19952. bool set_negative = false;
  19953. #endif
  19954. Server svr;
  19955. svr.set_mount_point("/static", ".");
  19956. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19957. svr.wait_until_ready();
  19958. Client cli(HOST, PORT);
  19959. auto res1 = cli.Get(std::string("/static/") + fname);
  19960. ASSERT_TRUE(res1);
  19961. ASSERT_EQ(200, res1->status);
  19962. bool has_last_modified = res1->has_header("Last-Modified");
  19963. std::string last_modified;
  19964. if (has_last_modified) {
  19965. last_modified = res1->get_header_value("Last-Modified");
  19966. }
  19967. if (set_negative) {
  19968. // If we successfully set a negative mtime, ensure server returns a
  19969. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  19970. // with an old date and ensure server handles it without crash.
  19971. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  19972. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  19973. ASSERT_TRUE(res2);
  19974. // Behavior may vary; at minimum ensure server responds (200 or 304).
  19975. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  19976. } else {
  19977. // Could not set negative mtime on this platform; fall back to verifying
  19978. // that normal invalid/malformed dates are treated safely (non-304).
  19979. Headers h_bad_date = {
  19980. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19981. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  19982. ASSERT_TRUE(res_bad);
  19983. EXPECT_EQ(200, res_bad->status);
  19984. }
  19985. svr.stop();
  19986. t.join();
  19987. std::remove(fname);
  19988. }
  19989. //==============================================================================
  19990. // Integration Tests with Server
  19991. //==============================================================================
  19992. class SSEIntegrationTest : public ::testing::Test {
  19993. protected:
  19994. void SetUp() override {
  19995. stop_server_.store(false);
  19996. events_.clear();
  19997. server_ = httplib::detail::make_unique<Server>();
  19998. setup_server();
  19999. start_server();
  20000. }
  20001. void TearDown() override {
  20002. stop_server_.store(true);
  20003. event_cv_.notify_all();
  20004. server_->stop();
  20005. if (server_thread_.joinable()) { server_thread_.join(); }
  20006. }
  20007. void setup_server() {
  20008. // Simple SSE endpoint
  20009. server_->Get("/events", [this](const Request &req, Response &res) {
  20010. auto last_id = req.get_header_value("Last-Event-ID");
  20011. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  20012. res.set_chunked_content_provider(
  20013. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  20014. std::unique_lock<std::mutex> lock(event_mutex_);
  20015. if (event_cv_.wait_for(
  20016. lock, std::chrono::milliseconds(200), [this] {
  20017. return !events_.empty() || stop_server_.load();
  20018. })) {
  20019. if (stop_server_.load()) { return false; }
  20020. if (!events_.empty()) {
  20021. std::string event = events_.front();
  20022. events_.erase(events_.begin());
  20023. sink.write(event.data(), event.size());
  20024. return true;
  20025. }
  20026. }
  20027. return !stop_server_.load();
  20028. });
  20029. });
  20030. // Endpoint that returns error
  20031. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  20032. res.status = 500;
  20033. res.set_content("Internal Server Error", "text/plain");
  20034. });
  20035. // Endpoint for custom event types
  20036. server_->Get("/custom-events", [](const Request &, Response &res) {
  20037. res.set_chunked_content_provider(
  20038. "text/event-stream", [](size_t offset, DataSink &sink) {
  20039. if (offset == 0) {
  20040. std::string event = "event: update\ndata: updated\n\n"
  20041. "event: delete\ndata: deleted\n\n";
  20042. sink.write(event.data(), event.size());
  20043. }
  20044. return false; // End stream after sending
  20045. });
  20046. });
  20047. }
  20048. void start_server() {
  20049. port_ = server_->bind_to_any_port(HOST);
  20050. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20051. // Wait for server to start
  20052. while (!server_->is_running()) {
  20053. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20054. }
  20055. }
  20056. int get_port() const { return port_; }
  20057. void send_event(const std::string &event) {
  20058. std::lock_guard<std::mutex> lock(event_mutex_);
  20059. events_.push_back(event);
  20060. event_cv_.notify_all();
  20061. }
  20062. std::unique_ptr<Server> server_;
  20063. std::thread server_thread_;
  20064. std::mutex event_mutex_;
  20065. std::condition_variable event_cv_;
  20066. std::vector<std::string> events_;
  20067. std::atomic<bool> stop_server_{false};
  20068. std::string last_received_event_id_;
  20069. int port_ = 0;
  20070. };
  20071. //==============================================================================
  20072. // SSE Parsing Tests
  20073. //==============================================================================
  20074. class SSEParsingTest : public SSEIntegrationTest {
  20075. protected:
  20076. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  20077. // A trailing sentinel event tells when the whole stream has been parsed.
  20078. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  20079. auto body = stream + "event: end\ndata: end\n\n";
  20080. server_->Get("/parse", [body](const Request &, Response &res) {
  20081. res.set_content(body, "text/event-stream");
  20082. });
  20083. return collect("/parse");
  20084. }
  20085. // Runs SSEClient against path until an "end" event arrives and returns the
  20086. // messages dispatched before it
  20087. std::vector<sse::SSEMessage> collect(const std::string &path) {
  20088. Client client(HOST, get_port());
  20089. sse::SSEClient sse(client, path);
  20090. std::mutex mutex;
  20091. std::condition_variable cv;
  20092. std::vector<sse::SSEMessage> messages;
  20093. auto done = false;
  20094. sse.on_message([&](const sse::SSEMessage &msg) {
  20095. std::lock_guard<std::mutex> lock(mutex);
  20096. // Ignore a replay from a reconnect that races with stop()
  20097. if (!done) { messages.push_back(msg); }
  20098. });
  20099. sse.on_event("end", [&](const sse::SSEMessage &) {
  20100. std::lock_guard<std::mutex> lock(mutex);
  20101. done = true;
  20102. cv.notify_all();
  20103. });
  20104. sse.set_reconnect_interval(100);
  20105. sse.start_async();
  20106. {
  20107. std::unique_lock<std::mutex> lock(mutex);
  20108. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  20109. }
  20110. sse.stop();
  20111. EXPECT_TRUE(done);
  20112. return messages;
  20113. }
  20114. };
  20115. TEST_F(SSEParsingTest, SingleLineData) {
  20116. auto msgs = parse("data: hello\n\n");
  20117. ASSERT_EQ(msgs.size(), 1u);
  20118. EXPECT_EQ(msgs[0].data, "hello");
  20119. EXPECT_EQ(msgs[0].event, "message");
  20120. }
  20121. TEST_F(SSEParsingTest, MultiLineData) {
  20122. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  20123. ASSERT_EQ(msgs.size(), 1u);
  20124. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  20125. }
  20126. TEST_F(SSEParsingTest, CustomEventType) {
  20127. auto msgs = parse("event: update\ndata: payload\n\n");
  20128. ASSERT_EQ(msgs.size(), 1u);
  20129. EXPECT_EQ(msgs[0].event, "update");
  20130. EXPECT_EQ(msgs[0].data, "payload");
  20131. }
  20132. TEST_F(SSEParsingTest, EventIdHandling) {
  20133. auto msgs = parse("id: 12345\ndata: test\n\n");
  20134. ASSERT_EQ(msgs.size(), 1u);
  20135. EXPECT_EQ(msgs[0].id, "12345");
  20136. }
  20137. TEST_F(SSEParsingTest, EmptyEventId) {
  20138. auto msgs = parse("id:\ndata: test\n\n");
  20139. ASSERT_EQ(msgs.size(), 1u);
  20140. EXPECT_EQ(msgs[0].id, "");
  20141. }
  20142. TEST_F(SSEParsingTest, CommentsIgnored) {
  20143. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  20144. ASSERT_EQ(msgs.size(), 1u);
  20145. EXPECT_EQ(msgs[0].data, "hello");
  20146. EXPECT_EQ(msgs[0].event, "message");
  20147. }
  20148. TEST_F(SSEParsingTest, ColonInValue) {
  20149. auto msgs = parse("data: hello:world:test\n\n");
  20150. ASSERT_EQ(msgs.size(), 1u);
  20151. EXPECT_EQ(msgs[0].data, "hello:world:test");
  20152. }
  20153. TEST_F(SSEParsingTest, FieldNameOnly) {
  20154. // A line without a colon is a field name with an empty value
  20155. auto msgs = parse("data\n\n");
  20156. ASSERT_EQ(msgs.size(), 1u);
  20157. EXPECT_EQ(msgs[0].data, "");
  20158. }
  20159. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  20160. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  20161. ASSERT_EQ(msgs.size(), 1u);
  20162. EXPECT_EQ(msgs[0].event, "update");
  20163. EXPECT_EQ(msgs[0].data, "hello");
  20164. }
  20165. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  20166. auto msgs = parse("data\r\n\r\n");
  20167. ASSERT_EQ(msgs.size(), 1u);
  20168. EXPECT_EQ(msgs[0].data, "");
  20169. }
  20170. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  20171. auto msgs = parse("event: update\rdata: hello\r\r");
  20172. ASSERT_EQ(msgs.size(), 1u);
  20173. EXPECT_EQ(msgs[0].event, "update");
  20174. EXPECT_EQ(msgs[0].data, "hello");
  20175. }
  20176. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  20177. // Chunk boundaries fall inside every \r\n and right before the first one
  20178. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  20179. "\n\r", "\nevent: end\ndata: end\n\n"};
  20180. server_->Get("/split", [chunks](const Request &, Response &res) {
  20181. auto i = std::make_shared<size_t>(0);
  20182. res.set_chunked_content_provider(
  20183. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  20184. if (*i == chunks.size()) {
  20185. sink.done();
  20186. } else {
  20187. sink.write(chunks[*i].data(), chunks[*i].size());
  20188. (*i)++;
  20189. }
  20190. return true;
  20191. });
  20192. });
  20193. auto msgs = collect("/split");
  20194. ASSERT_EQ(msgs.size(), 1u);
  20195. EXPECT_EQ(msgs[0].event, "update");
  20196. EXPECT_EQ(msgs[0].data, "hello");
  20197. }
  20198. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  20199. // Only a BOM at the start of the stream is ignored
  20200. auto msgs = parse("\xEF\xBB\xBF"
  20201. "data: first\n\n"
  20202. "\xEF\xBB\xBF"
  20203. "data: second\n\n");
  20204. ASSERT_EQ(msgs.size(), 1u);
  20205. EXPECT_EQ(msgs[0].data, "first");
  20206. }
  20207. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  20208. auto msgs = parse("unknown: value\ndata: hello\n\n");
  20209. ASSERT_EQ(msgs.size(), 1u);
  20210. EXPECT_EQ(msgs[0].data, "hello");
  20211. EXPECT_EQ(msgs[0].event, "message");
  20212. }
  20213. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  20214. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  20215. ASSERT_EQ(msgs.size(), 2u);
  20216. EXPECT_EQ(msgs[0].data, "hello");
  20217. EXPECT_EQ(msgs[1].data, "hello");
  20218. }
  20219. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  20220. // An event without data is not dispatched, and its type must not leak
  20221. // into the next event
  20222. auto msgs = parse("event: update\n\ndata: hello\n\n");
  20223. ASSERT_EQ(msgs.size(), 1u);
  20224. EXPECT_EQ(msgs[0].event, "message");
  20225. EXPECT_EQ(msgs[0].data, "hello");
  20226. }
  20227. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  20228. // The first connection sends only an id; the second echoes back the
  20229. // Last-Event-ID it was reconnected with
  20230. std::atomic<int> connection_count{0};
  20231. server_->Get("/id-only", [&](const Request &req, Response &res) {
  20232. if (connection_count++ == 0) {
  20233. res.set_content("id: 42\n\n", "text/event-stream");
  20234. } else {
  20235. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20236. "\n\nevent: end\ndata: end\n\n",
  20237. "text/event-stream");
  20238. }
  20239. });
  20240. auto msgs = collect("/id-only");
  20241. ASSERT_EQ(msgs.size(), 1u);
  20242. EXPECT_EQ(msgs[0].data, "42");
  20243. }
  20244. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  20245. // The first connection sets an id and then clears it with an empty one; the
  20246. // second reports whether it was reconnected with a Last-Event-ID
  20247. std::atomic<int> connection_count{0};
  20248. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  20249. if (connection_count++ == 0) {
  20250. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  20251. "text/event-stream");
  20252. } else {
  20253. res.set_content(
  20254. std::string("data: ") +
  20255. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  20256. "\n\nevent: end\ndata: end\n\n",
  20257. "text/event-stream");
  20258. }
  20259. });
  20260. auto msgs = collect("/id-clear");
  20261. ASSERT_EQ(msgs.size(), 3u);
  20262. EXPECT_EQ(msgs[0].id, "1");
  20263. EXPECT_EQ(msgs[1].id, "");
  20264. EXPECT_EQ(msgs[2].data, "not sent");
  20265. }
  20266. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  20267. // The first connection sets an id and then sends ids that cannot be carried
  20268. // in a header; the second echoes back the Last-Event-ID it was reconnected
  20269. // with
  20270. std::atomic<int> connection_count{0};
  20271. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  20272. if (connection_count++ == 0) {
  20273. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  20274. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  20275. "text/event-stream");
  20276. } else {
  20277. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20278. "\n\nevent: end\ndata: end\n\n",
  20279. "text/event-stream");
  20280. }
  20281. });
  20282. auto msgs = collect("/id-unsendable");
  20283. ASSERT_EQ(msgs.size(), 1u);
  20284. EXPECT_EQ(msgs[0].data, "42");
  20285. }
  20286. TEST_F(SSEParsingTest, CompleteEventParsing) {
  20287. auto msgs = parse("event: notification\nid: evt-42\n"
  20288. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  20289. ASSERT_EQ(msgs.size(), 1u);
  20290. EXPECT_EQ(msgs[0].event, "notification");
  20291. EXPECT_EQ(msgs[0].id, "evt-42");
  20292. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  20293. }
  20294. TEST(SSEMessageTest, Clear) {
  20295. sse::SSEMessage msg;
  20296. msg.event = "custom";
  20297. msg.data = "some data";
  20298. msg.id = "123";
  20299. msg.clear();
  20300. EXPECT_EQ(msg.event, "message");
  20301. EXPECT_EQ(msg.data, "");
  20302. EXPECT_EQ(msg.id, "");
  20303. }
  20304. //==============================================================================
  20305. // SSE Integration Tests
  20306. //==============================================================================
  20307. // Test: Successful connection and on_open callback
  20308. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  20309. // Add a simple endpoint that sends one event and closes
  20310. server_->Get("/simple-event", [](const Request &, Response &res) {
  20311. res.set_chunked_content_provider(
  20312. "text/event-stream", [](size_t offset, DataSink &sink) {
  20313. if (offset == 0) {
  20314. std::string event = "data: hello\n\n";
  20315. sink.write(event.data(), event.size());
  20316. }
  20317. return false; // Close stream after sending
  20318. });
  20319. });
  20320. Client client("localhost", get_port());
  20321. sse::SSEClient sse(client, "/simple-event");
  20322. std::atomic<bool> open_called{false};
  20323. std::atomic<bool> message_received{false};
  20324. sse.on_open([&open_called]() { open_called.store(true); });
  20325. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  20326. if (msg.data == "hello") { message_received.store(true); }
  20327. });
  20328. sse.set_reconnect_interval(100);
  20329. sse.set_max_reconnect_attempts(1);
  20330. // Start async
  20331. sse.start_async();
  20332. // Wait for message to be processed
  20333. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20334. sse.stop();
  20335. EXPECT_TRUE(open_called.load());
  20336. EXPECT_TRUE(message_received.load());
  20337. }
  20338. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  20339. // A data line that never ends.
  20340. server_->Get("/endless-line", [](const Request &, Response &res) {
  20341. res.set_chunked_content_provider(
  20342. "text/event-stream", [](size_t offset, DataSink &sink) {
  20343. if (offset == 0) { sink.write("data: ", 6); }
  20344. std::string chunk(64 * 1024, 'A');
  20345. return sink.write(chunk.data(), chunk.size());
  20346. });
  20347. });
  20348. Client client("localhost", get_port());
  20349. // Lift the payload limit, so that only the event limit can end this endless
  20350. // stream.
  20351. client.set_payload_max_length(0);
  20352. sse::SSEClient sse(client, "/endless-line");
  20353. std::atomic<bool> too_long{false};
  20354. sse.on_error([&](Error err) {
  20355. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  20356. });
  20357. sse.set_max_reconnect_attempts(1);
  20358. sse.start_async();
  20359. for (int i = 0; i < 500 && !too_long; i++) {
  20360. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20361. }
  20362. sse.stop();
  20363. EXPECT_TRUE(too_long);
  20364. }
  20365. // Test: on_message callback
  20366. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  20367. // Endpoint that sends multiple events then closes
  20368. server_->Get("/multi-event", [](const Request &, Response &res) {
  20369. res.set_chunked_content_provider(
  20370. "text/event-stream", [](size_t offset, DataSink &sink) {
  20371. if (offset == 0) {
  20372. std::string events = "data: message1\n\ndata: message2\n\n";
  20373. sink.write(events.data(), events.size());
  20374. }
  20375. return false;
  20376. });
  20377. });
  20378. Client client("localhost", get_port());
  20379. sse::SSEClient sse(client, "/multi-event");
  20380. std::vector<std::string> received_messages;
  20381. std::mutex messages_mutex;
  20382. sse.on_message([&](const sse::SSEMessage &msg) {
  20383. std::lock_guard<std::mutex> lock(messages_mutex);
  20384. received_messages.push_back(msg.data);
  20385. });
  20386. sse.set_reconnect_interval(100);
  20387. sse.set_max_reconnect_attempts(1);
  20388. sse.start_async();
  20389. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20390. sse.stop();
  20391. std::lock_guard<std::mutex> lock(messages_mutex);
  20392. EXPECT_GE(received_messages.size(), 2u);
  20393. if (received_messages.size() >= 2) {
  20394. EXPECT_EQ(received_messages[0], "message1");
  20395. EXPECT_EQ(received_messages[1], "message2");
  20396. }
  20397. }
  20398. // Test: on_event for specific types
  20399. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  20400. Client client("localhost", get_port());
  20401. sse::SSEClient sse(client, "/custom-events");
  20402. std::atomic<bool> update_received{false};
  20403. std::atomic<bool> delete_received{false};
  20404. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  20405. if (msg.data == "updated") { update_received.store(true); }
  20406. });
  20407. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  20408. if (msg.data == "deleted") { delete_received.store(true); }
  20409. });
  20410. sse.set_max_reconnect_attempts(1);
  20411. sse.start_async();
  20412. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  20413. sse.stop();
  20414. EXPECT_TRUE(update_received.load());
  20415. EXPECT_TRUE(delete_received.load());
  20416. }
  20417. // Test: on_error callback on connection failure
  20418. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  20419. // Connect to a non-existent port
  20420. Client client("localhost", 59999);
  20421. sse::SSEClient sse(client, "/events");
  20422. std::atomic<bool> error_called{false};
  20423. Error received_error = Error::Success;
  20424. sse.on_error([&](Error err) {
  20425. error_called.store(true);
  20426. received_error = err;
  20427. });
  20428. sse.set_reconnect_interval(50);
  20429. sse.set_max_reconnect_attempts(1);
  20430. sse.start_async();
  20431. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20432. sse.stop();
  20433. EXPECT_TRUE(error_called.load());
  20434. EXPECT_NE(received_error, Error::Success);
  20435. }
  20436. // Test: Last-Event-ID header sent on reconnect
  20437. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  20438. // Endpoint that sends event with ID
  20439. server_->Get("/event-with-id", [](const Request &, Response &res) {
  20440. res.set_chunked_content_provider(
  20441. "text/event-stream", [](size_t offset, DataSink &sink) {
  20442. if (offset == 0) {
  20443. std::string event = "id: evt-123\ndata: test\n\n";
  20444. sink.write(event.data(), event.size());
  20445. }
  20446. return false;
  20447. });
  20448. });
  20449. Client client("localhost", get_port());
  20450. sse::SSEClient sse(client, "/event-with-id");
  20451. std::atomic<bool> id_received{false};
  20452. sse.on_message([&](const sse::SSEMessage &msg) {
  20453. if (!msg.id.empty()) { id_received.store(true); }
  20454. });
  20455. sse.set_reconnect_interval(100);
  20456. sse.set_max_reconnect_attempts(1);
  20457. sse.start_async();
  20458. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20459. sse.stop();
  20460. EXPECT_TRUE(id_received.load());
  20461. EXPECT_EQ(sse.last_event_id(), "evt-123");
  20462. }
  20463. // Test: Manual stop
  20464. TEST_F(SSEIntegrationTest, ManualStop) {
  20465. // Endpoint that sends one event and stays open briefly
  20466. std::atomic<bool> handler_running{true};
  20467. server_->Get("/stay-open", [&handler_running](const Request &,
  20468. Response &res) {
  20469. res.set_chunked_content_provider(
  20470. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  20471. if (offset == 0) {
  20472. std::string event = "data: connected\n\n";
  20473. sink.write(event.data(), event.size());
  20474. }
  20475. // Keep connection open while handler_running is true
  20476. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  20477. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20478. }
  20479. return false;
  20480. });
  20481. });
  20482. Client client("localhost", get_port());
  20483. sse::SSEClient sse(client, "/stay-open");
  20484. std::atomic<bool> connected{false};
  20485. sse.on_open([&connected]() { connected.store(true); });
  20486. sse.set_reconnect_interval(100);
  20487. sse.set_max_reconnect_attempts(1);
  20488. sse.start_async();
  20489. // Wait for connection to establish
  20490. for (int i = 0; i < 20 && !connected.load(); ++i) {
  20491. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20492. }
  20493. EXPECT_TRUE(connected.load());
  20494. EXPECT_TRUE(sse.is_connected());
  20495. // Signal handler to stop
  20496. handler_running.store(false);
  20497. // Stop SSE client
  20498. sse.stop();
  20499. EXPECT_FALSE(sse.is_connected());
  20500. }
  20501. // Test: SSEClient with custom headers
  20502. TEST_F(SSEIntegrationTest, CustomHeaders) {
  20503. // Setup a server endpoint that checks for custom header
  20504. std::atomic<bool> header_received{false};
  20505. server_->Get("/header-check", [&](const Request &req, Response &res) {
  20506. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  20507. header_received.store(true);
  20508. }
  20509. res.set_chunked_content_provider("text/event-stream",
  20510. [](size_t, DataSink &) { return false; });
  20511. });
  20512. Client client("localhost", get_port());
  20513. Headers headers = {{"X-Custom-Header", "custom-value"}};
  20514. sse::SSEClient sse(client, "/header-check", headers);
  20515. sse.set_max_reconnect_attempts(1);
  20516. sse.start_async();
  20517. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20518. sse.stop();
  20519. EXPECT_TRUE(header_received.load());
  20520. }
  20521. // Test: Reconnect interval configuration
  20522. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  20523. Client client("localhost", get_port());
  20524. sse::SSEClient sse(client, "/events");
  20525. auto &result = sse.set_reconnect_interval(500);
  20526. // Builder pattern should return reference to self
  20527. EXPECT_EQ(&result, &sse);
  20528. }
  20529. // Test: Max reconnect attempts
  20530. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  20531. // Connect to non-existent port to force reconnects
  20532. Client client("localhost", 59998);
  20533. sse::SSEClient sse(client, "/events");
  20534. std::atomic<int> error_count{0};
  20535. sse.on_error([&](Error) { error_count.fetch_add(1); });
  20536. sse.set_reconnect_interval(50);
  20537. sse.set_max_reconnect_attempts(2);
  20538. auto start = std::chrono::steady_clock::now();
  20539. sse.start(); // Blocking call
  20540. auto end = std::chrono::steady_clock::now();
  20541. // Should have stopped after 2 failed attempts
  20542. EXPECT_GE(error_count.load(), 2);
  20543. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  20544. auto duration =
  20545. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  20546. #ifdef _WIN32
  20547. // Windows is much slower for socket connection failures
  20548. EXPECT_LT(duration.count(), 7000);
  20549. #else
  20550. EXPECT_LT(duration.count(), 1000);
  20551. #endif
  20552. }
  20553. // Test: Multi-line data in integration
  20554. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  20555. // Endpoint with multi-line data
  20556. server_->Get("/multiline-data", [](const Request &, Response &res) {
  20557. res.set_chunked_content_provider(
  20558. "text/event-stream", [](size_t offset, DataSink &sink) {
  20559. if (offset == 0) {
  20560. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  20561. sink.write(event.data(), event.size());
  20562. }
  20563. return false;
  20564. });
  20565. });
  20566. Client client("localhost", get_port());
  20567. sse::SSEClient sse(client, "/multiline-data");
  20568. std::string received_data;
  20569. std::mutex data_mutex;
  20570. sse.on_message([&](const sse::SSEMessage &msg) {
  20571. std::lock_guard<std::mutex> lock(data_mutex);
  20572. received_data = msg.data;
  20573. });
  20574. sse.set_reconnect_interval(100);
  20575. sse.set_max_reconnect_attempts(1);
  20576. sse.start_async();
  20577. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20578. sse.stop();
  20579. std::lock_guard<std::mutex> lock(data_mutex);
  20580. EXPECT_EQ(received_data, "line1\nline2\nline3");
  20581. }
  20582. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  20583. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  20584. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  20585. DataSink &sink) {
  20586. if (offset == 0) {
  20587. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  20588. sink.write(events.data(), events.size());
  20589. }
  20590. return false;
  20591. });
  20592. });
  20593. Client client("localhost", get_port());
  20594. sse::SSEClient sse(client, "/empty-data-lines");
  20595. std::mutex mutex;
  20596. std::condition_variable cv;
  20597. std::vector<std::string> received;
  20598. sse.on_message([&](const sse::SSEMessage &msg) {
  20599. std::lock_guard<std::mutex> lock(mutex);
  20600. received.push_back(msg.data);
  20601. cv.notify_all();
  20602. });
  20603. sse.set_max_reconnect_attempts(1);
  20604. sse.start_async();
  20605. {
  20606. std::unique_lock<std::mutex> lock(mutex);
  20607. cv.wait_for(lock, std::chrono::seconds(2),
  20608. [&] { return received.size() >= 3; });
  20609. }
  20610. sse.stop();
  20611. ASSERT_GE(received.size(), 3u);
  20612. EXPECT_EQ(received[0], "");
  20613. EXPECT_EQ(received[1], "\nhello");
  20614. EXPECT_EQ(received[2], "");
  20615. }
  20616. // Test: Auto-reconnect after server disconnection
  20617. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  20618. std::atomic<int> connection_count{0};
  20619. std::atomic<int> message_count{0};
  20620. // Endpoint that sends one event and closes, forcing reconnect
  20621. server_->Get("/reconnect-test",
  20622. [&connection_count](const Request &, Response &res) {
  20623. connection_count.fetch_add(1);
  20624. res.set_chunked_content_provider(
  20625. "text/event-stream", [](size_t offset, DataSink &sink) {
  20626. if (offset == 0) {
  20627. std::string event = "data: hello\n\n";
  20628. sink.write(event.data(), event.size());
  20629. }
  20630. return false; // Close connection after sending
  20631. });
  20632. });
  20633. Client client("localhost", get_port());
  20634. sse::SSEClient sse(client, "/reconnect-test");
  20635. sse.on_message([&message_count](const sse::SSEMessage &) {
  20636. message_count.fetch_add(1);
  20637. });
  20638. sse.set_reconnect_interval(100);
  20639. sse.set_max_reconnect_attempts(3);
  20640. sse.start_async();
  20641. // Wait long enough for multiple reconnects
  20642. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20643. sse.stop();
  20644. // Should have connected multiple times (initial + reconnects)
  20645. EXPECT_GE(connection_count.load(), 2);
  20646. // Should have received messages from multiple connections
  20647. EXPECT_GE(message_count.load(), 2);
  20648. }
  20649. // Test: A retry field that is not all ASCII digits is ignored
  20650. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  20651. std::atomic<int> connection_count{0};
  20652. server_->Get("/bad-retry",
  20653. [&connection_count](const Request &, Response &res) {
  20654. connection_count.fetch_add(1);
  20655. res.set_chunked_content_provider(
  20656. "text/event-stream", [](size_t offset, DataSink &sink) {
  20657. if (offset == 0) {
  20658. std::string event = "retry: -1\ndata: hello\n\n";
  20659. sink.write(event.data(), event.size());
  20660. }
  20661. return false;
  20662. });
  20663. });
  20664. Client client("localhost", get_port());
  20665. sse::SSEClient sse(client, "/bad-retry");
  20666. sse.set_reconnect_interval(10000);
  20667. sse.start_async();
  20668. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20669. sse.stop();
  20670. EXPECT_EQ(connection_count.load(), 1);
  20671. }
  20672. // Test: A retry field of all ASCII digits sets the reconnection time
  20673. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  20674. std::mutex mutex;
  20675. std::condition_variable cv;
  20676. std::vector<std::chrono::steady_clock::time_point> connected_at;
  20677. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  20678. {
  20679. std::lock_guard<std::mutex> lock(mutex);
  20680. connected_at.push_back(std::chrono::steady_clock::now());
  20681. cv.notify_all();
  20682. }
  20683. res.set_chunked_content_provider(
  20684. "text/event-stream", [](size_t offset, DataSink &sink) {
  20685. if (offset == 0) {
  20686. std::string event = "retry: 0\ndata: hello\n\n";
  20687. sink.write(event.data(), event.size());
  20688. }
  20689. return false;
  20690. });
  20691. });
  20692. Client client("localhost", get_port());
  20693. sse::SSEClient sse(client, "/zero-retry");
  20694. sse.set_reconnect_interval(10000);
  20695. sse.start_async();
  20696. {
  20697. std::unique_lock<std::mutex> lock(mutex);
  20698. cv.wait_for(lock, std::chrono::seconds(5),
  20699. [&] { return connected_at.size() >= 2; });
  20700. }
  20701. sse.stop();
  20702. // The server-supplied interval is applied, but never below 100ms, so
  20703. // "retry: 0" does not cause a busy reconnect loop
  20704. std::lock_guard<std::mutex> lock(mutex);
  20705. ASSERT_GE(connected_at.size(), 2u);
  20706. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  20707. connected_at[1] - connected_at[0])
  20708. .count();
  20709. EXPECT_GE(interval_ms, 100);
  20710. }
  20711. // Test: Last-Event-ID sent on reconnect
  20712. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  20713. std::atomic<int> connection_count{0};
  20714. std::vector<std::string> received_last_event_ids;
  20715. std::mutex id_mutex;
  20716. // Endpoint that checks Last-Event-ID header and sends event with ID
  20717. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  20718. int conn = connection_count.fetch_add(1);
  20719. // Capture the Last-Event-ID header from each connection
  20720. {
  20721. std::lock_guard<std::mutex> lock(id_mutex);
  20722. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  20723. }
  20724. res.set_chunked_content_provider(
  20725. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  20726. if (offset == 0) {
  20727. std::string event =
  20728. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  20729. sink.write(event.data(), event.size());
  20730. }
  20731. return false;
  20732. });
  20733. });
  20734. Client client("localhost", get_port());
  20735. sse::SSEClient sse(client, "/reconnect-with-id");
  20736. sse.set_reconnect_interval(100);
  20737. sse.set_max_reconnect_attempts(3);
  20738. sse.start_async();
  20739. // Wait for at least 2 connections
  20740. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20741. sse.stop();
  20742. // Verify behavior
  20743. std::lock_guard<std::mutex> lock(id_mutex);
  20744. EXPECT_GE(received_last_event_ids.size(), 2u);
  20745. // First connection should have no Last-Event-ID
  20746. if (!received_last_event_ids.empty()) {
  20747. EXPECT_EQ(received_last_event_ids[0], "");
  20748. }
  20749. // Second connection should have Last-Event-ID from first connection
  20750. if (received_last_event_ids.size() >= 2) {
  20751. EXPECT_EQ(received_last_event_ids[1], "event-0");
  20752. }
  20753. }
  20754. // Test: set_headers updates headers used on reconnect
  20755. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  20756. std::vector<std::string> received_tokens;
  20757. std::mutex token_mutex;
  20758. // Endpoint that captures Authorization header
  20759. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  20760. {
  20761. std::lock_guard<std::mutex> lock(token_mutex);
  20762. received_tokens.push_back(req.get_header_value("Authorization"));
  20763. }
  20764. res.set_chunked_content_provider(
  20765. "text/event-stream", [](size_t offset, DataSink &sink) {
  20766. if (offset == 0) {
  20767. std::string event = "data: hello\n\n";
  20768. sink.write(event.data(), event.size());
  20769. }
  20770. return false; // Close connection to trigger reconnect
  20771. });
  20772. });
  20773. Client client("localhost", get_port());
  20774. Headers headers = {{"Authorization", "Bearer old-token"}};
  20775. sse::SSEClient sse(client, "/auth-check", headers);
  20776. // Update headers on each successful connection
  20777. sse.on_open(
  20778. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  20779. sse.set_reconnect_interval(100);
  20780. sse.set_max_reconnect_attempts(3);
  20781. sse.start_async();
  20782. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20783. sse.stop();
  20784. std::lock_guard<std::mutex> lock(token_mutex);
  20785. ASSERT_GE(received_tokens.size(), 2u);
  20786. // First connection uses original header
  20787. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  20788. // Second connection uses updated header from set_headers
  20789. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  20790. }
  20791. // Test: 401 allows reconnection (so on_error can refresh headers)
  20792. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  20793. std::atomic<int> connection_count{0};
  20794. // Endpoint: returns 401 on first attempt, 200 on second
  20795. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  20796. int conn = connection_count.fetch_add(1);
  20797. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  20798. res.status = StatusCode::Unauthorized_401;
  20799. res.set_content("Unauthorized", "text/plain");
  20800. return;
  20801. }
  20802. res.set_chunked_content_provider(
  20803. "text/event-stream", [](size_t offset, DataSink &sink) {
  20804. if (offset == 0) {
  20805. std::string event = "data: authenticated\n\n";
  20806. sink.write(event.data(), event.size());
  20807. }
  20808. return false;
  20809. });
  20810. });
  20811. Client client("localhost", get_port());
  20812. Headers headers = {{"Authorization", "Bearer expired"}};
  20813. sse::SSEClient sse(client, "/auth-retry", headers);
  20814. std::atomic<bool> message_received{false};
  20815. // Refresh token on error
  20816. sse.on_error(
  20817. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  20818. sse.on_message([&](const sse::SSEMessage &msg) {
  20819. if (msg.data == "authenticated") { message_received.store(true); }
  20820. });
  20821. sse.set_reconnect_interval(100);
  20822. sse.set_max_reconnect_attempts(3);
  20823. sse.start_async();
  20824. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20825. sse.stop();
  20826. // Should have reconnected after 401 and succeeded with new token
  20827. EXPECT_GE(connection_count.load(), 2);
  20828. EXPECT_TRUE(message_received.load());
  20829. }
  20830. TEST(Issue2318Test, EmptyHostString) {
  20831. {
  20832. httplib::Client cli_empty("", PORT);
  20833. auto res = cli_empty.Get("/");
  20834. ASSERT_FALSE(res);
  20835. EXPECT_EQ(httplib::Error::Connection, res.error());
  20836. }
  20837. {
  20838. httplib::Client cli(" ", PORT);
  20839. auto res = cli.Get("/");
  20840. ASSERT_FALSE(res);
  20841. EXPECT_EQ(httplib::Error::Connection, res.error());
  20842. }
  20843. }
  20844. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20845. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  20846. Server svr;
  20847. // Set a small payload limit (1KB)
  20848. svr.set_payload_max_length(1024);
  20849. svr.Post("/test", [&](const Request &req, Response &res) {
  20850. res.set_content("Body size: " + std::to_string(req.body.size()),
  20851. "text/plain");
  20852. });
  20853. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  20854. auto se = detail::scope_exit([&] {
  20855. svr.stop();
  20856. listen_thread.join();
  20857. });
  20858. svr.wait_until_ready();
  20859. // Create data that compresses well but exceeds limit when decompressed
  20860. // 8KB of repeated null bytes compresses to a very small size
  20861. std::string original_data(8 * 1024, '\0');
  20862. // Compress the data using gzip
  20863. std::string compressed_data;
  20864. detail::gzip_compressor compressor;
  20865. compressor.compress(original_data.data(), original_data.size(), true,
  20866. [&](const char *data, size_t size) {
  20867. compressed_data.append(data, size);
  20868. return true;
  20869. });
  20870. // Verify compression worked (compressed should be much smaller)
  20871. ASSERT_LT(compressed_data.size(), original_data.size());
  20872. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  20873. // Send compressed data with Content-Encoding: gzip
  20874. Client cli(HOST, PORT);
  20875. Headers headers = {{"Content-Encoding", "gzip"}};
  20876. auto res =
  20877. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  20878. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  20879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20880. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  20881. }
  20882. #endif
  20883. // ============================================================================
  20884. // OpenSSL-Specific Tests
  20885. // ============================================================================
  20886. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  20887. X509 *readCertificate(const std::string &strFileName) {
  20888. std::ifstream inStream(strFileName);
  20889. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  20890. std::istreambuf_iterator<char>());
  20891. if (strCertPEM.empty()) return (nullptr);
  20892. BIO *pbCert = BIO_new(BIO_s_mem());
  20893. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  20894. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  20895. BIO_free(pbCert);
  20896. return (pCert);
  20897. }
  20898. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  20899. std::ifstream inStream(strFileName);
  20900. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  20901. std::istreambuf_iterator<char>());
  20902. if (strPrivateKeyPEM.empty()) return (nullptr);
  20903. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  20904. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  20905. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  20906. BIO_free(pbPrivKey);
  20907. return (pPrivateKey);
  20908. }
  20909. TEST(BindServerTest, UpdateCerts) {
  20910. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20911. int port = svr.bind_to_any_port("0.0.0.0");
  20912. ASSERT_TRUE(svr.is_valid());
  20913. ASSERT_TRUE(port > 0);
  20914. X509 *cert = readCertificate(SERVER_CERT_FILE);
  20915. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  20916. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  20917. ASSERT_TRUE(cert != nullptr);
  20918. ASSERT_TRUE(ca_cert != nullptr);
  20919. ASSERT_TRUE(key != nullptr);
  20920. X509_STORE *cert_store = X509_STORE_new();
  20921. X509_STORE_add_cert(cert_store, ca_cert);
  20922. // svr.update_certs(cert, key, cert_store); // deprecated
  20923. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  20924. CLIENT_CA_CERT_FILE);
  20925. ASSERT_TRUE(svr.is_valid());
  20926. svr.stop();
  20927. X509_STORE_free(cert_store);
  20928. X509_free(cert);
  20929. X509_free(ca_cert);
  20930. EVP_PKEY_free(key);
  20931. }
  20932. // Test that update_certs() updates client CA list correctly
  20933. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  20934. // Start with file-based constructor
  20935. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20936. ASSERT_TRUE(svr.is_valid());
  20937. // Initially no client CA list should be set
  20938. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20939. ASSERT_TRUE(ssl_ctx != nullptr);
  20940. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  20941. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  20942. EXPECT_EQ(0, count_before);
  20943. // Now update with client CA (PEM string)
  20944. std::string cert_pem, key_pem, ca_pem;
  20945. read_file(SERVER_CERT_FILE, cert_pem);
  20946. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  20947. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  20948. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  20949. ASSERT_TRUE(svr.is_valid());
  20950. // Now client CA list should be set
  20951. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  20952. ASSERT_TRUE(ca_list_after != nullptr);
  20953. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  20954. }
  20955. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  20956. // Test that the file-path SSLServer constructor properly sets the client CA
  20957. // list that is sent to clients during the TLS handshake (CertificateRequest)
  20958. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20959. ASSERT_TRUE(svr.is_valid());
  20960. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20961. ASSERT_TRUE(ssl_ctx != nullptr);
  20962. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  20963. ASSERT_TRUE(ca_list != nullptr);
  20964. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  20965. }
  20966. #endif
  20967. // ============================================================================
  20968. // MbedTLS-Specific Tests
  20969. // ============================================================================
  20970. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  20971. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  20972. using namespace httplib::tls;
  20973. // Track if callback was invoked
  20974. bool callback_invoked = false;
  20975. // The callback receives void* ctx which is actually MbedTlsContext*
  20976. // We can access the mbedtls_ssl_config via the context
  20977. auto setup_callback = [&callback_invoked](void *ctx) {
  20978. callback_invoked = true;
  20979. // Cast to MbedTlsContext* to access the ssl config
  20980. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  20981. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  20982. // Use static variables to hold certificate data (simplified for test)
  20983. static mbedtls_x509_crt own_cert;
  20984. static mbedtls_pk_context own_key;
  20985. static mbedtls_x509_crt ca_chain;
  20986. static bool initialized = false;
  20987. if (!initialized) {
  20988. mbedtls_x509_crt_init(&own_cert);
  20989. mbedtls_pk_init(&own_key);
  20990. mbedtls_x509_crt_init(&ca_chain);
  20991. // Load server certificate
  20992. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  20993. return false;
  20994. }
  20995. // Load server private key.
  20996. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  20997. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  20998. #if MBEDTLS_VERSION_MAJOR == 3
  20999. ,
  21000. mbedtls_ctr_drbg_random, nullptr
  21001. #endif
  21002. ) != 0) {
  21003. return false;
  21004. }
  21005. // Load CA chain for client verification
  21006. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  21007. return false;
  21008. }
  21009. initialized = true;
  21010. }
  21011. // Configure the SSL config
  21012. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  21013. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  21014. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  21015. // Set minimum TLS version using mbedTLS native API
  21016. #if MBEDTLS_VERSION_MAJOR >= 3
  21017. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  21018. #else
  21019. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  21020. MBEDTLS_SSL_MINOR_VERSION_3);
  21021. #endif
  21022. return true;
  21023. };
  21024. SSLServer svr(setup_callback);
  21025. ASSERT_TRUE(svr.is_valid());
  21026. ASSERT_TRUE(callback_invoked);
  21027. svr.Get("/test", [&](const Request &req, Response &res) {
  21028. res.set_content("test", "text/plain");
  21029. auto cert = req.peer_cert();
  21030. ASSERT_TRUE(static_cast<bool>(cert));
  21031. auto common_name = cert.subject_cn();
  21032. EXPECT_EQ("Common Name", common_name);
  21033. });
  21034. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21035. auto se = detail::scope_exit([&] {
  21036. svr.stop();
  21037. t.join();
  21038. ASSERT_FALSE(svr.is_running());
  21039. });
  21040. svr.wait_until_ready();
  21041. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  21042. cli.enable_server_certificate_verification(false);
  21043. cli.set_connection_timeout(30);
  21044. auto res = cli.Get("/test");
  21045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21046. ASSERT_EQ(StatusCode::OK_200, res->status);
  21047. }
  21048. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  21049. // context (owning mbedtls_ssl_config) before shutting down a still-open
  21050. // keep-alive SSL session, which reads through that config in
  21051. // mbedtls_ssl_close_notify.
  21052. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  21053. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21054. ASSERT_TRUE(svr.is_valid());
  21055. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  21056. res.set_content("test", "text/plain");
  21057. });
  21058. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  21059. auto se = detail::scope_exit([&] {
  21060. svr.stop();
  21061. t.join();
  21062. ASSERT_FALSE(svr.is_running());
  21063. });
  21064. svr.wait_until_ready();
  21065. {
  21066. SSLClient cli(HOST, PORT);
  21067. cli.enable_server_certificate_verification(false);
  21068. cli.set_keep_alive(true);
  21069. auto res = cli.Get("/test");
  21070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21071. ASSERT_EQ(StatusCode::OK_200, res->status);
  21072. // cli is destructed here with the keep-alive SSL session still open.
  21073. }
  21074. }
  21075. #endif
  21076. // WebSocket Tests
  21077. TEST(WebSocketTest, RSVBitsMustBeZero) {
  21078. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  21079. // defining the meaning of these bits has been negotiated.
  21080. auto make_frame = [](uint8_t first_byte) {
  21081. std::string frame;
  21082. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  21083. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  21084. frame += "Hello";
  21085. return frame;
  21086. };
  21087. // RSV1 set (0x40)
  21088. {
  21089. detail::BufferStream strm;
  21090. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  21091. ws::Opcode opcode;
  21092. std::string payload;
  21093. bool fin;
  21094. EXPECT_EQ(
  21095. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21096. ws::impl::FrameRead::Fail);
  21097. }
  21098. // RSV2 set (0x20)
  21099. {
  21100. detail::BufferStream strm;
  21101. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  21102. ws::Opcode opcode;
  21103. std::string payload;
  21104. bool fin;
  21105. EXPECT_EQ(
  21106. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21107. ws::impl::FrameRead::Fail);
  21108. }
  21109. // RSV3 set (0x10)
  21110. {
  21111. detail::BufferStream strm;
  21112. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  21113. ws::Opcode opcode;
  21114. std::string payload;
  21115. bool fin;
  21116. EXPECT_EQ(
  21117. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21118. ws::impl::FrameRead::Fail);
  21119. }
  21120. // No RSV bits set - should succeed
  21121. {
  21122. detail::BufferStream strm;
  21123. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  21124. ws::Opcode opcode;
  21125. std::string payload;
  21126. bool fin;
  21127. EXPECT_EQ(
  21128. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21129. ws::impl::FrameRead::Ok);
  21130. EXPECT_EQ(ws::Opcode::Text, opcode);
  21131. EXPECT_EQ("Hello", payload);
  21132. EXPECT_TRUE(fin);
  21133. }
  21134. }
  21135. TEST(WebSocketTest, ControlFrameValidation) {
  21136. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  21137. // payload length <= 125.
  21138. // Ping with FIN=0 - must be rejected
  21139. {
  21140. detail::BufferStream strm;
  21141. std::string frame;
  21142. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  21143. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21144. strm.write(frame.data(), frame.size());
  21145. ws::Opcode opcode;
  21146. std::string payload;
  21147. bool fin;
  21148. EXPECT_EQ(
  21149. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21150. ws::impl::FrameRead::Fail);
  21151. }
  21152. // Close with FIN=0 - must be rejected
  21153. {
  21154. detail::BufferStream strm;
  21155. std::string frame;
  21156. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  21157. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  21158. strm.write(frame.data(), frame.size());
  21159. ws::Opcode opcode;
  21160. std::string payload;
  21161. bool fin;
  21162. EXPECT_EQ(
  21163. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21164. ws::impl::FrameRead::Fail);
  21165. }
  21166. // Ping with payload_len=126 (extended length) - must be rejected
  21167. {
  21168. detail::BufferStream strm;
  21169. std::string frame;
  21170. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21171. frame += static_cast<char>(126); // payload_len=126 (>125)
  21172. frame += static_cast<char>(0x00); // extended length high byte
  21173. frame += static_cast<char>(126); // extended length low byte
  21174. frame += std::string(126, 'x');
  21175. strm.write(frame.data(), frame.size());
  21176. ws::Opcode opcode;
  21177. std::string payload;
  21178. bool fin;
  21179. EXPECT_EQ(
  21180. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21181. ws::impl::FrameRead::Fail);
  21182. }
  21183. // Ping with FIN=1 and payload_len=125 - should succeed
  21184. {
  21185. detail::BufferStream strm;
  21186. std::string frame;
  21187. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  21188. frame += static_cast<char>(125); // payload_len=125
  21189. frame += std::string(125, 'x');
  21190. strm.write(frame.data(), frame.size());
  21191. ws::Opcode opcode;
  21192. std::string payload;
  21193. bool fin;
  21194. EXPECT_EQ(
  21195. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21196. ws::impl::FrameRead::Ok);
  21197. EXPECT_EQ(ws::Opcode::Ping, opcode);
  21198. EXPECT_EQ(125u, payload.size());
  21199. EXPECT_TRUE(fin);
  21200. }
  21201. }
  21202. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  21203. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  21204. // length MUST be 0.
  21205. // MSB set - must be rejected
  21206. {
  21207. detail::BufferStream strm;
  21208. std::string frame;
  21209. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21210. frame += static_cast<char>(127); // 64-bit extended length
  21211. frame += static_cast<char>(0x80); // MSB set (invalid)
  21212. frame += std::string(7, '\0'); // remaining 7 bytes of length
  21213. strm.write(frame.data(), frame.size());
  21214. ws::Opcode opcode;
  21215. std::string payload;
  21216. bool fin;
  21217. EXPECT_EQ(
  21218. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21219. ws::impl::FrameRead::Fail);
  21220. }
  21221. // MSB clear - should pass length parsing (will be rejected by max_len,
  21222. // but that's a different check; use a small length to verify)
  21223. {
  21224. detail::BufferStream strm;
  21225. std::string frame;
  21226. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  21227. frame += static_cast<char>(127); // 64-bit extended length
  21228. frame += std::string(7, '\0'); // high bytes = 0
  21229. frame += static_cast<char>(0x03); // length = 3
  21230. frame += "abc";
  21231. strm.write(frame.data(), frame.size());
  21232. ws::Opcode opcode;
  21233. std::string payload;
  21234. bool fin;
  21235. EXPECT_EQ(
  21236. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  21237. ws::impl::FrameRead::Ok);
  21238. EXPECT_EQ(ws::Opcode::Text, opcode);
  21239. EXPECT_EQ("abc", payload);
  21240. }
  21241. }
  21242. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  21243. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  21244. // Valid UTF-8
  21245. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  21246. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  21247. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  21248. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  21249. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  21250. // Invalid UTF-8
  21251. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  21252. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  21253. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  21254. EXPECT_FALSE(
  21255. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  21256. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  21257. }
  21258. TEST(WebSocketTest, ConnectAndDisconnect) {
  21259. Server svr;
  21260. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21261. std::string msg;
  21262. while (ws.read(msg)) {}
  21263. });
  21264. auto port = svr.bind_to_any_port(HOST);
  21265. std::thread t([&]() { svr.listen_after_bind(); });
  21266. svr.wait_until_ready();
  21267. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21268. auto res = client.connect();
  21269. ASSERT_TRUE(res);
  21270. EXPECT_EQ(Error::Success, res.error());
  21271. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  21272. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  21273. EXPECT_TRUE(client.is_open());
  21274. client.close();
  21275. EXPECT_FALSE(client.is_open());
  21276. svr.stop();
  21277. t.join();
  21278. }
  21279. TEST(WebSocketTest, ValidURL) {
  21280. ws::WebSocketClient ws1("ws://localhost:8080/path");
  21281. EXPECT_TRUE(ws1.is_valid());
  21282. ws::WebSocketClient ws2("ws://example.com/path");
  21283. EXPECT_TRUE(ws2.is_valid());
  21284. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  21285. EXPECT_TRUE(ws3.is_valid());
  21286. #ifdef CPPHTTPLIB_SSL_ENABLED
  21287. ws::WebSocketClient wss1("wss://example.com/path");
  21288. EXPECT_TRUE(wss1.is_valid());
  21289. ws::WebSocketClient wss2("wss://example.com:443/path");
  21290. EXPECT_TRUE(wss2.is_valid());
  21291. #endif
  21292. }
  21293. TEST(WebSocketTest, InvalidURL) {
  21294. // No scheme
  21295. ws::WebSocketClient ws1("localhost:8080/path");
  21296. EXPECT_FALSE(ws1.is_valid());
  21297. // No path
  21298. ws::WebSocketClient ws2("ws://localhost:8080");
  21299. EXPECT_FALSE(ws2.is_valid());
  21300. // Empty string
  21301. ws::WebSocketClient ws3("");
  21302. EXPECT_FALSE(ws3.is_valid());
  21303. // Missing host
  21304. ws::WebSocketClient ws4("ws://:8080/path");
  21305. EXPECT_FALSE(ws4.is_valid());
  21306. // Port number overflow — should not crash
  21307. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  21308. EXPECT_FALSE(ws5.is_valid());
  21309. // Port out of range
  21310. ws::WebSocketClient ws6("ws://localhost:99999/path");
  21311. EXPECT_FALSE(ws6.is_valid());
  21312. }
  21313. TEST(WebSocketTest, UnsupportedScheme) {
  21314. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  21315. ws::WebSocketClient ws1("http://localhost:8080/path");
  21316. EXPECT_FALSE(ws1.is_valid());
  21317. ws::WebSocketClient ws2("https://localhost:8080/path");
  21318. EXPECT_FALSE(ws2.is_valid());
  21319. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  21320. EXPECT_FALSE(ws3.is_valid());
  21321. #else
  21322. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  21323. std::invalid_argument);
  21324. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  21325. std::invalid_argument);
  21326. #endif
  21327. }
  21328. TEST(WebSocketTest, ConnectWhenInvalid) {
  21329. ws::WebSocketClient ws("not a valid url");
  21330. EXPECT_FALSE(ws.is_valid());
  21331. auto res = ws.connect();
  21332. EXPECT_FALSE(res);
  21333. EXPECT_EQ(Error::Connection, res.error());
  21334. EXPECT_EQ(-1, res.status());
  21335. }
  21336. TEST(WebSocketTest, ConnectRefusedReportsError) {
  21337. // Grab a port that is free, then close it again so nothing listens there
  21338. Server svr;
  21339. auto port = svr.bind_to_any_port(HOST);
  21340. svr.stop();
  21341. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21342. auto res = client.connect();
  21343. ASSERT_FALSE(res);
  21344. EXPECT_EQ(Error::Connection, res.error());
  21345. EXPECT_EQ(-1, res.status());
  21346. }
  21347. TEST(WebSocketTest, DefaultPort) {
  21348. ws::WebSocketClient ws1("ws://example.com/path");
  21349. EXPECT_TRUE(ws1.is_valid());
  21350. // ws:// defaults to port 80 (verified by successful parse)
  21351. #ifdef CPPHTTPLIB_SSL_ENABLED
  21352. ws::WebSocketClient ws2("wss://example.com/path");
  21353. EXPECT_TRUE(ws2.is_valid());
  21354. // wss:// defaults to port 443 (verified by successful parse)
  21355. #endif
  21356. }
  21357. TEST(WebSocketTest, IPv6LiteralAddress) {
  21358. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  21359. EXPECT_TRUE(ws1.is_valid());
  21360. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  21361. EXPECT_TRUE(ws2.is_valid());
  21362. }
  21363. TEST(WebSocketTest, ComplexPath) {
  21364. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  21365. EXPECT_TRUE(ws1.is_valid());
  21366. ws::WebSocketClient ws2("ws://localhost:8080/");
  21367. EXPECT_TRUE(ws2.is_valid());
  21368. }
  21369. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  21370. Server svr;
  21371. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21372. std::string msg;
  21373. while (ws.read(msg)) {}
  21374. });
  21375. auto port = svr.bind_to_any_port(HOST);
  21376. std::thread t([&]() { svr.listen_after_bind(); });
  21377. svr.wait_until_ready();
  21378. auto another_host = "example.com";
  21379. auto wrong_ip = "192.0.2.1";
  21380. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21381. client.set_hostname_addr_map({{another_host, wrong_ip}});
  21382. ASSERT_TRUE(client.connect());
  21383. EXPECT_TRUE(client.is_open());
  21384. client.close();
  21385. svr.stop();
  21386. t.join();
  21387. }
  21388. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  21389. Server svr;
  21390. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21391. std::string msg;
  21392. while (ws.read(msg)) {}
  21393. });
  21394. auto port = svr.bind_to_any_port(HOST);
  21395. std::thread t([&]() { svr.listen_after_bind(); });
  21396. svr.wait_until_ready();
  21397. auto wrong_ip = "192.0.2.1";
  21398. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21399. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  21400. client.set_connection_timeout(1);
  21401. client.set_read_timeout(1);
  21402. client.set_write_timeout(1);
  21403. EXPECT_FALSE(client.connect());
  21404. EXPECT_FALSE(client.is_open());
  21405. svr.stop();
  21406. t.join();
  21407. }
  21408. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  21409. // A mapped value that is not an IP literal must be resolved. HOST resolves
  21410. // from the hosts file, so this test needs no external DNS. "target.invalid"
  21411. // (RFC 6761) is only a map key and the Host header value.
  21412. auto host = "target.invalid";
  21413. Server svr;
  21414. std::string received_host;
  21415. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21416. received_host = req.get_header_value("Host");
  21417. std::string msg;
  21418. while (ws.read(msg)) {}
  21419. });
  21420. auto port = svr.bind_to_any_port(HOST);
  21421. std::thread t([&]() { svr.listen_after_bind(); });
  21422. // ASSERT_* below returns from the test body, which would leave t joinable
  21423. // and make ~thread call std::terminate.
  21424. auto se = detail::scope_exit([&] {
  21425. svr.stop();
  21426. if (t.joinable()) { t.join(); }
  21427. });
  21428. svr.wait_until_ready();
  21429. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  21430. std::to_string(port) + "/ws");
  21431. client.set_hostname_addr_map({{host, HOST}});
  21432. ASSERT_TRUE(client.connect());
  21433. EXPECT_TRUE(client.is_open());
  21434. client.close();
  21435. svr.stop();
  21436. t.join();
  21437. // The mapping only redirects the connection; the identity stays host_.
  21438. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  21439. }
  21440. class WebSocketIntegrationTest : public ::testing::Test {
  21441. protected:
  21442. void SetUp() override {
  21443. server_ = httplib::detail::make_unique<Server>();
  21444. setup_server();
  21445. start_server();
  21446. }
  21447. void TearDown() override {
  21448. server_->stop();
  21449. if (server_thread_.joinable()) { server_thread_.join(); }
  21450. }
  21451. void setup_server() {
  21452. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21453. std::string msg;
  21454. ws::ReadResult ret;
  21455. while ((ret = ws.read(msg))) {
  21456. if (ret == ws::Binary) {
  21457. ws.send(msg.data(), msg.size());
  21458. } else {
  21459. ws.send(msg);
  21460. }
  21461. }
  21462. });
  21463. server_->WebSocket("/ws-echo-string",
  21464. [](const Request &, ws::WebSocket &ws) {
  21465. std::string msg;
  21466. while (ws.read(msg)) {
  21467. ws.send("echo: " + msg);
  21468. }
  21469. });
  21470. server_->WebSocket(
  21471. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  21472. // Echo back request metadata
  21473. ws.send("path:" + req.path);
  21474. ws.send("header:" + req.get_header_value("X-Test-Header"));
  21475. std::string msg;
  21476. while (ws.read(msg)) {}
  21477. });
  21478. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  21479. std::string msg;
  21480. ws.read(msg); // wait for a message
  21481. ws.close();
  21482. });
  21483. server_->WebSocket("/ws-close-status",
  21484. [](const Request &, ws::WebSocket &ws) {
  21485. std::string msg;
  21486. ws.read(msg); // wait for a message
  21487. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  21488. });
  21489. server_->WebSocket(
  21490. "/ws-subprotocol",
  21491. [](const Request &, ws::WebSocket &ws) {
  21492. std::string msg;
  21493. while (ws.read(msg)) {
  21494. ws.send(msg);
  21495. }
  21496. },
  21497. [](const std::vector<std::string> &protocols) -> std::string {
  21498. for (const auto &p : protocols) {
  21499. if (p == "graphql-ws") { return p; }
  21500. }
  21501. return "";
  21502. });
  21503. server_->WebSocket(
  21504. "/ws-subprotocol-unoffered",
  21505. [](const Request &, ws::WebSocket &ws) {
  21506. std::string msg;
  21507. while (ws.read(msg)) {
  21508. ws.send(msg);
  21509. }
  21510. },
  21511. [](const std::vector<std::string> &) -> std::string {
  21512. return "admin";
  21513. });
  21514. }
  21515. void start_server() {
  21516. port_ = server_->bind_to_any_port(HOST);
  21517. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21518. server_->wait_until_ready();
  21519. }
  21520. std::unique_ptr<Server> server_;
  21521. std::thread server_thread_;
  21522. int port_ = 0;
  21523. };
  21524. TEST_F(WebSocketIntegrationTest, TextEcho) {
  21525. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21526. "/ws-echo");
  21527. ASSERT_TRUE(client.connect());
  21528. ASSERT_TRUE(client.is_open());
  21529. ASSERT_TRUE(client.send("Hello WebSocket"));
  21530. std::string msg;
  21531. EXPECT_EQ(ws::Text, client.read(msg));
  21532. EXPECT_EQ("Hello WebSocket", msg);
  21533. client.close();
  21534. }
  21535. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  21536. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21537. "/ws-echo");
  21538. ASSERT_TRUE(client.connect());
  21539. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  21540. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  21541. std::string msg;
  21542. EXPECT_EQ(ws::Binary, client.read(msg));
  21543. EXPECT_EQ(binary_data, msg);
  21544. client.close();
  21545. }
  21546. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  21547. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21548. "/ws-echo");
  21549. ASSERT_TRUE(client.connect());
  21550. for (int i = 0; i < 10; i++) {
  21551. auto text = "message " + std::to_string(i);
  21552. ASSERT_TRUE(client.send(text));
  21553. std::string msg;
  21554. ASSERT_TRUE(client.read(msg));
  21555. EXPECT_EQ(text, msg);
  21556. }
  21557. client.close();
  21558. }
  21559. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  21560. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21561. "/ws-close");
  21562. ASSERT_TRUE(client.connect());
  21563. // Send a message to trigger the server to close
  21564. ASSERT_TRUE(client.send("trigger close"));
  21565. // The server will close, so read should return false
  21566. std::string msg;
  21567. EXPECT_FALSE(client.read(msg));
  21568. EXPECT_FALSE(client.is_open());
  21569. }
  21570. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  21571. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21572. "/ws-echo");
  21573. ASSERT_TRUE(client.connect());
  21574. // 128KB message
  21575. std::string large_data(128 * 1024, 'X');
  21576. ASSERT_TRUE(client.send(large_data));
  21577. std::string msg;
  21578. ASSERT_TRUE(client.read(msg));
  21579. EXPECT_EQ(large_data, msg);
  21580. client.close();
  21581. }
  21582. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  21583. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21584. "/ws-echo");
  21585. ASSERT_TRUE(client.connect());
  21586. const int num_threads = 4;
  21587. std::vector<std::thread> threads;
  21588. std::atomic<int> send_count{0};
  21589. for (int t = 0; t < num_threads; t++) {
  21590. threads.emplace_back([&client, &send_count, t]() {
  21591. for (int i = 0; i < 5; i++) {
  21592. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  21593. if (client.send(text)) { send_count++; }
  21594. }
  21595. });
  21596. }
  21597. for (auto &th : threads) {
  21598. th.join();
  21599. }
  21600. int received = 0;
  21601. std::string msg;
  21602. while (received < send_count.load()) {
  21603. if (!client.read(msg)) { break; }
  21604. received++;
  21605. }
  21606. EXPECT_EQ(send_count.load(), received);
  21607. client.close();
  21608. }
  21609. TEST_F(WebSocketIntegrationTest, ReadString) {
  21610. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21611. "/ws-echo-string");
  21612. ASSERT_TRUE(client.connect());
  21613. ASSERT_TRUE(client.send("hello"));
  21614. std::string msg;
  21615. ASSERT_TRUE(client.read(msg));
  21616. EXPECT_EQ("echo: hello", msg);
  21617. ASSERT_TRUE(client.send("world"));
  21618. ASSERT_TRUE(client.read(msg));
  21619. EXPECT_EQ("echo: world", msg);
  21620. client.close();
  21621. }
  21622. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  21623. Headers headers = {{"X-Test-Header", "test-value"}};
  21624. ws::WebSocketClient client(
  21625. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  21626. ASSERT_TRUE(client.connect());
  21627. std::string msg;
  21628. ASSERT_TRUE(client.read(msg));
  21629. EXPECT_EQ("path:/ws-request-info", msg);
  21630. ASSERT_TRUE(client.read(msg));
  21631. EXPECT_EQ("header:test-value", msg);
  21632. client.close();
  21633. }
  21634. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  21635. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21636. "/ws-echo");
  21637. client.set_read_timeout(1, 0); // 1 second
  21638. ASSERT_TRUE(client.connect());
  21639. // Don't send anything — server echo handler waits for a message, so read()
  21640. // should time out. The connection survives it: nothing was consumed.
  21641. std::string msg;
  21642. EXPECT_EQ(client.read(msg), ws::Timeout);
  21643. EXPECT_TRUE(client.is_open());
  21644. // And it is still usable afterwards.
  21645. EXPECT_TRUE(client.send("after timeout"));
  21646. EXPECT_EQ(client.read(msg), ws::Text);
  21647. EXPECT_EQ(msg, "after timeout");
  21648. }
  21649. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  21650. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21651. "/ws-echo");
  21652. client.set_read_timeout(1, 0);
  21653. ASSERT_TRUE(client.connect());
  21654. ASSERT_TRUE(client.send("first"));
  21655. std::string msg;
  21656. ASSERT_EQ(client.read(msg), ws::Text);
  21657. ASSERT_EQ(msg, "first");
  21658. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  21659. // not be used with a read timeout: it would reprocess the previous message.
  21660. EXPECT_EQ(client.read(msg), ws::Timeout);
  21661. EXPECT_EQ(msg, "first");
  21662. }
  21663. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  21664. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21665. "/ws-echo");
  21666. ASSERT_TRUE(client.connect());
  21667. // Setting it once the connection is open reaches the live stream, not just
  21668. // the seed for the next connect().
  21669. client.set_read_timeout(1, 0);
  21670. std::string msg;
  21671. EXPECT_EQ(client.read(msg), ws::Timeout);
  21672. EXPECT_TRUE(client.is_open());
  21673. }
  21674. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  21675. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21676. "/ws-echo");
  21677. client.set_read_timeout(5, 0);
  21678. ASSERT_TRUE(client.connect());
  21679. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21680. // The server should reject it and close the connection.
  21681. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  21682. client.send(oversized);
  21683. // The server's read() should have failed due to payload limit,
  21684. // so our read() should return false (connection closed).
  21685. std::string msg;
  21686. EXPECT_FALSE(client.read(msg));
  21687. }
  21688. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  21689. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21690. "/ws-echo");
  21691. client.set_read_timeout(10, 0);
  21692. ASSERT_TRUE(client.connect());
  21693. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21694. // This should succeed.
  21695. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  21696. ASSERT_TRUE(client.send(at_limit));
  21697. std::string msg;
  21698. ASSERT_TRUE(client.read(msg));
  21699. EXPECT_EQ(at_limit.size(), msg.size());
  21700. client.close();
  21701. }
  21702. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  21703. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21704. "/nonexistent");
  21705. auto res = client.connect();
  21706. EXPECT_FALSE(res);
  21707. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21708. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  21709. EXPECT_FALSE(client.is_open());
  21710. }
  21711. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  21712. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21713. "/ws-echo");
  21714. ASSERT_TRUE(client.connect());
  21715. ASSERT_TRUE(client.send(""));
  21716. std::string msg;
  21717. EXPECT_EQ(ws::Text, client.read(msg));
  21718. EXPECT_EQ("", msg);
  21719. client.close();
  21720. }
  21721. TEST_F(WebSocketIntegrationTest, Reconnect) {
  21722. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21723. "/ws-echo");
  21724. // First connection
  21725. ASSERT_TRUE(client.connect());
  21726. ASSERT_TRUE(client.send("first"));
  21727. std::string msg;
  21728. ASSERT_TRUE(client.read(msg));
  21729. EXPECT_EQ("first", msg);
  21730. client.close();
  21731. EXPECT_FALSE(client.is_open());
  21732. // Reconnect using the same client object
  21733. ASSERT_TRUE(client.connect());
  21734. ASSERT_TRUE(client.is_open());
  21735. ASSERT_TRUE(client.send("second"));
  21736. ASSERT_TRUE(client.read(msg));
  21737. EXPECT_EQ("second", msg);
  21738. client.close();
  21739. }
  21740. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  21741. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21742. "/ws-close-status");
  21743. ASSERT_TRUE(client.connect());
  21744. // Trigger the server to close with GoingAway status
  21745. ASSERT_TRUE(client.send("trigger"));
  21746. // read() should return false after receiving the close frame
  21747. std::string msg;
  21748. EXPECT_FALSE(client.read(msg));
  21749. EXPECT_FALSE(client.is_open());
  21750. }
  21751. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  21752. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21753. "/ws-echo");
  21754. ASSERT_TRUE(client.connect());
  21755. client.close(ws::CloseStatus::GoingAway, "client leaving");
  21756. EXPECT_FALSE(client.is_open());
  21757. }
  21758. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  21759. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  21760. ws::WebSocketClient client(
  21761. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21762. ASSERT_TRUE(client.connect());
  21763. // Server should have selected graphql-ws
  21764. EXPECT_EQ("graphql-ws", client.subprotocol());
  21765. client.close();
  21766. }
  21767. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  21768. Headers headers;
  21769. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  21770. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  21771. ws::WebSocketClient client(
  21772. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21773. ASSERT_TRUE(client.connect());
  21774. // The offer on the second field line counts too, so graphql-ws is selected
  21775. EXPECT_EQ("graphql-ws", client.subprotocol());
  21776. client.close();
  21777. }
  21778. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  21779. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  21780. ws::WebSocketClient client(
  21781. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21782. ASSERT_TRUE(client.connect());
  21783. // Server should not have selected any subprotocol
  21784. EXPECT_TRUE(client.subprotocol().empty());
  21785. client.close();
  21786. }
  21787. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  21788. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21789. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21790. "/ws-subprotocol-unoffered",
  21791. headers);
  21792. ASSERT_TRUE(client.connect());
  21793. EXPECT_TRUE(client.subprotocol().empty());
  21794. client.close();
  21795. }
  21796. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  21797. // Connect without requesting any subprotocol
  21798. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21799. "/ws-subprotocol");
  21800. ASSERT_TRUE(client.connect());
  21801. EXPECT_TRUE(client.subprotocol().empty());
  21802. client.close();
  21803. }
  21804. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  21805. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21806. "/ws-echo");
  21807. client.set_tcp_nodelay(true);
  21808. client.set_connection_timeout(3, 0);
  21809. bool socket_options_called = false;
  21810. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  21811. ASSERT_TRUE(client.connect());
  21812. ASSERT_TRUE(client.is_open());
  21813. EXPECT_TRUE(socket_options_called);
  21814. ASSERT_TRUE(client.send("hello"));
  21815. std::string msg;
  21816. auto result = client.read(msg);
  21817. EXPECT_EQ(result, ws::ReadResult::Text);
  21818. EXPECT_EQ(msg, "hello");
  21819. client.close();
  21820. }
  21821. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  21822. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21823. "/ws-echo");
  21824. client.set_connection_timeout(std::chrono::seconds(3));
  21825. client.set_write_timeout(std::chrono::seconds(3));
  21826. // A sub-second remainder exercises the seconds/microseconds split.
  21827. client.set_read_timeout(std::chrono::milliseconds(1500));
  21828. ASSERT_TRUE(client.connect());
  21829. auto start = std::chrono::steady_clock::now();
  21830. std::string msg;
  21831. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  21832. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  21833. std::chrono::steady_clock::now() - start)
  21834. .count();
  21835. // Above 1s so that dropping the microseconds half of the split fails here.
  21836. // Ignoring the setter altogether would not reach this line at all: a client
  21837. // waits forever by default.
  21838. EXPECT_GE(elapsed, 1400);
  21839. EXPECT_LT(elapsed, 30000);
  21840. }
  21841. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  21842. Server svr;
  21843. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  21844. if (!req.has_header("Authorization")) {
  21845. res.status = StatusCode::Unauthorized_401;
  21846. res.set_content("Unauthorized", "text/plain");
  21847. return Server::HandlerResponse::Handled;
  21848. }
  21849. return Server::HandlerResponse::Unhandled;
  21850. });
  21851. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21852. std::string msg;
  21853. while (ws.read(msg)) {
  21854. ws.send(msg);
  21855. }
  21856. });
  21857. auto port = svr.bind_to_any_port("localhost");
  21858. std::thread t([&]() { svr.listen_after_bind(); });
  21859. svr.wait_until_ready();
  21860. // Without Authorization header - should be rejected before upgrade
  21861. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  21862. EXPECT_FALSE(client1.connect());
  21863. // The rejection is framed like any other HTTP response
  21864. {
  21865. Client cli("localhost", port);
  21866. Headers headers = {{"Upgrade", "websocket"},
  21867. {"Connection", "Upgrade"},
  21868. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21869. {"Sec-WebSocket-Version", "13"}};
  21870. auto res = cli.Get("/ws", headers);
  21871. ASSERT_TRUE(res);
  21872. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21873. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21874. EXPECT_EQ("Unauthorized", res->body);
  21875. }
  21876. // With Authorization header - should succeed
  21877. Headers headers = {{"Authorization", "Bearer token123"}};
  21878. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  21879. headers);
  21880. ASSERT_TRUE(client2.connect());
  21881. ASSERT_TRUE(client2.send("hello"));
  21882. std::string msg;
  21883. ASSERT_TRUE(client2.read(msg));
  21884. EXPECT_EQ("hello", msg);
  21885. client2.close();
  21886. svr.stop();
  21887. t.join();
  21888. }
  21889. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  21890. Server svr;
  21891. std::atomic<int> pre_request_calls{0};
  21892. std::atomic<bool> route_matched{false};
  21893. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  21894. pre_request_calls++;
  21895. if (req.matched_route == "/ws/:id") { route_matched = true; }
  21896. if (req.get_header_value("Authorization") != "Bearer token123") {
  21897. res.status = StatusCode::Unauthorized_401;
  21898. res.set_content("Unauthorized", "text/plain");
  21899. return Server::HandlerResponse::Handled;
  21900. }
  21901. return Server::HandlerResponse::Unhandled;
  21902. });
  21903. std::atomic<bool> handler_called{false};
  21904. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  21905. handler_called = true;
  21906. ws.send(req.matched_route + " " + req.path_params.at("id"));
  21907. });
  21908. auto port = svr.bind_to_any_port("localhost");
  21909. std::thread t([&]() { svr.listen_after_bind(); });
  21910. svr.wait_until_ready();
  21911. // Without Authorization header - should be rejected before upgrade
  21912. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  21913. "/ws/1");
  21914. EXPECT_FALSE(client1.connect());
  21915. EXPECT_FALSE(handler_called);
  21916. EXPECT_EQ(1, pre_request_calls);
  21917. EXPECT_TRUE(route_matched);
  21918. // The rejection is an ordinary HTTP response, not a protocol switch
  21919. {
  21920. Client cli("localhost", port);
  21921. Headers headers = {{"Upgrade", "websocket"},
  21922. {"Connection", "Upgrade"},
  21923. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21924. {"Sec-WebSocket-Version", "13"}};
  21925. auto res = cli.Get("/ws/1", headers);
  21926. ASSERT_TRUE(res);
  21927. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21928. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21929. EXPECT_EQ("Unauthorized", res->body);
  21930. }
  21931. EXPECT_FALSE(handler_called);
  21932. // With Authorization header - should succeed
  21933. Headers headers = {{"Authorization", "Bearer token123"}};
  21934. ws::WebSocketClient client2(
  21935. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  21936. ASSERT_TRUE(client2.connect());
  21937. std::string msg;
  21938. ASSERT_TRUE(client2.read(msg));
  21939. EXPECT_EQ("/ws/:id 2", msg);
  21940. EXPECT_TRUE(handler_called);
  21941. client2.close();
  21942. svr.stop();
  21943. t.join();
  21944. }
  21945. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  21946. Server svr;
  21947. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21948. // A read timeout is how a handler gets control back. Without it, a handler
  21949. // parked in read() can never write on the connection it is reading.
  21950. ws.set_read_timeout(std::chrono::milliseconds(100));
  21951. std::string msg;
  21952. while (ws.is_open()) {
  21953. auto r = ws.read(msg);
  21954. if (r == httplib::ws::Timeout) {
  21955. ws.send("tick");
  21956. continue;
  21957. }
  21958. if (r == httplib::ws::Fail) { break; }
  21959. ws.send(msg);
  21960. }
  21961. });
  21962. auto port = svr.bind_to_any_port("localhost");
  21963. std::thread t([&]() { svr.listen_after_bind(); });
  21964. svr.wait_until_ready();
  21965. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21966. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  21967. ASSERT_TRUE(client.connect());
  21968. // The client sends nothing, so anything it receives came out of the
  21969. // handler's timeout path.
  21970. std::string msg;
  21971. ASSERT_EQ(client.read(msg), ws::Text);
  21972. EXPECT_EQ("tick", msg);
  21973. client.close();
  21974. svr.stop();
  21975. t.join();
  21976. }
  21977. // Stream::read may return fewer bytes than asked for. This is that contract at
  21978. // its worst -- one byte per call -- which is what a frame header straddling a
  21979. // read buffer's boundary looks like to the frame parser.
  21980. class WsByteAtATimeStream : public Stream {
  21981. public:
  21982. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  21983. bool is_readable() const override { return true; }
  21984. bool wait_readable() const override { return true; }
  21985. bool wait_writable() const override { return true; }
  21986. ssize_t read(char *ptr, size_t size) override {
  21987. if (size == 0 || pos_ >= data_.size()) { return 0; }
  21988. *ptr = data_[pos_++];
  21989. return 1;
  21990. }
  21991. ssize_t write(const char *, size_t size) override {
  21992. return static_cast<ssize_t>(size);
  21993. }
  21994. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  21995. ip = "127.0.0.1";
  21996. port = 0;
  21997. }
  21998. void get_local_ip_and_port(std::string &ip, int &port) const override {
  21999. ip = "127.0.0.1";
  22000. port = 0;
  22001. }
  22002. socket_t socket() const override { return INVALID_SOCKET; }
  22003. time_t duration() const override { return 0; }
  22004. private:
  22005. std::string data_;
  22006. size_t pos_ = 0;
  22007. };
  22008. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  22009. // The payload uses the 16-bit extended length, so the header, the length
  22010. // and the mask key are all multi-byte fields here. Each used to be read
  22011. // with a single read() call, which fails as soon as one is split. The
  22012. // payload is also a little over one read chunk, so it is read in two.
  22013. std::string body;
  22014. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  22015. body += static_cast<char>(i % 251);
  22016. }
  22017. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  22018. std::string frame;
  22019. frame += static_cast<char>(0x81); // FIN + Text
  22020. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  22021. frame += static_cast<char>(body.size() >> 8);
  22022. frame += static_cast<char>(body.size() & 0xff);
  22023. for (size_t i = 0; i < 4; i++) {
  22024. frame += static_cast<char>(mask[i]);
  22025. }
  22026. for (size_t i = 0; i < body.size(); i++) {
  22027. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  22028. }
  22029. WsByteAtATimeStream strm(frame);
  22030. ws::Opcode opcode;
  22031. std::string payload;
  22032. bool fin = false;
  22033. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  22034. /*expect_masked=*/true, body.size()),
  22035. ws::impl::FrameRead::Ok);
  22036. EXPECT_TRUE(fin);
  22037. EXPECT_EQ(opcode, ws::Opcode::Text);
  22038. EXPECT_EQ(payload, body);
  22039. }
  22040. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  22041. std::string body(2000, 'x');
  22042. std::string frame;
  22043. frame += static_cast<char>(0x82); // FIN + Binary
  22044. frame += static_cast<char>(126); // 16-bit length follows
  22045. frame += static_cast<char>(body.size() >> 8);
  22046. frame += static_cast<char>(body.size() & 0xff);
  22047. frame += body;
  22048. detail::BufferStream strm;
  22049. strm.write(frame.data(), frame.size());
  22050. ws::Opcode opcode;
  22051. std::string payload;
  22052. bool fin;
  22053. EXPECT_EQ(
  22054. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  22055. ws::impl::FrameRead::Ok);
  22056. EXPECT_EQ(body, payload);
  22057. }
  22058. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  22059. // The header announces the largest payload allowed, and only 3 bytes of it
  22060. // ever arrive.
  22061. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  22062. std::string frame;
  22063. frame += static_cast<char>(0x82); // FIN + Binary
  22064. frame += static_cast<char>(127); // 64-bit length follows
  22065. for (int shift = 56; shift >= 0; shift -= 8) {
  22066. frame += static_cast<char>((len >> shift) & 0xff);
  22067. }
  22068. frame += "abc";
  22069. detail::BufferStream strm;
  22070. strm.write(frame.data(), frame.size());
  22071. ws::Opcode opcode;
  22072. std::string payload;
  22073. bool fin;
  22074. EXPECT_EQ(
  22075. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  22076. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  22077. ws::impl::FrameRead::Fail);
  22078. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  22079. }
  22080. TEST(WebSocketTest, QueryStringInHandshake) {
  22081. Server svr;
  22082. std::mutex mtx;
  22083. std::string received_target;
  22084. std::string received_token;
  22085. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22086. {
  22087. std::lock_guard<std::mutex> lock(mtx);
  22088. received_target = req.target;
  22089. if (req.has_param("token")) {
  22090. received_token = req.get_param_value("token");
  22091. }
  22092. }
  22093. std::string msg;
  22094. while (ws.read(msg)) {
  22095. ws.send(msg);
  22096. }
  22097. });
  22098. auto port = svr.bind_to_any_port("localhost");
  22099. std::thread t([&]() { svr.listen_after_bind(); });
  22100. svr.wait_until_ready();
  22101. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  22102. "/ws?token=ABC&session=123");
  22103. ASSERT_TRUE(client.connect());
  22104. // Round-trip ensures the handler has run and captured the request.
  22105. ASSERT_TRUE(client.send("hello"));
  22106. std::string msg;
  22107. ASSERT_TRUE(client.read(msg));
  22108. EXPECT_EQ("hello", msg);
  22109. client.close();
  22110. {
  22111. std::lock_guard<std::mutex> lock(mtx);
  22112. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  22113. EXPECT_EQ("ABC", received_token);
  22114. }
  22115. svr.stop();
  22116. t.join();
  22117. }
  22118. // Run a handshake against a throwaway server and hand the request the server
  22119. // received back to the caller, so tests can assert on the headers the client
  22120. // actually put on the wire.
  22121. static void capture_websocket_handshake_request(
  22122. const Headers &client_headers,
  22123. std::function<void(const Request &, int port)> verify) {
  22124. Server svr;
  22125. std::mutex mtx;
  22126. Request received;
  22127. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22128. {
  22129. std::lock_guard<std::mutex> lock(mtx);
  22130. received = req;
  22131. }
  22132. std::string msg;
  22133. while (ws.read(msg)) {
  22134. ws.send(msg);
  22135. }
  22136. });
  22137. auto port = svr.bind_to_any_port("localhost");
  22138. std::thread t([&]() { svr.listen_after_bind(); });
  22139. auto se = detail::scope_exit([&] {
  22140. svr.stop();
  22141. t.join();
  22142. });
  22143. svr.wait_until_ready();
  22144. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  22145. client_headers);
  22146. ASSERT_TRUE(client.connect());
  22147. ASSERT_TRUE(client.send("hello"));
  22148. std::string msg;
  22149. ASSERT_TRUE(client.read(msg));
  22150. client.close();
  22151. {
  22152. std::lock_guard<std::mutex> lock(mtx);
  22153. verify(received, port);
  22154. }
  22155. }
  22156. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  22157. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  22158. // Non-default port must be present in the Host header. Default ports
  22159. // (80/443) are omitted; that logic is covered by
  22160. // MakeHostAndPortStringTest.
  22161. EXPECT_EQ("localhost:" + std::to_string(port),
  22162. req.get_header_value("Host"));
  22163. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  22164. req.get_header_value("User-Agent"));
  22165. EXPECT_FALSE(req.has_header("Accept"));
  22166. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  22167. EXPECT_FALSE(req.has_header("Content-Length"));
  22168. });
  22169. }
  22170. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  22171. capture_websocket_handshake_request(
  22172. {{"Host", "example.com"},
  22173. {"User-Agent", "custom-agent"},
  22174. {"X-Custom", "value"}},
  22175. [](const Request &req, int) {
  22176. EXPECT_EQ("example.com", req.get_header_value("Host"));
  22177. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  22178. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  22179. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  22180. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  22181. });
  22182. }
  22183. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  22184. capture_websocket_handshake_request(
  22185. {{"Upgrade", "bogus"},
  22186. {"Connection", "close"},
  22187. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  22188. {"Sec-WebSocket-Version", "8"}},
  22189. [](const Request &req, int) {
  22190. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  22191. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  22192. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  22193. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  22194. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  22195. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  22196. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  22197. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  22198. req.get_header_value("Sec-WebSocket-Key"));
  22199. });
  22200. }
  22201. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  22202. // A header the client refuses to send must abort the handshake before any
  22203. // part of it reaches the wire; a lone request line would otherwise sit in
  22204. // the peer's buffer as a truncated request.
  22205. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  22206. ASSERT_NE(INVALID_SOCKET, srv);
  22207. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  22208. sockaddr_in addr{};
  22209. addr.sin_family = AF_INET;
  22210. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  22211. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22212. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  22213. ASSERT_EQ(0, ::listen(srv, 1));
  22214. sockaddr_in bound{};
  22215. socklen_t bound_len = sizeof(bound);
  22216. ASSERT_EQ(
  22217. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  22218. auto port = ntohs(bound.sin_port);
  22219. ssize_t received = -1;
  22220. std::thread t([&] {
  22221. // Bound every blocking call so a regression fails the test with a bad
  22222. // value instead of hanging the suite.
  22223. fd_set rfds;
  22224. FD_ZERO(&rfds);
  22225. FD_SET(srv, &rfds);
  22226. timeval tv{5, 0};
  22227. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  22228. 0) {
  22229. return;
  22230. }
  22231. sockaddr_in cli_addr{};
  22232. socklen_t cli_len = sizeof(cli_addr);
  22233. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  22234. if (cli == INVALID_SOCKET) { return; }
  22235. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  22236. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22237. char buf[4096];
  22238. received = ::recv(cli, buf, sizeof(buf), 0);
  22239. });
  22240. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  22241. // connect() has already shut the socket down by the time it returns false,
  22242. // so the peer sees EOF without waiting for the client to be destroyed.
  22243. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  22244. {{"X-Bad", "a\r\nInjected: 1"}});
  22245. EXPECT_FALSE(client.connect());
  22246. t.join();
  22247. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  22248. EXPECT_EQ(0, received);
  22249. }
  22250. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  22251. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  22252. // contains "upgrade" as a substring is a different token and must not
  22253. // start a WebSocket handshake.
  22254. auto make_request = [](const std::vector<std::string> &connection_values) {
  22255. Request req;
  22256. req.method = "GET";
  22257. req.headers.emplace("Upgrade", "websocket");
  22258. for (const auto &value : connection_values) {
  22259. req.headers.emplace("Connection", value);
  22260. }
  22261. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22262. req.headers.emplace("Sec-WebSocket-Version", "13");
  22263. return req;
  22264. };
  22265. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  22266. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  22267. EXPECT_TRUE(
  22268. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  22269. EXPECT_TRUE(
  22270. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  22271. EXPECT_TRUE(
  22272. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  22273. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  22274. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  22275. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  22276. EXPECT_FALSE(
  22277. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  22278. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  22279. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22280. }
  22281. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  22282. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  22283. // asks recipients to match each protocol-name case-insensitively, and RFC
  22284. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  22285. // client naming websocket alongside another protocol, or on a second field
  22286. // line, is offering websocket; a value that merely contains "websocket" as a
  22287. // substring is a different protocol name and is not.
  22288. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  22289. Request req;
  22290. req.method = "GET";
  22291. for (const auto &value : upgrade_values) {
  22292. req.headers.emplace("Upgrade", value);
  22293. }
  22294. req.headers.emplace("Connection", "Upgrade");
  22295. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22296. req.headers.emplace("Sec-WebSocket-Version", "13");
  22297. return req;
  22298. };
  22299. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  22300. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  22301. EXPECT_TRUE(
  22302. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  22303. EXPECT_TRUE(
  22304. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  22305. EXPECT_TRUE(
  22306. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  22307. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  22308. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  22309. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  22310. EXPECT_FALSE(
  22311. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  22312. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  22313. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22314. }
  22315. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  22316. Server svr;
  22317. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  22318. auto port = svr.bind_to_any_port("localhost");
  22319. std::thread t([&]() { svr.listen_after_bind(); });
  22320. auto se = detail::scope_exit([&] {
  22321. svr.stop();
  22322. t.join();
  22323. });
  22324. svr.wait_until_ready();
  22325. Headers headers = {{"Upgrade", "websocket"},
  22326. {"Connection", "notupgrade"},
  22327. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22328. {"Sec-WebSocket-Version", "13"}};
  22329. Client cli("localhost", port);
  22330. auto res = cli.Get("/ws", headers);
  22331. // The route exists only as a WebSocket route, so a request that fails the
  22332. // handshake check falls through to ordinary routing.
  22333. ASSERT_TRUE(res);
  22334. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  22335. }
  22336. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  22337. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  22338. // Connection value is the only thing left for the client to reject.
  22339. Server svr;
  22340. svr.Get("/ws", [](const Request &req, Response &res) {
  22341. res.status = StatusCode::SwitchingProtocol_101;
  22342. res.set_header("Upgrade", "websocket");
  22343. res.set_header("Connection", "notupgrade");
  22344. res.set_header("Sec-WebSocket-Accept",
  22345. detail::websocket_accept_key(
  22346. req.get_header_value("Sec-WebSocket-Key")));
  22347. });
  22348. auto port = svr.bind_to_any_port("localhost");
  22349. std::thread t([&]() { svr.listen_after_bind(); });
  22350. auto se = detail::scope_exit([&] {
  22351. svr.stop();
  22352. t.join();
  22353. });
  22354. svr.wait_until_ready();
  22355. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22356. auto res = client.connect();
  22357. EXPECT_FALSE(res);
  22358. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22359. EXPECT_FALSE(client.is_open());
  22360. }
  22361. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  22362. Server svr;
  22363. svr.Get("/ws", [](const Request &req, Response &res) {
  22364. res.status = StatusCode::SwitchingProtocol_101;
  22365. res.set_header("Upgrade", "websocket");
  22366. res.set_header("Connection", "Upgrade");
  22367. res.set_header("Sec-WebSocket-Accept",
  22368. detail::websocket_accept_key(
  22369. req.get_header_value("Sec-WebSocket-Key")));
  22370. res.set_header("Sec-WebSocket-Protocol", "admin");
  22371. });
  22372. auto port = svr.bind_to_any_port("localhost");
  22373. std::thread t([&]() { svr.listen_after_bind(); });
  22374. auto se = detail::scope_exit([&] {
  22375. svr.stop();
  22376. t.join();
  22377. });
  22378. svr.wait_until_ready();
  22379. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  22380. // Server selects a subprotocol the client never offered
  22381. {
  22382. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22383. ws::WebSocketClient client(url, headers);
  22384. auto res = client.connect();
  22385. EXPECT_FALSE(res);
  22386. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22387. EXPECT_FALSE(client.is_open());
  22388. EXPECT_TRUE(client.subprotocol().empty());
  22389. }
  22390. // Client offered none but the server named one anyway
  22391. {
  22392. ws::WebSocketClient client(url);
  22393. auto res = client.connect();
  22394. EXPECT_FALSE(res);
  22395. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22396. EXPECT_FALSE(client.is_open());
  22397. EXPECT_TRUE(client.subprotocol().empty());
  22398. }
  22399. }
  22400. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  22401. // The socket path doubles as the URL host, so it must not contain '/'.
  22402. const char *shard = getenv("GTEST_SHARD_INDEX");
  22403. const std::string sock_path =
  22404. shard ? std::string("httplib-ws-") + shard + ".sock"
  22405. : std::string("httplib-ws.sock");
  22406. std::remove(sock_path.c_str());
  22407. Server svr;
  22408. std::mutex mtx;
  22409. std::string received_host;
  22410. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22411. {
  22412. std::lock_guard<std::mutex> lock(mtx);
  22413. received_host = req.get_header_value("Host");
  22414. }
  22415. std::string msg;
  22416. while (ws.read(msg)) {
  22417. ws.send(msg);
  22418. }
  22419. });
  22420. svr.set_address_family(AF_UNIX);
  22421. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  22422. auto se = detail::scope_exit([&] {
  22423. svr.stop();
  22424. t.join();
  22425. std::remove(sock_path.c_str());
  22426. });
  22427. svr.wait_until_ready();
  22428. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  22429. client.set_address_family(AF_UNIX);
  22430. ASSERT_TRUE(client.connect());
  22431. ASSERT_TRUE(client.send("hello"));
  22432. std::string msg;
  22433. ASSERT_TRUE(client.read(msg));
  22434. client.close();
  22435. {
  22436. std::lock_guard<std::mutex> lock(mtx);
  22437. // There is no host:port for a Unix socket, so the same "localhost"
  22438. // placeholder the HTTP client uses is expected.
  22439. EXPECT_EQ("localhost", received_host);
  22440. }
  22441. }
  22442. // Two threads must never parse WebSocket frames from the same stream.
  22443. // close() used to read the peer's Close reply with its own frame read, so it
  22444. // raced a reader thread that was in the middle of a payload: the payload loop
  22445. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  22446. // so bytes taken by close() were replaced with bytes from further along the
  22447. // stream. The message kept its length and silently changed content.
  22448. //
  22449. // The raw peer below sends a frame header plus part of the payload, waits for
  22450. // the handler to call close(), and only then sends the rest. Whichever thread
  22451. // would win the race for those bytes, the message must arrive intact, because
  22452. // close() must not touch the stream while read() owns it.
  22453. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  22454. #ifndef _WIN32
  22455. signal(SIGPIPE, SIG_IGN);
  22456. #endif
  22457. const size_t payload_len = 120; // fits the 7-bit length field
  22458. const size_t prefix_len = 8;
  22459. const int attempts = 8;
  22460. std::string expected(payload_len, '\0');
  22461. for (size_t i = 0; i < payload_len; i++) {
  22462. expected[i] = static_cast<char>('a' + i % 26);
  22463. }
  22464. std::atomic<bool> peer_stalled{false};
  22465. std::atomic<bool> handler_done{false};
  22466. std::mutex received_mutex;
  22467. std::vector<std::string> received;
  22468. // Bound every wait, so a regression fails the test instead of hanging the
  22469. // suite.
  22470. auto wait_for = [](const std::atomic<bool> &flag) {
  22471. for (int i = 0; i < 500 && !flag; i++) {
  22472. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22473. }
  22474. };
  22475. Server svr;
  22476. svr.set_websocket_ping_interval(0);
  22477. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22478. std::thread reader([&]() {
  22479. std::string msg;
  22480. while (ws.read(msg)) {
  22481. std::lock_guard<std::mutex> guard(received_mutex);
  22482. received.push_back(msg);
  22483. }
  22484. });
  22485. // Wait until the peer stalls mid-payload, so the reader thread is parked
  22486. // inside read_websocket_frame() when close() runs.
  22487. wait_for(peer_stalled);
  22488. ws.close();
  22489. reader.join();
  22490. handler_done = true;
  22491. });
  22492. auto port = svr.bind_to_any_port("127.0.0.1");
  22493. std::thread t([&]() { svr.listen_after_bind(); });
  22494. auto se = detail::scope_exit([&] {
  22495. svr.stop();
  22496. t.join();
  22497. });
  22498. svr.wait_until_ready();
  22499. auto send_bytes = [](socket_t s, const std::string &data) {
  22500. #ifdef _WIN32
  22501. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  22502. #else
  22503. auto n = ::send(s, data.data(), data.size(), 0);
  22504. #endif
  22505. return n == static_cast<decltype(n)>(data.size());
  22506. };
  22507. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  22508. // Every length used here fits the 7-bit length field.
  22509. auto masked_header = [](uint8_t first_byte, size_t len) {
  22510. std::string h;
  22511. h += static_cast<char>(first_byte);
  22512. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  22513. h.append(4, '\0'); // mask key
  22514. return h;
  22515. };
  22516. for (int attempt = 0; attempt < attempts; attempt++) {
  22517. peer_stalled = false;
  22518. handler_done = false;
  22519. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22520. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  22521. auto se_sock = detail::scope_exit([&] {
  22522. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  22523. });
  22524. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22525. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  22526. sockaddr_in addr{};
  22527. addr.sin_family = AF_INET;
  22528. addr.sin_port = htons(static_cast<uint16_t>(port));
  22529. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22530. ASSERT_EQ(
  22531. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  22532. << "attempt " << attempt;
  22533. ASSERT_TRUE(send_bytes(sock,
  22534. "GET /ws HTTP/1.1\r\n"
  22535. "Host: 127.0.0.1\r\n"
  22536. "Upgrade: websocket\r\n"
  22537. "Connection: Upgrade\r\n"
  22538. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22539. "Sec-WebSocket-Version: 13\r\n"
  22540. "\r\n"))
  22541. << "attempt " << attempt;
  22542. std::string response;
  22543. while (response.find("\r\n\r\n") == std::string::npos) {
  22544. char buf[512];
  22545. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  22546. if (n <= 0) { break; }
  22547. response.append(buf, static_cast<size_t>(n));
  22548. }
  22549. ASSERT_NE(std::string::npos, response.find(" 101 "))
  22550. << "attempt " << attempt;
  22551. // Send the header of a Binary message but only the first prefix_len bytes
  22552. // of its payload, leaving the reader thread stalled inside the payload.
  22553. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  22554. expected.substr(0, prefix_len)))
  22555. << "attempt " << attempt;
  22556. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22557. peer_stalled = true;
  22558. // Let close() send its Close frame and park in its own read before the
  22559. // rest of the payload arrives, so both threads are waiting for it.
  22560. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22561. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  22562. close_frame += static_cast<char>(0x03); // status 1000
  22563. close_frame += static_cast<char>(0xE8);
  22564. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  22565. << "attempt " << attempt;
  22566. // Closing the peer releases the reader thread even on the buggy path,
  22567. // where it waits for bytes another thread already consumed.
  22568. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22569. detail::close_socket(sock);
  22570. sock = INVALID_SOCKET;
  22571. wait_for(handler_done);
  22572. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  22573. }
  22574. std::lock_guard<std::mutex> guard(received_mutex);
  22575. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  22576. << "a message in flight when close() ran was dropped";
  22577. for (size_t i = 0; i < received.size(); i++) {
  22578. EXPECT_EQ(expected, received[i]) << "message " << i;
  22579. }
  22580. }
  22581. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  22582. // returning the socket, or INVALID_SOCKET.
  22583. static socket_t connect_raw_websocket(int port, const std::string &path) {
  22584. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22585. if (sock == INVALID_SOCKET) { return sock; }
  22586. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22587. sockaddr_in addr{};
  22588. addr.sin_family = AF_INET;
  22589. addr.sin_port = htons(static_cast<uint16_t>(port));
  22590. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22591. std::string req = "GET " + path +
  22592. " HTTP/1.1\r\n"
  22593. "Host: 127.0.0.1\r\n"
  22594. "Upgrade: websocket\r\n"
  22595. "Connection: Upgrade\r\n"
  22596. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22597. "Sec-WebSocket-Version: 13\r\n"
  22598. "\r\n";
  22599. std::string res;
  22600. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  22601. ::send(sock, req.data(), static_cast<int>(req.size()), 0) ==
  22602. static_cast<int>(req.size())) {
  22603. char c;
  22604. while (res.find("\r\n\r\n") == std::string::npos &&
  22605. ::recv(sock, &c, 1, 0) == 1) {
  22606. res += c;
  22607. }
  22608. }
  22609. if (res.find(" 101 ") == std::string::npos) {
  22610. detail::close_socket(sock);
  22611. return INVALID_SOCKET;
  22612. }
  22613. return sock;
  22614. }
  22615. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  22616. // The payload must fit the 7-bit length field.
  22617. static std::string masked_frame(uint8_t first_byte,
  22618. const std::string &payload) {
  22619. std::string f;
  22620. f += static_cast<char>(first_byte);
  22621. f += static_cast<char>(0x80 | payload.size());
  22622. f.append(4, '\0');
  22623. return f + payload;
  22624. }
  22625. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  22626. std::atomic<bool> done{false};
  22627. std::string received;
  22628. Server svr;
  22629. svr.set_websocket_ping_interval(0);
  22630. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22631. std::string msg;
  22632. if (ws.read(msg) == ws::Binary) { received = msg; }
  22633. done = true;
  22634. });
  22635. auto port = svr.bind_to_any_port("127.0.0.1");
  22636. std::thread t([&]() { svr.listen_after_bind(); });
  22637. auto se = detail::scope_exit([&] {
  22638. svr.stop();
  22639. t.join();
  22640. });
  22641. svr.wait_until_ready();
  22642. auto sock = connect_raw_websocket(port, "/ws");
  22643. ASSERT_NE(INVALID_SOCKET, sock);
  22644. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  22645. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  22646. masked_frame(0x89, "p") + // FIN + Ping
  22647. masked_frame(0x80, "lo"); // FIN + Continuation
  22648. ::send(sock, frames.data(), static_cast<int>(frames.size()), 0);
  22649. for (int i = 0; i < 500 && !done; i++) {
  22650. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22651. }
  22652. ASSERT_TRUE(done);
  22653. EXPECT_EQ("Hello", received);
  22654. }
  22655. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  22656. Server svr;
  22657. svr.set_websocket_ping_interval(0);
  22658. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22659. std::string msg;
  22660. while (ws.read(msg)) {}
  22661. });
  22662. auto port = svr.bind_to_any_port("127.0.0.1");
  22663. std::thread t([&]() { svr.listen_after_bind(); });
  22664. auto se = detail::scope_exit([&] {
  22665. svr.stop();
  22666. t.join();
  22667. });
  22668. svr.wait_until_ready();
  22669. // Each Close payload and the reply it should get: an echo when valid, 1002
  22670. // otherwise.
  22671. std::vector<std::pair<std::string, std::string>> cases = {
  22672. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  22673. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  22674. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  22675. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  22676. };
  22677. for (const auto &c : cases) {
  22678. auto sock = connect_raw_websocket(port, "/ws");
  22679. ASSERT_NE(INVALID_SOCKET, sock);
  22680. auto close_frame = masked_frame(0x88, c.first);
  22681. ::send(sock, close_frame.data(), static_cast<int>(close_frame.size()), 0);
  22682. std::string reply;
  22683. char buf[256];
  22684. while (reply.size() < 2 + c.second.size()) {
  22685. auto n = ::recv(sock, buf, sizeof(buf), 0);
  22686. if (n <= 0) { break; }
  22687. reply.append(buf, static_cast<size_t>(n));
  22688. }
  22689. detail::close_socket(sock);
  22690. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  22691. c.second,
  22692. reply);
  22693. }
  22694. }
  22695. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22696. class WebSocketSSLIntegrationTest : public ::testing::Test {
  22697. protected:
  22698. void SetUp() override {
  22699. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  22700. SERVER_PRIVATE_KEY_FILE);
  22701. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22702. std::string msg;
  22703. ws::ReadResult ret;
  22704. while ((ret = ws.read(msg))) {
  22705. if (ret == ws::Binary) {
  22706. ws.send(msg.data(), msg.size());
  22707. } else {
  22708. ws.send(msg);
  22709. }
  22710. }
  22711. });
  22712. port_ = server_->bind_to_any_port(HOST);
  22713. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22714. server_->wait_until_ready();
  22715. }
  22716. void TearDown() override {
  22717. server_->stop();
  22718. if (server_thread_.joinable()) { server_thread_.join(); }
  22719. }
  22720. std::unique_ptr<SSLServer> server_;
  22721. std::thread server_thread_;
  22722. int port_ = 0;
  22723. };
  22724. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  22725. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  22726. {
  22727. ws::WebSocketClient client(url);
  22728. client.enable_server_certificate_verification(false);
  22729. auto calls = 0;
  22730. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  22731. calls++;
  22732. return false;
  22733. });
  22734. EXPECT_FALSE(client.connect());
  22735. EXPECT_GT(calls, 0);
  22736. }
  22737. {
  22738. ws::WebSocketClient client(url);
  22739. client.enable_server_certificate_verification(false);
  22740. client.set_session_verifier([](tls::session_t) {
  22741. return SSLVerifierResponse::CertificateRejected;
  22742. });
  22743. EXPECT_FALSE(client.connect());
  22744. }
  22745. {
  22746. ws::WebSocketClient client(url);
  22747. client.enable_server_certificate_verification(false);
  22748. client.set_session_verifier([](tls::session_t) {
  22749. return SSLVerifierResponse::CertificateAccepted;
  22750. });
  22751. EXPECT_TRUE(client.connect());
  22752. }
  22753. }
  22754. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  22755. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22756. "/ws-echo");
  22757. client.enable_server_certificate_verification(false);
  22758. ASSERT_TRUE(client.connect());
  22759. ASSERT_TRUE(client.is_open());
  22760. ASSERT_TRUE(client.send("Hello WSS"));
  22761. std::string msg;
  22762. EXPECT_EQ(ws::Text, client.read(msg));
  22763. EXPECT_EQ("Hello WSS", msg);
  22764. client.close();
  22765. }
  22766. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  22767. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  22768. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  22769. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  22770. // client (without calling close() first) is the only path that runs
  22771. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  22772. // bug exactly.
  22773. //
  22774. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  22775. // when linked against an instrumented libssl; run under Valgrind to catch it
  22776. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  22777. // suite (the freed session otherwise stalls on the close handshake) — this test
  22778. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  22779. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  22780. {
  22781. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22782. "/ws-echo");
  22783. client.enable_server_certificate_verification(false);
  22784. client.set_read_timeout(2, 0);
  22785. client.set_write_timeout(2, 0);
  22786. ASSERT_TRUE(client.connect());
  22787. ASSERT_TRUE(client.is_open());
  22788. ASSERT_TRUE(client.send("still open"));
  22789. // Intentionally do NOT call client.close(): leaving scope runs
  22790. // shutdown_and_close() with the WebSocket still open, which must send the
  22791. // close frame while the TLS session is still alive.
  22792. }
  22793. }
  22794. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  22795. // shutdown_and_close() at the start of connect(), reproducing the same
  22796. // use-after-free within the test body rather than at scope exit. The second
  22797. // connect must succeed and echo, proving the close handshake ran over a live
  22798. // session. See the note above about memory-tool requirements.
  22799. TEST_F(WebSocketSSLIntegrationTest,
  22800. ReconnectWhileOpenSendsCloseOverLiveSession) {
  22801. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22802. "/ws-echo");
  22803. client.enable_server_certificate_verification(false);
  22804. client.set_read_timeout(2, 0);
  22805. client.set_write_timeout(2, 0);
  22806. ASSERT_TRUE(client.connect());
  22807. ASSERT_TRUE(client.is_open());
  22808. ASSERT_TRUE(client.send("still open"));
  22809. // Reconnect without closing first: connect() calls shutdown_and_close() on
  22810. // the still-open connection, which must not touch a freed TLS session.
  22811. ASSERT_TRUE(client.connect());
  22812. ASSERT_TRUE(client.is_open());
  22813. ASSERT_TRUE(client.send("after reconnect"));
  22814. std::string msg;
  22815. EXPECT_EQ(ws::Text, client.read(msg));
  22816. EXPECT_EQ("after reconnect", msg);
  22817. client.close();
  22818. }
  22819. #endif
  22820. #ifdef CPPHTTPLIB_SSL_ENABLED
  22821. class WebSocketSSLCATest : public ::testing::Test {
  22822. protected:
  22823. void SetUp() override {
  22824. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  22825. SERVER_PRIVATE_KEY_FILE);
  22826. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22827. std::string msg;
  22828. while (ws.read(msg)) {
  22829. ws.send(msg);
  22830. }
  22831. });
  22832. port_ = server_->bind_to_any_port("127.0.0.1");
  22833. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22834. server_->wait_until_ready();
  22835. }
  22836. void TearDown() override {
  22837. server_->stop();
  22838. if (server_thread_.joinable()) { server_thread_.join(); }
  22839. }
  22840. std::string url() const {
  22841. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  22842. }
  22843. std::unique_ptr<SSLServer> server_;
  22844. std::thread server_thread_;
  22845. int port_ = 0;
  22846. };
  22847. // A custom CA loaded as PEM verifies the server with full certificate
  22848. // verification enabled
  22849. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  22850. ws::WebSocketClient client(url());
  22851. std::string cert;
  22852. read_file(SERVER_CERT2_FILE, cert);
  22853. client.load_ca_cert_store(cert.c_str(), cert.size());
  22854. ASSERT_TRUE(client.connect());
  22855. ASSERT_TRUE(client.send("hello"));
  22856. std::string msg;
  22857. EXPECT_EQ(ws::Text, client.read(msg));
  22858. EXPECT_EQ("hello", msg);
  22859. client.close();
  22860. }
  22861. // A custom CA that does not cover the server must fail verification (the
  22862. // custom CA is exclusive; system certs are not loaded alongside it)
  22863. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  22864. ws::WebSocketClient client(url());
  22865. std::string cert;
  22866. read_file(CLIENT_CA_CERT_FILE, cert);
  22867. client.load_ca_cert_store(cert.c_str(), cert.size());
  22868. auto res = client.connect();
  22869. ASSERT_FALSE(res);
  22870. EXPECT_EQ(Error::SSLServerVerification, res.error());
  22871. EXPECT_EQ(-1, res.status());
  22872. EXPECT_NE(0u, res.ssl_backend_error());
  22873. }
  22874. // The same CA as a file path rather than PEM in memory
  22875. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  22876. ws::WebSocketClient client(url());
  22877. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22878. ASSERT_TRUE(client.connect());
  22879. ASSERT_TRUE(client.send("hello"));
  22880. std::string msg;
  22881. EXPECT_EQ(ws::Text, client.read(msg));
  22882. EXPECT_EQ("hello", msg);
  22883. client.close();
  22884. }
  22885. // ...and a CA file that does not cover the server still fails, so it is the
  22886. // path above that decides the outcome
  22887. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  22888. ws::WebSocketClient client(url());
  22889. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22890. ASSERT_FALSE(client.connect());
  22891. }
  22892. // Regression test: reconnecting with a native custom CA store used to reuse
  22893. // a store handle the previous TLS context had already freed (use-after-free
  22894. // under the OpenSSL backend). The context now lives as long as the client.
  22895. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  22896. ws::WebSocketClient client(url());
  22897. std::string cert;
  22898. read_file(SERVER_CERT2_FILE, cert);
  22899. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  22900. ASSERT_TRUE(client.connect());
  22901. client.close();
  22902. ASSERT_TRUE(client.connect());
  22903. ASSERT_TRUE(client.send("again"));
  22904. std::string msg;
  22905. EXPECT_EQ(ws::Text, client.read(msg));
  22906. EXPECT_EQ("again", msg);
  22907. client.close();
  22908. }
  22909. // Regression test: a certificate with a trusted chain but no identity match
  22910. // for the server IP must be rejected. The Mbed TLS backend used to skip
  22911. // verification entirely for IP hosts, so this connection succeeded there.
  22912. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  22913. // chain verification while the identity check must still fail.
  22914. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  22915. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22916. ASSERT_TRUE(svr.is_valid());
  22917. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22918. std::string msg;
  22919. while (ws.read(msg)) {
  22920. ws.send(msg);
  22921. }
  22922. });
  22923. auto port = svr.bind_to_any_port("127.0.0.1");
  22924. auto t = std::thread([&]() { svr.listen_after_bind(); });
  22925. auto se = detail::scope_exit([&] {
  22926. svr.stop();
  22927. t.join();
  22928. });
  22929. svr.wait_until_ready();
  22930. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  22931. "/echo");
  22932. std::string cert;
  22933. read_file(SERVER_CERT_FILE, cert);
  22934. client.load_ca_cert_store(cert.c_str(), cert.size());
  22935. ASSERT_FALSE(client.connect());
  22936. }
  22937. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  22938. // SNI, so nothing binds the host name to the TLS session. These bind the
  22939. // server to "localhost" instead, the only shape that exercises the SNI and
  22940. // hostname-verification path with certificate verification left enabled.
  22941. class WebSocketSSLDnsHostTest : public ::testing::Test {
  22942. protected:
  22943. void Start(const char *cert_file) {
  22944. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  22945. SERVER_PRIVATE_KEY_FILE);
  22946. ASSERT_TRUE(server_->is_valid());
  22947. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22948. std::string msg;
  22949. while (ws.read(msg)) {
  22950. ws.send(msg);
  22951. }
  22952. });
  22953. port_ = server_->bind_to_any_port("localhost");
  22954. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22955. server_->wait_until_ready();
  22956. }
  22957. void TearDown() override {
  22958. if (server_) { server_->stop(); }
  22959. if (server_thread_.joinable()) { server_thread_.join(); }
  22960. }
  22961. std::string url() const {
  22962. return "wss://localhost:" + std::to_string(port_) + "/echo";
  22963. }
  22964. std::unique_ptr<SSLServer> server_;
  22965. std::thread server_thread_;
  22966. int port_ = 0;
  22967. };
  22968. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  22969. // out and the connection is usable
  22970. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  22971. Start(SERVER_CERT2_FILE);
  22972. ws::WebSocketClient client(url());
  22973. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22974. ASSERT_TRUE(client.connect());
  22975. ASSERT_TRUE(client.send("hello"));
  22976. std::string msg;
  22977. EXPECT_EQ(ws::Text, client.read(msg));
  22978. EXPECT_EQ("hello", msg);
  22979. client.close();
  22980. }
  22981. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  22982. // while the identity check must still reject "localhost"
  22983. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  22984. Start(SERVER_CERT_FILE);
  22985. ws::WebSocketClient client(url());
  22986. client.set_ca_cert_path(SERVER_CERT_FILE);
  22987. auto res = client.connect();
  22988. ASSERT_FALSE(res);
  22989. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  22990. EXPECT_EQ(-1, res.status());
  22991. }
  22992. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  22993. // disabled: the chain is still checked, only the identity check is skipped
  22994. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  22995. Start(SERVER_CERT_FILE);
  22996. ws::WebSocketClient client(url());
  22997. client.set_ca_cert_path(SERVER_CERT_FILE);
  22998. client.enable_server_hostname_verification(false);
  22999. ASSERT_TRUE(client.connect());
  23000. ASSERT_TRUE(client.send("hello"));
  23001. std::string msg;
  23002. EXPECT_EQ(ws::Text, client.read(msg));
  23003. EXPECT_EQ("hello", msg);
  23004. client.close();
  23005. }
  23006. // A CA that did not sign the server certificate fails the chain, even though
  23007. // the name would match
  23008. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  23009. Start(SERVER_CERT2_FILE);
  23010. ws::WebSocketClient client(url());
  23011. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  23012. ASSERT_FALSE(client.connect());
  23013. }
  23014. // With verification disabled, neither the chain nor the name is checked
  23015. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  23016. Start(SERVER_CERT_FILE);
  23017. ws::WebSocketClient client(url());
  23018. client.enable_server_certificate_verification(false);
  23019. ASSERT_TRUE(client.connect());
  23020. ASSERT_TRUE(client.send("hello"));
  23021. std::string msg;
  23022. EXPECT_EQ(ws::Text, client.read(msg));
  23023. EXPECT_EQ("hello", msg);
  23024. client.close();
  23025. }
  23026. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  23027. protected:
  23028. void SetUp() override {
  23029. server_ = httplib::detail::make_unique<SSLServer>(
  23030. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23031. ASSERT_TRUE(server_->is_valid());
  23032. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23033. std::string msg;
  23034. while (ws.read(msg)) {
  23035. ws.send(msg);
  23036. }
  23037. });
  23038. port_ = server_->bind_to_any_port("localhost");
  23039. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23040. server_->wait_until_ready();
  23041. }
  23042. void TearDown() override {
  23043. server_->stop();
  23044. if (server_thread_.joinable()) { server_thread_.join(); }
  23045. }
  23046. std::string url() const {
  23047. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  23048. }
  23049. void ConnectWithClientCert(const std::string &client_cert_file,
  23050. const std::string &client_private_key_file,
  23051. const char *private_key_password) {
  23052. std::string cert_pem, key_pem;
  23053. read_file(client_cert_file, cert_pem);
  23054. read_file(client_private_key_file, key_pem);
  23055. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  23056. key_pem.c_str(), key_pem.size(),
  23057. private_key_password};
  23058. ws::WebSocketClient client(url(), pem);
  23059. ASSERT_TRUE(client.is_valid());
  23060. client.enable_server_certificate_verification(false);
  23061. ASSERT_TRUE(client.connect());
  23062. ASSERT_TRUE(client.send("hello"));
  23063. std::string msg;
  23064. EXPECT_EQ(ws::Text, client.read(msg));
  23065. EXPECT_EQ("hello", msg);
  23066. client.close();
  23067. }
  23068. std::unique_ptr<SSLServer> server_;
  23069. std::thread server_thread_;
  23070. int port_ = 0;
  23071. };
  23072. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  23073. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  23074. }
  23075. // Control for the tests above: the fixture's server really does require a
  23076. // client certificate, so it is the PEM the constructor installed that decides
  23077. // the outcome.
  23078. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  23079. ws::WebSocketClient client(url());
  23080. ASSERT_TRUE(client.is_valid());
  23081. client.enable_server_certificate_verification(false);
  23082. EXPECT_FALSE(client.connect());
  23083. }
  23084. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  23085. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  23086. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  23087. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  23088. }
  23089. #endif
  23090. #if !defined(_WIN32)
  23091. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  23092. auto secret_dir = std::string("./symlink_test_secret");
  23093. auto served_dir = std::string("./symlink_test_served");
  23094. auto secret_file = secret_dir + "/secret.txt";
  23095. auto symlink_path = served_dir + "/escape";
  23096. // Setup: create directories and files
  23097. mkdir(secret_dir.c_str(), 0755);
  23098. mkdir(served_dir.c_str(), 0755);
  23099. {
  23100. std::ofstream ofs(secret_file);
  23101. ofs << "SECRET_DATA";
  23102. }
  23103. // Create symlink using absolute path so it resolves correctly
  23104. #ifdef PATH_MAX
  23105. char abs_secret[PATH_MAX];
  23106. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  23107. #else
  23108. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  23109. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  23110. ASSERT_NE(nullptr, abs_secret);
  23111. #endif
  23112. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  23113. auto se = detail::scope_exit([&] {
  23114. unlink(symlink_path.c_str());
  23115. unlink(secret_file.c_str());
  23116. rmdir(served_dir.c_str());
  23117. rmdir(secret_dir.c_str());
  23118. });
  23119. Server svr;
  23120. svr.set_mount_point("/", served_dir);
  23121. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  23122. auto se2 = detail::scope_exit([&] {
  23123. svr.stop();
  23124. listen_thread.join();
  23125. });
  23126. svr.wait_until_ready();
  23127. Client cli("localhost", PORT);
  23128. // Symlink pointing outside base dir should be blocked
  23129. auto res = cli.Get("/escape/secret.txt");
  23130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23131. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  23132. }
  23133. #endif
  23134. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  23135. // "GET /smuggled" request), reads the first response, and only then sends the
  23136. // embedded request as the body. Returns how many times /smuggled ran.
  23137. //
  23138. // The body is sent AFTER receiving the first response (as in the original
  23139. // PoC) so that the stream_line_reader cannot buffer it together with the
  23140. // headers of the first request.
  23141. static int count_smuggled_requests(const std::string &outer_head,
  23142. std::string &first_response) {
  23143. Server svr;
  23144. svr.set_mount_point("/", "./www");
  23145. std::atomic<int> smuggled_count(0);
  23146. svr.Get("/smuggled", [&](const Request &, Response &res) {
  23147. smuggled_count++;
  23148. res.set_content("oops", "text/plain");
  23149. });
  23150. svr.Post("/post", [&](const Request &req, Response &res) {
  23151. res.set_content(req.body, "text/plain");
  23152. });
  23153. auto port = svr.bind_to_any_port("localhost");
  23154. thread t = thread([&] { svr.listen_after_bind(); });
  23155. auto se = detail::scope_exit([&] {
  23156. svr.stop();
  23157. t.join();
  23158. });
  23159. svr.wait_until_ready();
  23160. auto error = Error::Success;
  23161. auto sock = detail::create_client_socket(
  23162. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  23163. /*connection_timeout_sec=*/2, 0,
  23164. /*read_timeout_sec=*/2, 0,
  23165. /*write_timeout_sec=*/2, 0, std::string(), error);
  23166. EXPECT_NE(INVALID_SOCKET, sock);
  23167. if (sock == INVALID_SOCKET) { return -1; }
  23168. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23169. // The "smuggled" request will be sent as the body of the outer request
  23170. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  23171. "Host: localhost\r\n"
  23172. "Connection: close\r\n"
  23173. "\r\n";
  23174. auto head = outer_head;
  23175. auto len = std::to_string(smuggled.size());
  23176. for (auto pos = head.find("{len}"); pos != std::string::npos;
  23177. pos = head.find("{len}", pos + len.size())) {
  23178. head.replace(pos, 5, len);
  23179. }
  23180. // Step 1: Send only the outer request headers (no body yet)
  23181. auto sent = send(sock, head.data(), head.size(), 0);
  23182. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  23183. // Step 2: Read the first response
  23184. char buf[4096];
  23185. for (;;) {
  23186. auto n = recv(sock, buf, sizeof(buf), 0);
  23187. if (n <= 0) break;
  23188. first_response.append(buf, static_cast<size_t>(n));
  23189. // Stop once we have a complete response (headers + body)
  23190. auto hdr_end = first_response.find("\r\n\r\n");
  23191. if (hdr_end != std::string::npos) {
  23192. // Check for Content-Length to know when the body is complete
  23193. auto cl_pos = first_response.find("Content-Length:");
  23194. if (cl_pos != std::string::npos) {
  23195. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  23196. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  23197. auto cl = std::stoul(
  23198. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  23199. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  23200. } else {
  23201. break; // No Content-Length, assume headers-only response
  23202. }
  23203. }
  23204. }
  23205. // Step 3: Now send the body, which looks like a new HTTP request. On a
  23206. // vulnerable server the keep-alive loop reads this as a second request. The
  23207. // server may already have closed the connection, so the result is ignored.
  23208. send(sock, smuggled.data(), smuggled.size(), 0);
  23209. // Half-close so that a server which drained the body sees EOF and closes,
  23210. // instead of the read below waiting for the read timeout.
  23211. #ifdef _WIN32
  23212. ::shutdown(sock, SD_SEND);
  23213. #else
  23214. ::shutdown(sock, SHUT_WR);
  23215. #endif
  23216. // Step 4: Read until the server closes the connection
  23217. for (;;) {
  23218. auto n = recv(sock, buf, sizeof(buf), 0);
  23219. if (n <= 0) break;
  23220. }
  23221. return smuggled_count.load();
  23222. }
  23223. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  23224. // A GET request with Content-Length to a static file handler must have its
  23225. // body drained before the keep-alive connection is reused. Otherwise the
  23226. // unread body bytes are interpreted as the next HTTP request.
  23227. std::string first_response;
  23228. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23229. "Host: localhost\r\n"
  23230. "Content-Length: {len}\r\n"
  23231. "\r\n",
  23232. first_response));
  23233. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  23234. }
  23235. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  23236. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  23237. // be answered with 400 and the connection closed. Treating it as "no body"
  23238. // leaves the body to be parsed as the next request.
  23239. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  23240. const char *targets[] = {
  23241. "GET /file", // handler that never reads the body
  23242. "GET /not-found", // no handler matches (404)
  23243. "POST /post", // handler that reads the body
  23244. };
  23245. for (auto target : targets) {
  23246. for (auto value : values) {
  23247. std::string first_response;
  23248. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  23249. " HTTP/1.1\r\n"
  23250. "Host: localhost\r\n"
  23251. "Content-Length: " +
  23252. value + "\r\n\r\n",
  23253. first_response))
  23254. << target << " with Content-Length: " << value;
  23255. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  23256. << target << " with Content-Length: " << value;
  23257. }
  23258. }
  23259. }
  23260. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  23261. // A 400 for an unparseable request line leaves the rest of the message
  23262. // unread, so the connection must be closed rather than reused.
  23263. std::string first_response;
  23264. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  23265. "Host: localhost\r\n"
  23266. "Content-Length: {len}\r\n"
  23267. "\r\n",
  23268. first_response));
  23269. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  23270. }
  23271. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  23272. // Same as above for a header block that fails to parse.
  23273. std::string first_response;
  23274. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  23275. "Host: localhost\r\n"
  23276. "Bad Header\r\n"
  23277. "Content-Length: {len}\r\n"
  23278. "\r\n",
  23279. first_response));
  23280. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  23281. }
  23282. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  23283. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  23284. // server must not read another request on that connection, even when the
  23285. // request had no body to drain.
  23286. std::string first_response;
  23287. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  23288. "Host: localhost\r\n"
  23289. "\r\n",
  23290. first_response));
  23291. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  23292. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  23293. }
  23294. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  23295. // A content reader that stops early leaves the stream inside the body.
  23296. // Draining the whole Content-Length from there, or reading the body again,
  23297. // reads into the next request, and whatever follows is parsed as a request
  23298. // of its own.
  23299. Server svr;
  23300. std::atomic<int> smuggled_count(0);
  23301. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  23302. svr.Post("/upload", [](const Request &req, Response &res,
  23303. const ContentReader &content_reader) {
  23304. // Stop at the last chunk, so the whole body has been read however it
  23305. // arrives.
  23306. auto length = req.get_header_value_u64("Content-Length");
  23307. size_t total = 0;
  23308. auto consumed = content_reader([&](const char *, size_t n) {
  23309. total += n;
  23310. return total < length;
  23311. });
  23312. EXPECT_FALSE(consumed);
  23313. if (req.has_param("retry")) {
  23314. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  23315. }
  23316. // Replace the 400 the aborted read set, which would close the connection.
  23317. res.set_redirect("/done");
  23318. });
  23319. auto port = svr.bind_to_any_port(HOST);
  23320. thread t = thread([&] { svr.listen_after_bind(); });
  23321. auto se = detail::scope_exit([&] {
  23322. svr.stop();
  23323. t.join();
  23324. });
  23325. svr.wait_until_ready();
  23326. // A front end sees the second request as a POST whose body is the GET. The
  23327. // first body is as long as the POST's headers, so draining it again reads
  23328. // exactly those and leaves the GET to be parsed next.
  23329. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  23330. "Host: localhost\r\n"
  23331. "\r\n";
  23332. std::string second_head = "POST /post HTTP/1.1\r\n"
  23333. "Host: localhost\r\n"
  23334. "Content-Length: " +
  23335. std::to_string(inner.size()) +
  23336. "\r\n"
  23337. "\r\n";
  23338. for (auto target : {"/upload", "/upload?retry"}) {
  23339. smuggled_count = 0;
  23340. std::string request = "POST " + std::string(target) +
  23341. " HTTP/1.1\r\n"
  23342. "Host: localhost\r\n"
  23343. "Content-Length: " +
  23344. std::to_string(second_head.size()) +
  23345. "\r\n"
  23346. "\r\n" +
  23347. std::string(second_head.size(), 'A') + second_head +
  23348. inner;
  23349. std::string response;
  23350. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  23351. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  23352. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  23353. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  23354. EXPECT_EQ(0, smuggled_count.load()) << target;
  23355. }
  23356. }
  23357. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  23358. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  23359. // must be rejected with 400 Bad Request.
  23360. Server svr;
  23361. svr.Post("/test", [&](const Request &, Response &res) {
  23362. res.set_content("ok", "text/plain");
  23363. });
  23364. thread t = thread([&] { svr.listen(HOST, PORT); });
  23365. auto se = detail::scope_exit([&] {
  23366. svr.stop();
  23367. t.join();
  23368. ASSERT_FALSE(svr.is_running());
  23369. });
  23370. svr.wait_until_ready();
  23371. // Exact "chunked"
  23372. {
  23373. auto req = "POST /test HTTP/1.1\r\n"
  23374. "Host: localhost\r\n"
  23375. "Content-Length: 5\r\n"
  23376. "Transfer-Encoding: chunked\r\n"
  23377. "Connection: close\r\n"
  23378. "\r\n"
  23379. "hello";
  23380. std::string response;
  23381. ASSERT_TRUE(send_request(1, req, &response));
  23382. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23383. response.substr(0, response.find("\r\n")));
  23384. }
  23385. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  23386. {
  23387. auto req = "POST /test HTTP/1.1\r\n"
  23388. "Host: localhost\r\n"
  23389. "Content-Length: 5\r\n"
  23390. "Transfer-Encoding: gzip, chunked\r\n"
  23391. "Connection: close\r\n"
  23392. "\r\n"
  23393. "hello";
  23394. std::string response;
  23395. ASSERT_TRUE(send_request(1, req, &response));
  23396. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23397. response.substr(0, response.find("\r\n")));
  23398. }
  23399. }
  23400. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  23401. Server svr;
  23402. svr.Post("/test", [&](const Request &, Response &res) {
  23403. res.set_content("ok", "text/plain");
  23404. });
  23405. thread t = thread([&] { svr.listen(HOST, PORT); });
  23406. auto se = detail::scope_exit([&] {
  23407. svr.stop();
  23408. t.join();
  23409. ASSERT_FALSE(svr.is_running());
  23410. });
  23411. svr.wait_until_ready();
  23412. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  23413. // length cannot be determined, so the server must answer 400 and close
  23414. // rather than treat the request as bodyless and leave the body in the
  23415. // socket for the next request to pick up.
  23416. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  23417. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  23418. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  23419. std::string response;
  23420. ASSERT_TRUE(send_request(1, req, &response));
  23421. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23422. response.substr(0, response.find("\r\n")))
  23423. << transfer_encoding;
  23424. }
  23425. // RFC 9110 5.3: the codings may also be split across several
  23426. // Transfer-Encoding lines, which combine in the order they were received.
  23427. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  23428. // just like the single-line "chunked, gzip" above.
  23429. {
  23430. auto req = "POST /test HTTP/1.1\r\n"
  23431. "Host: localhost\r\n"
  23432. "Transfer-Encoding: chunked\r\n"
  23433. "Transfer-Encoding: gzip\r\n"
  23434. "\r\n"
  23435. "0\r\n\r\n";
  23436. std::string response;
  23437. ASSERT_TRUE(send_request(1, req, &response));
  23438. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23439. response.substr(0, response.find("\r\n")));
  23440. }
  23441. // A sequence ending in chunked stays valid.
  23442. auto req = "POST /test HTTP/1.1\r\n"
  23443. "Host: localhost\r\n"
  23444. "Transfer-Encoding: gzip, chunked\r\n"
  23445. "Connection: close\r\n"
  23446. "\r\n"
  23447. "0\r\n\r\n";
  23448. std::string response;
  23449. ASSERT_TRUE(send_request(1, req, &response));
  23450. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  23451. // ...including when it is spread over several lines.
  23452. auto split_req = "POST /test HTTP/1.1\r\n"
  23453. "Host: localhost\r\n"
  23454. "Transfer-Encoding: gzip\r\n"
  23455. "Transfer-Encoding: chunked\r\n"
  23456. "Connection: close\r\n"
  23457. "\r\n"
  23458. "0\r\n\r\n";
  23459. std::string split_response;
  23460. ASSERT_TRUE(send_request(1, split_req, &split_response));
  23461. EXPECT_EQ("HTTP/1.1 200 OK",
  23462. split_response.substr(0, split_response.find("\r\n")));
  23463. }
  23464. // Regression for issue #2450: a DELETE without Content-Length on a
  23465. // keep-alive connection must not let the post-response drain consume the
  23466. // next request's bytes.
  23467. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  23468. Server svr;
  23469. std::atomic<int> delete_count(0);
  23470. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  23471. delete_count++;
  23472. res.status = StatusCode::NoContent_204;
  23473. });
  23474. auto port = svr.bind_to_any_port(HOST);
  23475. thread t = thread([&] { svr.listen_after_bind(); });
  23476. auto se = detail::scope_exit([&] {
  23477. svr.stop();
  23478. t.join();
  23479. });
  23480. svr.wait_until_ready();
  23481. auto error = Error::Success;
  23482. auto sock = detail::create_client_socket(
  23483. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23484. /*connection_timeout_sec=*/2, 0,
  23485. /*read_timeout_sec=*/2, 0,
  23486. /*write_timeout_sec=*/2, 0, std::string(), error);
  23487. ASSERT_NE(INVALID_SOCKET, sock);
  23488. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23489. auto send_request_and_read_response = [&](const std::string &req,
  23490. std::string &out) -> bool {
  23491. auto sent = send(sock, req.data(), req.size(), 0);
  23492. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  23493. char buf[4096];
  23494. for (;;) {
  23495. auto n = recv(sock, buf, sizeof(buf), 0);
  23496. if (n <= 0) { return !out.empty(); }
  23497. out.append(buf, static_cast<size_t>(n));
  23498. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  23499. }
  23500. };
  23501. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  23502. "Host: localhost\r\n"
  23503. "\r\n";
  23504. std::string resp1;
  23505. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  23506. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  23507. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  23508. "Host: localhost\r\n"
  23509. "Connection: close\r\n"
  23510. "\r\n";
  23511. std::string resp2;
  23512. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  23513. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  23514. EXPECT_EQ(2, delete_count.load());
  23515. }
  23516. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  23517. Server svr;
  23518. svr.Post("/ingest", [&](const Request &, Response &res,
  23519. const ContentReader &content_reader) {
  23520. auto consumed = content_reader([](const char *, size_t) { return false; });
  23521. EXPECT_FALSE(consumed);
  23522. res.status = StatusCode::Conflict_409;
  23523. res.set_header("Connection", "close");
  23524. });
  23525. auto port = svr.bind_to_any_port(HOST);
  23526. thread t = thread([&] { svr.listen_after_bind(); });
  23527. auto se = detail::scope_exit([&] {
  23528. svr.stop();
  23529. t.join();
  23530. });
  23531. svr.wait_until_ready();
  23532. auto error = Error::Success;
  23533. auto sock = detail::create_client_socket(
  23534. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23535. /*connection_timeout_sec=*/2, 0,
  23536. /*read_timeout_sec=*/1, 0,
  23537. /*write_timeout_sec=*/2, 0, std::string(), error);
  23538. ASSERT_NE(INVALID_SOCKET, sock);
  23539. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23540. std::string request = "POST /ingest HTTP/1.1\r\n"
  23541. "Host: localhost\r\n"
  23542. "Transfer-Encoding: chunked\r\n"
  23543. "\r\n"
  23544. "4\r\n"
  23545. "data\r\n";
  23546. auto sent = send(sock, request.data(), request.size(), 0);
  23547. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  23548. std::string response;
  23549. ssize_t received = 0;
  23550. do {
  23551. char buf[4096];
  23552. received = recv(sock, buf, sizeof(buf), 0);
  23553. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  23554. } while (received > 0);
  23555. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  23556. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  23557. EXPECT_EQ(0, received);
  23558. }
  23559. namespace no_proxy_test {
  23560. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  23561. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  23562. // calling listen().
  23563. class ScopedServer {
  23564. public:
  23565. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  23566. ~ScopedServer() {
  23567. svr_.stop();
  23568. if (th_.joinable()) { th_.join(); }
  23569. }
  23570. Server &svr() { return svr_; }
  23571. int port() const { return port_; }
  23572. void listen() {
  23573. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23574. svr_.wait_until_ready();
  23575. }
  23576. private:
  23577. Server svr_;
  23578. std::thread th_;
  23579. int port_ = 0;
  23580. };
  23581. class ProxyAndTargetServers {
  23582. public:
  23583. ProxyAndTargetServers() {
  23584. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  23585. proxy_hits_++;
  23586. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23587. res.set_content("via-proxy", "text/plain");
  23588. });
  23589. target_.Get(".*", [this](const Request &req, Response &res) {
  23590. target_hits_++;
  23591. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23592. res.set_content("direct", "text/plain");
  23593. });
  23594. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  23595. target_port_ = target_.bind_to_any_port("127.0.0.1");
  23596. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  23597. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  23598. proxy_mock_.wait_until_ready();
  23599. target_.wait_until_ready();
  23600. }
  23601. ~ProxyAndTargetServers() {
  23602. proxy_mock_.stop();
  23603. target_.stop();
  23604. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  23605. if (target_thread_.joinable()) { target_thread_.join(); }
  23606. }
  23607. Server &proxy_mock() { return proxy_mock_; }
  23608. Server &target() { return target_; }
  23609. int proxy_port() const { return proxy_port_; }
  23610. int target_port() const { return target_port_; }
  23611. int proxy_hits() const { return proxy_hits_.load(); }
  23612. int target_hits() const { return target_hits_.load(); }
  23613. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  23614. void reset_counters() {
  23615. proxy_hits_ = 0;
  23616. target_hits_ = 0;
  23617. last_had_proxy_authz_ = false;
  23618. }
  23619. private:
  23620. Server proxy_mock_;
  23621. Server target_;
  23622. std::thread proxy_thread_;
  23623. std::thread target_thread_;
  23624. int proxy_port_ = 0;
  23625. int target_port_ = 0;
  23626. std::atomic<int> proxy_hits_{0};
  23627. std::atomic<int> target_hits_{0};
  23628. std::atomic<bool> last_had_proxy_authz_{false};
  23629. };
  23630. inline std::unique_ptr<Client> make_client(const std::string &host,
  23631. ProxyAndTargetServers &s) {
  23632. auto cli = detail::make_unique<Client>(host, s.target_port());
  23633. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  23634. cli->set_proxy("127.0.0.1", s.proxy_port());
  23635. return cli;
  23636. }
  23637. } // namespace no_proxy_test
  23638. using no_proxy_test::make_client;
  23639. using no_proxy_test::ProxyAndTargetServers;
  23640. TEST(NoProxyTest, ExactHostnameBypasses) {
  23641. ProxyAndTargetServers s;
  23642. auto cli = make_client("example.com", s);
  23643. cli->set_no_proxy({"example.com"});
  23644. auto res = cli->Get("/");
  23645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23646. EXPECT_EQ(0, s.proxy_hits());
  23647. EXPECT_EQ(1, s.target_hits());
  23648. }
  23649. TEST(NoProxyTest, SubdomainBypasses) {
  23650. ProxyAndTargetServers s;
  23651. auto cli = make_client("foo.example.com", s);
  23652. cli->set_no_proxy({"example.com"});
  23653. auto res = cli->Get("/");
  23654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23655. EXPECT_EQ(0, s.proxy_hits());
  23656. EXPECT_EQ(1, s.target_hits());
  23657. }
  23658. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  23659. // Regression guard: "evilexample.com" must not be considered a subdomain
  23660. // of "example.com". Without the dot-boundary rule, a naive endsWith
  23661. // check would let traffic bypass the proxy and leak credentials direct
  23662. // to the attacker host.
  23663. ProxyAndTargetServers s;
  23664. auto cli = make_client("evilexample.com", s);
  23665. cli->set_no_proxy({"example.com"});
  23666. auto res = cli->Get("/");
  23667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23668. EXPECT_GE(s.proxy_hits(), 1);
  23669. EXPECT_EQ(0, s.target_hits());
  23670. }
  23671. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  23672. ProxyAndTargetServers s;
  23673. auto cli = make_client("example.com.evil.com", s);
  23674. cli->set_no_proxy({"example.com"});
  23675. auto res = cli->Get("/");
  23676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23677. EXPECT_GE(s.proxy_hits(), 1);
  23678. EXPECT_EQ(0, s.target_hits());
  23679. }
  23680. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  23681. ProxyAndTargetServers s;
  23682. auto cli = make_client("example.com", s);
  23683. cli->set_no_proxy({".example.com"});
  23684. auto res = cli->Get("/");
  23685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23686. EXPECT_EQ(0, s.proxy_hits());
  23687. EXPECT_EQ(1, s.target_hits());
  23688. }
  23689. TEST(NoProxyTest, CaseInsensitiveHostname) {
  23690. ProxyAndTargetServers s;
  23691. auto cli = make_client("Example.COM", s);
  23692. cli->set_no_proxy({"EXAMPLE.com"});
  23693. auto res = cli->Get("/");
  23694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23695. EXPECT_EQ(0, s.proxy_hits());
  23696. EXPECT_EQ(1, s.target_hits());
  23697. }
  23698. TEST(NoProxyTest, TrailingDotIsNormalized) {
  23699. ProxyAndTargetServers s;
  23700. auto cli = make_client("example.com.", s);
  23701. cli->set_no_proxy({"example.com"});
  23702. auto res = cli->Get("/");
  23703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23704. EXPECT_EQ(0, s.proxy_hits());
  23705. EXPECT_EQ(1, s.target_hits());
  23706. }
  23707. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  23708. // Trailing dots must be normalized on BOTH sides — host and entry.
  23709. // An implementation that only strips the host-side trailing dot would
  23710. // fail to match host "example.com" against entry "example.com." because
  23711. // a literal substring search would compare 11 chars against 12.
  23712. ProxyAndTargetServers s;
  23713. auto cli = make_client("example.com", s);
  23714. cli->set_no_proxy({"example.com."});
  23715. auto res = cli->Get("/");
  23716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23717. EXPECT_EQ(0, s.proxy_hits());
  23718. EXPECT_EQ(1, s.target_hits());
  23719. }
  23720. TEST(NoProxyTest, WildcardBypassesEverything) {
  23721. ProxyAndTargetServers s;
  23722. auto cli = make_client("anything.invalid.test", s);
  23723. cli->set_no_proxy({"*"});
  23724. auto res = cli->Get("/");
  23725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23726. EXPECT_EQ(0, s.proxy_hits());
  23727. EXPECT_EQ(1, s.target_hits());
  23728. }
  23729. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  23730. ProxyAndTargetServers s;
  23731. Client cli("127.0.0.1", s.target_port());
  23732. cli.set_proxy("127.0.0.1", s.proxy_port());
  23733. cli.set_no_proxy({"127.0.0.1"});
  23734. auto res = cli.Get("/");
  23735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23736. EXPECT_EQ(0, s.proxy_hits());
  23737. EXPECT_EQ(1, s.target_hits());
  23738. }
  23739. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  23740. ProxyAndTargetServers s;
  23741. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  23742. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  23743. cli.set_proxy("127.0.0.1", s.proxy_port());
  23744. cli.set_no_proxy({"::1"});
  23745. auto res = cli.Get("/");
  23746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23747. EXPECT_EQ(0, s.proxy_hits());
  23748. EXPECT_EQ(1, s.target_hits());
  23749. }
  23750. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  23751. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  23752. // must still be recognized as IPv6 for CIDR matching. Implementations
  23753. // that detect IPv6 only when the host begins with '[' would parse the
  23754. // host as a hostname and miss the match.
  23755. ProxyAndTargetServers s;
  23756. Client cli("fe80::1", s.target_port());
  23757. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23758. cli.set_proxy("127.0.0.1", s.proxy_port());
  23759. cli.set_no_proxy({"fe80::/10"});
  23760. auto res = cli.Get("/");
  23761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23762. EXPECT_EQ(0, s.proxy_hits());
  23763. EXPECT_EQ(1, s.target_hits());
  23764. }
  23765. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  23766. ProxyAndTargetServers s;
  23767. Client cli("::1", s.target_port());
  23768. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  23769. cli.set_proxy("127.0.0.1", s.proxy_port());
  23770. cli.set_no_proxy({"[::1]"});
  23771. auto res = cli.Get("/");
  23772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23773. EXPECT_EQ(0, s.proxy_hits());
  23774. EXPECT_EQ(1, s.target_hits());
  23775. }
  23776. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  23777. ProxyAndTargetServers s;
  23778. Client cli("fe80::1", s.target_port());
  23779. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23780. cli.set_proxy("127.0.0.1", s.proxy_port());
  23781. cli.set_no_proxy({"[fe80::]/10"});
  23782. auto res = cli.Get("/");
  23783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23784. EXPECT_EQ(0, s.proxy_hits());
  23785. EXPECT_EQ(1, s.target_hits());
  23786. }
  23787. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  23788. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  23789. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  23790. // tricks via address-family conversion.
  23791. ProxyAndTargetServers s;
  23792. Client cli("::ffff:127.0.0.1", s.target_port());
  23793. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  23794. cli.set_proxy("127.0.0.1", s.proxy_port());
  23795. cli.set_no_proxy({"127.0.0.1"});
  23796. auto res = cli.Get("/");
  23797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23798. EXPECT_GE(s.proxy_hits(), 1);
  23799. EXPECT_EQ(0, s.target_hits());
  23800. }
  23801. TEST(NoProxyTest, IPv4CidrMatch) {
  23802. ProxyAndTargetServers s;
  23803. Client cli("127.0.0.1", s.target_port());
  23804. cli.set_proxy("127.0.0.1", s.proxy_port());
  23805. cli.set_no_proxy({"127.0.0.0/8"});
  23806. auto res = cli.Get("/");
  23807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23808. EXPECT_EQ(0, s.proxy_hits());
  23809. EXPECT_EQ(1, s.target_hits());
  23810. }
  23811. TEST(NoProxyTest, IPv4CidrNonMatch) {
  23812. ProxyAndTargetServers s;
  23813. Client cli("127.0.0.1", s.target_port());
  23814. cli.set_proxy("127.0.0.1", s.proxy_port());
  23815. cli.set_no_proxy({"10.0.0.0/8"});
  23816. auto res = cli.Get("/");
  23817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23818. EXPECT_GE(s.proxy_hits(), 1);
  23819. EXPECT_EQ(0, s.target_hits());
  23820. }
  23821. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  23822. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  23823. // IPv4 target matches.
  23824. ProxyAndTargetServers s;
  23825. Client cli("127.0.0.1", s.target_port());
  23826. cli.set_proxy("127.0.0.1", s.proxy_port());
  23827. cli.set_no_proxy({"0.0.0.0/0"});
  23828. auto res = cli.Get("/");
  23829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23830. EXPECT_EQ(0, s.proxy_hits());
  23831. EXPECT_EQ(1, s.target_hits());
  23832. }
  23833. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  23834. ProxyAndTargetServers s;
  23835. Client cli("127.0.0.1", s.target_port());
  23836. cli.set_proxy("127.0.0.1", s.proxy_port());
  23837. cli.set_no_proxy({"127.0.0.1"});
  23838. auto res = cli.Get("/");
  23839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23840. EXPECT_EQ(0, s.proxy_hits());
  23841. EXPECT_EQ(1, s.target_hits());
  23842. }
  23843. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  23844. ProxyAndTargetServers s;
  23845. Client cli("127.0.0.1", s.target_port());
  23846. cli.set_proxy("127.0.0.1", s.proxy_port());
  23847. cli.set_no_proxy({"127.0.0.0/33"});
  23848. auto res = cli.Get("/");
  23849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23850. EXPECT_GE(s.proxy_hits(), 1);
  23851. EXPECT_EQ(0, s.target_hits());
  23852. }
  23853. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  23854. // Empty prefix after the slash must be rejected, not silently treated as /32.
  23855. ProxyAndTargetServers s;
  23856. Client cli("127.0.0.1", s.target_port());
  23857. cli.set_proxy("127.0.0.1", s.proxy_port());
  23858. cli.set_no_proxy({"127.0.0.1/"});
  23859. auto res = cli.Get("/");
  23860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23861. EXPECT_GE(s.proxy_hits(), 1);
  23862. EXPECT_EQ(0, s.target_hits());
  23863. }
  23864. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  23865. ProxyAndTargetServers s;
  23866. auto cli = make_client("internal.corp", s);
  23867. cli->set_proxy_basic_auth("u", "p");
  23868. cli->set_no_proxy({"internal.corp"});
  23869. auto res = cli->Get("/");
  23870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23871. EXPECT_EQ(1, s.target_hits());
  23872. EXPECT_EQ(0, s.proxy_hits());
  23873. EXPECT_FALSE(s.last_had_proxy_authz())
  23874. << "Proxy-Authorization must not be sent direct to the target";
  23875. }
  23876. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  23877. ProxyAndTargetServers s;
  23878. auto cli = make_client("public.example", s);
  23879. cli->set_proxy_basic_auth("u", "p");
  23880. cli->set_no_proxy({"internal.corp"}); // does not match
  23881. auto res = cli->Get("/");
  23882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23883. EXPECT_GE(s.proxy_hits(), 1);
  23884. EXPECT_TRUE(s.last_had_proxy_authz());
  23885. }
  23886. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  23887. std::atomic<int> hits{0};
  23888. std::atomic<int> hits_with_authz{0};
  23889. no_proxy_test::ScopedServer proxy_mock;
  23890. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23891. hits++;
  23892. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  23893. if (req.target.find("/redir") != std::string::npos) {
  23894. res.set_redirect("http://other.example/landed");
  23895. } else {
  23896. res.set_content("via-proxy", "text/plain");
  23897. }
  23898. });
  23899. proxy_mock.listen();
  23900. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  23901. hits = 0;
  23902. hits_with_authz = 0;
  23903. Client cli("public.example", 80);
  23904. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23905. cli.set_proxy_basic_auth(c.first, c.second);
  23906. cli.set_follow_location(true);
  23907. // The redirect to another host goes through the proxy as well
  23908. auto res = cli.Get("/redir");
  23909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23910. EXPECT_EQ(2, hits.load());
  23911. EXPECT_EQ(2, hits_with_authz.load());
  23912. }
  23913. }
  23914. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  23915. ProxyAndTargetServers s;
  23916. auto cli = make_client("anything.test", s);
  23917. auto res = cli->Get("/");
  23918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23919. EXPECT_GE(s.proxy_hits(), 1);
  23920. EXPECT_EQ(0, s.target_hits());
  23921. }
  23922. TEST(NoProxyTest, PortSpecificEntryRejected) {
  23923. ProxyAndTargetServers s;
  23924. auto cli = make_client("example.com", s);
  23925. cli->set_no_proxy({"example.com:8080"});
  23926. auto res = cli->Get("/");
  23927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23928. EXPECT_GE(s.proxy_hits(), 1);
  23929. EXPECT_EQ(0, s.target_hits());
  23930. }
  23931. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  23932. ProxyAndTargetServers s;
  23933. auto cli = make_client("anything.test", s);
  23934. cli->set_no_proxy({"", " ", "\t"});
  23935. auto res = cli->Get("/");
  23936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23937. EXPECT_GE(s.proxy_hits(), 1);
  23938. EXPECT_EQ(0, s.target_hits());
  23939. }
  23940. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  23941. // An entry with leading/trailing whitespace must still match — env-style
  23942. // values are commonly pasted with stray spaces and an implementation
  23943. // that feeds the raw token directly to inet_pton would fail to match
  23944. // valid CIDRs because of the spaces.
  23945. ProxyAndTargetServers s;
  23946. Client cli("127.0.0.1", s.target_port());
  23947. cli.set_proxy("127.0.0.1", s.proxy_port());
  23948. cli.set_no_proxy({" 127.0.0.0/8 "});
  23949. auto res = cli.Get("/");
  23950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23951. EXPECT_EQ(0, s.proxy_hits());
  23952. EXPECT_EQ(1, s.target_hits());
  23953. }
  23954. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  23955. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  23956. // go direct and must NOT carry Proxy-Authorization.
  23957. std::atomic<int> proxy_hits{0};
  23958. std::atomic<int> target_hits{0};
  23959. std::atomic<bool> target_saw_authz{false};
  23960. no_proxy_test::ScopedServer proxy_mock, target;
  23961. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23962. proxy_hits++;
  23963. res.status = 302;
  23964. res.set_header("Location", "http://127.0.0.1:" +
  23965. std::to_string(target.port()) + "/landed");
  23966. });
  23967. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23968. target_hits++;
  23969. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  23970. res.set_content("direct", "text/plain");
  23971. });
  23972. proxy_mock.listen();
  23973. target.listen();
  23974. Client cli("public.example", target.port());
  23975. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23976. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23977. cli.set_proxy_basic_auth("u", "p");
  23978. cli.set_no_proxy({"127.0.0.1"});
  23979. cli.set_follow_location(true);
  23980. auto res = cli.Get("/redir");
  23981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23982. EXPECT_GE(proxy_hits.load(), 1);
  23983. EXPECT_GE(target_hits.load(), 1);
  23984. EXPECT_FALSE(target_saw_authz.load());
  23985. }
  23986. #ifdef CPPHTTPLIB_SSL_ENABLED
  23987. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  23988. // Direct origin replying 407 must not trigger the digest retry; otherwise
  23989. // proxy creds would be sent to the (possibly hostile) origin.
  23990. std::atomic<int> target_hits{0};
  23991. std::atomic<bool> target_saw_proxy_authz{false};
  23992. no_proxy_test::ScopedServer target;
  23993. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23994. target_hits++;
  23995. if (req.has_header("Proxy-Authorization")) {
  23996. target_saw_proxy_authz = true;
  23997. }
  23998. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23999. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  24000. "nonce=\"abc\", algorithm=MD5");
  24001. });
  24002. target.listen();
  24003. // The proxy address is set to the target's port: the bypass MUST kick in;
  24004. // if it doesn't, the test still routes "via proxy" to the same server and
  24005. // the Proxy-Authorization assertion below catches the leak.
  24006. Client cli("evil.example", target.port());
  24007. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  24008. cli.set_proxy("127.0.0.1", target.port());
  24009. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  24010. cli.set_no_proxy({"evil.example"});
  24011. auto res = cli.Get("/x");
  24012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24013. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  24014. EXPECT_EQ(1, target_hits.load());
  24015. EXPECT_FALSE(target_saw_proxy_authz.load());
  24016. }
  24017. #endif
  24018. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  24019. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  24020. std::atomic<int> proxy_hits{0};
  24021. std::atomic<int> bypass_hits{0};
  24022. std::atomic<bool> proxy_saw_c_url{false};
  24023. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  24024. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  24025. proxy_hits++;
  24026. if (req.path.find("/start") != std::string::npos) {
  24027. res.status = 302;
  24028. res.set_header("Location", "http://127.0.0.1:" +
  24029. std::to_string(bypass_server.port()) +
  24030. "/middle");
  24031. return;
  24032. }
  24033. if (req.path.find("/end") != std::string::npos) {
  24034. proxy_saw_c_url = true;
  24035. res.set_content("c-via-proxy", "text/plain");
  24036. return;
  24037. }
  24038. res.set_content("unexpected", "text/plain");
  24039. });
  24040. // public.example's "advertised" port is arbitrary (the request never lands
  24041. // there — it goes through the proxy), but use a dynamic value to stay
  24042. // friendly with sharded parallel runs.
  24043. int public_port = bypass_server.port();
  24044. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  24045. bypass_hits++;
  24046. res.status = 302;
  24047. res.set_header("Location", "http://public.example:" +
  24048. std::to_string(public_port) + "/end");
  24049. });
  24050. proxy_mock.listen();
  24051. bypass_server.listen();
  24052. Client cli("public.example", public_port);
  24053. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24054. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24055. cli.set_no_proxy({"127.0.0.1"});
  24056. cli.set_follow_location(true);
  24057. auto res = cli.Get("/start");
  24058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24059. EXPECT_EQ(StatusCode::OK_200, res->status);
  24060. EXPECT_EQ("c-via-proxy", res->body);
  24061. EXPECT_GE(proxy_hits.load(), 2);
  24062. EXPECT_GE(bypass_hits.load(), 1);
  24063. EXPECT_TRUE(proxy_saw_c_url.load());
  24064. }
  24065. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  24066. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  24067. // request reconnects to the correct endpoint.
  24068. std::atomic<int> proxy_hits{0};
  24069. std::atomic<int> target_hits{0};
  24070. no_proxy_test::ScopedServer proxy_mock, target;
  24071. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  24072. proxy_hits++;
  24073. res.set_content("via-proxy", "text/plain");
  24074. });
  24075. target.svr().Get(".*", [&](const Request &, Response &res) {
  24076. target_hits++;
  24077. res.set_content("direct", "text/plain");
  24078. });
  24079. proxy_mock.listen();
  24080. target.listen();
  24081. Client cli("public.example", target.port());
  24082. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  24083. cli.set_proxy("127.0.0.1", proxy_mock.port());
  24084. cli.set_keep_alive(true);
  24085. auto res1 = cli.Get("/a");
  24086. ASSERT_TRUE(res1);
  24087. EXPECT_EQ("via-proxy", res1->body);
  24088. EXPECT_EQ(1, proxy_hits.load());
  24089. EXPECT_EQ(0, target_hits.load());
  24090. cli.set_no_proxy({"public.example"});
  24091. auto res2 = cli.Get("/b");
  24092. ASSERT_TRUE(res2);
  24093. EXPECT_EQ("direct", res2->body);
  24094. EXPECT_EQ(1, proxy_hits.load());
  24095. EXPECT_EQ(1, target_hits.load());
  24096. }
  24097. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  24098. namespace proxy_tunnel_test {
  24099. // SSLServer counterpart to no_proxy_test::ScopedServer.
  24100. class ScopedSSLServer {
  24101. public:
  24102. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  24103. port_ = svr_.bind_to_any_port("127.0.0.1");
  24104. }
  24105. ~ScopedSSLServer() {
  24106. svr_.stop();
  24107. if (th_.joinable()) { th_.join(); }
  24108. }
  24109. SSLServer &svr() { return svr_; }
  24110. int port() const { return port_; }
  24111. void listen() {
  24112. th_ = std::thread([this] { svr_.listen_after_bind(); });
  24113. svr_.wait_until_ready();
  24114. }
  24115. private:
  24116. SSLServer svr_;
  24117. std::thread th_;
  24118. int port_ = 0;
  24119. };
  24120. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  24121. class ScopedConnectProxy {
  24122. public:
  24123. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  24124. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  24125. if (listen_fd_ < 0) { return; }
  24126. int yes = 1;
  24127. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  24128. sockaddr_in a{};
  24129. a.sin_family = AF_INET;
  24130. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24131. a.sin_port = 0;
  24132. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  24133. return;
  24134. }
  24135. socklen_t alen = sizeof(a);
  24136. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  24137. 0) {
  24138. return;
  24139. }
  24140. port_ = ntohs(a.sin_port);
  24141. if (::listen(listen_fd_, 1) != 0) { return; }
  24142. th_ = std::thread([this] { run(); });
  24143. }
  24144. ~ScopedConnectProxy() {
  24145. stop_ = true;
  24146. if (listen_fd_ >= 0) {
  24147. ::shutdown(listen_fd_, SHUT_RDWR);
  24148. ::close(listen_fd_);
  24149. }
  24150. if (th_.joinable()) { th_.join(); }
  24151. }
  24152. int port() const { return port_; }
  24153. int connect_hits() const { return connect_hits_.load(); }
  24154. // Head of the last CONNECT request, as the proxy saw it on the wire.
  24155. std::string connect_request() const {
  24156. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24157. return connect_request_;
  24158. }
  24159. private:
  24160. void run() {
  24161. while (!stop_.load()) {
  24162. fd_set rfds;
  24163. FD_ZERO(&rfds);
  24164. FD_SET(listen_fd_, &rfds);
  24165. timeval tv{0, 100 * 1000};
  24166. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  24167. if (sel <= 0) { continue; }
  24168. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  24169. if (client_fd < 0) { continue; }
  24170. std::string req;
  24171. char buf[2048];
  24172. while (req.find("\r\n\r\n") == std::string::npos) {
  24173. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  24174. if (n <= 0) { break; }
  24175. req.append(buf, static_cast<size_t>(n));
  24176. }
  24177. if (req.compare(0, 7, "CONNECT") != 0) {
  24178. ::close(client_fd);
  24179. continue;
  24180. }
  24181. connect_hits_++;
  24182. {
  24183. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  24184. connect_request_ = req;
  24185. }
  24186. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  24187. ::send(client_fd, ok, std::strlen(ok), 0);
  24188. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  24189. sockaddr_in o{};
  24190. o.sin_family = AF_INET;
  24191. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  24192. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  24193. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  24194. 0) {
  24195. ::close(client_fd);
  24196. ::close(origin_fd);
  24197. continue;
  24198. }
  24199. auto forward = [](int from, int to) {
  24200. char b[8192];
  24201. for (;;) {
  24202. ssize_t n = ::recv(from, b, sizeof(b), 0);
  24203. if (n <= 0) { break; }
  24204. ssize_t off = 0;
  24205. while (off < n) {
  24206. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  24207. if (s <= 0) {
  24208. off = n;
  24209. break;
  24210. }
  24211. off += s;
  24212. }
  24213. }
  24214. ::shutdown(to, SHUT_WR);
  24215. };
  24216. std::thread t1([&] { forward(client_fd, origin_fd); });
  24217. std::thread t2([&] { forward(origin_fd, client_fd); });
  24218. t1.join();
  24219. t2.join();
  24220. ::close(client_fd);
  24221. ::close(origin_fd);
  24222. }
  24223. }
  24224. int forward_port_ = -1;
  24225. int listen_fd_ = -1;
  24226. int port_ = 0;
  24227. std::thread th_;
  24228. std::atomic<bool> stop_{false};
  24229. std::atomic<int> connect_hits_{0};
  24230. mutable std::mutex connect_request_mutex_;
  24231. std::string connect_request_;
  24232. };
  24233. // Sends one request through the CONNECT proxy to the TLS origin with a
  24234. // credential configured for each hop, and checks that each credential reaches
  24235. // only the hop it was configured for: the proxy's on the CONNECT request, the
  24236. // origin's (every header in origin_headers) on the tunnelled request.
  24237. void CredentialsStayWithTheirHop(
  24238. const std::function<void(SSLClient &)> &set_credentials,
  24239. const std::string &scheme,
  24240. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  24241. std::atomic<int> origin_hits{0};
  24242. std::atomic<bool> origin_saw_proxy_authz{false};
  24243. std::atomic<bool> origin_saw_headers{false};
  24244. ScopedSSLServer origin;
  24245. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24246. origin_hits++;
  24247. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  24248. origin_saw_headers =
  24249. std::all_of(origin_headers.begin(), origin_headers.end(),
  24250. [&](const std::string &h) { return req.has_header(h); });
  24251. res.set_content("ok", "text/plain");
  24252. });
  24253. origin.listen();
  24254. ScopedConnectProxy proxy(origin.port());
  24255. ASSERT_NE(0, proxy.port());
  24256. // Pinned to 127.0.0.1 for the same reason as the test below.
  24257. SSLClient cli("127.0.0.1", origin.port());
  24258. cli.enable_server_certificate_verification(false);
  24259. cli.set_proxy("127.0.0.1", proxy.port());
  24260. set_credentials(cli);
  24261. auto res = cli.Get("/x");
  24262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24263. EXPECT_EQ(StatusCode::OK_200, res->status);
  24264. EXPECT_EQ(1, origin_hits.load());
  24265. EXPECT_EQ(1, proxy.connect_hits());
  24266. EXPECT_TRUE(origin_saw_headers.load());
  24267. EXPECT_FALSE(origin_saw_proxy_authz.load())
  24268. << "Proxy-Authorization must not be sent inside the tunnel";
  24269. auto connect_req = proxy.connect_request();
  24270. EXPECT_NE(std::string::npos,
  24271. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  24272. for (const auto &h : origin_headers) {
  24273. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  24274. << h << " must not be sent to the proxy on CONNECT";
  24275. }
  24276. }
  24277. } // namespace proxy_tunnel_test
  24278. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  24279. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24280. [](SSLClient &cli) {
  24281. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  24282. cli.set_basic_auth("origin-user", "origin-pass");
  24283. },
  24284. "Basic");
  24285. }
  24286. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  24287. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24288. [](SSLClient &cli) {
  24289. cli.set_proxy_bearer_token_auth("proxy-token");
  24290. cli.set_bearer_token_auth("origin-token");
  24291. },
  24292. "Bearer");
  24293. }
  24294. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  24295. proxy_tunnel_test::CredentialsStayWithTheirHop(
  24296. [](SSLClient &cli) {
  24297. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  24298. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  24299. {"Cookie", "sid=origin-session"},
  24300. {"X-Api-Key", "origin-key"}});
  24301. },
  24302. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  24303. }
  24304. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  24305. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  24306. // retry; otherwise proxy creds would be sent to the origin.
  24307. std::atomic<int> origin_hits{0};
  24308. std::atomic<bool> origin_saw_proxy_authz{false};
  24309. proxy_tunnel_test::ScopedSSLServer origin;
  24310. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  24311. origin_hits++;
  24312. if (req.has_header("Proxy-Authorization")) {
  24313. origin_saw_proxy_authz = true;
  24314. }
  24315. res.status = StatusCode::ProxyAuthenticationRequired_407;
  24316. res.set_header("Proxy-Authenticate",
  24317. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  24318. "algorithm=MD5");
  24319. });
  24320. origin.listen();
  24321. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  24322. ASSERT_NE(0, proxy.port());
  24323. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  24324. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  24325. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  24326. // and answer with its own status, making this test flaky.
  24327. SSLClient cli("127.0.0.1", origin.port());
  24328. cli.enable_server_certificate_verification(false);
  24329. cli.set_proxy("127.0.0.1", proxy.port());
  24330. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  24331. auto res = cli.Get("/x");
  24332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24333. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  24334. EXPECT_EQ(1, origin_hits.load());
  24335. EXPECT_FALSE(origin_saw_proxy_authz.load());
  24336. EXPECT_EQ(1, proxy.connect_hits());
  24337. }
  24338. #endif